-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuobipro.js
514 lines (488 loc) · 19.5 KB
/
huobipro.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
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class huobipro extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'huobipro',
'name': 'Huobi Pro',
'countries': 'CN',
'rateLimit': 2000,
'userAgent': this.userAgents['chrome39'],
'version': 'v1',
'accounts': undefined,
'accountsById': undefined,
'hostname': 'api.huobi.pro',
'has': {
'CORS': false,
'fetchOHCLV': true,
'fetchOrders': true,
'fetchOpenOrders': true,
'withdraw': true,
},
'timeframes': {
'1m': '1min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '60min',
'1d': '1day',
'1w': '1week',
'1M': '1mon',
'1y': '1year',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766569-15aa7b9a-5edd-11e7-9e7f-44791f4ee49c.jpg',
'api': 'https://api.huobi.pro',
'www': 'https://www.huobi.pro',
'doc': 'https://github.com/huobiapi/API_Docs/wiki/REST_api_reference',
'fees': 'https://www.huobi.pro/about/fee/',
},
'api': {
'market': {
'get': [
'history/kline', // 获取K线数据
'detail/merged', // 获取聚合行情(Ticker)
'depth', // 获取 Market Depth 数据
'trade', // 获取 Trade Detail 数据
'history/trade', // 批量获取最近的交易记录
'detail', // 获取 Market Detail 24小时成交量数据
],
},
'public': {
'get': [
'common/symbols', // 查询系统支持的所有交易对
'common/currencys', // 查询系统支持的所有币种
'common/timestamp', // 查询系统当前时间
],
},
'private': {
'get': [
'account/accounts', // 查询当前用户的所有账户(即account-id)
'account/accounts/{id}/balance', // 查询指定账户的余额
'order/orders/{id}', // 查询某个订单详情
'order/orders/{id}/matchresults', // 查询某个订单的成交明细
'order/orders', // 查询当前委托、历史委托
'order/matchresults', // 查询当前成交、历史成交
'dw/withdraw-virtual/addresses', // 查询虚拟币提现地址
],
'post': [
'order/orders/place', // 创建并执行一个新订单 (一步下单, 推荐使用)
'order/orders', // 创建一个新的订单请求 (仅创建订单,不执行下单)
'order/orders/{id}/place', // 执行一个订单 (仅执行已创建的订单)
'order/orders/{id}/submitcancel', // 申请撤销一个订单请求
'order/orders/batchcancel', // 批量撤销订单
'dw/balance/transfer', // 资产划转
'dw/withdraw/api/create', // 申请提现虚拟币
'dw/withdraw-virtual/create', // 申请提现虚拟币
'dw/withdraw-virtual/{id}/place', // 确认申请虚拟币提现
'dw/withdraw-virtual/{id}/cancel', // 申请取消提现虚拟币
],
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'maker': 0.002,
'taker': 0.002,
},
},
});
}
async fetchMarkets () {
let response = await this.publicGetCommonSymbols ();
let markets = response['data'];
let numMarkets = markets.length;
if (numMarkets < 1)
throw new ExchangeError (this.id + ' publicGetCommonSymbols returned empty response: ' + this.json (response));
let result = [];
for (let i = 0; i < markets.length; i++) {
let market = markets[i];
let baseId = market['base-currency'];
let quoteId = market['quote-currency'];
let base = baseId.toUpperCase ();
let quote = quoteId.toUpperCase ();
let id = baseId + quoteId;
base = this.commonCurrencyCode (base);
quote = this.commonCurrencyCode (quote);
let symbol = base + '/' + quote;
let precision = {
'amount': market['amount-precision'],
'price': market['price-precision'],
};
let lot = Math.pow (10, -precision['amount']);
let maker = (base === 'OMG') ? 0 : 0.2 / 100;
let taker = (base === 'OMG') ? 0 : 0.2 / 100;
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'lot': lot,
'precision': precision,
'taker': taker,
'maker': maker,
'limits': {
'amount': {
'min': lot,
'max': Math.pow (10, precision['amount']),
},
'price': {
'min': Math.pow (10, -precision['price']),
'max': undefined,
},
'cost': {
'min': 0,
'max': undefined,
},
},
'info': market,
});
}
return result;
}
parseTicker (ticker, market = undefined) {
let symbol = undefined;
if (market)
symbol = market['symbol'];
let last = undefined;
if ('last' in ticker)
last = ticker['last'];
let timestamp = this.milliseconds ();
if ('ts' in ticker)
timestamp = ticker['ts'];
let bid = undefined;
let ask = undefined;
if ('bid' in ticker) {
if (ticker['bid'])
bid = this.safeFloat (ticker['bid'], 0);
}
if ('ask' in ticker) {
if (ticker['ask'])
ask = this.safeFloat (ticker['ask'], 0);
}
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': ticker['high'],
'low': ticker['low'],
'bid': bid,
'ask': ask,
'vwap': undefined,
'open': ticker['open'],
'close': ticker['close'],
'first': undefined,
'last': last,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': parseFloat (ticker['amount']),
'quoteVolume': ticker['vol'],
'info': ticker,
};
}
async fetchOrderBook (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.marketGetDepth (this.extend ({
'symbol': market['id'],
'type': 'step0',
}, params));
if ('tick' in response) {
if (!response['tick']) {
throw new ExchangeError (this.id + ' fetchOrderBook() returned empty response: ' + this.json (response));
}
return this.parseOrderBook (response['tick'], response['tick']['ts']);
}
throw new ExchangeError (this.id + ' fetchOrderBook() returned unrecognized response: ' + this.json (response));
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.marketGetDetailMerged (this.extend ({
'symbol': market['id'],
}, params));
return this.parseTicker (response['tick'], market);
}
parseTrade (trade, market) {
let timestamp = trade['ts'];
return {
'info': trade,
'id': trade['id'].toString (),
'order': undefined,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market['symbol'],
'type': undefined,
'side': trade['direction'],
'price': trade['price'],
'amount': trade['amount'],
};
}
parseTradesData (data, market, since = undefined, limit = undefined) {
let result = [];
for (let i = 0; i < data.length; i++) {
let trades = this.parseTrades (data[i]['data'], market, since, limit);
for (let k = 0; k < trades.length; k++) {
result.push (trades[k]);
}
}
return result;
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.marketGetHistoryTrade (this.extend ({
'symbol': market['id'],
'size': 2000,
}, params));
return this.parseTradesData (response['data'], market, since, limit);
}
parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
return [
ohlcv['id'] * 1000,
ohlcv['open'],
ohlcv['high'],
ohlcv['low'],
ohlcv['close'],
ohlcv['amount'],
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.marketGetHistoryKline (this.extend ({
'symbol': market['id'],
'period': this.timeframes[timeframe],
'size': 2000, // max = 2000
}, params));
return this.parseOHLCVs (response['data'], market, timeframe, since, limit);
}
async loadAccounts (reload = false) {
if (reload) {
this.accounts = await this.fetchAccounts ();
} else {
if (this.accounts) {
return this.accounts;
} else {
this.accounts = await this.fetchAccounts ();
this.accountsById = this.indexBy (this.accounts, 'id');
}
}
return this.accounts;
}
async fetchAccounts () {
await this.loadMarkets ();
let response = await this.privateGetAccountAccounts ();
return response['data'];
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
let response = await this.privateGetAccountAccountsIdBalance (this.extend ({
'id': this.accounts[0]['id'],
}, params));
let balances = response['data']['list'];
let result = { 'info': response };
for (let i = 0; i < balances.length; i++) {
let balance = balances[i];
let uppercase = balance['currency'].toUpperCase ();
let currency = this.commonCurrencyCode (uppercase);
let account = undefined;
if (currency in result)
account = result[currency];
else
account = this.account ();
if (balance['type'] === 'trade')
account['free'] = parseFloat (balance['balance']);
if (balance['type'] === 'frozen')
account['used'] = parseFloat (balance['balance']);
account['total'] = this.sum (account['free'], account['used']);
result[currency] = account;
}
return this.parseBalance (result);
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (!symbol)
throw new ExchangeError (this.id + ' fetchOrders() requires a symbol parameter');
this.loadMarkets ();
let market = this.market (symbol);
let status = undefined;
if ('type' in params) {
status = params['type'];
} else if ('status' in params) {
status = params['status'];
} else {
throw new ExchangeError (this.id + ' fetchOrders() requires a type param or status param for spot market ' + symbol + ' (0 or "open" for unfilled or partial filled orders, 1 or "closed" for filled orders)');
}
if ((status === 0) || (status === 'open')) {
status = 'submitted,partial-filled';
} else if ((status === 1) || (status === 'closed')) {
status = 'filled,partial-canceled';
} else {
throw new ExchangeError (this.id + ' fetchOrders() wrong type param or status param for spot market ' + symbol + ' (0 or "open" for unfilled or partial filled orders, 1 or "closed" for filled orders)');
}
let response = await this.privateGetOrderOrders (this.extend ({
'symbol': market['id'],
'states': status,
}));
return this.parseOrders (response['data'], market, since, limit);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let open = 0; // 0 for unfilled orders, 1 for filled orders
return this.fetchOrders (symbol, undefined, undefined, this.extend ({
'status': open,
}, params));
}
parseOrderStatus (status) {
if (status === 'partial-filled') {
return 'open';
} else if (status === 'filled') {
return 'closed';
} else if (status === 'canceled') {
return 'canceled';
} else if (status === 'submitted') {
return 'open';
}
return status;
}
parseOrder (order, market = undefined) {
let side = undefined;
let type = undefined;
let status = undefined;
if ('type' in order) {
let orderType = order['type'].split ('-');
side = orderType[0];
type = orderType[1];
status = this.parseOrderStatus (order['state']);
}
let symbol = undefined;
if (!market) {
if ('symbol' in order) {
if (order['symbol'] in this.markets_by_id) {
let marketId = order['symbol'];
market = this.markets_by_id[marketId];
}
}
}
if (market)
symbol = market['symbol'];
let timestamp = order['created-at'];
let amount = parseFloat (order['amount']);
let filled = parseFloat (order['field-amount']);
let remaining = amount - filled;
let price = parseFloat (order['price']);
let cost = parseFloat (order['field-cash-amount']);
let average = 0;
if (filled)
average = parseFloat (cost / filled);
let result = {
'info': order,
'id': order['id'],
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'average': average,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': undefined,
};
return result;
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
await this.loadAccounts ();
let market = this.market (symbol);
let order = {
'account-id': this.accounts[0]['id'],
'amount': this.amountToPrecision (symbol, amount),
'symbol': market['id'],
'type': side + '-' + type,
};
if (type === 'limit')
order['price'] = this.priceToPrecision (symbol, price);
let response = await this.privatePostOrderOrdersPlace (this.extend (order, params));
return {
'info': response,
'id': response['data'],
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
return await this.privatePostOrderOrdersIdSubmitcancel ({ 'id': id });
}
async withdraw (currency, amount, address, tag = undefined, params = {}) {
let request = {
'address': address, // only supports existing addresses in your withdraw address list
'amount': amount,
'currency': currency.toLowerCase (),
};
if (tag)
request['addr-tag'] = tag; // only for XRP?
let response = await this.privatePostDwWithdrawApiCreate (this.extend (request, params));
let id = undefined;
if ('data' in response) {
id = response['data'];
}
return {
'info': response,
'id': id,
};
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = '/';
if (api === 'market')
url += api;
else
url += this.version;
url += '/' + this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path));
if (api === 'private') {
this.checkRequiredCredentials ();
let timestamp = this.ymdhms (this.milliseconds (), 'T');
let request = this.keysort (this.extend ({
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '2',
'AccessKeyId': this.apiKey,
'Timestamp': timestamp,
}, query));
let auth = this.urlencode (request);
// unfortunately, PHP demands double quotes for the escaped newline symbol
let payload = [ method, this.hostname, url, auth ].join ("\n");
let signature = this.hmac (this.encode (payload), this.encode (this.secret), 'sha256', 'base64');
auth += '&' + this.urlencode ({ 'Signature': signature });
url += '?' + auth;
if (method === 'POST') {
body = this.json (query);
headers = {
'Content-Type': 'application/json',
};
} else {
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
};
}
} else {
if (Object.keys (params).length)
url += '?' + this.urlencode (params);
}
url = this.urls['api'] + url;
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let response = await this.fetch2 (path, api, method, params, headers, body);
if ('status' in response)
if (response['status'] === 'error')
throw new ExchangeError (this.id + ' ' + this.json (response));
return response;
}
}