forked from ccxt/ccxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
poloniex.js
807 lines (767 loc) · 29.3 KB
/
poloniex.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
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeNotAvailable, ExchangeError, InsufficientFunds, OrderNotFound, OrderNotCached, InvalidOrder, CancelPending } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class poloniex extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'poloniex',
'name': 'Poloniex',
'countries': 'US',
'rateLimit': 1000, // up to 6 calls per second
'has': {
'createDepositAddress': true,
'fetchDepositAddress': true,
'CORS': false,
'fetchOHLCV': true,
'fetchMyTrades': true,
'fetchOrder': 'emulated',
'fetchOrders': 'emulated',
'fetchOpenOrders': true,
'fetchClosedOrders': 'emulated',
'fetchTickers': true,
'fetchCurrencies': true,
'withdraw': true,
},
'timeframes': {
'5m': 300,
'15m': 900,
'30m': 1800,
'2h': 7200,
'4h': 14400,
'1d': 86400,
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766817-e9456312-5ee6-11e7-9b3c-b628ca5626a5.jpg',
'api': {
'public': 'https://poloniex.com/public',
'private': 'https://poloniex.com/tradingApi',
},
'www': 'https://poloniex.com',
'doc': [
'https://poloniex.com/support/api/',
'http://pastebin.com/dMX7mZE0',
],
'fees': 'https://poloniex.com/fees',
},
'api': {
'public': {
'get': [
'return24hVolume',
'returnChartData',
'returnCurrencies',
'returnLoanOrders',
'returnOrderBook',
'returnTicker',
'returnTradeHistory',
],
},
'private': {
'post': [
'buy',
'cancelLoanOffer',
'cancelOrder',
'closeMarginPosition',
'createLoanOffer',
'generateNewAddress',
'getMarginPosition',
'marginBuy',
'marginSell',
'moveOrder',
'returnActiveLoans',
'returnAvailableAccountBalances',
'returnBalances',
'returnCompleteBalances',
'returnDepositAddresses',
'returnDepositsWithdrawals',
'returnFeeInfo',
'returnLendingHistory',
'returnMarginAccountSummary',
'returnOpenLoanOffers',
'returnOpenOrders',
'returnOrderTrades',
'returnTradableBalances',
'returnTradeHistory',
'sell',
'toggleAutoRenew',
'transferBalance',
'withdraw',
],
},
},
'fees': {
'trading': {
'maker': 0.0015,
'taker': 0.0025,
},
'funding': {},
},
'limits': {
'amount': {
'min': 0.00000001,
'max': 1000000000,
},
'price': {
'min': 0.00000001,
'max': 1000000000,
},
'cost': {
'min': 0.00000000,
'max': 1000000000,
},
},
'precision': {
'amount': 8,
'price': 8,
},
});
}
calculateFee (symbol, type, side, amount, price, takerOrMaker = 'taker', params = {}) {
let market = this.markets[symbol];
let key = 'quote';
let rate = market[takerOrMaker];
let cost = parseFloat (this.costToPrecision (symbol, amount * rate));
if (side === 'sell') {
cost *= price;
} else {
key = 'base';
}
return {
'type': takerOrMaker,
'currency': market[key],
'rate': rate,
'cost': parseFloat (this.feeToPrecision (symbol, cost)),
};
}
commonCurrencyCode (currency) {
if (currency === 'BTM')
return 'Bitmark';
if (currency === 'STR')
return 'XLM';
return currency;
}
currencyId (currency) {
if (currency === 'Bitmark')
return 'BTM';
if (currency === 'XLM')
return 'STR';
return currency;
}
parseOHLCV (ohlcv, market = undefined, timeframe = '5m', since = undefined, limit = undefined) {
return [
ohlcv['date'] * 1000,
ohlcv['open'],
ohlcv['high'],
ohlcv['low'],
ohlcv['close'],
ohlcv['volume'],
];
}
async fetchOHLCV (symbol, timeframe = '5m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
if (!since)
since = 0;
let request = {
'currencyPair': market['id'],
'period': this.timeframes[timeframe],
'start': parseInt (since / 1000),
};
if (typeof limit !== 'undefined')
request['end'] = this.sum (request['start'], limit * this.timeframes[timeframe]);
let response = await this.publicGetReturnChartData (this.extend (request, params));
return this.parseOHLCVs (response, market, timeframe, since, limit);
}
async fetchMarkets () {
let markets = await this.publicGetReturnTicker ();
let keys = Object.keys (markets);
let result = [];
for (let p = 0; p < keys.length; p++) {
let id = keys[p];
let market = markets[id];
let [ quote, base ] = id.split ('_');
base = this.commonCurrencyCode (base);
quote = this.commonCurrencyCode (quote);
let symbol = base + '/' + quote;
result.push (this.extend (this.fees['trading'], {
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'active': true,
'lot': this.limits['amount']['min'],
'info': market,
}));
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let balances = await this.privatePostReturnCompleteBalances (this.extend ({
'account': 'all',
}, params));
let result = { 'info': balances };
let currencies = Object.keys (balances);
for (let c = 0; c < currencies.length; c++) {
let id = currencies[c];
let balance = balances[id];
let currency = this.commonCurrencyCode (id);
let account = {
'free': parseFloat (balance['available']),
'used': parseFloat (balance['onOrders']),
'total': 0.0,
};
account['total'] = this.sum (account['free'], account['used']);
result[currency] = account;
}
return this.parseBalance (result);
}
async fetchFees (params = {}) {
await this.loadMarkets ();
let fees = await this.privatePostReturnFeeInfo ();
return {
'info': fees,
'maker': parseFloat (fees['makerFee']),
'taker': parseFloat (fees['takerFee']),
'withdraw': {},
'deposit': {},
};
}
async fetchOrderBook (symbol, params = {}) {
await this.loadMarkets ();
let orderbook = await this.publicGetReturnOrderBook (this.extend ({
'currencyPair': this.marketId (symbol),
// 'depth': 100,
}, params));
return this.parseOrderBook (orderbook);
}
parseTicker (ticker, market = undefined) {
let timestamp = this.milliseconds ();
let symbol = undefined;
if (market)
symbol = market['symbol'];
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': parseFloat (ticker['high24hr']),
'low': parseFloat (ticker['low24hr']),
'bid': parseFloat (ticker['highestBid']),
'ask': parseFloat (ticker['lowestAsk']),
'vwap': undefined,
'open': undefined,
'close': undefined,
'first': undefined,
'last': parseFloat (ticker['last']),
'change': parseFloat (ticker['percentChange']),
'percentage': undefined,
'average': undefined,
'baseVolume': parseFloat (ticker['quoteVolume']),
'quoteVolume': parseFloat (ticker['baseVolume']),
'info': ticker,
};
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
let tickers = await this.publicGetReturnTicker (params);
let ids = Object.keys (tickers);
let result = {};
for (let i = 0; i < ids.length; i++) {
let id = ids[i];
let market = this.markets_by_id[id];
let symbol = market['symbol'];
let ticker = tickers[id];
result[symbol] = this.parseTicker (ticker, market);
}
return result;
}
async fetchCurrencies (params = {}) {
let currencies = await this.publicGetReturnCurrencies (params);
let ids = Object.keys (currencies);
let result = {};
for (let i = 0; i < ids.length; i++) {
let id = ids[i];
let currency = currencies[id];
// todo: will need to rethink the fees
// to add support for multiple withdrawal/deposit methods and
// differentiated fees for each particular method
let precision = 8; // default precision, todo: fix "magic constants"
let code = this.commonCurrencyCode (id);
let active = (currency['delisted'] === 0);
let status = (currency['disabled']) ? 'disabled' : 'ok';
if (status !== 'ok')
active = false;
result[code] = {
'id': id,
'code': code,
'info': currency,
'name': currency['name'],
'active': active,
'status': status,
'fee': currency['txFee'], // todo: redesign
'precision': precision,
'limits': {
'amount': {
'min': Math.pow (10, -precision),
'max': Math.pow (10, precision),
},
'price': {
'min': Math.pow (10, -precision),
'max': Math.pow (10, precision),
},
'cost': {
'min': undefined,
'max': undefined,
},
'withdraw': {
'min': currency['txFee'],
'max': Math.pow (10, precision),
},
},
};
}
return result;
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let tickers = await this.publicGetReturnTicker (params);
let ticker = tickers[market['id']];
return this.parseTicker (ticker, market);
}
parseTrade (trade, market = undefined) {
let timestamp = this.parse8601 (trade['date']);
let symbol = undefined;
let base = undefined;
let quote = undefined;
if ((!market) && ('currencyPair' in trade)) {
let currencyPair = trade['currencyPair'];
if (currencyPair in this.markets_by_id) {
market = this.markets_by_id[currencyPair];
} else {
let parts = currencyPair.split ('_');
quote = parts[0];
base = parts[1];
symbol = base + '/' + quote;
}
}
if (market) {
symbol = market['symbol'];
base = market['base'];
quote = market['quote'];
}
let side = trade['type'];
let fee = undefined;
let cost = this.safeFloat (trade, 'total');
let amount = parseFloat (trade['amount']);
if ('fee' in trade) {
let rate = parseFloat (trade['fee']);
let feeCost = undefined;
let currency = undefined;
if (side === 'buy') {
currency = base;
feeCost = amount * rate;
} else {
currency = quote;
if (typeof cost !== 'undefined')
feeCost = cost * rate;
}
fee = {
'type': undefined,
'rate': rate,
'cost': feeCost,
'currency': currency,
};
}
return {
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'id': this.safeString (trade, 'tradeID'),
'order': this.safeString (trade, 'orderNumber'),
'type': 'limit',
'side': side,
'price': parseFloat (trade['rate']),
'amount': amount,
'cost': cost,
'fee': fee,
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'currencyPair': market['id'],
};
if (typeof since !== 'undefined') {
request['start'] = parseInt (since / 1000);
request['end'] = this.seconds (); // last 50000 trades by default
}
let trades = await this.publicGetReturnTradeHistory (this.extend (request, params));
return this.parseTrades (trades, market, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol)
market = this.market (symbol);
let pair = market ? market['id'] : 'all';
let request = { 'currencyPair': pair };
if (typeof since !== 'undefined') {
request['start'] = parseInt (since / 1000);
request['end'] = this.seconds ();
}
// limit is disabled (does not really work as expected)
// if (limit)
// request['limit'] = parseInt (limit);
let response = await this.privatePostReturnTradeHistory (this.extend (request, params));
let result = [];
if (market) {
result = this.parseTrades (response, market);
} else {
if (response) {
let ids = Object.keys (response);
for (let i = 0; i < ids.length; i++) {
let id = ids[i];
let market = undefined;
if (id in this.markets_by_id)
market = this.markets_by_id[id];
let trades = this.parseTrades (response[id], market);
for (let j = 0; j < trades.length; j++) {
result.push (trades[j]);
}
}
}
}
return this.filterBySinceLimit (result, since, limit);
}
parseOrder (order, market = undefined) {
let timestamp = this.safeInteger (order, 'timestamp');
if (!timestamp)
timestamp = this.parse8601 (order['date']);
let trades = undefined;
if ('resultingTrades' in order)
trades = this.parseTrades (order['resultingTrades'], market);
let symbol = undefined;
if (market)
symbol = market['symbol'];
let price = this.safeFloat (order, 'price');
let cost = this.safeFloat (order, 'total', 0.0);
let remaining = this.safeFloat (order, 'amount');
let amount = this.safeFloat (order, 'startingAmount', remaining);
let filled = undefined;
if (typeof amount !== 'undefined') {
if (typeof remaining !== 'undefined')
filled = amount - remaining;
}
if (typeof filled === 'undefined') {
if (typeof trades !== 'undefined') {
filled = 0;
cost = 0;
for (let i = 0; i < trades.length; i++) {
let trade = trades[i];
let tradeAmount = trade['amount'];
let tradePrice = trade['price'];
filled = this.sum (filled, tradeAmount);
cost += tradePrice * tradeAmount;
}
}
}
return {
'info': order,
'id': order['orderNumber'],
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'status': order['status'],
'symbol': symbol,
'type': order['type'],
'side': order['side'],
'price': price,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'trades': trades,
'fee': undefined,
};
}
parseOpenOrders (orders, market, result = []) {
for (let i = 0; i < orders.length; i++) {
let order = orders[i];
let extended = this.extend (order, {
'status': 'open',
'type': 'limit',
'side': order['type'],
'price': order['rate'],
});
result.push (this.parseOrder (extended, market));
}
return result;
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
if (symbol)
market = this.market (symbol);
let pair = market ? market['id'] : 'all';
let response = await this.privatePostReturnOpenOrders (this.extend ({
'currencyPair': pair,
}));
let openOrders = [];
if (market) {
openOrders = this.parseOpenOrders (response, market, openOrders);
} else {
let marketIds = Object.keys (response);
for (let i = 0; i < marketIds.length; i++) {
let marketId = marketIds[i];
let orders = response[marketId];
let m = this.markets_by_id[marketId];
openOrders = this.parseOpenOrders (orders, m, openOrders);
}
}
for (let j = 0; j < openOrders.length; j++) {
this.orders[openOrders[j]['id']] = openOrders[j];
}
let openOrdersIndexedById = this.indexBy (openOrders, 'id');
let cachedOrderIds = Object.keys (this.orders);
let result = [];
for (let k = 0; k < cachedOrderIds.length; k++) {
let id = cachedOrderIds[k];
if (id in openOrdersIndexedById) {
this.orders[id] = this.extend (this.orders[id], openOrdersIndexedById[id]);
} else {
let order = this.orders[id];
if (order['status'] === 'open') {
this.orders[id] = this.extend (order, {
'status': 'closed',
'cost': order['amount'] * order['price'],
'filled': order['amount'],
'remaining': 0.0,
});
}
}
let order = this.orders[id];
if (market) {
if (order['symbol'] === symbol)
result.push (order);
} else {
result.push (order);
}
}
return this.filterBySinceLimit (result, since, limit);
}
async fetchOrder (id, symbol = undefined, params = {}) {
let since = this.safeValue (params, 'since');
let limit = this.safeValue (params, 'limit');
let request = this.omit (params, [ 'since', 'limit' ]);
let orders = await this.fetchOrders (symbol, since, limit, request);
for (let i = 0; i < orders.length; i++) {
if (orders[i]['id'] === id)
return orders[i];
}
throw new OrderNotCached (this.id + ' order id ' + id.toString () + ' not found in cache');
}
filterOrdersByStatus (orders, status) {
let result = [];
for (let i = 0; i < orders.length; i++) {
if (orders[i]['status'] === status)
result.push (orders[i]);
}
return result;
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let orders = await this.fetchOrders (symbol, since, limit, params);
return this.filterOrdersByStatus (orders, 'open');
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let orders = await this.fetchOrders (symbol, since, limit, params);
return this.filterOrdersByStatus (orders, 'closed');
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
if (type === 'market')
throw new ExchangeError (this.id + ' allows limit orders only');
await this.loadMarkets ();
let method = 'privatePost' + this.capitalize (side);
let market = this.market (symbol);
price = parseFloat (price);
amount = parseFloat (amount);
let response = await this[method] (this.extend ({
'currencyPair': market['id'],
'rate': this.priceToPrecision (symbol, price),
'amount': this.amountToPrecision (symbol, amount),
}, params));
let timestamp = this.milliseconds ();
let order = this.parseOrder (this.extend ({
'timestamp': timestamp,
'status': 'open',
'type': type,
'side': side,
'price': price,
'amount': amount,
}, response), market);
let id = order['id'];
this.orders[id] = order;
return this.extend ({ 'info': response }, order);
}
async editOrder (id, symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
price = parseFloat (price);
let request = {
'orderNumber': id,
'rate': this.priceToPrecision (symbol, price),
};
if (typeof amount !== 'undefined') {
amount = parseFloat (amount);
request['amount'] = this.amountToPrecision (symbol, amount);
}
let response = await this.privatePostMoveOrder (this.extend (request, params));
let result = undefined;
if (id in this.orders) {
this.orders[id]['status'] = 'canceled';
let newid = response['orderNumber'];
this.orders[newid] = this.extend (this.orders[id], {
'id': newid,
'price': price,
'status': 'open',
});
if (typeof amount !== 'undefined')
this.orders[newid]['amount'] = amount;
result = this.extend (this.orders[newid], { 'info': response });
} else {
let market = undefined;
if (symbol)
market = this.market (symbol);
result = this.parseOrder (response, market);
this.orders[result['id']] = result;
}
return result;
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let response = undefined;
try {
response = await this.privatePostCancelOrder (this.extend ({
'orderNumber': id,
}, params));
if (id in this.orders)
this.orders[id]['status'] = 'canceled';
} catch (e) {
if (this.last_http_response) {
if (this.last_http_response.indexOf ('Invalid order') >= 0)
throw new OrderNotFound (this.id + ' cancelOrder() error: ' + this.last_http_response);
}
throw e;
}
return response;
}
async fetchOrderStatus (id, symbol = undefined) {
await this.loadMarkets ();
let orders = await this.fetchOpenOrders (symbol);
let indexed = this.indexBy (orders, 'id');
return (id in indexed) ? 'open' : 'closed';
}
async fetchOrderTrades (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let trades = await this.privatePostReturnOrderTrades (this.extend ({
'orderNumber': id,
}, params));
return this.parseTrades (trades);
}
async createDepositAddress (currency, params = {}) {
let currencyId = this.currencyId (currency);
let response = await this.privatePostGenerateNewAddress ({
'currency': currencyId,
});
let address = undefined;
if (response['success'] === 1)
address = this.safeString (response, 'response');
if (!address)
throw new ExchangeError (this.id + ' createDepositAddress failed: ' + this.last_http_response);
return {
'currency': currency,
'address': address,
'status': 'ok',
'info': response,
};
}
async fetchDepositAddress (currency, params = {}) {
let response = await this.privatePostReturnDepositAddresses ();
let currencyId = this.currencyId (currency);
let address = this.safeString (response, currencyId);
let status = address ? 'ok' : 'none';
return {
'currency': currency,
'address': address,
'status': status,
'info': response,
};
}
async withdraw (currency, amount, address, tag = undefined, params = {}) {
await this.loadMarkets ();
let currencyId = this.currencyId (currency);
let request = {
'currency': currencyId,
'amount': amount,
'address': address,
};
if (tag)
request['paymentId'] = tag;
let result = await this.privatePostWithdraw (this.extend (request, params));
return {
'info': result,
'id': result['response'],
};
}
nonce () {
return this.milliseconds ();
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.urls['api'][api];
let query = this.extend ({ 'command': path }, params);
if (api === 'public') {
url += '?' + this.urlencode (query);
} else {
this.checkRequiredCredentials ();
query['nonce'] = this.nonce ();
body = this.urlencode (query);
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': this.apiKey,
'Sign': this.hmac (this.encode (body), this.encode (this.secret), 'sha512'),
};
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (code, reason, url, method, headers, body) {
if (code >= 400) {
if (body[0] === '{') {
let response = JSON.parse (body);
if ('error' in response) {
let error = this.id + ' ' + body;
if (response['error'].indexOf ('Total must be at least') >= 0) {
throw new InvalidOrder (error);
} else if (response['error'].indexOf ('Not enough') >= 0) {
throw new InsufficientFunds (error);
} else if (response['error'].indexOf ('Nonce must be greater') >= 0) {
throw new ExchangeNotAvailable (error);
} else if (response['error'].indexOf ('You have already called cancelOrder or moveOrder on this order.') >= 0) {
throw new CancelPending (error);
}
}
}
}
}
async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let response = await this.fetch2 (path, api, method, params, headers, body);
if ('error' in response) {
let error = this.id + ' ' + this.json (response);
let failed = response['error'].indexOf ('Not enough') >= 0;
if (failed)
throw new InsufficientFunds (error);
throw new ExchangeError (error);
}
return response;
}
}