forked from ccxt/ccxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuobi.js
1733 lines (1684 loc) · 77.5 KB
/
huobi.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 { AuthenticationError, ExchangeError, PermissionDenied, ExchangeNotAvailable, OnMaintenance, InvalidOrder, OrderNotFound, InsufficientFunds, ArgumentsRequired, BadSymbol, BadRequest, RequestTimeout, NetworkError, InvalidAddress } = require ('./base/errors');
const { TRUNCATE } = require ('./base/functions/number');
const Precise = require ('./base/Precise');
// ---------------------------------------------------------------------------
module.exports = class huobi extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'huobi',
'name': 'Huobi',
'countries': [ 'CN' ],
'rateLimit': 100,
'userAgent': this.userAgents['chrome39'],
'certified': true,
'version': 'v1',
'accounts': undefined,
'accountsById': undefined,
'hostname': 'api.huobi.pro', // api.testnet.huobi.pro
'pro': true,
'has': {
'cancelAllOrders': true,
'cancelOrder': true,
'cancelOrders': true,
'CORS': undefined,
'createOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDepositAddressesByNetwork': true,
'fetchDeposits': true,
'fetchMarkets': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': true,
'fetchOrderTrades': true,
'fetchPremiumIndexOHLCV': false,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchTradingLimits': true,
'fetchWithdrawals': true,
'withdraw': true,
},
'timeframes': {
'1m': '1min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '60min',
'4h': '4hour',
'1d': '1day',
'1w': '1week',
'1M': '1mon',
'1y': '1year',
},
'urls': {
'test': {
'market': 'https://api.testnet.huobi.pro',
'public': 'https://api.testnet.huobi.pro',
'private': 'https://api.testnet.huobi.pro',
},
'logo': 'https://user-images.githubusercontent.com/1294454/76137448-22748a80-604e-11ea-8069-6e389271911d.jpg',
'api': {
'market': 'https://{hostname}',
'public': 'https://{hostname}',
'private': 'https://{hostname}',
'v2Public': 'https://{hostname}',
'v2Private': 'https://{hostname}',
},
'www': 'https://www.huobi.com',
// 'referral': {
// 'url': 'https://www.huobi.com/en-us/topic/double-reward/?invite_code=6rmm2223',
// 'discount': 0.15,
// },
'doc': [
'https://huobiapi.github.io/docs/spot/v1/cn/',
'https://huobiapi.github.io/docs/dm/v1/cn/',
'https://huobiapi.github.io/docs/coin_margined_swap/v1/cn/',
'https://huobiapi.github.io/docs/usdt_swap/v1/cn/',
'https://huobiapi.github.io/docs/option/v1/cn/',
],
'fees': 'https://www.huobi.com/about/fee/',
},
'api': {
'v2Public': {
'get': {
'reference/currencies': 1, // 币链参考信息
'market-status': 1, // 获取当前市场状态
},
},
'v2Private': {
'get': {
'account/ledger': 1,
'account/withdraw/quota': 1,
'account/withdraw/address': 1, // 提币地址查询(限母用户可用)
'account/deposit/address': 1,
'account/repayment': 5, // 还币交易记录查询
'reference/transact-fee-rate': 1,
'account/asset-valuation': 0.2, // 获取账户资产估值
'point/account': 5, // 点卡余额查询
'sub-user/user-list': 1, // 获取子用户列表
'sub-user/user-state': 1, // 获取特定子用户的用户状态
'sub-user/account-list': 1, // 获取特定子用户的账户列表
'sub-user/deposit-address': 1, // 子用户充币地址查询
'sub-user/query-deposit': 1, // 子用户充币记录查询
'user/api-key': 1, // 母子用户API key信息查询
'user/uid': 1, // 母子用户获取用户UID
'algo-orders/opening': 1, // 查询未触发OPEN策略委托
'algo-orders/history': 1, // 查询策略委托历史
'algo-orders/specific': 1, // 查询特定策略委托
'c2c/offers': 1, // 查询借入借出订单
'c2c/offer': 1, // 查询特定借入借出订单及其交易记录
'c2c/transactions': 1, // 查询借入借出交易记录
'c2c/repayment': 1, // 查询还币交易记录
'c2c/account': 1, // 查询账户余额
'etp/reference': 1, // 基础参考信息
'etp/transactions': 5, // 获取杠杆ETP申赎记录
'etp/transaction': 5, // 获取特定杠杆ETP申赎记录
'etp/rebalance': 1, // 获取杠杆ETP调仓记录
'etp/limit': 1, // 获取ETP持仓限额
},
'post': {
'account/transfer': 1,
'account/repayment': 5, // 归还借币(全仓逐仓通用)
'point/transfer': 5, // 点卡划转
'sub-user/management': 1, // 冻结/解冻子用户
'sub-user/creation': 1, // 子用户创建
'sub-user/tradable-market': 1, // 设置子用户交易权限
'sub-user/transferability': 1, // 设置子用户资产转出权限
'sub-user/api-key-generation': 1, // 子用户API key创建
'sub-user/api-key-modification': 1, // 修改子用户API key
'sub-user/api-key-deletion': 1, // 删除子用户API key
'sub-user/deduct-mode': 1, // 设置子用户手续费抵扣模式
'algo-orders': 1, // 策略委托下单
'algo-orders/cancel-all-after': 1, // 自动撤销订单
'algo-orders/cancellation': 1, // 策略委托(触发前)撤单
'c2c/offer': 1, // 借入借出下单
'c2c/cancellation': 1, // 借入借出撤单
'c2c/cancel-all': 1, // 撤销所有借入借出订单
'c2c/repayment': 1, // 还币
'c2c/transfer': 1, // 资产划转
'etp/creation': 5, // 杠杆ETP换入
'etp/redemption': 5, // 杠杆ETP换出
'etp/{transactId}/cancel': 10, // 杠杆ETP单个撤单
'etp/batch-cancel': 50, // 杠杆ETP批量撤单
},
},
'market': {
'get': {
'history/kline': 1, // 获取K线数据
'detail/merged': 1, // 获取聚合行情(Ticker)
'depth': 1, // 获取 Market Depth 数据
'trade': 1, // 获取 Trade Detail 数据
'history/trade': 1, // 批量获取最近的交易记录
'detail': 1, // 获取 Market Detail 24小时成交量数据
'tickers': 1,
'etp': 1, // 获取杠杆ETP实时净值
},
},
'public': {
'get': {
'common/symbols': 1, // 查询系统支持的所有交易对
'common/currencys': 1, // 查询系统支持的所有币种
'common/timestamp': 1, // 查询系统当前时间
'common/exchange': 1, // order limits
'settings/currencys': 1, // ?language=en-US
},
},
'private': {
'get': {
'account/accounts': 0.2, // 查询当前用户的所有账户(即account-id)
'account/accounts/{id}/balance': 0.2, // 查询指定账户的余额
'account/accounts/{sub-uid}': 1,
'account/history': 4,
'cross-margin/loan-info': 1,
'margin/loan-info': 1, // 查询借币币息率及额度
'fee/fee-rate/get': 1,
'order/openOrders': 0.4,
'order/orders': 0.4,
'order/orders/{id}': 0.4, // 查询某个订单详情
'order/orders/{id}/matchresults': 0.4, // 查询某个订单的成交明细
'order/orders/getClientOrder': 0.4,
'order/history': 1, // 查询当前委托、历史委托
'order/matchresults': 1, // 查询当前成交、历史成交
// 'dw/withdraw-virtual/addresses', // 查询虚拟币提现地址(Deprecated)
'query/deposit-withdraw': 1,
// 'margin/loan-info', // duplicate
'margin/loan-orders': 0.2, // 借贷订单
'margin/accounts/balance': 0.2, // 借贷账户详情
'cross-margin/loan-orders': 1, // 查询借币订单
'cross-margin/accounts/balance': 1, // 借币账户详情
'points/actions': 1,
'points/orders': 1,
'subuser/aggregate-balance': 10,
'stable-coin/exchange_rate': 1,
'stable-coin/quote': 1,
},
'post': {
'account/transfer': 1, // 资产划转(该节点为母用户和子用户进行资产划转的通用接口。)
'futures/transfer': 1,
'order/batch-orders': 0.4,
'order/orders/place': 0.2, // 创建并执行一个新订单 (一步下单, 推荐使用)
'order/orders/submitCancelClientOrder': 0.2,
'order/orders/batchCancelOpenOrders': 0.4,
// 'order/orders', // 创建一个新的订单请求 (仅创建订单,不执行下单)
// 'order/orders/{id}/place', // 执行一个订单 (仅执行已创建的订单)
'order/orders/{id}/submitcancel': 0.2, // 申请撤销一个订单请求
'order/orders/batchcancel': 0.4, // 批量撤销订单
// 'dw/balance/transfer', // 资产划转
'dw/withdraw/api/create': 1, // 申请提现虚拟币
// 'dw/withdraw-virtual/create', // 申请提现虚拟币
// 'dw/withdraw-virtual/{id}/place', // 确认申请虚拟币提现(Deprecated)
'dw/withdraw-virtual/{id}/cancel': 1, // 申请取消提现虚拟币
'dw/transfer-in/margin': 10, // 现货账户划入至借贷账户
'dw/transfer-out/margin': 10, // 借贷账户划出至现货账户
'margin/orders': 10, // 申请借贷
'margin/orders/{id}/repay': 10, // 归还借贷
'cross-margin/transfer-in': 1, // 资产划转
'cross-margin/transfer-out': 1, // 资产划转
'cross-margin/orders': 1, // 申请借币
'cross-margin/orders/{id}/repay': 1, // 归还借币
'stable-coin/exchange': 1,
'subuser/transfer': 10,
},
},
},
'fees': {
'trading': {
'feeSide': 'get',
'tierBased': false,
'percentage': true,
'maker': this.parseNumber ('0.002'),
'taker': this.parseNumber ('0.002'),
},
},
'exceptions': {
'broad': {
'contract is restricted of closing positions on API. Please contact customer service': OnMaintenance,
'maintain': OnMaintenance,
},
'exact': {
// err-code
'bad-request': BadRequest,
'base-date-limit-error': BadRequest, // {"status":"error","err-code":"base-date-limit-error","err-msg":"date less than system limit","data":null}
'api-not-support-temp-addr': PermissionDenied, // {"status":"error","err-code":"api-not-support-temp-addr","err-msg":"API withdrawal does not support temporary addresses","data":null}
'timeout': RequestTimeout, // {"ts":1571653730865,"status":"error","err-code":"timeout","err-msg":"Request Timeout"}
'gateway-internal-error': ExchangeNotAvailable, // {"status":"error","err-code":"gateway-internal-error","err-msg":"Failed to load data. Try again later.","data":null}
'account-frozen-balance-insufficient-error': InsufficientFunds, // {"status":"error","err-code":"account-frozen-balance-insufficient-error","err-msg":"trade account balance is not enough, left: `0.0027`","data":null}
'invalid-amount': InvalidOrder, // eg "Paramemter `amount` is invalid."
'order-limitorder-amount-min-error': InvalidOrder, // limit order amount error, min: `0.001`
'order-limitorder-amount-max-error': InvalidOrder, // market order amount error, max: `1000000`
'order-marketorder-amount-min-error': InvalidOrder, // market order amount error, min: `0.01`
'order-limitorder-price-min-error': InvalidOrder, // limit order price error
'order-limitorder-price-max-error': InvalidOrder, // limit order price error
'order-holding-limit-failed': InvalidOrder, // {"status":"error","err-code":"order-holding-limit-failed","err-msg":"Order failed, exceeded the holding limit of this currency","data":null}
'order-orderprice-precision-error': InvalidOrder, // {"status":"error","err-code":"order-orderprice-precision-error","err-msg":"order price precision error, scale: `4`","data":null}
'order-etp-nav-price-max-error': InvalidOrder, // {"status":"error","err-code":"order-etp-nav-price-max-error","err-msg":"Order price cannot be higher than 5% of NAV","data":null}
'order-orderstate-error': OrderNotFound, // canceling an already canceled order
'order-queryorder-invalid': OrderNotFound, // querying a non-existent order
'order-update-error': ExchangeNotAvailable, // undocumented error
'api-signature-check-failed': AuthenticationError,
'api-signature-not-valid': AuthenticationError, // {"status":"error","err-code":"api-signature-not-valid","err-msg":"Signature not valid: Incorrect Access key [Access key错误]","data":null}
'base-record-invalid': OrderNotFound, // https://github.com/ccxt/ccxt/issues/5750
'base-symbol-trade-disabled': BadSymbol, // {"status":"error","err-code":"base-symbol-trade-disabled","err-msg":"Trading is disabled for this symbol","data":null}
'base-symbol-error': BadSymbol, // {"status":"error","err-code":"base-symbol-error","err-msg":"The symbol is invalid","data":null}
'system-maintenance': OnMaintenance, // {"status": "error", "err-code": "system-maintenance", "err-msg": "System is in maintenance!", "data": null}
// err-msg
'invalid symbol': BadSymbol, // {"ts":1568813334794,"status":"error","err-code":"invalid-parameter","err-msg":"invalid symbol"}
'symbol trade not open now': BadSymbol, // {"ts":1576210479343,"status":"error","err-code":"invalid-parameter","err-msg":"symbol trade not open now"}
},
},
'options': {
'defaultNetwork': 'ERC20',
'networks': {
'ETH': 'erc20',
'TRX': 'trc20',
'HRC20': 'hrc20',
'HECO': 'hrc20',
'HT': 'hrc20',
'ALGO': 'algo',
'OMNI': '',
},
// https://github.com/ccxt/ccxt/issues/5376
'fetchOrdersByStatesMethod': 'private_get_order_orders', // 'private_get_order_history' // https://github.com/ccxt/ccxt/pull/5392
'fetchOpenOrdersMethod': 'fetch_open_orders_v1', // 'fetch_open_orders_v2' // https://github.com/ccxt/ccxt/issues/5388
'createMarketBuyOrderRequiresPrice': true,
'fetchMarketsMethod': 'publicGetCommonSymbols',
'fetchBalanceMethod': 'privateGetAccountAccountsIdBalance',
'createOrderMethod': 'privatePostOrderOrdersPlace',
'language': 'en-US',
'broker': {
'id': 'AA03022abc',
},
},
'commonCurrencies': {
// https://github.com/ccxt/ccxt/issues/6081
// https://github.com/ccxt/ccxt/issues/3365
// https://github.com/ccxt/ccxt/issues/2873
'GET': 'Themis', // conflict with GET (Guaranteed Entrance Token, GET Protocol)
'GTC': 'Game.com', // conflict with Gitcoin and Gastrocoin
'HIT': 'HitChain',
'HOT': 'Hydro Protocol', // conflict with HOT (Holo) https://github.com/ccxt/ccxt/issues/4929
// https://github.com/ccxt/ccxt/issues/7399
// https://coinmarketcap.com/currencies/pnetwork/
// https://coinmarketcap.com/currencies/penta/markets/
// https://en.cryptonomist.ch/blog/eidoo/the-edo-to-pnt-upgrade-what-you-need-to-know-updated/
'PNT': 'Penta',
'SBTC': 'Super Bitcoin',
'BIFI': 'Bitcoin File', // conflict with Beefy.Finance https://github.com/ccxt/ccxt/issues/8706
},
});
}
async fetchTime (params = {}) {
const response = await this.publicGetCommonTimestamp (params);
return this.safeInteger (response, 'data');
}
async fetchTradingLimits (symbols = undefined, params = {}) {
// this method should not be called directly, use loadTradingLimits () instead
// by default it will try load withdrawal fees of all currencies (with separate requests)
// however if you define symbols = [ 'ETH/BTC', 'LTC/BTC' ] in args it will only load those
await this.loadMarkets ();
if (symbols === undefined) {
symbols = this.symbols;
}
const result = {};
for (let i = 0; i < symbols.length; i++) {
const symbol = symbols[i];
result[symbol] = await this.fetchTradingLimitsById (this.marketId (symbol), params);
}
return result;
}
async fetchTradingLimitsById (id, params = {}) {
const request = {
'symbol': id,
};
const response = await this.publicGetCommonExchange (this.extend (request, params));
//
// { status: "ok",
// data: { symbol: "aidocbtc",
// 'buy-limit-must-less-than': 1.1,
// 'sell-limit-must-greater-than': 0.9,
// 'limit-order-must-greater-than': 1,
// 'limit-order-must-less-than': 5000000,
// 'market-buy-order-must-greater-than': 0.0001,
// 'market-buy-order-must-less-than': 100,
// 'market-sell-order-must-greater-than': 1,
// 'market-sell-order-must-less-than': 500000,
// 'circuit-break-when-greater-than': 10000,
// 'circuit-break-when-less-than': 10,
// 'market-sell-order-rate-must-less-than': 0.1,
// 'market-buy-order-rate-must-less-than': 0.1 } }
//
return this.parseTradingLimits (this.safeValue (response, 'data', {}));
}
parseTradingLimits (limits, symbol = undefined, params = {}) {
//
// { symbol: "aidocbtc",
// 'buy-limit-must-less-than': 1.1,
// 'sell-limit-must-greater-than': 0.9,
// 'limit-order-must-greater-than': 1,
// 'limit-order-must-less-than': 5000000,
// 'market-buy-order-must-greater-than': 0.0001,
// 'market-buy-order-must-less-than': 100,
// 'market-sell-order-must-greater-than': 1,
// 'market-sell-order-must-less-than': 500000,
// 'circuit-break-when-greater-than': 10000,
// 'circuit-break-when-less-than': 10,
// 'market-sell-order-rate-must-less-than': 0.1,
// 'market-buy-order-rate-must-less-than': 0.1 }
//
return {
'info': limits,
'limits': {
'amount': {
'min': this.safeNumber (limits, 'limit-order-must-greater-than'),
'max': this.safeNumber (limits, 'limit-order-must-less-than'),
},
},
};
}
costToPrecision (symbol, cost) {
return this.decimalToPrecision (cost, TRUNCATE, this.markets[symbol]['precision']['cost'], this.precisionMode);
}
async fetchMarkets (params = {}) {
const method = this.options['fetchMarketsMethod'];
const response = await this[method] (params);
const markets = this.safeValue (response, 'data');
const numMarkets = markets.length;
if (numMarkets < 1) {
throw new NetworkError (this.id + ' publicGetCommonSymbols returned empty response: ' + this.json (markets));
}
const result = [];
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const baseId = this.safeString (market, 'base-currency');
const quoteId = this.safeString (market, 'quote-currency');
const id = baseId + quoteId;
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const precision = {
'amount': this.safeInteger (market, 'amount-precision'),
'price': this.safeInteger (market, 'price-precision'),
'cost': this.safeInteger (market, 'value-precision'),
};
const maker = (base === 'OMG') ? 0 : 0.2 / 100;
const taker = (base === 'OMG') ? 0 : 0.2 / 100;
const minAmount = this.safeNumber (market, 'min-order-amt', Math.pow (10, -precision['amount']));
const maxAmount = this.safeNumber (market, 'max-order-amt');
const minCost = this.safeNumber (market, 'min-order-value', 0);
const state = this.safeString (market, 'state');
const active = (state === 'online');
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'type': 'spot',
'spot': true,
'active': active,
'precision': precision,
'taker': taker,
'maker': maker,
'limits': {
'amount': {
'min': minAmount,
'max': maxAmount,
},
'price': {
'min': Math.pow (10, -precision['price']),
'max': undefined,
},
'cost': {
'min': minCost,
'max': undefined,
},
'leverage': {
'max': this.safeNumber (market, 'leverage-ratio', 1),
'superMax': this.safeNumber (market, 'super-margin-leverage-ratio', 1),
},
},
'info': market,
});
}
return result;
}
parseTicker (ticker, market = undefined) {
//
// fetchTicker
//
// {
// "amount": 26228.672978342216,
// "open": 9078.95,
// "close": 9146.86,
// "high": 9155.41,
// "id": 209988544334,
// "count": 265846,
// "low": 8988.0,
// "version": 209988544334,
// "ask": [ 9146.87, 0.156134 ],
// "vol": 2.3822168242201668E8,
// "bid": [ 9146.86, 0.080758 ],
// }
//
// fetchTickers
// {
// symbol: "bhdht",
// open: 2.3938,
// high: 2.4151,
// low: 2.3323,
// close: 2.3909,
// amount: 628.992,
// vol: 1493.71841095,
// count: 2088,
// bid: 2.3643,
// bidSize: 0.7136,
// ask: 2.4061,
// askSize: 0.4156
// }
//
const symbol = this.safeSymbol (undefined, market);
const timestamp = this.safeInteger (ticker, 'ts');
let bid = undefined;
let bidVolume = undefined;
let ask = undefined;
let askVolume = undefined;
if ('bid' in ticker) {
if (Array.isArray (ticker['bid'])) {
bid = this.safeNumber (ticker['bid'], 0);
bidVolume = this.safeNumber (ticker['bid'], 1);
} else {
bid = this.safeNumber (ticker, 'bid');
bidVolume = this.safeValue (ticker, 'bidSize');
}
}
if ('ask' in ticker) {
if (Array.isArray (ticker['ask'])) {
ask = this.safeNumber (ticker['ask'], 0);
askVolume = this.safeNumber (ticker['ask'], 1);
} else {
ask = this.safeNumber (ticker, 'ask');
askVolume = this.safeValue (ticker, 'askSize');
}
}
const open = this.safeNumber (ticker, 'open');
const close = this.safeNumber (ticker, 'close');
const baseVolume = this.safeNumber (ticker, 'amount');
const quoteVolume = this.safeNumber (ticker, 'vol');
const vwap = this.vwap (baseVolume, quoteVolume);
return this.safeTicker ({
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeNumber (ticker, 'high'),
'low': this.safeNumber (ticker, 'low'),
'bid': bid,
'bidVolume': bidVolume,
'ask': ask,
'askVolume': askVolume,
'vwap': vwap,
'open': open,
'close': close,
'last': close,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
}, market);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
'type': 'step0',
};
const response = await this.marketGetDepth (this.extend (request, params));
//
// {
// "status": "ok",
// "ch": "market.btcusdt.depth.step0",
// "ts": 1583474832790,
// "tick": {
// "bids": [
// [ 9100.290000000000000000, 0.200000000000000000 ],
// [ 9099.820000000000000000, 0.200000000000000000 ],
// [ 9099.610000000000000000, 0.205000000000000000 ],
// ],
// "asks": [
// [ 9100.640000000000000000, 0.005904000000000000 ],
// [ 9101.010000000000000000, 0.287311000000000000 ],
// [ 9101.030000000000000000, 0.012121000000000000 ],
// ],
// "ts":1583474832008,
// "version":104999698780
// }
// }
//
if ('tick' in response) {
if (!response['tick']) {
throw new BadSymbol (this.id + ' fetchOrderBook() returned empty response: ' + this.json (response));
}
const tick = this.safeValue (response, 'tick');
const timestamp = this.safeInteger (tick, 'ts', this.safeInteger (response, 'ts'));
const result = this.parseOrderBook (tick, symbol, timestamp);
result['nonce'] = this.safeInteger (tick, 'version');
return result;
}
throw new ExchangeError (this.id + ' fetchOrderBook() returned unrecognized response: ' + this.json (response));
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const response = await this.marketGetDetailMerged (this.extend (request, params));
//
// {
// "status": "ok",
// "ch": "market.btcusdt.detail.merged",
// "ts": 1583494336669,
// "tick": {
// "amount": 26228.672978342216,
// "open": 9078.95,
// "close": 9146.86,
// "high": 9155.41,
// "id": 209988544334,
// "count": 265846,
// "low": 8988.0,
// "version": 209988544334,
// "ask": [ 9146.87, 0.156134 ],
// "vol": 2.3822168242201668E8,
// "bid": [ 9146.86, 0.080758 ],
// }
// }
//
const ticker = this.parseTicker (response['tick'], market);
const timestamp = this.safeInteger (response, 'ts');
ticker['timestamp'] = timestamp;
ticker['datetime'] = this.iso8601 (timestamp);
return ticker;
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.marketGetTickers (params);
const tickers = this.safeValue (response, 'data');
const timestamp = this.safeInteger (response, 'ts');
const result = {};
for (let i = 0; i < tickers.length; i++) {
const marketId = this.safeString (tickers[i], 'symbol');
const market = this.safeMarket (marketId);
const symbol = market['symbol'];
const ticker = this.parseTicker (tickers[i], market);
ticker['timestamp'] = timestamp;
ticker['datetime'] = this.iso8601 (timestamp);
result[symbol] = ticker;
}
return this.filterByArray (result, 'symbol', symbols);
}
parseTrade (trade, market = undefined) {
//
// fetchTrades (public)
//
// {
// "amount": 0.010411000000000000,
// "trade-id": 102090736910,
// "ts": 1583497692182,
// "id": 10500517034273194594947,
// "price": 9096.050000000000000000,
// "direction": "sell"
// }
//
// fetchMyTrades (private)
//
// {
// 'symbol': 'swftcbtc',
// 'fee-currency': 'swftc',
// 'filled-fees': '0',
// 'source': 'spot-api',
// 'id': 83789509854000,
// 'type': 'buy-limit',
// 'order-id': 83711103204909,
// 'filled-points': '0.005826843283532154',
// 'fee-deduct-currency': 'ht',
// 'filled-amount': '45941.53',
// 'price': '0.0000001401',
// 'created-at': 1597933260729,
// 'match-id': 100087455560,
// 'role': 'maker',
// 'trade-id': 100050305348
// },
//
const marketId = this.safeString (trade, 'symbol');
const symbol = this.safeSymbol (marketId, market);
const timestamp = this.safeInteger2 (trade, 'ts', 'created-at');
const order = this.safeString (trade, 'order-id');
let side = this.safeString (trade, 'direction');
let type = this.safeString (trade, 'type');
if (type !== undefined) {
const typeParts = type.split ('-');
side = typeParts[0];
type = typeParts[1];
}
const takerOrMaker = this.safeString (trade, 'role');
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString2 (trade, 'filled-amount', 'amount');
const price = this.parseNumber (priceString);
const amount = this.parseNumber (amountString);
const cost = this.parseNumber (Precise.stringMul (priceString, amountString));
let fee = undefined;
let feeCost = this.safeNumber (trade, 'filled-fees');
let feeCurrency = this.safeCurrencyCode (this.safeString (trade, 'fee-currency'));
const filledPoints = this.safeNumber (trade, 'filled-points');
if (filledPoints !== undefined) {
if ((feeCost === undefined) || (feeCost === 0.0)) {
feeCost = filledPoints;
feeCurrency = this.safeCurrencyCode (this.safeString (trade, 'fee-deduct-currency'));
}
}
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': feeCurrency,
};
}
const tradeId = this.safeString2 (trade, 'trade-id', 'tradeId');
const id = this.safeString (trade, 'id', tradeId);
return {
'id': id,
'info': trade,
'order': order,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': type,
'side': side,
'takerOrMaker': takerOrMaker,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
};
}
async fetchOrderTrades (id, symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'id': id,
};
const response = await this.privateGetOrderOrdersIdMatchresults (this.extend (request, params));
return this.parseTrades (response['data'], undefined, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
const request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (limit !== undefined) {
request['size'] = limit; // 1-100 orders, default is 100
}
if (since !== undefined) {
request['start-time'] = since; // a date within 120 days from today
// request['end-time'] = this.sum (since, 172800000); // 48 hours window
}
const response = await this.privateGetOrderMatchresults (this.extend (request, params));
return this.parseTrades (response['data'], market, since, limit);
}
async fetchTrades (symbol, since = undefined, limit = 1000, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
if (limit !== undefined) {
request['size'] = limit;
}
const response = await this.marketGetHistoryTrade (this.extend (request, params));
//
// {
// "status": "ok",
// "ch": "market.btcusdt.trade.detail",
// "ts": 1583497692365,
// "data": [
// {
// "id": 105005170342,
// "ts": 1583497692182,
// "data": [
// {
// "amount": 0.010411000000000000,
// "trade-id": 102090736910,
// "ts": 1583497692182,
// "id": 10500517034273194594947,
// "price": 9096.050000000000000000,
// "direction": "sell"
// }
// ]
// },
// // ...
// ]
// }
//
const data = this.safeValue (response, 'data');
let result = [];
for (let i = 0; i < data.length; i++) {
const trades = this.safeValue (data[i], 'data', []);
for (let j = 0; j < trades.length; j++) {
const trade = this.parseTrade (trades[j], market);
result.push (trade);
}
}
result = this.sortBy (result, 'timestamp');
return this.filterBySymbolSinceLimit (result, symbol, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// {
// "amount":1.2082,
// "open":0.025096,
// "close":0.025095,
// "high":0.025096,
// "id":1591515300,
// "count":6,
// "low":0.025095,
// "vol":0.0303205097
// }
//
return [
this.safeTimestamp (ohlcv, 'id'),
this.safeNumber (ohlcv, 'open'),
this.safeNumber (ohlcv, 'high'),
this.safeNumber (ohlcv, 'low'),
this.safeNumber (ohlcv, 'close'),
this.safeNumber (ohlcv, 'amount'),
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = 1000, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
'period': this.timeframes[timeframe],
};
if (limit !== undefined) {
request['size'] = limit;
}
const response = await this.marketGetHistoryKline (this.extend (request, params));
//
// {
// "status":"ok",
// "ch":"market.ethbtc.kline.1min",
// "ts":1591515374371,
// "data":[
// {"amount":0.0,"open":0.025095,"close":0.025095,"high":0.025095,"id":1591515360,"count":0,"low":0.025095,"vol":0.0},
// {"amount":1.2082,"open":0.025096,"close":0.025095,"high":0.025096,"id":1591515300,"count":6,"low":0.025095,"vol":0.0303205097},
// {"amount":0.0648,"open":0.025096,"close":0.025096,"high":0.025096,"id":1591515240,"count":2,"low":0.025096,"vol":0.0016262208},
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseOHLCVs (data, market, timeframe, since, limit);
}
async fetchAccounts (params = {}) {
await this.loadMarkets ();
const response = await this.privateGetAccountAccounts (params);
return response['data'];
}
async fetchCurrencies (params = {}) {
const response = await this.v2PublicGetReferenceCurrencies ();
// {
// "code": 200,
// "data": [
// {
// "currency": "sxp",
// "assetType": "1",
// "chains": [
// {
// "chain": "sxp",
// "displayName": "ERC20",
// "baseChain": "ETH",
// "baseChainProtocol": "ERC20",
// "isDynamic": true,
// "numOfConfirmations": "12",
// "numOfFastConfirmations": "12",
// "depositStatus": "allowed",
// "minDepositAmt": "0.23",
// "withdrawStatus": "allowed",
// "minWithdrawAmt": "0.23",
// "withdrawPrecision": "8",
// "maxWithdrawAmt": "227000.000000000000000000",
// "withdrawQuotaPerDay": "227000.000000000000000000",
// "withdrawQuotaPerYear": null,
// "withdrawQuotaTotal": null,
// "withdrawFeeType": "fixed",
// "transactFeeWithdraw": "11.1653",
// "addrWithTag": false,
// "addrDepositTag": false
// }
// ],
// "instStatus": "normal"
// }
// ]
// }
//
const data = this.safeValue (response, 'data', []);
const result = {};
for (let i = 0; i < data.length; i++) {
const entry = data[i];
const currencyId = this.safeString (entry, 'currency');
const code = this.safeCurrencyCode (currencyId);
const chains = this.safeValue (entry, 'chains', []);
const networks = {};
const instStatus = this.safeString (entry, 'instStatus');
const currencyActive = instStatus === 'normal';
let fee = undefined;
let precision = undefined;
let minWithdraw = undefined;
let maxWithdraw = undefined;
for (let j = 0; j < chains.length; j++) {
const chain = chains[j];
const networkId = this.safeString (chain, 'chain');
let baseChainProtocol = this.safeString (chain, 'baseChainProtocol');
const huobiToken = 'h' + currencyId;
if (baseChainProtocol === undefined) {
if (huobiToken === networkId) {
baseChainProtocol = 'ERC20';
} else {
baseChainProtocol = this.safeString (chain, 'displayName');
}
}
const network = this.safeNetwork (baseChainProtocol);
minWithdraw = this.safeNumber (chain, 'minWithdrawAmt');
maxWithdraw = this.safeNumber (chain, 'maxWithdrawAmt');
const withdraw = this.safeString (chain, 'withdrawStatus');
const deposit = this.safeString (chain, 'depositStatus');
const active = (withdraw === 'allowed') && (deposit === 'allowed');
precision = this.safeInteger (chain, 'withdrawPrecision');
fee = this.safeNumber (chain, 'transactFeeWithdraw');
networks[network] = {
'info': chain,
'id': networkId,
'network': network,
'limits': {
'withdraw': {
'min': minWithdraw,
'max': maxWithdraw,
},
},
'active': active,
'fee': fee,
'precision': precision,
};
}
const networksKeys = Object.keys (networks);
const networkLength = networksKeys.length;
result[code] = {
'info': entry,
'code': code,
'id': currencyId,
'active': currencyActive,
'fee': (networkLength <= 1) ? fee : undefined,
'name': undefined,
'limits': {
'amount': {
'min': undefined,
'max': undefined,
},
'withdraw': {
'min': (networkLength <= 1) ? minWithdraw : undefined,
'max': (networkLength <= 1) ? maxWithdraw : undefined,
},
},
'precision': (networkLength <= 1) ? precision : undefined,
'networks': networks,
};
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
const method = this.options['fetchBalanceMethod'];
const request = {
'id': this.accounts[0]['id'],
};
const response = await this[method] (this.extend (request, params));
const balances = this.safeValue (response['data'], 'list', []);
const result = { 'info': response };
for (let i = 0; i < balances.length; i++) {
const balance = balances[i];
const currencyId = this.safeString (balance, 'currency');
const code = this.safeCurrencyCode (currencyId);
let account = undefined;
if (code in result) {
account = result[code];
} else {
account = this.account ();
}
if (balance['type'] === 'trade') {
account['free'] = this.safeString (balance, 'balance');
}
if (balance['type'] === 'frozen') {
account['used'] = this.safeString (balance, 'balance');