This repository has been archived by the owner on Sep 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 186
/
binance-base.js
505 lines (459 loc) · 13.1 KB
/
binance-base.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
const { CandlePeriod } = require("../enums");
const https = require("../https");
const Ticker = require("../ticker");
const Trade = require("../trade");
const Candle = require("../candle");
const Level2Point = require("../level2-point");
const Level2Update = require("../level2-update");
const Level2Snapshot = require("../level2-snapshot");
const BasicClient = require("../basic-client");
const { throttle } = require("../flowcontrol/throttle");
const { batch } = require("../flowcontrol/batch");
/**
* Binance now (as of Nov 2019) has the ability to perform live subscribes using
* a single socket. With this functionality, there is no longer a need to
* use the URL-mutation code and we can use a BasicClient and allow subscribing
* and unsubscribing.
*
* Binance allows subscribing to many streams at the same time, however there is
* a max payload length that cannot be exceeded. This requires the use of a
* subscription batching method.
*
* Binance limits the number of messages that can be sent as well so throttling
* of batched sends must be performed.
*
* _sendSubTrades calls _batchSub
* _batchSub uses the `batch` flow control helper to batch all calls on the
* same tick into a single call
* _batchSub calls _sendMessage
* _sendMessage uses the `throttle` flow controler helper to limit calls to
* 1 per second
*
*/
class BinanceBase extends BasicClient {
constructor({
name,
wssPath,
restL2SnapshotPath,
watcherMs = 30000,
useAggTrades = true,
requestSnapshot = true,
socketBatchSize = 200,
socketThrottleMs = 1000,
restThrottleMs = 1000,
l2updateSpeed = "",
l2snapshotSpeed = "",
batchTickers,
} = {}) {
super(wssPath, name, undefined, watcherMs);
this._restL2SnapshotPath = restL2SnapshotPath;
this.useAggTrades = useAggTrades;
this.l2updateSpeed = l2updateSpeed;
this.l2snapshotSpeed = l2snapshotSpeed;
this.requestSnapshot = requestSnapshot;
this.hasTickers = true;
this.hasTrades = true;
this.hasCandles = true;
this.hasLevel2Snapshots = true;
this.hasLevel2Updates = true;
this.batchTickers = batchTickers;
this._messageId = 0;
this._tickersActive = false;
this.candlePeriod = CandlePeriod._1m;
this._batchSub = batch(this._batchSub.bind(this), socketBatchSize);
this._batchUnsub = batch(this._batchUnsub.bind(this), socketBatchSize);
this._sendMessage = throttle(this._sendMessage.bind(this), socketThrottleMs);
this._requestLevel2Snapshot = throttle(this._requestLevel2Snapshot.bind(this), restThrottleMs);
}
//////////////////////////////////////////////
_onClosing() {
this._tickersActive = false;
this._batchSub.cancel();
this._batchUnsub.cancel();
this._sendMessage.cancel();
this._requestLevel2Snapshot.cancel();
super._onClosing();
}
_sendSubTicker(remote_id) {
if (this._tickersActive) return;
this._tickersActive = true;
const params = this.batchTickers ? ['!ticker@arr'] : [`${remote_id.toLowerCase()}@ticker`];
this._wss.send(
JSON.stringify({
method: "SUBSCRIBE",
params: params,
id: ++this._messageId,
})
);
}
_sendUnsubTicker(remote_id) {
if (this._tickerSubs.size > 1) return;
this._tickersActive = false;
const params = this.batchTickers ? ['!ticker@arr'] : [`${remote_id.toLowerCase()}@ticker`];
this._wss.send(
JSON.stringify({
method: "UNSUBSCRIBE",
params: params,
id: ++this._messageId,
})
);
}
_batchSub(args) {
const params = args.map(p => p[0]);
const id = ++this._messageId;
const msg = JSON.stringify({
method: "SUBSCRIBE",
params,
id,
});
this._sendMessage(msg);
}
_batchUnsub(args) {
const params = args.map(p => p[0]);
const id = ++this._messageId;
const msg = JSON.stringify({
method: "UNSUBSCRIBE",
params,
id,
});
this._sendMessage(msg);
}
_sendMessage(msg) {
this._wss.send(msg);
}
_sendSubTrades(remote_id) {
const stream = remote_id.toLowerCase() + (this.useAggTrades ? "@aggTrade" : "@trade");
this._batchSub(stream);
}
_sendUnsubTrades(remote_id) {
const stream = remote_id.toLowerCase() + (this.useAggTrades ? "@aggTrade" : "@trade");
this._batchUnsub(stream);
}
_sendSubCandles(remote_id) {
const stream = remote_id.toLowerCase() + "@kline_" + candlePeriod(this.candlePeriod);
this._batchSub(stream);
}
_sendUnsubCandles(remote_id) {
const stream = remote_id.toLowerCase() + "@kline_" + candlePeriod(this.candlePeriod);
this._batchUnsub(stream);
}
_sendSubLevel2Snapshots(remote_id) {
const stream =
remote_id.toLowerCase() +
"@depth20" +
(this.l2snapshotSpeed ? `@${this.l2snapshotSpeed}` : "");
this._batchSub(stream);
}
_sendUnsubLevel2Snapshots(remote_id) {
const stream =
remote_id.toLowerCase() +
"@depth20" +
(this.l2snapshotSpeed ? `@${this.l2snapshotSpeed}` : "");
this._batchUnsub(stream);
}
_sendSubLevel2Updates(remote_id) {
if (this.requestSnapshot) this._requestLevel2Snapshot(this._level2UpdateSubs.get(remote_id));
const stream =
remote_id.toLowerCase() + "@depth" + (this.l2updateSpeed ? `@${this.l2updateSpeed}` : "");
this._batchSub(stream);
}
_sendUnsubLevel2Updates(remote_id) {
const stream =
remote_id.toLowerCase() + "@depth" + (this.l2updateSpeed ? `@${this.l2updateSpeed}` : "");
this._batchUnsub(stream);
}
/////////////////////////////////////////////
_onMessage(raw) {
let msg = JSON.parse(raw);
// subscribe/unsubscribe responses
if (msg.result === null && msg.id) {
// console.log(msg);
return;
}
// errors
if (msg.error) {
const error = new Error(msg.error.msg);
error.msg = msg;
this.emit("error", error);
}
// All code past this point relies on msg.stream in some manner. This code
// acts as a guard on msg.stream and aborts prematurely if the property is
// not available.
if (!msg.stream) {
return;
}
// batch tickers
if (msg.stream === "!ticker@arr") {
for (let raw of msg.data) {
let remote_id = raw.s;
let market = this._tickerSubs.get(remote_id);
if (!market) continue;
let ticker = this._constructTicker(raw, market);
this.emit("ticker", ticker, market);
}
return;
}
// single ticker
if (msg.stream.toLowerCase().endsWith("ticker")) {
let remote_id = msg.data.s;
let market = this._tickerSubs.get(remote_id);
if (!market) return;
let ticker = this._constructTicker(msg.data, market);
this.emit("ticker", ticker, market);
return;
}
// trades
if (msg.stream.toLowerCase().endsWith("trade")) {
let remote_id = msg.data.s;
let market = this._tradeSubs.get(remote_id);
if (!market) return;
let trade = this.useAggTrades
? this._constructAggTrade(msg, market)
: this._constructRawTrade(msg, market);
this.emit("trade", trade, market);
return;
}
// candle
if (msg.data.e === "kline") {
let remote_id = msg.data.s;
let market = this._candleSubs.get(remote_id);
if (!market) return;
let candle = this._constructCandle(msg, market);
this.emit("candle", candle, market);
return;
}
// l2snapshot
if (msg.stream.match(/@depth20/)) {
let remote_id = msg.stream.split("@")[0].toUpperCase();
let market = this._level2SnapshotSubs.get(remote_id);
if (!market) return;
let snapshot = this._constructLevel2Snapshot(msg, market);
this.emit("l2snapshot", snapshot, market);
return;
}
// l2update
if (msg.stream.match(/@depth/)) {
let remote_id = msg.stream.split("@")[0].toUpperCase();
let market = this._level2UpdateSubs.get(remote_id);
if (!market) return;
let update = this._constructLevel2Update(msg, market);
this.emit("l2update", update, market);
return;
}
}
_constructTicker(msg, market) {
let {
E: timestamp,
c: last,
v: volume,
q: quoteVolume,
h: high,
l: low,
p: change,
P: changePercent,
a: ask,
A: askVolume,
b: bid,
B: bidVolume,
} = msg;
let open = parseFloat(last) + parseFloat(change);
return new Ticker({
exchange: this._name,
base: market.base,
quote: market.quote,
timestamp: timestamp,
last,
open: open.toFixed(8),
high,
low,
volume,
quoteVolume,
change,
changePercent,
bid,
bidVolume,
ask,
askVolume,
});
}
_constructAggTrade({ data }, market) {
let { a: trade_id, p: price, q: size, T: time, m: buyer } = data;
let unix = time;
let amount = size;
let side = buyer ? "buy" : "sell";
return new Trade({
exchange: this._name,
base: market.base,
quote: market.quote,
tradeId: trade_id.toFixed(),
unix,
side,
price,
amount,
});
}
_constructRawTrade({ data }, market) {
let { t: trade_id, p: price, q: size, b: buyOrderId, a: sellOrderId, T: time, m: buyer } = data;
let unix = time;
let amount = size;
let side = buyer ? "buy" : "sell";
return new Trade({
exchange: this._name,
base: market.base,
quote: market.quote,
tradeId: trade_id,
unix,
side,
price,
amount,
buyOrderId,
sellOrderId,
});
}
/**
* Kline data looks like:
{ stream: 'btcusdt@kline_1m',
data:
{ e: 'kline',
E: 1571068845689,
s: 'BTCUSDT',
k:
{ t: 1571068800000,
T: 1571068859999,
s: 'BTCUSDT',
i: '1m',
f: 189927800,
L: 189928107,
o: '8254.05000000',
c: '8253.61000000',
h: '8256.58000000',
l: '8250.93000000',
v: '19.10571600',
n: 308,
x: false,
q: '157694.32610840',
V: '8.19456200',
Q: '67640.56793106',
B: '0' } } }
*/
_constructCandle({ data }) {
let k = data.k;
return new Candle(k.t, k.o, k.h, k.l, k.c, k.v);
}
_constructLevel2Snapshot(msg, market) {
let sequenceId = msg.data.lastUpdateId;
let asks = msg.data.asks.map(p => new Level2Point(p[0], p[1]));
let bids = msg.data.bids.map(p => new Level2Point(p[0], p[1]));
return new Level2Snapshot({
exchange: this._name,
base: market.base,
quote: market.quote,
sequenceId,
asks,
bids,
});
}
/**
{
"e": "depthUpdate", // Event type
"E": 123456789, // Event time
"s": "BNBBTC", // Symbol
"U": 157, // First update ID in event
"u": 160, // Final update ID in event
"b": [ // Bids to be updated
[
"0.0024", // Price level to be updated
"10" // Quantity
]
],
"a": [ // Asks to be updated
[
"0.0026", // Price level to be updated
"100" // Quantity
]
]
}
*/
_constructLevel2Update(msg, market) {
let eventMs = msg.data.E;
let sequenceId = msg.data.U;
let lastSequenceId = msg.data.u;
let asks = msg.data.a.map(p => new Level2Point(p[0], p[1]));
let bids = msg.data.b.map(p => new Level2Point(p[0], p[1]));
return new Level2Update({
exchange: this._name,
base: market.base,
quote: market.quote,
sequenceId,
lastSequenceId,
eventMs,
asks,
bids,
});
}
async _requestLevel2Snapshot(market) {
let failed = false;
try {
let remote_id = market.id;
let uri = `${this._restL2SnapshotPath}?limit=1000&symbol=${remote_id}`;
let raw = await https.get(uri);
let sequenceId = raw.lastUpdateId;
let timestampMs = raw.E;
let asks = raw.asks.map(p => new Level2Point(p[0], p[1]));
let bids = raw.bids.map(p => new Level2Point(p[0], p[1]));
let snapshot = new Level2Snapshot({
exchange: this._name,
base: market.base,
quote: market.quote,
sequenceId,
timestampMs,
asks,
bids,
});
this.emit("l2snapshot", snapshot, market);
} catch (ex) {
this.emit("error", ex);
failed = true;
} finally {
if (failed) this._requestLevel2Snapshot(market);
}
}
}
function candlePeriod(p) {
switch (p) {
case CandlePeriod._1m:
return "1m";
case CandlePeriod._3m:
return "3m";
case CandlePeriod._5m:
return "5m";
case CandlePeriod._15m:
return "15m";
case CandlePeriod._30m:
return "30m";
case CandlePeriod._1h:
return "1h";
case CandlePeriod._2h:
return "2h";
case CandlePeriod._4h:
return "4h";
case CandlePeriod._6h:
return "6h";
case CandlePeriod._8h:
return "8h";
case CandlePeriod._12h:
return "12h";
case CandlePeriod._1d:
return "1d";
case CandlePeriod._3d:
return "3d";
case CandlePeriod._1w:
return "1w";
case CandlePeriod._1M:
return "1M";
}
}
module.exports = {
candlePeriod,
BinanceBase,
};