forked from tiagosiebler/TriangularArbitrage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CurrencyCore.js
349 lines (278 loc) · 9.85 KB
/
CurrencyCore.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
var CurrencyCore = {};
CurrencyCore.events = {};
CurrencyCore.events.onAllTickerStream = ()=>{},
controller = {};
// constructor
CurrencyCore.init = (ctrl) => {
if(!ctrl.exchange){
throw "Undefined currency exchange connector. Will not be able to communicate with exchange API.";
}
// Stores
CurrencyCore.currencies = {},
CurrencyCore.sockets = {},
CurrencyCore.streams = {},
controller = ctrl,
CurrencyCore.steps = ['BTC','ETH','BNB','USDT'];
//CurrencyCore.startWSockets(exchange, ctrl);
CurrencyCore.startAllTickerStream(ctrl.exchange, ctrl);
CurrencyCore.queueTicker(5000);
return CurrencyCore;
};
CurrencyCore.queueTicker = (interval)=>{
if(!interval) interval = 3000;
setTimeout(()=>{
CurrencyCore.queueTicker(interval);
}, interval);
CurrencyCore.tick();
}
CurrencyCore.tick = ()=>{
//debugger;
//controller.UI.updateTickers(candidates);
}
CurrencyCore.getCurrencyFromStream = (stream, fromCur, toCur)=>{
if(!stream || !fromCur || !toCur) return;
var currency = stream.obj[fromCur + toCur];
if(currency){
currency.flipped = false;
currency.rate = currency.b;
}else{
currency = stream.obj[toCur + fromCur];
if(!currency){
return false;
}
currency.flipped = true;
currency.rate = (1/currency.b);
}
currency.stepFrom = fromCur;
currency.toCurrency = toCur;
return currency;
}
CurrencyCore.getArbitageRate = (stream, step1, step2, step3)=>{
if(!stream || !step1 || !step2 || !step3) return;
var ret = {
a: CurrencyCore.getCurrencyFromStream(stream, step1, step2),
b: CurrencyCore.getCurrencyFromStream(stream, step2, step3),
c: CurrencyCore.getCurrencyFromStream(stream, step3, step1)
};
if(!ret.a || !ret.b || !ret.c) return;
ret.rate = (ret.a.rate) * (ret.b.rate) * (ret.c.rate);
return ret;
}
CurrencyCore.getCandidatesFromStreamViaPath = (stream, aPair, bPair)=>{
var keys = {
a: aPair.toUpperCase(),
b: bPair.toUpperCase(),
c: 'findme'.toUpperCase(),
};
var candidates = {};
var apairs = stream.markets[keys.a];
var bpairs = stream.markets[keys.b];
var akeys = [];
apairs.map((obj, i, array)=>{ akeys[obj.s.replace(keys.a, '')] = obj; });
// prevent 1-steps
delete akeys[keys.b];
/*
Loop through BPairs
for each bpair key, check if apair has it too.
If it does, run arbitrage math
*/
var bmatches = [];
for(ib=0;ib<bpairs.length;ib++){
var bPairTicker = bpairs[ib];
bPairTicker.key = bPairTicker.s.replace(keys.b,'');
// from B to C
bPairTicker.startsWithKey = bPairTicker.s.startsWith(keys.b);
// from C to B
bPairTicker.endsWithKey = bPairTicker.s.endsWith(keys.b);
if(akeys[bPairTicker.key]){
var match = bPairTicker;
// check price from bPairTicker.key to keys.a
var stepC = stream.obj[match.key + keys.a];
if(stepC){
stepC.flipped = false;
stepC.rate = stepC.b;
}else{
stepC = stream.obj[keys.a + match.key];
if(!stepC){
// does this happen? should probably handle it just in case
debugger;
}else{
stepC.flipped = true;
stepC.rate = (1/stepC.b);
}
}
// only do this if we definitely found a path. Some paths are impossible, so will result in an empty stepC quote.
if(stepC){
keys.c = match.key;
var comparison = CurrencyCore.getArbitageRate(stream, keys.a, keys.b, keys.c);
if(comparison){
var dt = new Date();
var triangle = {
ws_ts: comparison.a.E,
ts: +dt,
dt: dt,
// these are for storage later
a: comparison.a,
a_symbol: comparison.a.s,
a_step: comparison.a.key,
a_bid_price: comparison.a.b,
a_bid_quantity: comparison.a.B,
a_ask_price: comparison.a.a,
a_ask_quantity: comparison.a.A,
a_volume: comparison.a.v,
a_trades: comparison.a.n,
b: comparison.b,
b_symbol: comparison.b.s,
b_step: comparison.b.key,
b_bid_price: comparison.b.b,
b_bid_quantity: comparison.b.B,
b_ask_price: comparison.b.a,
b_ask_quantity: comparison.b.A,
b_volume: comparison.b.v,
b_trades: comparison.b.n,
c: comparison.c,
c_symbol: comparison.c.s,
c_step: comparison.c.key,
c_bid_price: comparison.c.b,
c_bid_quantity: comparison.c.B,
c_ask_price: comparison.c.a,
c_ask_quantity: comparison.c.A,
c_volume: comparison.c.v,
c_trades: comparison.c.n,
rate: comparison.rate
};
bmatches.push(triangle);
}
}
}
}
if(bmatches.length){
bmatches.sort(function(a, b) { return parseFloat(b.rate) - parseFloat(a.rate); });
}
return bmatches;
}
CurrencyCore.getDynamicCandidatesFromStream = (stream, options)=>{
var matches = []
for(i=0;i<options.paths.length;i++){
var pMatches = CurrencyCore.getCandidatesFromStreamViaPath(stream, options.start, options.paths[i]);
matches = matches.concat(pMatches);
// console.log("adding: " + pMatches.length + " to : " + matches.length);
}
if(matches.length){
matches.sort(function(a, b) { return parseFloat(b.rate) - parseFloat(a.rate); });
}
return matches;
}
/*
starts at btc
assumes purchase of eth via btc
looks for a purhase via eth that leads back to btc.
*/
CurrencyCore.getBTCETHCandidatesFromStream = (stream)=>{
var keys = {
a: 'btc'.toUpperCase(),
b: 'eth'.toUpperCase(),
c: 'findme'.toUpperCase(),
};
var candidates = {};
var apairs = stream.markets.BTC;
var bpairs = stream.markets.ETH;
var akeys = [];
apairs.map((obj, i, array)=>{ akeys[obj.s.replace(keys.a, '')] = obj; });
// prevent 1-steps
delete akeys[keys.b];
/*
Loop through BPairs
for each bpair key, check if apair has it too.
If it does, run arbitrage math
*/
var bmatches = [];
for(ib=0;ib<bpairs.length;ib++){
var bPairTicker = bpairs[ib];
bPairTicker.key = bPairTicker.s.replace(keys.b,'');
// from B to C
bPairTicker.startsWithKey = bPairTicker.s.startsWith(keys.b);
// from C to B
bPairTicker.endsWithKey = bPairTicker.s.endsWith(keys.b);
if(akeys[bPairTicker.key]){
var match = bPairTicker;
// check price from bPairTicker.key to keys.a
var stepC = stream.obj[match.key + keys.a];
if(stepC){
stepC.flipped = false;
stepC.rate = stepC.b;
}else{
stepC = stream.obj[keys.a + match.key];
stepC.flipped = true;
stepC.rate = (1/stepC.b);
}
keys.c = match.key;
var rate = CurrencyCore.getArbitageRate(stream, keys.a, keys.b, keys.c);
var triangle = {
a: keys.a,
b: keys.b,
c: keys.c,
rate: rate
};
bmatches.push(triangle);
}
}
if(bmatches.length){
bmatches.sort(function(a, b) { return parseFloat(b.rate) - parseFloat(a.rate); });
}
return bmatches;
}
CurrencyCore.simpleArbitrageMath = (stream, candidates)=>{
if(!stream || !candidates) return;
//EURUSD * (1/GBPUSD) * (1/EURGBP) = 1
//start btc
//via xUSDT
//end btc
var a = candidates['BTCUSDT'];
var b = candidates['ETHUSDT'];
var c = candidates['ETHBTC'];
if(!a || isNaN(a) || !b || isNaN(b) || !c || isNaN(c)) return;
//btcusd : (flip/usdEth) : ethbtc
var d = (a.b) * (1/b.b) * (c.b);
//debugger;
return d;
}
// Fires once per second, with all ticker data from Binance
CurrencyCore.events.onAllTickerStream = stream =>{
var key = 'allMarketTickers';
// Basic array from api arr[0].s = ETHBTC
CurrencyCore.streams.allMarketTickers.arr = stream;
// Mapped object arr[ETHBTC]
CurrencyCore.streams.allMarketTickers.obj = stream.reduce(function ( array, current ) {
array[ current.s ] = current;
return array;
}, {});
// Sub objects with only data on specific markets
for(i=0;i<CurrencyCore.steps.length;i++)
CurrencyCore.streams.allMarketTickers.markets[CurrencyCore.steps[i]] = stream.filter(e => (e.s.endsWith(CurrencyCore.steps[i]) || e.s.startsWith(CurrencyCore.steps[i])));
// something's wrong here. The BNB tree doesn't have BTC, although the BTC tree does.
if(controller && controller.storage.streamTick)
controller.storage.streamTick(CurrencyCore.streams[key], key);
};
// starts one global stream for all selectors. Stream feeds back info every second:
// https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#all-market-tickers-stream
CurrencyCore.startAllTickerStream = function(exchange, ctrl){
if(!CurrencyCore.streams.allMarketTickers){
CurrencyCore.streams.allMarketTickers = {};
CurrencyCore.streams.allMarketTickers.arr = [],
CurrencyCore.streams.allMarketTickers.obj = {};
CurrencyCore.streams.allMarketTickers.markets = [];
}
CurrencyCore.sockets.allMarketTickerStream = exchange.WS.onAllTickerStream(CurrencyCore.events.onAllTickerStream);
}
// starts streams for specific selectors
CurrencyCore.startWSockets = function(exchange, ctrl){
// loop through provided csv selectors, and initiate trades & orderBook sockets for each
for(i = 0;i < CurrencyCore.selectors.length;i++){
let selector = require('./CurrencySelector.js')(CurrencyCore.selectors[i], exchange);
CurrencyCore.currencies[selector.key] = selector;
CurrencyCore.currencies[selector.key].handleEvent = ctrl.events.wsEvent;
CurrencyCore.currencies[selector.key].startWSockets(ctrl.events);
}
}
module.exports = CurrencyCore.init;