forked from jaggedsoft/node-binance-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node-binance-api.js
2029 lines (1866 loc) · 81.5 KB
/
node-binance-api.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ============================================================
* node-binance-api
* https://github.com/jaggedsoft/node-binance-api
* ============================================================
* Copyright 2017-, Jon Eyrick
* Released under the MIT License
* ============================================================ */
/**
* Node Binance API
* @module jaggedsoft/node-binance-api
* @return {object} instance to class object
*/
let api = function Binance() {
let Binance = this; // eslint-disable-line consistent-this
'use strict'; // eslint-disable-line no-unused-expressions
const WebSocket = require('ws');
const request = require('request');
const crypto = require('crypto');
const file = require('fs');
const url = require('url');
const HttpsProxyAgent = require('https-proxy-agent');
const SocksProxyAgent = require('socks-proxy-agent');
const stringHash = require('string-hash');
const async = require('async');
const base = 'https://api.binance.com/api/';
const wapi = 'https://api.binance.com/wapi/';
const stream = 'wss://stream.binance.com:9443/ws/';
const combineStream = 'wss://stream.binance.com:9443/stream?streams=';
const userAgent = 'Mozilla/4.0 (compatible; Node Binance API)';
const contentType = 'application/x-www-form-urlencoded';
Binance.subscriptions = {};
Binance.depthCache = {};
Binance.depthCacheContext = {};
Binance.ohlcLatest = {};
Binance.klineQueue = {};
Binance.ohlc = {};
const default_options = {
recvWindow: 5000,
useServerTime: false,
reconnect: true,
verbose: false,
test: false,
log: function (...args) {
console.log(Array.prototype.slice.call(args));
}
};
Binance.options = default_options;
Binance.info = { timeOffset: 0 };
Binance.socketHeartbeatInterval = null;
/**
* Replaces socks connection uri hostname with IP address
* @param {string} connString - socks connection string
* @return {string} modified string with ip address
*/
const proxyReplacewithIp = function (connString) {
return connString;
}
/**
* Returns an array in the form of [host, port]
* @param {string} connString - connection string
* @return {array} array of host and port
*/
const parseProxy = function (connString) {
let arr = connString.split('/');
let host = arr[2].split(':')[0];
let port = arr[2].split(':')[1];
return [arr[0], host, port];
}
/**
* Checks to see of the object is iterable
* @param {object} obj - The object check
* @return {boolean} true or false is iterable
*/
const isIterable = function (obj) {
// checks for null and undefined
if (obj === null) {
return false;
}
return typeof obj[Symbol.iterator] === 'function';
}
const addProxy = opt => {
let socksproxy = process.env.socks_proxy || false;
if (socksproxy === false) return opt;
socksproxy = proxyReplacewithIp(socksproxy);
if (Binance.options.verbose) Binance.options.log('using socks proxy server ' + socksproxy);
opt.agentClass = SocksProxyAgent;
opt.agentOptions = {
protocol: parseProxy(socksproxy)[0],
host: parseProxy(socksproxy)[1],
port: parseProxy(socksproxy)[2]
}
return opt;
}
const reqHandler = cb => (error, response, body) => {
if (!cb) return;
if (error) return cb(error, {});
if (response && response.statusCode !== 200) return cb(response, {});
return cb(null, JSON.parse(body));
}
const proxyRequest = (opt, cb) => request(addProxy(opt), reqHandler(cb));
const reqObj = (url, data = {}, method = 'GET', key) => ({
url: url,
qs: data,
method: method,
timeout: Binance.options.recvWindow,
proxy: process.env.QUOTAGUARDSTATIC_URL,
headers: {
'User-Agent': userAgent,
'Content-type': contentType,
'X-MBX-APIKEY': key || ''
}
})
/**
* Create a http request to the public API
* @param {string} url - The http endpoint
* @param {object} data - The data to send
* @param {function} callback - The callback method to call
* @param {string} method - the http method
* @return {undefined}
*/
const publicRequest = function (url, data = {}, callback, method = 'GET') {
let opt = reqObj(url, data, method);
proxyRequest(opt, callback);
};
/**
* Create a http request to the public API
* @param {string} url - The http endpoint
* @param {object} data - The data to send
* @param {function} callback - The callback method to call
* @param {string} method - the http method
* @return {undefined}
*/
const apiRequest = function (url, data = {}, callback, method = 'GET') {
if (!Binance.options.APIKEY) throw Error('apiRequest: Invalid API Key');
let opt = reqObj(
url,
data,
method,
Binance.options.APIKEY
);
proxyRequest(opt, callback);
};
/**
* Make market request
* @param {string} url - The http endpoint
* @param {object} data - The data to send
* @param {function} callback - The callback method to call
* @param {string} method - the http method
* @return {undefined}
*/
const marketRequest = function (url, data = {}, callback, method = 'GET') {
if (!Binance.options.APIKEY) throw Error('apiRequest: Invalid API Key');
let query = Object.keys(data).reduce(function (a, k) {
a.push(k + '=' + encodeURIComponent(data[k]));
return a;
}, []).join('&');
let opt = reqObj(
url + (query ? '?' + query : ''),
data,
method,
Binance.options.APIKEY
);
proxyRequest(opt, callback);
};
/**
* Create a signed http request to the signed API
* @param {string} url - The http endpoint
* @param {object} data - The data to send
* @param {function} callback - The callback method to call
* @param {string} method - the http method
* @return {undefined}
*/
const signedRequest = function (url, data = {}, callback, method = 'GET') {
if (!Binance.options.APIKEY) throw Error('apiRequest: Invalid API Key');
if (!Binance.options.APISECRET) throw Error('signedRequest: Invalid API Secret');
data.timestamp = new Date().getTime() + Binance.info.timeOffset;
if (typeof data.recvWindow === 'undefined') data.recvWindow = Binance.options.recvWindow;
let query = Object.keys(data).reduce(function (a, k) {
a.push(k + '=' + encodeURIComponent(data[k]));
return a;
}, []).join('&');
let signature = crypto.createHmac('sha256', Binance.options.APISECRET).update(query).digest('hex'); // set the HMAC hash header
let opt = reqObj(
url + '?' + query + '&signature=' + signature,
data,
method,
Binance.options.APIKEY
);
proxyRequest(opt, callback);
};
/**
* Create a signed http request to the signed API
* @param {string} side - BUY or SELL
* @param {string} symbol - The symbol to buy or sell
* @param {string} quantity - The quantity to buy or sell
* @param {string} price - The price per unit to transact each unit at
* @param {object} flags - additional order settings
* @param {function} callback - the callback function
* @return {undefined}
*/
const order = function (side, symbol, quantity, price, flags = {}, callback = false) {
let endpoint = 'v3/order';
if (Binance.options.test) endpoint += '/test';
let opt = {
symbol: symbol,
side: side,
type: 'LIMIT',
quantity: quantity
};
if (typeof flags.type !== 'undefined') opt.type = flags.type;
if (opt.type.includes('LIMIT')) {
opt.price = price;
opt.timeInForce = 'GTC';
}
if (typeof flags.timeInForce !== 'undefined') opt.timeInForce = flags.timeInForce;
if (typeof flags.newOrderRespType !== 'undefined') opt.newOrderRespType = flags.newOrderRespType;
if (typeof flags.newClientOrderId !== 'undefined') opt.newClientOrderId = flags.newClientOrderId;
/*
* STOP_LOSS
* STOP_LOSS_LIMIT
* TAKE_PROFIT
* TAKE_PROFIT_LIMIT
* LIMIT_MAKER
*/
if (typeof flags.icebergQty !== 'undefined') opt.icebergQty = flags.icebergQty;
if (typeof flags.stopPrice !== 'undefined') {
opt.stopPrice = flags.stopPrice;
if (opt.type === 'LIMIT') throw Error('stopPrice: Must set "type" to one of the following: STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT');
}
signedRequest(base + endpoint, opt, function (error, response) {
if (!response) {
if (callback) callback(error, response);
else Binance.options.log('Order() error:', error);
return;
}
if (typeof response.msg !== 'undefined' && response.msg === 'Filter failure: MIN_NOTIONAL') {
Binance.options.log('Order quantity too small. See exchangeInfo() for minimum amounts');
}
if (callback) callback(error, response);
else Binance.options.log(side + '(' + symbol + ',' + quantity + ',' + price + ') ', response);
}, 'POST');
};
/**
* No-operation function
* @return {undefined}
*/
const noop = function () {
// do nothing
};
/**
* Reworked Tuitio's heartbeat code into a shared single interval tick
* @return {undefined}
*/
const socketHeartbeat = function () {
/* sockets removed from `subscriptions` during a manual terminate()
will no longer be at risk of having functions called on them */
for (let endpointId in Binance.subscriptions) {
const ws = Binance.subscriptions[endpointId];
if (ws.isAlive) {
ws.isAlive = false;
if (ws.readyState === WebSocket.OPEN) ws.ping(noop);
} else {
if (Binance.options.verbose) Binance.options.log('Terminating inactive/broken WebSocket: ' + ws.endpoint);
if (ws.readyState === WebSocket.OPEN) ws.terminate();
}
}
};
/**
* Called when socket is opened, subscriptions are registered for later reference
* @param {function} opened_callback - a callback function
* @return {undefined}
*/
const handleSocketOpen = function (opened_callback) {
this.isAlive = true;
if (Object.keys(Binance.subscriptions).length === 0) {
Binance.socketHeartbeatInterval = setInterval(socketHeartbeat, 30000);
}
Binance.subscriptions[this.endpoint] = this;
if (typeof opened_callback === 'function') opened_callback(this.endpoint);
};
/**
* Called when socket is closed, subscriptions are de-registered for later reference
* @param {boolean} reconnect - true or false to reconnect the socket
* @param {string} code - code associated with the socket
* @param {string} reason - string with the response
* @return {undefined}
*/
const handleSocketClose = function (reconnect, code, reason) {
delete Binance.subscriptions[this.endpoint];
if ( Binance.subscriptions && Object.keys(Binance.subscriptions).length === 0 ) {
clearInterval(Binance.socketHeartbeatInterval);
}
Binance.options.log('WebSocket closed: ' + this.endpoint +
(code ? ' (' + code + ')' : '') +
(reason ? ' ' + reason : ''));
if ( Binance.options.reconnect && this.reconnect && reconnect) {
if ( this.endpoint && parseInt(this.endpoint.length, 10) === 60) Binance.options.log('Account data WebSocket reconnecting...');
else Binance.options.log('WebSocket reconnecting: ' + this.endpoint + '...');
try {
reconnect();
} catch (error) {
Binance.options.log('WebSocket reconnect error: ' + error.message);
}
}
};
/**
* Called when socket errors
* @param {object} error - error object message
* @return {undefined}
*/
const handleSocketError = function (error) {
/* Errors ultimately result in a `close` event.
see: https://github.com/websockets/ws/blob/828194044bf247af852b31c49e2800d557fedeff/lib/websocket.js#L126 */
Binance.options.log('WebSocket error: ' + this.endpoint +
(error.code ? ' (' + error.code + ')' : '') +
(error.message ? ' ' + error.message : ''));
};
/**
* Called on each socket heartbeat
* @return {undefined}
*/
const handleSocketHeartbeat = function () {
this.isAlive = true;
};
/**
* Used to subscribe to a single websocket endpoint
* @param {string} endpoint - endpoint to connect to
* @param {function} callback - the function to called when information is received
* @param {boolean} reconnect - whether to reconnect on disconnect
* @param {object} opened_callback - the function to called when opened
* @return {WebSocket} - websocket reference
*/
const subscribe = function (endpoint, callback, reconnect = false, opened_callback = false) {
let httpsproxy = process.env.https_proxy || false;
let socksproxy = process.env.socks_proxy || false;
let ws = false;
if (socksproxy !== false) {
socksproxy = proxyReplacewithIp(socksproxy);
if (Binance.options.verbose) Binance.options.log('using socks proxy server ' + socksproxy);
let agent = new SocksProxyAgent({
protocol: parseProxy(socksproxy)[0],
host: parseProxy(socksproxy)[1],
port: parseProxy(socksproxy)[2]
});
ws = new WebSocket(stream + endpoint, { agent: agent });
} else if (httpsproxy !== false) {
if (Binance.options.verbose) Binance.options.log('using proxy server ' + agent);
let config = url.parse(httpsproxy);
let agent = new HttpsProxyAgent(config);
ws = new WebSocket(stream + endpoint, { agent: agent });
} else {
ws = new WebSocket(stream + endpoint);
}
if (Binance.options.verbose) Binance.options.log('Subscribed to ' + endpoint);
ws.reconnect = Binance.options.reconnect;
ws.endpoint = endpoint;
ws.isAlive = false;
ws.on('open', handleSocketOpen.bind(ws, opened_callback));
ws.on('pong', handleSocketHeartbeat);
ws.on('error', handleSocketError);
ws.on('close', handleSocketClose.bind(ws, reconnect));
ws.on('message', function (data) {
try {
callback(JSON.parse(data));
} catch (error) {
Binance.options.log('Parse error: ' + error.message);
}
});
return ws;
};
/**
* Used to subscribe to a combined websocket endpoint
* @param {string} streams - streams to connect to
* @param {function} callback - the function to called when information is received
* @param {boolean} reconnect - whether to reconnect on disconnect
* @param {object} opened_callback - the function to called when opened
* @return {WebSocket} - websocket reference
*/
const subscribeCombined = function (streams, callback, reconnect = false, opened_callback = false) {
let httpsproxy = process.env.https_proxy || false;
let socksproxy = process.env.https_proxy || false;
const queryParams = streams.join('/');
let ws = false;
if (socksproxy !== false) {
socksproxy = proxyReplacewithIp(socksproxy);
if (Binance.options.verbose) Binance.options.log('using socks proxy server ' + socksproxy);
let agent = new SocksProxyAgent({
protocol: parseProxy(socksproxy)[0],
host: parseProxy(socksproxy)[1],
port: parseProxy(socksproxy)[2]
});
ws = new WebSocket(combineStream + queryParams, { agent: agent });
} else if (httpsproxy !== false) {
if (Binance.options.verbose) Binance.options.log('using proxy server ' + httpsproxy);
let config = url.parse(httpsproxy);
let agent = new HttpsProxyAgent(config);
ws = new WebSocket(combineStream + queryParams, { agent: agent });
} else {
ws = new WebSocket(combineStream + queryParams);
}
ws.reconnect = Binance.options.reconnect;
ws.endpoint = stringHash(queryParams);
ws.isAlive = false;
if (Binance.options.verbose) {
Binance.options.log('CombinedStream: Subscribed to [' + ws.endpoint + '] ' + queryParams);
}
ws.on('open', handleSocketOpen.bind(ws, opened_callback));
ws.on('pong', handleSocketHeartbeat);
ws.on('error', handleSocketError);
ws.on('close', handleSocketClose.bind(ws, reconnect));
ws.on('message', function (data) {
try {
callback(JSON.parse(data).data);
} catch (error) {
Binance.options.log('CombinedStream: Parse error: ' + error.message);
}
});
return ws;
};
/**
* Used to terminate a web socket
* @param {string} endpoint - endpoint identifier associated with the web socket
* @param {boolean} reconnect - auto reconnect after termination
* @return {undefined}
*/
const terminate = function (endpoint, reconnect = false) {
let ws = Binance.subscriptions[endpoint];
if (!ws) return;
ws.removeAllListeners('message');
ws.reconnect = reconnect;
ws.terminate();
}
/**
* Used as part of the user data websockets callback
* @param {object} data - user data callback data type
* @return {undefined}
*/
const userDataHandler = function (data) {
let type = data.e;
if (type === 'outboundAccountInfo') {
Binance.options.balance_callback(data);
} else if (type === 'executionReport') {
if (Binance.options.execution_callback) Binance.options.execution_callback(data);
} else {
Binance.options.log('Unexpected userData: ' + type);
}
};
/**
* Parses the previous day stream and calls the user callback with friendly object
* @param {object} data - user data callback data type
* @param {function} callback - user data callback data type
* @return {undefined}
*/
const prevDayStreamHandler = function (data, callback) {
let {
e: eventType,
E: eventTime,
s: symbol,
p: priceChange,
P: percentChange,
w: averagePrice,
x: prevClose,
c: close,
Q: closeQty,
b: bestBid,
B: bestBidQty,
a: bestAsk,
A: bestAskQty,
o: open,
h: high,
l: low,
v: volume,
q: quoteVolume,
O: openTime,
C: closeTime,
F: firstTradeId,
L: lastTradeId,
n: numTrades
} = data;
callback(null, {
eventType,
eventTime,
symbol,
priceChange,
percentChange,
averagePrice,
prevClose,
close,
closeQty,
bestBid,
bestBidQty,
bestAsk,
bestAskQty,
open,
high,
low,
volume,
quoteVolume,
openTime,
closeTime,
firstTradeId,
lastTradeId,
numTrades
});
};
/**
* Gets the price of a given symbol or symbols
* @param {array} data - array of symbols
* @return {array} - symbols with their current prices
*/
const priceData = function (data) {
const prices = {};
if (Array.isArray(data)) {
for (let obj of data) {
prices[obj.symbol] = obj.price;
}
} else { // Single price returned
prices[data.symbol] = data.price;
}
return prices;
};
/**
* Used by bookTickers to format the bids and asks given given symbols
* @param {array} data - array of symbols
* @return {object} - symbols with their bids and asks data
*/
const bookPriceData = function (data) {
let prices = {};
for (let obj of data) {
prices[obj.symbol] = {
bid: obj.bidPrice,
bids: obj.bidQty,
ask: obj.askPrice,
asks: obj.askQty
};
}
return prices;
};
/**
* Used by balance to get the balance data
* @param {array} data - account info object
* @return {object} - balances hel with available, onorder amounts
*/
const balanceData = function (data) {
let balances = {};
if (typeof data === 'undefined') return {};
if (typeof data.balances === 'undefined') {
Binance.options.log('balanceData error', data);
return {};
}
for (let obj of data.balances) {
balances[obj.asset] = { available: obj.free, onOrder: obj.locked };
}
return balances;
};
/**
* Used by web sockets depth and populates OHLC and info
* @param {string} symbol - symbol to get candlestick info
* @param {string} interval - time interval, 1m, 3m, 5m ....
* @param {array} ticks - tick array
* @return {undefined}
*/
const klineData = function (symbol, interval, ticks) { // Used for /depth
let last_time = 0;
if (isIterable(ticks)) {
for (let tick of ticks) {
// eslint-disable-next-line no-unused-vars
let [time, open, high, low, close, volume, closeTime, assetVolume, trades, buyBaseVolume, buyAssetVolume, ignored] = tick;
Binance.ohlc[symbol][interval][time] = { open: open, high: high, low: low, close: close, volume: volume };
last_time = time;
}
Binance.info[symbol][interval].timestamp = last_time;
}
};
/**
* Combines all OHLC data with latest update
* @param {string} symbol - the symbol
* @param {string} interval - time interval, 1m, 3m, 5m ....
* @return {array} - interval data for given symbol
*/
const klineConcat = function (symbol, interval) {
let output = Binance.ohlc[symbol][interval];
if (typeof Binance.ohlcLatest[symbol][interval].time === 'undefined') return output;
const time = Binance.ohlcLatest[symbol][interval].time;
const last_updated = Object.keys(Binance.ohlc[symbol][interval]).pop();
if (time >= last_updated) {
output[time] = Binance.ohlcLatest[symbol][interval];
delete output[time].time;
output[time].isFinal = false;
}
return output;
};
/**
* Used for websocket @kline
* @param {string} symbol - the symbol
* @param {object} kline - object with kline info
* @param {string} firstTime - time filter
* @return {undefined}
*/
const klineHandler = function (symbol, kline, firstTime = 0) {
// TODO: add Taker buy base asset volume
// eslint-disable-next-line no-unused-vars
let { e: eventType, E: eventTime, k: ticks } = kline;
// eslint-disable-next-line no-unused-vars
let { o: open, h: high, l: low, c: close, v: volume, i: interval, x: isFinal, q: quoteVolume, t: time } = ticks; //n:trades, V:buyVolume, Q:quoteBuyVolume
if (time <= firstTime) return;
if (!isFinal) {
if (typeof Binance.ohlcLatest[symbol][interval].time !== 'undefined') {
if (Binance.ohlcLatest[symbol][interval].time > time) return;
}
Binance.ohlcLatest[symbol][interval] = { open: open, high: high, low: low, close: close, volume: volume, time: time };
return;
}
// Delete an element from the beginning so we don't run out of memory
const first_updated = Object.keys(Binance.ohlc[symbol][interval]).shift();
if (first_updated) delete Binance.ohlc[symbol][interval][first_updated];
Binance.ohlc[symbol][interval][time] = { open: open, high: high, low: low, close: close, volume: volume };
};
/**
* Used for /depth endpoint
* @param {object} data - containing the bids and asks
* @return {undefined}
*/
const depthData = function (data) {
if (!data) return { bids: [], asks: [] };
let bids = {}, asks = {}, obj;
if (typeof data.bids !== 'undefined') {
for (obj of data.bids) {
bids[obj[0]] = parseFloat(obj[1]);
}
}
if (typeof data.asks !== 'undefined') {
for (obj of data.asks) {
asks[obj[0]] = parseFloat(obj[1]);
}
}
return { lastUpdateId: data.lastUpdateId, bids: bids, asks: asks };
}
/**
* Used for /depth endpoint
* @param {object} depth - information
* @return {undefined}
*/
const depthHandler = function (depth) {
let symbol = depth.s, obj;
let context = Binance.depthCacheContext[symbol];
let updateDepthCache = function () {
for (obj of depth.b) { //bids
Binance.depthCache[symbol].bids[obj[0]] = parseFloat(obj[1]);
if (obj[1] === '0.00000000') {
delete Binance.depthCache[symbol].bids[obj[0]];
}
}
for (obj of depth.a) { //asks
Binance.depthCache[symbol].asks[obj[0]] = parseFloat(obj[1]);
if (obj[1] === '0.00000000') {
delete Binance.depthCache[symbol].asks[obj[0]];
}
}
context.skipCount = 0;
context.lastEventUpdateId = depth.u;
context.lastEventUpdateTime = depth.E;
}
// This now conforms 100% to the Binance docs constraints on managing a local order book
if (context.lastEventUpdateId) {
const expectedUpdateId = context.lastEventUpdateId + 1;
if (depth.U <= expectedUpdateId) {
updateDepthCache();
} else {
let msg = 'depthHandler: [' + symbol + '] The depth cache is out of sync.';
msg += ' Symptom: Unexpected Update ID. Expected "' + expectedUpdateId + '", got "' + depth.U + '"';
if (Binance.options.verbose) Binance.options.log(msg);
throw new Error(msg);
}
} else if (depth.U > context.snapshotUpdateId + 1) {
/* In this case we have a gap between the data of the stream and the snapshot.
This is an out of sync error, and the connection must be torn down and reconnected. */
let msg = 'depthHandler: [' + symbol + '] The depth cache is out of sync.';
msg += ' Symptom: Gap between snapshot and first stream data.';
if (Binance.options.verbose) Binance.options.log(msg);
throw new Error(msg);
} else if (depth.u < context.snapshotUpdateId + 1) {
/* In this case we've received data that we've already had since the snapshot.
This isn't really an issue, and we can just update the cache again, or ignore it entirely. */
// do nothing
} else {
// This is our first legal update from the stream data
updateDepthCache();
}
};
/**
* Gets depth cache for given symbol
* @param {string} symbol - the symbol to fetch
* @return {object} - the depth cache object
*/
const getDepthCache = function (symbol) {
if (typeof Binance.depthCache[symbol] === 'undefined') return { bids: {}, asks: {} };
return Binance.depthCache[symbol];
};
/**
* Calculate Buy/Sell volume from DepthCache
* @param {string} symbol - the symbol to fetch
* @return {object} - the depth volume cache object
*/
const depthVolume = function (symbol) {
let cache = getDepthCache(symbol), quantity, price;
let bidbase = 0, askbase = 0, bidqty = 0, askqty = 0;
for (price in cache.bids) {
quantity = cache.bids[price];
bidbase += parseFloat((quantity * parseFloat(price)).toFixed(8));
bidqty += quantity;
}
for (price in cache.asks) {
quantity = cache.asks[price];
askbase += parseFloat((quantity * parseFloat(price)).toFixed(8));
askqty += quantity;
}
return { bids: bidbase, asks: askbase, bidQty: bidqty, askQty: askqty };
};
/**
* Checks whether or not an array contains any duplicate elements
* Note(keith1024): at the moment this only works for primitive types,
* will require modification to work with objects
* @param {array} array - the array to check
* @return {boolean} - true or false
*/
const isArrayUnique = function (array) {
let s = new Set(array);
return s.size === array.length;
};
return {
/**
* Gets depth cache for given symbol
* @param {symbol} symbol - get depch cache for this symbol
* @return {object} - object
*/
depthCache: function (symbol) {
return getDepthCache(symbol);
},
/**
* Gets depth volume for given symbol
* @param {symbol} symbol - get depch volume for this symbol
* @return {object} - object
*/
depthVolume: function (symbol) {
return depthVolume(symbol);
},
/**
* Count decimal places
* @param {float} float - get the price precision point
* @return {int} - number of place
*/
getPrecision: function (float) { //
return float.toString().split('.')[1].length || 0;
},
/**
* rounds number with given step
* @param {float} qty - quantity to round
* @param {float} stepSize - stepSize as specified by exchangeInfo
* @return {float} - number
*/
roundStep: function (qty, stepSize) {
const precision = stepSize.toString().split('.')[1].length || 0;
return ((Math.round(qty / stepSize) | 0) * stepSize).toFixed(precision);
},
/**
* rounds price to required precision
* @param {float} price - price to round
* @param {float} tickSize - tickSize as specified by exchangeInfo
* @return {float} - number
*/
roundTicks: function (price, tickSize) {
const formatter = new Intl.NumberFormat('en-US', { style: 'decimal', minimumFractionDigits: 0, maximumFractionDigits: 8 });
const precision = formatter.format(tickSize).split('.')[1].length || 0;
if ( typeof price === 'string' ) price = parseFloat(price);
return price.toFixed(precision);
},
/**
* Gets percentage of given numbers
* @param {float} min - the smaller number
* @param {float} max - the bigger number
* @param {int} width - percentage width
* @return {float} - percentage
*/
percent: function (min, max, width = 100) {
return (min * 0.01) / (max * 0.01) * width;
},
/**
* Gets the sum of an array of numbers
* @param {array} array - the number to add
* @return {float} - sum
*/
sum: function (array) {
return array.reduce((a, b) => a + b, 0);
},
/**
* Reverses the keys of an object
* @param {object} object - the object
* @return {object} - the object
*/
reverse: function (object) {
let range = Object.keys(object).reverse(), output = {};
for (let price of range) {
output[price] = object[price];
}
return output;
},
/**
* Converts an object to an array
* @param {object} obj - the object
* @return {array} - the array
*/
array: function (obj) {
return Object.keys(obj).map(function (key) {
return [Number(key), obj[key]];
});
},
/**
* Sorts bids
* @param {string} symbol - the object
* @param {int} max - the max number of bids
* @param {string} baseValue - the object
* @return {object} - the object
*/
sortBids: function (symbol, max = Infinity, baseValue = false) {
let object = {}, count = 0, cache;
if (typeof symbol === 'object') cache = symbol;
else cache = getDepthCache(symbol).bids;
let sorted = Object.keys(cache).sort(function (a, b) {
return parseFloat(b) - parseFloat(a)
});
let cumulative = 0;
for (let price of sorted) {
if (baseValue === 'cumulative') {
cumulative += parseFloat(cache[price]);
object[price] = cumulative;
} else if (!baseValue) object[price] = parseFloat(cache[price]);
else object[price] = parseFloat((cache[price] * parseFloat(price)).toFixed(8));
if (++count >= max) break;
}
return object;
},
/**
* Sorts asks
* @param {string} symbol - the object
* @param {int} max - the max number of bids
* @param {string} baseValue - the object
* @return {object} - the object
*/
sortAsks: function (symbol, max = Infinity, baseValue = false) {
let object = {}, count = 0, cache;
if (typeof symbol === 'object') cache = symbol;
else cache = getDepthCache(symbol).asks;
let sorted = Object.keys(cache).sort(function (a, b) {
return parseFloat(a) - parseFloat(b);
});
let cumulative = 0;
for (let price of sorted) {
if (baseValue === 'cumulative') {
cumulative += parseFloat(cache[price]);
object[price] = cumulative;
} else if (!baseValue) object[price] = parseFloat(cache[price]);
else object[price] = parseFloat((cache[price] * parseFloat(price)).toFixed(8));
if (++count >= max) break;
}
return object;
},
/**
* Returns the first property of an object
* @param {object} object - the object to get the first member
* @return {string} - the object key
*/
first: function (object) {
return Object.keys(object).shift();
},
/**
* Returns the last property of an object
* @param {object} object - the object to get the first member
* @return {string} - the object key
*/
last: function (object) {
return Object.keys(object).pop();
},
/**
* Returns an array of properties starting at start
* @param {object} object - the object to get the properties form
* @param {int} start - the starting index
* @return {array} - the array of entires
*/
slice: function (object, start = 0) {
return Object.entries(object).slice(start).map(entry => entry[0]);
},
/**
* Gets the minimum key form object
* @param {object} object - the object to get the properties form
* @return {string} - the minimum key
*/
min: function (object) {
return Math.min.apply(Math, Object.keys(object));
},
/**
* Gets the maximum key form object
* @param {object} object - the object to get the properties form
* @return {string} - the minimum key
*/
max: function (object) {
return Math.max.apply(Math, Object.keys(object));
},
/**
* Sets an option given a key and value
* @param {string} key - the key to set
* @param {object} value - the value of the key
* @return {undefined}
*/
setOption: function (key, value) {
Binance.options[key] = value;
},
/**
* Gets an option given a key
* @param {string} key - the key to set
* @return {undefined}
*/
getOption: function (key) {
return Binance.options[key];
},
/**