forked from katsu1110/ccxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzb.js
1169 lines (1135 loc) · 46.5 KB
/
zb.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
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { BadRequest, ExchangeError, ArgumentsRequired, AuthenticationError, InsufficientFunds, OrderNotFound, ExchangeNotAvailable, RateLimitExceeded, PermissionDenied, InvalidOrder, InvalidAddress, OnMaintenance, RequestTimeout, AccountSuspended } = require ('./base/errors');
const Precise = require ('./base/Precise');
// ---------------------------------------------------------------------------
module.exports = class zb extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'zb',
'name': 'ZB',
'countries': [ 'CN' ],
'rateLimit': 100,
'version': 'v1',
'has': {
'cancelOrder': true,
'CORS': false,
'createMarketOrder': false,
'createOrder': true,
'fetchBalance': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDepositAddresses': true,
'fetchDeposits': true,
'fetchMarkets': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': true,
'fetchClosedOrders': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTrades': true,
'fetchWithdrawals': true,
'withdraw': true,
},
'timeframes': {
'1m': '1min',
'3m': '3min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '1hour',
'2h': '2hour',
'4h': '4hour',
'6h': '6hour',
'12h': '12hour',
'1d': '1day',
'3d': '3day',
'1w': '1week',
},
'exceptions': {
'ws': {
// '1000': ExchangeError, // The call is successful.
'1001': ExchangeError, // General error prompt
'1002': ExchangeError, // Internal Error
'1003': AuthenticationError, // Fail to verify
'1004': AuthenticationError, // The transaction password is locked
'1005': AuthenticationError, // Wrong transaction password, please check it and re-enter。
'1006': PermissionDenied, // Real-name authentication is pending approval or unapproved
'1007': ExchangeError, // Channel does not exist
'1009': OnMaintenance, // This interface is under maintenance
'1010': ExchangeNotAvailable, // Not available now
'1012': PermissionDenied, // Insufficient permissions
'1013': ExchangeError, // Cannot trade, please contact email: [email protected] for support.
'1014': ExchangeError, // Cannot sell during the pre-sale period
'2001': InsufficientFunds, // Insufficient CNY account balance
'2002': InsufficientFunds, // Insufficient BTC account balance
'2003': InsufficientFunds, // Insufficient LTC account balance
'2005': InsufficientFunds, // Insufficient ETH account balance
'2006': InsufficientFunds, // ETCInsufficient account balance
'2007': InsufficientFunds, // BTSInsufficient account balance
'2008': InsufficientFunds, // EOSInsufficient account balance
'2009': InsufficientFunds, // BCCInsufficient account balance
'3001': OrderNotFound, // Order not found or is completed
'3002': InvalidOrder, // Invalid amount
'3003': InvalidOrder, // Invalid quantity
'3004': AuthenticationError, // User does not exist
'3005': BadRequest, // Invalid parameter
'3006': PermissionDenied, // Invalid IP or not consistent with the bound IP
'3007': RequestTimeout, // The request time has expired
'3008': ExchangeError, // Transaction not found
'3009': InvalidOrder, // The price exceeds the limit
'3010': PermissionDenied, // It fails to place an order, due to you have set up to prohibit trading of this market.
'3011': InvalidOrder, // The entrusted price is abnormal, please modify it and place order again
'3012': InvalidOrder, // Duplicate custom customerOrderId
'4001': AccountSuspended, // APIThe interface is locked for one hour
'4002': RateLimitExceeded, // Request too frequently
},
'exact': {
// '1000': 'Successful operation',
'1001': ExchangeError, // 'General error message',
'1002': ExchangeError, // 'Internal error',
'1003': AuthenticationError, // 'Verification does not pass',
'1004': AuthenticationError, // 'Funding security password lock',
'1005': AuthenticationError, // 'Funds security password is incorrect, please confirm and re-enter.',
'1006': AuthenticationError, // 'Real-name certification pending approval or audit does not pass',
'1009': ExchangeNotAvailable, // 'This interface is under maintenance',
'1010': ExchangeNotAvailable, // Not available now
'1012': PermissionDenied, // Insufficient permissions
'1013': ExchangeError, // Cannot trade, please contact email: [email protected] for support.
'1014': ExchangeError, // Cannot sell during the pre-sale period
'2001': InsufficientFunds, // 'Insufficient CNY Balance',
'2002': InsufficientFunds, // 'Insufficient BTC Balance',
'2003': InsufficientFunds, // 'Insufficient LTC Balance',
'2005': InsufficientFunds, // 'Insufficient ETH Balance',
'2006': InsufficientFunds, // 'Insufficient ETC Balance',
'2007': InsufficientFunds, // 'Insufficient BTS Balance',
'2008': InsufficientFunds, // EOSInsufficient account balance
'2009': InsufficientFunds, // 'Account balance is not enough',
'3001': OrderNotFound, // 'Pending orders not found',
'3002': InvalidOrder, // 'Invalid price',
'3003': InvalidOrder, // 'Invalid amount',
'3004': AuthenticationError, // 'User does not exist',
'3005': BadRequest, // 'Invalid parameter',
'3006': AuthenticationError, // 'Invalid IP or inconsistent with the bound IP',
'3007': AuthenticationError, // 'The request time has expired',
'3008': OrderNotFound, // 'Transaction records not found',
'3009': InvalidOrder, // 'The price exceeds the limit',
'3010': PermissionDenied, // It fails to place an order, due to you have set up to prohibit trading of this market.
'3011': InvalidOrder, // 'The entrusted price is abnormal, please modify it and place order again',
'3012': InvalidOrder, // Duplicate custom customerOrderId
'4001': ExchangeNotAvailable, // 'API interface is locked or not enabled',
'4002': RateLimitExceeded, // 'Request too often',
},
'broad': {
'提币地址有误,请先添加提币地址。': InvalidAddress, // {"code":1001,"message":"提币地址有误,请先添加提币地址。"}
},
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/32859187-cd5214f0-ca5e-11e7-967d-96568e2e2bd1.jpg',
'api': {
'public': 'https://api.zb.today/data',
'private': 'https://trade.zb.today/api',
'trade': 'https://trade.zb.today/api',
},
'www': 'https://www.zb.com',
'doc': 'https://www.zb.com/i/developer',
'fees': 'https://www.zb.com/i/rate',
},
'api': {
'trade': {
'get': [
'getFeeInfo',
],
},
'public': {
'get': [
'markets',
'ticker',
'allTicker',
'depth',
'trades',
'kline',
'getGroupMarkets',
],
},
'private': {
'get': [
// spot API
'order',
'orderMoreV2',
'cancelOrder',
'getOrder',
'getOrders',
'getOrdersNew',
'getOrdersIgnoreTradeType',
'getUnfinishedOrdersIgnoreTradeType',
'getFinishedAndPartialOrders',
'getAccountInfo',
'getUserAddress',
'getPayinAddress',
'getWithdrawAddress',
'getWithdrawRecord',
'getChargeRecord',
'getCnyWithdrawRecord',
'getCnyChargeRecord',
'withdraw',
// sub accounts
'addSubUser',
'getSubUserList',
'doTransferFunds',
'createSubUserKey', // removed on 2021-03-16 according to the update log in the API doc
// leverage API
'getLeverAssetsInfo',
'getLeverBills',
'transferInLever',
'transferOutLever',
'loan',
'cancelLoan',
'getLoans',
'getLoanRecords',
'borrow',
'autoBorrow',
'repay',
'doAllRepay',
'getRepayments',
'getFinanceRecords',
'changeInvestMark',
'changeLoop',
// cross API
'getCrossAssets',
'getCrossBills',
'transferInCross',
'transferOutCross',
'doCrossLoan',
'doCrossRepay',
'getCrossRepayRecords',
],
},
},
'fees': {
'funding': {
'withdraw': {
'BTC': 0.0001,
'BCH': 0.0006,
'LTC': 0.005,
'ETH': 0.01,
'ETC': 0.01,
'BTS': 3,
'EOS': 1,
'QTUM': 0.01,
'HSR': 0.001,
'XRP': 0.1,
'USDT': '0.1%',
'QCASH': 5,
'DASH': 0.002,
'BCD': 0,
'UBTC': 0,
'SBTC': 0,
'INK': 20,
'TV': 0.1,
'BTH': 0,
'BCX': 0,
'LBTC': 0,
'CHAT': 20,
'bitCNY': 20,
'HLC': 20,
'BTP': 0,
'BCW': 0,
},
},
'trading': {
'maker': 0.2 / 100,
'taker': 0.2 / 100,
},
},
'commonCurrencies': {
'ENT': 'ENTCash',
},
});
}
async fetchMarkets (params = {}) {
const markets = await this.publicGetMarkets (params);
//
// {
// "zb_qc":{
// "amountScale":2,
// "minAmount":0.01,
// "minSize":5,
// "priceScale":4,
// },
// }
//
const keys = Object.keys (markets);
const result = [];
for (let i = 0; i < keys.length; i++) {
const id = keys[i];
const market = markets[id];
const [ baseId, quoteId ] = id.split ('_');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const amountPrecisionString = this.safeString (market, 'amountScale');
const pricePrecisionString = this.safeString (market, 'priceScale');
const amountLimit = this.parsePrecision (amountPrecisionString);
const priceLimit = this.parsePrecision (pricePrecisionString);
const precision = {
'amount': parseInt (amountPrecisionString),
'price': parseInt (pricePrecisionString),
};
result.push ({
'id': id,
'symbol': symbol,
'baseId': baseId,
'quoteId': quoteId,
'base': base,
'quote': quote,
'active': true,
'precision': precision,
'limits': {
'amount': {
'min': this.parseNumber (amountLimit),
'max': undefined,
},
'price': {
'min': this.parseNumber (priceLimit),
'max': undefined,
},
'cost': {
'min': 0,
'max': undefined,
},
},
'info': market,
});
}
return result;
}
async fetchCurrencies (params = {}) {
const response = await this.tradeGetGetFeeInfo (params);
//
// {
// "code":1000,
// "message":"success",
// "result":{
// "USDT":[
// {
// "chainName":"TRC20",
// "canWithdraw":true,
// "fee":1.0,
// "mainChainName":"TRX",
// "canDeposit":true
// },
// {
// "chainName":"OMNI",
// "canWithdraw":true,
// "fee":5.0,
// "mainChainName":"BTC",
// "canDeposit":true
// },
// {
// "chainName":"ERC20",
// "canWithdraw":true,
// "fee":15.0,
// "mainChainName":"ETH",
// "canDeposit":true
// }
// ],
// }
// }
//
const currencies = this.safeValue (response, 'result', {});
const ids = Object.keys (currencies);
const result = {};
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const currency = currencies[id];
const code = this.safeCurrencyCode (id);
const precision = undefined;
let isWithdrawEnabled = true;
let isDepositEnabled = true;
const fees = {};
for (let j = 0; j < currency.length; j++) {
const networkItem = currency[j];
const network = this.safeString (networkItem, 'chainName');
// const name = this.safeString (networkItem, 'name');
const withdrawFee = this.safeNumber (networkItem, 'fee');
const depositEnable = this.safeValue (networkItem, 'canDeposit');
const withdrawEnable = this.safeValue (networkItem, 'canWithdraw');
isDepositEnabled = isDepositEnabled || depositEnable;
isWithdrawEnabled = isWithdrawEnabled || withdrawEnable;
fees[network] = withdrawFee;
}
const active = (isWithdrawEnabled && isDepositEnabled);
result[code] = {
'id': id,
'name': undefined,
'code': code,
'precision': precision,
'info': currency,
'active': active,
'fee': undefined,
'fees': fees,
'limits': this.limits,
};
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
const response = await this.privateGetGetAccountInfo (params);
// todo: use this somehow
// let permissions = response['result']['base'];
const balances = this.safeValue (response['result'], 'coins');
const result = {
'info': response,
'timestamp': undefined,
'datetime': undefined,
};
for (let i = 0; i < balances.length; i++) {
const balance = balances[i];
// { enName: "BTC",
// freez: "0.00000000",
// unitDecimal: 8, // always 8
// cnName: "BTC",
// isCanRecharge: true, // TODO: should use this
// unitTag: "฿",
// isCanWithdraw: true, // TODO: should use this
// available: "0.00000000",
// key: "btc" }
const account = this.account ();
const currencyId = this.safeString (balance, 'key');
const code = this.safeCurrencyCode (currencyId);
account['free'] = this.safeString (balance, 'available');
account['used'] = this.safeString (balance, 'freez');
result[code] = account;
}
return this.parseBalance (result, false);
}
parseDepositAddress (depositAddress, currency = undefined) {
//
// fetchDepositAddress
//
// {
// "key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
// }
//
// fetchDepositAddresses
//
// {
// "blockChain": "btc",
// "isUseMemo": false,
// "address": "1LL5ati6pXHZnTGzHSA3rWdqi4mGGXudwM",
// "canWithdraw": true,
// "canDeposit": true
// }
// {
// "blockChain": "bts",
// "isUseMemo": true,
// "account": "btstest",
// "memo": "123",
// "canWithdraw": true,
// "canDeposit": true
// }
//
let address = this.safeString2 (depositAddress, 'key', 'address');
let tag = undefined;
const memo = this.safeString (depositAddress, 'memo');
if (memo !== undefined) {
tag = memo;
} else if (address.indexOf ('_') >= 0) {
const parts = address.split ('_');
address = parts[0]; // WARNING: MAY BE tag_address INSTEAD OF address_tag FOR SOME CURRENCIES!!
tag = parts[1];
}
const currencyId = this.safeString (depositAddress, 'blockChain');
const code = this.safeCurrencyCode (currencyId, currency);
return {
'currency': code,
'address': address,
'tag': tag,
'info': depositAddress,
};
}
async fetchDepositAddresses (codes = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.privateGetGetPayinAddress (params);
//
// {
// "code": 1000,
// "message": {
// "des": "success",
// "isSuc": true,
// "datas": [
// {
// "blockChain": "btc",
// "isUseMemo": false,
// "address": "1LL5ati6pXHZnTGzHSA3rWdqi4mGGXudwM",
// "canWithdraw": true,
// "canDeposit": true
// },
// {
// "blockChain": "bts",
// "isUseMemo": true,
// "account": "btstest",
// "memo": "123",
// "canWithdraw": true,
// "canDeposit": true
// },
// ]
// }
// }
//
const message = this.safeValue (response, 'message', {});
const datas = this.safeValue (message, 'datas', []);
return this.parseDepositAddresses (datas, codes);
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const response = await this.privateGetGetUserAddress (this.extend (request, params));
//
// {
// "code": 1000,
// "message": {
// "des": "success",
// "isSuc": true,
// "datas": {
// "key": "0x0af7f36b8f09410f3df62c81e5846da673d4d9a9"
// }
// }
// }
//
const message = this.safeValue (response, 'message', {});
const datas = this.safeValue (message, 'datas', {});
return this.parseDepositAddress (datas, currency);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
};
if (limit !== undefined) {
request['size'] = limit;
}
const response = await this.publicGetDepth (this.extend (request, params));
return this.parseOrderBook (response, symbol);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.publicGetAllTicker (params);
const result = {};
const anotherMarketsById = {};
const marketIds = Object.keys (this.marketsById);
for (let i = 0; i < marketIds.length; i++) {
const tickerId = marketIds[i].replace ('_', '');
anotherMarketsById[tickerId] = this.marketsById[marketIds[i]];
}
const ids = Object.keys (response);
for (let i = 0; i < ids.length; i++) {
const market = anotherMarketsById[ids[i]];
result[market['symbol']] = this.parseTicker (response[ids[i]], market);
}
return this.filterByArray (result, 'symbol', symbols);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
};
const response = await this.publicGetTicker (this.extend (request, params));
const ticker = response['ticker'];
return this.parseTicker (ticker, market);
}
parseTicker (ticker, market = undefined) {
const timestamp = this.milliseconds ();
let symbol = undefined;
if (market !== undefined) {
symbol = market['symbol'];
}
const last = this.safeNumber (ticker, 'last');
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeNumber (ticker, 'high'),
'low': this.safeNumber (ticker, 'low'),
'bid': this.safeNumber (ticker, 'buy'),
'bidVolume': undefined,
'ask': this.safeNumber (ticker, 'sell'),
'askVolume': undefined,
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': this.safeNumber (ticker, 'vol'),
'quoteVolume': undefined,
'info': ticker,
};
}
parseOHLCV (ohlcv, market = undefined) {
return [
this.safeInteger (ohlcv, 0),
this.safeNumber (ohlcv, 1),
this.safeNumber (ohlcv, 2),
this.safeNumber (ohlcv, 3),
this.safeNumber (ohlcv, 4),
this.safeNumber (ohlcv, 5),
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
if (limit === undefined) {
limit = 1000;
}
const request = {
'market': market['id'],
'type': this.timeframes[timeframe],
'limit': limit,
};
if (since !== undefined) {
request['since'] = since;
}
const response = await this.publicGetKline (this.extend (request, params));
const data = this.safeValue (response, 'data', []);
return this.parseOHLCVs (data, market, timeframe, since, limit);
}
parseTrade (trade, market = undefined) {
const timestamp = this.safeTimestamp (trade, 'date');
let side = this.safeString (trade, 'trade_type');
side = (side === 'bid') ? 'buy' : 'sell';
const id = this.safeString (trade, 'tid');
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString (trade, 'amount');
const costString = Precise.stringMul (priceString, amountString);
const price = this.parseNumber (priceString);
const amount = this.parseNumber (amountString);
const cost = this.parseNumber (costString);
let symbol = undefined;
if (market !== undefined) {
symbol = market['symbol'];
}
return {
'info': trade,
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'side': side,
'order': undefined,
'takerOrMaker': undefined,
'price': price,
'amount': amount,
'cost': cost,
'fee': undefined,
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'market': market['id'],
};
const response = await this.publicGetTrades (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
if (type !== 'limit') {
throw new InvalidOrder (this.id + ' allows limit orders only');
}
await this.loadMarkets ();
const request = {
'price': this.priceToPrecision (symbol, price),
'amount': this.amountToPrecision (symbol, amount),
'tradeType': (side === 'buy') ? '1' : '0',
'currency': this.marketId (symbol),
};
const response = await this.privateGetOrder (this.extend (request, params));
return {
'info': response,
'id': response['id'],
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'id': id.toString (),
'currency': this.marketId (symbol),
};
return await this.privateGetCancelOrder (this.extend (request, params));
}
async fetchOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrder() requires a symbol argument');
}
await this.loadMarkets ();
const request = {
'id': id.toString (),
'currency': this.marketId (symbol),
};
const response = await this.privateGetGetOrder (this.extend (request, params));
//
// {
// 'total_amount': 0.01,
// 'id': '20180910244276459',
// 'price': 180.0,
// 'trade_date': 1536576744960,
// 'status': 2,
// 'trade_money': '1.96742',
// 'trade_amount': 0.01,
// 'type': 0,
// 'currency': 'eth_usdt'
// }
//
return this.parseOrder (response, undefined);
}
async fetchOrders (symbol = undefined, since = undefined, limit = 50, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + 'fetchOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'currency': market['id'],
'pageIndex': 1, // default pageIndex is 1
'pageSize': limit, // default pageSize is 50
};
let method = 'privateGetGetOrdersIgnoreTradeType';
// tradeType 交易类型1/0[buy/sell]
if ('tradeType' in params) {
method = 'privateGetGetOrdersNew';
}
let response = undefined;
try {
response = await this[method] (this.extend (request, params));
} catch (e) {
if (e instanceof OrderNotFound) {
return [];
}
throw e;
}
return this.parseOrders (response, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + 'fetchClosedOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'currency': market['id'],
'pageIndex': 1, // default pageIndex is 1
'pageSize': 10, // default pageSize is 10, doesn't work with other values now
};
const response = await this.privateGetGetFinishedAndPartialOrders (this.extend (request, params));
return this.parseOrders (response, market, since, limit);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = 10, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + 'fetchOpenOrders() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'currency': market['id'],
'pageIndex': 1, // default pageIndex is 1
'pageSize': limit, // default pageSize is 10
};
let method = 'privateGetGetUnfinishedOrdersIgnoreTradeType';
// tradeType 交易类型1/0[buy/sell]
if ('tradeType' in params) {
method = 'privateGetGetOrdersNew';
}
let response = undefined;
try {
response = await this[method] (this.extend (request, params));
} catch (e) {
if (e instanceof OrderNotFound) {
return [];
}
throw e;
}
return this.parseOrders (response, market, since, limit);
}
parseOrder (order, market = undefined) {
//
// {
// acctType: 0,
// currency: 'btc_usdt',
// fees: 3.6e-7,
// id: '202102282829772463',
// price: 45177.5,
// status: 2,
// total_amount: 0.0002,
// trade_amount: 0.0002,
// trade_date: 1614515104998,
// trade_money: 8.983712,
// type: 1,
// useZbFee: false
// },
//
let side = this.safeInteger (order, 'type');
side = (side === 1) ? 'buy' : 'sell';
const type = 'limit'; // market order is not availalbe in ZB
const timestamp = this.safeInteger (order, 'trade_date');
const marketId = this.safeString (order, 'currency');
const symbol = this.safeSymbol (marketId, market, '_');
const price = this.safeNumber (order, 'price');
const filled = this.safeNumber (order, 'trade_amount');
const amount = this.safeNumber (order, 'total_amount');
const cost = this.safeNumber (order, 'trade_money');
const status = this.parseOrderStatus (this.safeString (order, 'status'));
const id = this.safeString (order, 'id');
const feeCost = this.safeNumber (order, 'fees');
let fee = undefined;
if (feeCost !== undefined) {
let feeCurrency = undefined;
const zbFees = this.safeValue (order, 'useZbFee');
if (zbFees === true) {
feeCurrency = 'ZB';
} else if (market !== undefined) {
feeCurrency = (side === 'sell') ? market['quote'] : market['base'];
}
fee = {
'cost': feeCost,
'currency': feeCurrency,
};
}
return this.safeOrder ({
'info': order,
'id': id,
'clientOrderId': undefined,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': type,
'timeInForce': undefined,
'postOnly': undefined,
'side': side,
'price': price,
'stopPrice': undefined,
'average': undefined,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': undefined,
'status': status,
'fee': fee,
'trades': undefined,
});
}
parseOrderStatus (status) {
const statuses = {
'0': 'open',
'1': 'canceled',
'2': 'closed',
'3': 'open', // partial
};
return this.safeString (statuses, status, status);
}
parseTransactionStatus (status) {
const statuses = {
'0': 'pending', // submitted, pending confirmation
'1': 'failed',
'2': 'ok',
'3': 'canceled',
'5': 'ok', // confirmed
};
return this.safeString (statuses, status, status);
}
parseTransaction (transaction, currency = undefined) {
//
// withdraw
//
// {
// "code": 1000,
// "message": "success",
// "id": "withdrawalId"
// }
//
// fetchWithdrawals
//
// {
// "amount": 0.01,
// "fees": 0.001,
// "id": 2016042556231,
// "manageTime": 1461579340000,
// "status": 3,
// "submitTime": 1461579288000,
// "toAddress": "14fxEPirL9fyfw1i9EF439Pq6gQ5xijUmp",
// }
//
// fetchDeposits
//
// {
// "address": "1FKN1DZqCm8HaTujDioRL2Aezdh7Qj7xxx",
// "amount": "1.00000000",
// "confirmTimes": 1,
// "currency": "BTC",
// "description": "Successfully Confirm",
// "hash": "7ce842de187c379abafadd64a5fe66c5c61c8a21fb04edff9532234a1dae6xxx",
// "id": 558,
// "itransfer": 1,
// "status": 2,
// "submit_time": "2016-12-07 18:51:57",
// }
//
const id = this.safeString (transaction, 'id');
const txid = this.safeString (transaction, 'hash');
const amount = this.safeNumber (transaction, 'amount');
let timestamp = this.parse8601 (this.safeString (transaction, 'submit_time'));
timestamp = this.safeInteger (transaction, 'submitTime', timestamp);
let address = this.safeString2 (transaction, 'toAddress', 'address');
let tag = undefined;
if (address !== undefined) {
const parts = address.split ('_');
address = this.safeString (parts, 0);
tag = this.safeString (parts, 1);
}
const confirmTimes = this.safeInteger (transaction, 'confirmTimes');
const updated = this.safeInteger (transaction, 'manageTime');
let type = undefined;
const currencyId = this.safeString (transaction, 'currency');
const code = this.safeCurrencyCode (currencyId, currency);
if (address !== undefined) {
type = (confirmTimes === undefined) ? 'withdrawal' : 'deposit';
}
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
let fee = undefined;
const feeCost = this.safeNumber (transaction, 'fees');
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': code,
};
}
return {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'addressFrom': undefined,
'address': address,
'addressTo': address,
'tagFrom': undefined,
'tag': tag,
'tagTo': tag,
'type': type,
'amount': amount,
'currency': code,
'status': status,
'updated': updated,
'fee': fee,
};
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
const password = this.safeString (params, 'safePwd', this.password);
if (password === undefined) {
throw new ArgumentsRequired (this.id + ' withdraw() requires exchange.password or a safePwd parameter');
}
const fees = this.safeNumber (params, 'fees');
if (fees === undefined) {
throw new ArgumentsRequired (this.id + ' withdraw() requires a fees parameter');
}
this.checkAddress (address);
await this.loadMarkets ();
const currency = this.currency (code);
if (tag !== undefined) {
address += '_' + tag;
}
const request = {
'amount': this.currencyToPrecision (code, amount),
'currency': currency['id'],
'fees': this.currencyToPrecision (code, fees),
// 'itransfer': 0, // agree for an internal transfer, 0 disagree, 1 agree, the default is to disagree
'method': 'withdraw',
'receiveAddr': address,
'safePwd': password,
};
const response = await this.privateGetWithdraw (this.extend (request, params));
//
// {
// "code": 1000,
// "message": "success",
// "id": "withdrawalId"
// }