forked from ccxt/node-binance-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode-binance-api.ts
More file actions
6794 lines (6250 loc) · 274 KB
/
node-binance-api.ts
File metadata and controls
6794 lines (6250 loc) · 274 KB
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
import WebSocket from 'ws';
// import request from 'request';
import crypto from 'crypto';
import file from 'fs';
import url from 'url';
import JSONbig from 'json-bigint';
// @ts-ignore
import { HttpsProxyAgent } from 'https-proxy-agent';
// @ts-ignore
import { SocksProxyAgent } from 'socks-proxy-agent';
// @ts-ignore
import nodeFetch from 'node-fetch';
// @ts-ignore
import zip from 'lodash.zipobject';
import stringHash from 'string-hash';
// eslint-disable-next-line
import { Interval, PositionRisk, Order, FuturesOrder, PositionSide, WorkingType, OrderType, OrderStatus, TimeInForce, Callback, IConstructorArgs, OrderSide, FundingRate, CancelOrder, AggregatedTrade, Trade, MyTrade, WithdrawHistoryResponse, DepositHistoryResponse, DepositAddress, WithdrawResponse, Candle, FuturesCancelAllOpenOrder, OrderBook, Ticker, FuturesUserTrade, Account, FuturesAccountInfo, FuturesBalance, QueryOrder, HttpMethod, BookTicker, DailyStats, PremiumIndex, OpenInterest, IWebsocketsMethods, SymbolConfig, OCOOrder, FuturesAlgoOrder, CancelAlgoOrder } from './types.js';
// export { Interval, PositionRisk, Order, FuturesOrder, PositionSide, WorkingType, OrderType, OrderStatus, TimeInForce, Callback, IConstructorArgs, OrderSide, FundingRate, CancelOrder, AggregatedTrade, Trade, MyTrade, WithdrawHistoryResponse, DepositHistoryResponse, DepositAddress, WithdrawResponse, Candle, FuturesCancelAllOpenOrder, OrderBook, Ticker, FuturesUserTrade, FuturesAccountInfo, FuturesBalance, QueryOrder } from './types';
export interface Dictionary<T> {
[key: string]: T;
}
export type Dict = Dictionary<any>;
export default class Binance {
domain = 'com';
base = `https://api.binance.${this.domain}/api/`;
baseTest = `https://testnet.binance.vision/api/`;
baseDemo = `https://demo-api.binance.com/api/`;
wapi = `https://api.binance.${this.domain}/wapi/`;
sapi = `https://api.binance.${this.domain}/sapi/`;
fapi = `https://fapi.binance.${this.domain}/fapi/`;
dapi = `https://dapi.binance.${this.domain}/dapi/`;
fapiTest = `https://testnet.binancefuture.com/fapi/`;
fapiDemo = `https://demo-fapi.binance.com/fapi/`;
dapiTest = `https://testnet.binancefuture.com/dapi/`;
dapiDemo = `https://demo-dapi.binance.com/dapi/`;
fstream = `wss://fstream.binance.${this.domain}/stream?streams=`;
fstreamSingle = `wss://fstream.binance.${this.domain}/ws/`;
fstreamSingleTest = `wss://stream.binancefuture.${this.domain}/ws/`;
fstreamSingleDemo = `wss://fstream.binancefuture.com/ws/`;
fstreamTest = `wss://stream.binancefuture.${this.domain}/stream?streams=`;
fstreamDemo = `wss://fstream.binancefuture.com/stream?streams=`;
dstream = `wss://dstream.binance.${this.domain}/stream?streams=`;
dstreamSingle = `wss://dstream.binance.${this.domain}/ws/`;
dstreamSingleTest = `wss://dstream.binancefuture.${this.domain}/ws/`;
dstreamSingleDemo = `wss://dstream.binancefuture.com/ws/`;
dstreamTest = `wss://dstream.binancefuture.${this.domain}/stream?streams=`;
dstreamDemo = `wss://dstream.binancefuture.com/stream?streams=`;
stream = `wss://stream.binance.${this.domain}:9443/ws/`;
streamTest = `wss://stream.testnet.binance.vision/ws/`;
streamDemo = `wss://demo-stream.binance.com/ws/`;
combineStream = `wss://stream.binance.${this.domain}:9443/stream?streams=`;
combineStreamTest = `wss://stream.testnet.binance.vision/stream?streams=`;
combineStreamDemo = `wss://demo-stream.binance.com/stream?streams=`;
wsApi = `wss://ws-api.binance.${this.domain}:443/ws-api/v3`;
wsApiTest = `wss://ws-api.testnet.binance.vision/ws-api/v3`;
verbose = false;
futuresListenKeyKeepAlive: number = 60 * 30 * 1000; // 30 minutes
spotListenKeyKeepAlive: number = 60 * 30 * 1000; // 30 minutes
heartBeatInterval: number = 30000; // 30 seconds
// proxy variables
urlProxy: string = undefined;
httpsProxy: string = undefined;
socksProxy: string = undefined;
nodeFetch: any = undefined;
APIKEY: string = undefined;
APISECRET: string = undefined;
PRIVATEKEY: string = undefined;
PRIVATEKEYPASSWORD: string = undefined;
test = false; // sandbox mode
demo = false; // demo mode
timeOffset: number = 0;
userAgent = 'Mozilla/4.0 (compatible; Node Binance API)';
contentType = 'application/x-www-form-urlencoded';
SPOT_PREFIX = "x-B3AUXNYV";
CONTRACT_PREFIX = "x-ftGmvgAN";
// Websockets Options
isAlive = false;
socketHeartbeatInterval: any = null;
// endpoint: string = ""; // endpoint for WS?
reconnect = true;
headers: Dict = {};
subscriptions: Dict = {};
futuresSubscriptions: Dict = {};
wsApiConnections: Dict = {}; // WebSocket API connections
wsApiPendingRequests: Dict = {}; // Pending JSON-RPC requests
futuresInfo: Dict = {};
futuresMeta: Dict = {};
futuresTicks: Dict = {};
futuresRealtime: Dict = {};
futuresKlineQueue: Dict = {};
deliverySubscriptions: Dict = {};
deliveryInfo: Dict = {};
deliveryMeta: Dict = {};
deliveryTicks: Dict = {};
deliveryRealtime: Dict = {};
deliveryKlineQueue: Dict = {};
depthCache: Dict = {};
depthCacheContext: Dict = {};
ohlcLatest: Dict = {};
klineQueue: Dict = {};
ohlc: Dict = {};
info: Dict = {};
websockets: IWebsocketsMethods = { // deprecated structure, keeping it for backwards compatibility
userData: this.userData.bind(this),
userMarginData: this.userMarginData.bind(this),
depthCacheStaggered: this.depthCacheStaggered.bind(this),
userFutureData: this.userFutureData.bind(this),
userDeliveryData: this.userDeliveryData.bind(this),
subscribeCombined: this.subscribeCombined.bind(this),
subscribe: this.subscribe.bind(this),
subscriptions: () => this.subscriptions,
terminate: this.terminate.bind(this),
depth: this.depthStream.bind(this),
depthCache: this.depthCacheStream.bind(this),
clearDepthCache: this.clearDepthCache.bind(this),
aggTrades: this.aggTradesStream.bind(this),
trades: this.tradesStream.bind(this),
chart: this.chart.bind(this),
candlesticks: this.candlesticksStream.bind(this),
miniTicker: this.miniTicker.bind(this),
bookTickers: this.bookTickersStream.bind(this),
prevDay: this.prevDayStream.bind(this),
futuresCandlesticks: this.futuresCandlesticksStream.bind(this),
futuresTicker: this.futuresTickerStream.bind(this),
futuresMiniTicker: this.futuresMiniTickerStream.bind(this),
futuresAggTrades: this.futuresAggTradeStream.bind(this),
futuresMarkPrice: this.futuresMarkPriceStream.bind(this),
futuresLiquidation: this.futuresLiquidationStream.bind(this),
futuresBookTicker: this.futuresBookTickerStream.bind(this),
futuresChart: this.futuresChart.bind(this),
deliveryAggTrade: this.deliveryAggTradeStream.bind(this),
deliveryCandlesticks: this.deliveryCandlesticks.bind(this),
deliveryTicker: this.deliveryTickerStream.bind(this),
deliveryMiniTicker: this.deliveryMiniTickerStream.bind(this),
deliveryMarkPrice: this.deliveryMarkPriceStream.bind(this),
deliveryBookTicker: this.deliveryBookTickerStream.bind(this),
deliveryChart: this.deliveryChart.bind(this),
deliveryLiquidation: this.deliveryLiquidationStream.bind(this),
futuresSubcriptions: () => this.futuresSubscriptions,
deliverySubcriptions: () => this.deliverySubscriptions,
futuresTerminate: this.futuresTerminate.bind(this),
deliveryTerminate: this.deliveryTerminate.bind(this),
};
default_options = {
recvWindow: 5000,
useServerTime: false,
reconnect: true,
keepAlive: true,
verbose: false,
test: false,
demo: false,
hedgeMode: false,
localAddress: false,
family: 4,
log(...args) {
console.log(Array.prototype.slice.call(args));
}
};
Options: any = {
};
constructor(userOptions: Partial<IConstructorArgs> | string = {}) {
if (userOptions) {
this.setOptions(userOptions);
}
}
options(opt = {}): Binance {
// // return await this.setOptions(opt, callback); // keep this method for backwards compatibility
// this.assignOptions(opt, callback);
this.setOptions(opt);
return this;
}
assignOptions(opt = {}) {
if (typeof opt === 'string') { // Pass json config filename
this.Options = JSON.parse(file.readFileSync(opt) as any);
} else this.Options = opt;
if (!this.Options.recvWindow) this.Options.recvWindow = this.default_options.recvWindow;
if (!this.Options.useServerTime) this.Options.useServerTime = this.default_options.useServerTime;
if (!this.Options.reconnect) this.Options.reconnect = this.default_options.reconnect;
if (!this.Options.test) this.Options.test = this.default_options.test;
if (!this.Options.hedgeMode) this.Options.hedgeMode = this.default_options.hedgeMode;
if (!this.Options.log) this.Options.log = this.default_options.log;
if (!this.Options.verbose) this.Options.verbose = this.default_options.verbose;
if (!this.Options.keepAlive) this.Options.keepAlive = this.default_options.keepAlive;
if (!this.Options.localAddress) this.Options.localAddress = this.default_options.localAddress;
if (!this.Options.family) this.Options.family = this.default_options.family;
if (this.Options.urls !== undefined) {
const { urls } = this.Options;
if (urls.base) this.base = urls.base;
if (urls.wapi) this.wapi = urls.wapi;
if (urls.sapi) this.sapi = urls.sapi;
if (urls.fapi) this.fapi = urls.fapi;
if (urls.fapiTest) this.fapiTest = urls.fapiTest;
if (urls.stream) this.stream = urls.stream;
if (urls.combineStream) this.combineStream = urls.combineStream;
if (urls.fstream) this.fstream = urls.fstream;
if (urls.fstreamSingle) this.fstreamSingle = urls.fstreamSingle;
if (urls.fstreamTest) this.fstreamTest = urls.fstreamTest;
if (urls.fstreamSingleTest) this.fstreamSingleTest = urls.fstreamSingleTest;
if (urls.dstream) this.dstream = urls.dstream;
if (urls.dstreamSingle) this.dstreamSingle = urls.dstreamSingle;
if (urls.dstreamTest) this.dstreamTest = urls.dstreamTest;
if (urls.dstreamSingleTest) this.dstreamSingleTest = urls.dstreamSingleTest;
}
if (this.Options.APIKEY) this.APIKEY = this.Options.APIKEY;
if (this.Options.APISECRET) this.APISECRET = this.Options.APISECRET;
if (this.Options.PRIVATEKEY) this.PRIVATEKEY = this.Options.PRIVATEKEY;
if (this.Options.PRIVATEKEYPASSWORD) this.PRIVATEKEYPASSWORD = this.Options.PRIVATEKEYPASSWORD;
if (this.Options.test) this.test = true;
if (this.Options.demo) this.demo = true;
if (this.Options.headers) this.headers = this.Options.Headers;
if (this.Options.domain) this.domain = this.Options.domain;
if (this.Options.httpsProxy) this.httpsProxy = this.Options.httpsProxy;
}
async setOptions(opt = {}): Promise<Binance> {
this.assignOptions(opt);
if (this.Options.useServerTime) {
const res = await this.publicSpotRequest('v3/time');
this.timeOffset = res.serverTime - new Date().getTime();
}
return this;
}
// ---- HELPER FUNCTIONS ---- //
extend = (...args: any[]) => Object.assign({}, ...args);
getSpotUrl() {
if (this.Options.demo) return this.baseDemo;
if (this.Options.test) return this.baseTest;
return this.base;
}
getSapiUrl() {
return this.sapi;
}
getFapiUrl() {
if (this.Options.demo) return this.fapiDemo;
if (this.Options.test) return this.fapiTest;
return this.fapi;
}
getDapiUrl() {
if (this.Options.demo) return this.dapiDemo;
if (this.Options.test) return this.dapiTest;
return this.dapi;
}
getCombineStreamUrl() {
if (this.Options.demo) return this.combineStreamDemo;
if (this.Options.test) return this.combineStreamTest;
return this.combineStream;
}
getStreamUrl() {
if (this.Options.demo) return this.streamDemo;
if (this.Options.test) return this.streamTest;
return this.stream;
}
getWsApiUrl() {
if (this.Options.test) return this.wsApiTest;
return this.wsApi;
}
getDStreamSingleUrl() {
if (this.Options.demo) return this.dstreamSingleDemo;
if (this.Options.test) return this.dstreamSingleTest;
return this.dstreamSingle;
}
getFStreamSingleUrl() {
if (this.Options.demo) return this.fstreamSingleDemo;
if (this.Options.test) return this.fstreamSingleTest;
return this.fstreamSingle;
}
getFStreamUrl() {
if (this.Options.demo) return this.fstreamDemo;
if (this.Options.test) return this.fstreamTest;
return this.fstream;
}
getDStreamUrl() {
if (this.Options.demo) return this.dstreamDemo;
if (this.Options.test) return this.dstreamTest;
return this.dstream;
}
uuid22(a?: any) {
return a ? (a ^ Math.random() * 16 >> a / 4).toString(16) : (([1e7] as any) + 1e3 + 4e3 + 8e5).replace(/[018]/g, this.uuid22);
}
getUrlProxy() {
if (this.urlProxy) {
return this.urlProxy;
}
return undefined;
}
getHttpsProxy() {
if (this.httpsProxy) {
return this.httpsProxy;
}
if (process.env.https_proxy) {
return process.env.https_proxy;
}
return undefined;
}
getSocksProxy() {
if (this.socksProxy) {
return this.socksProxy;
}
if (process.env.socks_proxy) {
return process.env.socks_proxy;
}
return undefined;
}
// ------ Request Related Functions ------ //
/**
* Replaces socks connection uri hostname with IP address
* @param {string} connString - socks connection string
* @return {string} modified string with ip address
*/
proxyReplacewithIp(connString: string) {
return connString;
}
/**
* Returns an array in the form of [host, port]
* @param {string} connString - connection string
* @return {array} array of host and port
*/
parseProxy(connString: string) {
const arr = connString.split('/');
const host = arr[2].split(':')[0];
const 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
*/
isIterable(obj) {
if (obj === null) return false;
return typeof obj[Symbol.iterator] === 'function';
}
addProxy(opt) {
if (this.Options.proxy) {
const proxyauth = this.Options.proxy.auth ? `${this.Options.proxy.auth.username}:${this.Options.proxy.auth.password}@` : '';
opt.proxy = `http://${proxyauth}${this.Options.proxy.host}:${this.Options.proxy.port}`;
}
return opt;
}
async reqHandler(response) {
this.info.lastRequest = new Date().getTime();
if (response) {
this.info.statusCode = response.status || 0;
if (response.request) this.info.lastURL = response.request.uri.href;
if (response.headers) {
this.info.usedWeight = response.headers['x-mbx-used-weight-1m'] || 0;
this.info.orderCount1s = response.headers['x-mbx-order-count-1s'] || 0;
this.info.orderCount1m = response.headers['x-mbx-order-count-1m'] || 0;
this.info.orderCount1h = response.headers['x-mbx-order-count-1h'] || 0;
this.info.orderCount1d = response.headers['x-mbx-order-count-1d'] || 0;
}
}
if (response && response.status !== 200) {
// let parsedResponse = '';
// try {
// parsedResponse = await response.json();
// } catch (e) {
// parsedResponse = await response.text();
// }
const error = new Error(await response.text());
// error.code = response.status;
// error.url = response.url;
throw error;
}
}
async proxyRequest(opt: any) {
const urlBody = new URLSearchParams(opt.form);
const reqOptions: Dict = {
method: opt.method,
headers: opt.headers,
};
if (opt.method !== 'GET') {
reqOptions.body = urlBody;
}
if (this.Options.verbose) {
this.Options.log('HTTP Request:', opt.method, opt.url, reqOptions);
}
// https-proxy
const httpsproxy = this.getHttpsProxy();
const socksproxy = this.getSocksProxy();
const urlProxy = this.getUrlProxy();
if (httpsproxy) {
if (this.Options.verbose) this.Options.log('using https proxy: ' + httpsproxy);
reqOptions.agent = new HttpsProxyAgent(httpsproxy);
} else if (socksproxy) {
if (this.Options.verbose) this.Options.log('using socks proxy: ' + socksproxy);
reqOptions.agent = new SocksProxyAgent(socksproxy);
}
if (urlProxy) {
opt.url = urlProxy + opt.url;
}
// Apply timeout via AbortController
const timeout = opt.timeout || this.Options.recvWindow || 30000;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
reqOptions.signal = controller.signal;
let fetchImplementation = fetch;
// require node-fetch
if (reqOptions.agent) {
fetchImplementation = nodeFetch;
}
try {
const response = await fetchImplementation(opt.url, reqOptions);
clearTimeout(timeoutId);
await this.reqHandler(response);
const json = await response.json();
if (this.Options.verbose) {
this.Options.log('HTTP Response:', json);
}
return json;
} catch (error) {
clearTimeout(timeoutId);
if (error.name === 'AbortError') {
throw new Error(`Request timeout: ${opt.method} ${opt.url} (${timeout}ms)`);
}
throw error;
}
}
reqObj(url: string, data: Dict = {}, method: HttpMethod = 'GET', key?: string) {
return {
url: url,
qs: data,
method: method,
family: this.Options.family,
localAddress: this.Options.localAddress,
timeout: this.Options.recvWindow,
forever: this.Options.keepAlive,
headers: {
'User-Agent': this.userAgent,
'Content-type': this.contentType,
'X-MBX-APIKEY': key || ''
}
};
}
reqObjPOST(url: string, data: Dict = {}, method = 'POST', key: string) {
return {
url: url,
form: data,
method: method,
family: this.Options.family,
localAddress: this.Options.localAddress,
timeout: this.Options.recvWindow,
forever: this.Options.keepAlive,
qsStringifyOptions: {
arrayFormat: 'repeat'
},
headers: {
'User-Agent': this.userAgent,
'Content-type': this.contentType,
'X-MBX-APIKEY': key || ''
}
};
}
async publicRequest(url: string, data: Dict = {}, method: HttpMethod = 'GET') {
const query = this.makeQueryString(data);
const opt = this.reqObj(url + (query ? '?' + query : ''), data, method);
const res = await this.proxyRequest(opt);
return res;
}
/**
* Used to make public requests to the futures (FAPI) API
* @param path
* @param data
* @param method
* @returns
*/
async publicFuturesRequest(path: string, data: Dict = {}, method: HttpMethod = 'GET') {
return await this.publicRequest(this.getFapiUrl() + path, data, method);
}
/**
* Used to make public requests to the delivery (DAPI) API
* @param path
* @param data
* @param method
* @returns
*/
async publicDeliveryRequest(path: string, data: Dict = {}, method: HttpMethod = 'GET') {
return await this.publicRequest(this.getDapiUrl() + path, data, method);
}
/**
* Used to make private requests to the futures (FAPI) API
* @param path
* @param data
* @param method
* @returns
*/
async privateFuturesRequest(path: string, data: Dict = {}, method: HttpMethod = 'GET'): Promise<any> {
return await this.futuresRequest(this.getFapiUrl() + path, data, method, true);
}
/**
* Used to make private requests to the delivery (DAPI) API
* @param path
* @param data
* @param method
* @returns
*/
async privateDeliveryRequest(path: string, data: Dict = {}, method: HttpMethod = 'GET'): Promise<any> {
return await this.futuresRequest(this.getDapiUrl() + path, data, method, true);
}
/**
* Used to make a request to the futures API, this is a generic function that can be used to make any request to the futures API
* @param url
* @param data
* @param method
* @param isPrivate
* @returns
*/
async futuresRequest(url: string, data: Dict = {}, method: HttpMethod = 'GET', isPrivate = false) {
let query = '';
const headers = {
'User-Agent': this.userAgent,
'Content-type': 'application/x-www-form-urlencoded'
} as Dict;
if (isPrivate) {
if (!data.recvWindow) data.recvWindow = this.Options.recvWindow;
this.requireApiKey('promiseRequest');
headers['X-MBX-APIKEY'] = this.APIKEY;
}
const opt = {
headers: this.extend(headers, this.headers),
url: url,
method: method,
timeout: this.Options.recvWindow,
followAllRedirects: true
};
query = this.makeQueryString(data);
if (method === 'GET') {
opt.url = `${url}?${query}`;
}
if (isPrivate) {
data.timestamp = new Date().getTime();
if (this.timeOffset) {
data.timestamp += this.timeOffset;
}
query = this.makeQueryString(data);
data.signature = this.generateSignature(query);
opt.url = `${url}?${query}&signature=${data.signature}`;
}
(opt as any).qs = data;
const response = await this.proxyRequest(opt);
return response;
}
// ------ Request Related Functions ------ //
// XXX: This one works with array (e.g. for dust.transfer)
// XXX: I _guess_ we could use replace this function with the `qs` module
makeQueryString(q) {
const res = Object.keys(q)
.reduce((a, k) => {
if (Array.isArray(q[k])) {
q[k].forEach(v => {
a.push(k + "=" + encodeURIComponent(v));
});
} else if (q[k] !== undefined) {
a.push(k + "=" + encodeURIComponent(q[k]));
}
return a;
}, [])
.join("&");
return res;
}
/**
* 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}
*/
async apiRequest(url: string, data: Dict = {}, method: HttpMethod = 'GET') {
this.requireApiKey('apiRequest');
const opt = this.reqObj(
url,
data,
method,
this.APIKEY
);
const res = await this.proxyRequest(opt);
return res;
}
requireApiKey(source = 'requireApiKey', fatalError = true) {
if (!this.APIKEY) {
if (fatalError) throw Error(`${source}: Invalid API Key!`);
return false;
}
return true;
}
// Check if API secret is present
requireApiSecret(source = 'requireApiSecret', fatalError = true) {
if (!this.APIKEY) {
if (fatalError) throw Error(`${source}: Invalid API Key!`);
return false;
}
if (!this.APISECRET && !this.PRIVATEKEY) {
if (fatalError) throw Error(`${source}: Invalid API Secret or Private Key!`);
return false;
}
return true;
}
/**
* Create a public spot/margin request
* @param {string} path - url path
* @param {object} data - The data to send
* @param {string} method - the http method
* @param {boolean} noDataInSignature - Prevents data from being added to signature
* @return {undefined}
*/
async publicSpotRequest(path: string, data: Dict = {}, method: HttpMethod = 'GET') {
return await this.publicRequest/**/(this.getSpotUrl() + path, data, method);
}
/**
* Create a signed spot request
* @param {string} path - url path
* @param {object} data - The data to send
* @param {string} method - the http method
* @param {boolean} noDataInSignature - Prevents data from being added to signature
* @return {undefined}
*/
async privateSpotRequest(path: string, data: Dict = {}, method: HttpMethod = 'GET', noDataInSignature = false) {
return await this.signedRequest/**/(this.getSpotUrl() + path, data, method, noDataInSignature);
}
/**
* Create a signed SAPI request
*/
async privateSapiRequest(path: string, data: Dict = {}, method: HttpMethod = 'GET', noDataInSignature = false) {
return await this.signedRequest/**/(this.getSapiUrl() + path, data, method, noDataInSignature);
}
/**
* Create a signed http 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
* @param {boolean} noDataInSignature - Prevents data from being added to signature
* @return {undefined}
*/
async signedRequest(url: string, data: Dict = {}, method: HttpMethod = 'GET', noDataInSignature = false) {
this.requireApiSecret('signedRequest');
const isListenKeyEndpoint = url.includes('v3/userDataStream');
let query = method === 'POST' && noDataInSignature ? '' : this.makeQueryString(data);
let signature = undefined;
if (!noDataInSignature && !isListenKeyEndpoint) {
data.timestamp = new Date().getTime();
if (this.timeOffset) data.timestamp += this.timeOffset;
if (!data.recvWindow) data.recvWindow = this.Options.recvWindow;
query = this.makeQueryString(data);
signature = this.generateSignature(query);
}
if (method === 'POST') {
const opt = this.reqObjPOST(
url,
data,
method,
this.APIKEY
);
if (signature) {
opt.form.signature = signature;
}
const reqPost = await this.proxyRequest(opt);
return reqPost;
} else {
let encodedUrl = url;
if (query) encodedUrl += '?' + query;
if (signature) encodedUrl += '&signature=' + signature;
const opt = this.reqObj(
encodedUrl,
data,
method,
this.APIKEY
);
const reqGet = await this.proxyRequest(opt);
return reqGet;
}
}
generateSignature(query: string, encode = true) {
const secret = this.APISECRET || this.PRIVATEKEY;
let signature = '';
if (secret.includes('PRIVATE KEY')) {
// if less than the below length, then it can't be RSA key
let keyObject: crypto.KeyObject;
try {
const privateKeyObj: crypto.PrivateKeyInput = { key: secret };
if (this.PRIVATEKEYPASSWORD) {
privateKeyObj.passphrase = this.PRIVATEKEYPASSWORD;
}
keyObject = crypto.createPrivateKey(privateKeyObj);
} catch (e) {
throw new Error(
'Invalid private key. Please provide a valid RSA or ED25519 private key. ' + e.toString()
);
}
if (secret.length > 120) {
// RSA key
signature = crypto
.sign('RSA-SHA256', Buffer.from(query), keyObject)
.toString('base64');
if (encode) signature = encodeURIComponent(signature);
return signature;
} else {
// Ed25519 key
signature = crypto.sign(null, Buffer.from(query), keyObject).toString('base64');
}
} else {
signature = crypto.createHmac('sha256', this.Options.APISECRET).update(query).digest('hex'); // set the HMAC hash header
}
return signature;
}
// --- ENDPOINTS --- //
/**
* Create a signed spot order
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/public-api-endpoints#test-new-order-trade
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-list---oco-trade
* @param {OrderType} type - LIMIT, MARKET, STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, LIMIT_MAKER, OCO
* @param {OrderSide} 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} params - additional order settings
* @param {number} [params.quoteOrderQty] - The quote order quantity, used for MARKET orders
* @param {number} [params.stopPrice] - The stop price, used for STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT orders
* @param {number} [params.trailingDelta] - Delta price
* @return {undefined}
*/
async order(type: OrderType, side: OrderSide, symbol: string, quantity: number, price?: number, params: Dict = {}): Promise<Order> {
const isOCO = type === 'OCO' || params.type === 'OCO';
let endpoint = isOCO ? 'v3/orderList/oco' : 'v3/order';
if (params.test) {
delete params.test;
endpoint += '/test';
}
const request = {
symbol: symbol,
side: side,
// type: type
} as Dict;
if (!isOCO) request.type = type;
if (params.quoteOrderQty && params.quoteOrderQty > 0)
request.quoteOrderQty = params.quoteOrderQty;
else
request.quantity = quantity;
if (!isOCO && request.type.includes('LIMIT')) {
request.price = price;
if (request.type !== 'LIMIT_MAKER') {
request.timeInForce = 'GTC';
}
}
if (!isOCO && request.type == 'MARKET' && typeof params.quoteOrderQty !== 'undefined') {
request.quoteOrderQty = params.quoteOrderQty;
delete request.quantity;
}
// if (typeof params.timeInForce !== 'undefined') opt.timeInForce = params.timeInForce;
// if (typeof params.newOrderRespType !== 'undefined') opt.newOrderRespType = params.newOrderRespType;
if (!params.newClientOrderId && !params.listClientOrderId) {
const id = this.SPOT_PREFIX + this.uuid22();
if (!isOCO) {
request.newClientOrderId = id;
} else {
request.listClientOrderId = id;
}
}
const allowedTypesForStopAndTrailing = ['STOP_LOSS', 'STOP_LOSS_LIMIT', 'TAKE_PROFIT', 'TAKE_PROFIT_LIMIT', 'OCO'];
if (params.trailingDelta) {
request.trailingDelta = params.trailingDelta;
if (!isOCO && !allowedTypesForStopAndTrailing.includes(request.type)) {
throw Error('trailingDelta: Must set "type" to one of the following: STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, OCO');
}
}
/*
* STOP_LOSS
* STOP_LOSS_LIMIT
* TAKE_PROFIT
* TAKE_PROFIT_LIMIT
* LIMIT_MAKER
*/
// if (typeof params.icebergQty !== 'undefined') request.icebergQty = params.icebergQty;
if (params.stopPrice) {
request.stopPrice = params.stopPrice;
if (!isOCO && !allowedTypesForStopAndTrailing.includes(request.type)) {
throw Error('stopPrice: Must set "type" to one of the following: STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, OCO');
}
}
const response = await this.privateSpotRequest(endpoint, this.extend(request, params), 'POST');
// to do error handling
// if ( !response ) {
// if ( callback ) callback( error, response );
// else this.options.log( 'Order() error:', error );
// return;
// }
// if ( typeof response.msg !== 'undefined' && response.msg === 'Filter failure: MIN_NOTIONAL' ) {
// this.options.log( 'Order quantity too small. See exchangeInfo() for minimum amounts' );
// }
// if ( callback ) callback( error, response );
// else this.options.log( side + '(' + symbol + ',' + quantity + ',' + price + ') ', response );
return response;
}
/**
* Create an OCO spot order
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-list---oco-trade
* @param {OrderSide} 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} params - additional order settings
* @param {string} params.aboveType - The type of the above order
* @param {string} params.belowType - The type of the below order
* @param {string} params.abovePrice - The price of the above order
* @param {string} params.aboveStopPrice - The stop price of the above order
* @param {string} params.aboveTrailingDelta - The trailing delta of the above order
* @param {string} params.aboveTimeInForce - The time in force of the above order
* @param {string} params.belowPrice - The price of the below order
* @param {string} params.belowStopPrice - The stop price of the below order
* @param {string} params.belowTrailingDelta - The trailing delta of the below order
* @param {string} params.belowTimeInForce - The time in force of the below order
* @return {undefined}
*/
async ocoOrder(side: OrderSide, symbol: string, quantity: number, params: Dict = {}): Promise<OCOOrder> {
const request = {
symbol: symbol,
side: side,
quantity: quantity,
} as Dict;
if (!params.listClientOrderId) {
const id = this.SPOT_PREFIX + this.uuid22();
request.listClientOrderId = id;
}
const endpoint = 'v3/orderList/oco';
const response = await this.privateSpotRequest(endpoint, this.extend(request, params), 'POST');
return response;
}
/**
* Creates a buy order
* @param {string} symbol - the symbol to buy
* @param {numeric} quantity - the quantity required
* @param {numeric} price - the price to pay for each unit
* @param {object} flags - additional buy order flags
* @return {promise or undefined} - omitting the callback returns a promise
*/
async buy(symbol: string, quantity: number, price: number, flags = {}) {
return await this.order('LIMIT', 'BUY', symbol, quantity, price, flags);
}
/**
* Creates a sell order
* @param {string} symbol - the symbol to sell
* @param {numeric} quantity - the quantity required
* @param {numeric} price - the price to pay for each unit
* @param {object} flags - additional buy order flags
* @param {function} callback - the callback function
* @return {promise or undefined} - omitting the callback returns a promise
*/
async sell(symbol: string, quantity: number, price: number, flags = {}) {
return await this.order('LIMIT', 'SELL', symbol, quantity, price, flags);
}
/**
* Creates a market buy order
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/public-api-endpoints#test-new-order-trade
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-list---oco-trade
* @param {string} symbol - the symbol to buy
* @param {numeric} quantity - the quantity required
* @param {object} params - additional buy order flags
* @return {promise or undefined} - omitting the callback returns a promise
*/
async marketBuy(symbol: string, quantity: number, params: Dict = {}) {
return await this.order('MARKET', 'BUY', symbol, quantity, 0, params);
}
/**
* Creates a spot limit order
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/public-api-endpoints#test-new-order-trade
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-list---oco-trade
* @param {string} side - the side of the order (BUY or SELL)
* @param {string} symbol - the symbol to buy
* @param {numeric} quantity - the quantity required
* @param {numeric} price - the price to pay for each unit
* @param {object} params - additional buy order flags
* @return {promise or undefined} - omitting the callback returns a promise
*/
async limitOrder(side: OrderSide, symbol: string, quantity: number, price: number, params: Dict = {}) {
return await this.order('LIMIT', side, symbol, quantity, price, params);
}
/**
* Creates a market buy order using the cost instead of the quantity (eg: 100usd instead of 0.01btc)
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/public-api-endpoints#test-new-order-trade
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-list---oco-trade
* @param {string} symbol - the symbol to buy
* @param {numeric} quantity - the quantity required
* @param {object} params - additional buy order flags
* @return {promise or undefined} - omitting the callback returns a promise
*/
async marketBuyWithCost(symbol: string, cost: number, params: Dict = {}) {
params.quoteOrderQty = cost;
return await this.order('MARKET', 'BUY', symbol, 0, 0, params);
}
/**
* Creates a market sell order
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade
* @see https://developers.binance.com/docs/binance-spot-api-docs/rest-api/public-api-endpoints#test-new-order-trade