-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkucoin.js
814 lines (786 loc) · 31.3 KB
/
kucoin.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
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, InvalidNonce, InvalidOrder, AuthenticationError, InsufficientFunds, OrderNotFound } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class kucoin extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'kucoin',
'name': 'Kucoin',
'countries': 'HK', // Hong Kong
'version': 'v1',
'rateLimit': 2000,
'userAgent': this.userAgents['chrome'],
'has': {
'CORS': false,
'cancelOrders': true,
'createMarketOrder': false,
'fetchDepositAddress': true,
'fetchTickers': true,
'fetchOHLCV': true, // see the method implementation below
'fetchOrder': true,
'fetchOrders': false,
'fetchClosedOrders': true,
'fetchOpenOrders': true,
'fetchMyTrades': true,
'fetchCurrencies': true,
'withdraw': true,
},
'timeframes': {
'1m': 1,
'5m': 5,
'15m': 15,
'30m': 30,
'1h': 60,
'8h': 480,
'1d': 'D',
'1w': 'W',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/33795655-b3c46e48-dcf6-11e7-8abe-dc4588ba7901.jpg',
'api': {
'public': 'https://api.kucoin.com',
'private': 'https://api.kucoin.com',
'kitchen': 'https://kitchen.kucoin.com',
'kitchen-2': 'https://kitchen-2.kucoin.com',
},
'www': 'https://kucoin.com',
'doc': 'https://kucoinapidocs.docs.apiary.io',
'fees': 'https://news.kucoin.com/en/fee',
},
'api': {
'kitchen': {
'get': [
'open/chart/history',
],
},
'public': {
'get': [
'open/chart/config',
'open/chart/history',
'open/chart/symbol',
'open/currencies',
'open/deal-orders',
'open/kline',
'open/lang-list',
'open/orders',
'open/orders-buy',
'open/orders-sell',
'open/tick',
'market/open/coin-info',
'market/open/coins',
'market/open/coins-trending',
'market/open/symbols',
],
},
'private': {
'get': [
'account/balance',
'account/{coin}/wallet/address',
'account/{coin}/wallet/records',
'account/{coin}/balance',
'account/promotion/info',
'account/promotion/sum',
'deal-orders',
'order/active',
'order/active-map',
'order/dealt',
'order/detail',
'referrer/descendant/count',
'user/info',
],
'post': [
'account/{coin}/withdraw/apply',
'account/{coin}/withdraw/cancel',
'account/promotion/draw',
'cancel-order',
'order',
'order/cancel-all',
'user/change-lang',
],
},
},
'fees': {
'trading': {
'maker': 0.001,
'taker': 0.001,
},
'funding': {
'tierBased': false,
'percentage': false,
'withdraw': {
'KCS': 2.0,
'BTC': 0.0005,
'USDT': 10.0,
'ETH': 0.01,
'LTC': 0.001,
'NEO': 0.0,
'GAS': 0.0,
'KNC': 0.5,
'BTM': 5.0,
'QTUM': 0.1,
'EOS': 0.5,
'CVC': 3.0,
'OMG': 0.1,
'PAY': 0.5,
'SNT': 20.0,
'BHC': 1.0,
'HSR': 0.01,
'WTC': 0.1,
'VEN': 2.0,
'MTH': 10.0,
'RPX': 1.0,
'REQ': 20.0,
'EVX': 0.5,
'MOD': 0.5,
'NEBL': 0.1,
'DGB': 0.5,
'CAG': 2.0,
'CFD': 0.5,
'RDN': 0.5,
'UKG': 5.0,
'BCPT': 5.0,
'PPT': 0.1,
'BCH': 0.0005,
'STX': 2.0,
'NULS': 1.0,
'GVT': 0.1,
'HST': 2.0,
'PURA': 0.5,
'SUB': 2.0,
'QSP': 5.0,
'POWR': 1.0,
'FLIXX': 10.0,
'LEND': 20.0,
'AMB': 3.0,
'RHOC': 2.0,
'R': 2.0,
'DENT': 50.0,
'DRGN': 1.0,
'ACT': 0.1,
},
'deposit': 0.00,
},
},
});
}
async fetchMarkets () {
let response = await this.publicGetMarketOpenSymbols ();
let markets = response['data'];
let result = [];
for (let i = 0; i < markets.length; i++) {
let market = markets[i];
let id = market['symbol'];
let base = market['coinType'];
let quote = market['coinTypePair'];
base = this.commonCurrencyCode (base);
quote = this.commonCurrencyCode (quote);
let symbol = base + '/' + quote;
let precision = {
'amount': 8,
'price': 8,
};
let active = market['trading'];
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'active': active,
'taker': this.safeFloat (market, 'feeRate'),
'maker': this.safeFloat (market, 'feeRate'),
'info': market,
'lot': Math.pow (10, -precision['amount']),
'precision': precision,
'limits': {
'amount': {
'min': Math.pow (10, -precision['amount']),
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
},
});
}
return result;
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
let currency = this.currency (code);
let response = await this.privateGetAccountCoinWalletAddress (this.extend ({
'coin': currency['id'],
}, params));
let data = response['data'];
let address = this.safeString (data, 'address');
let tag = this.safeString (data, 'userOid');
return {
'currency': code,
'address': address,
'tag': tag,
'status': 'ok',
'info': response,
};
}
async fetchCurrencies (params = {}) {
let response = await this.publicGetMarketOpenCoins (params);
let currencies = response['data'];
let result = {};
for (let i = 0; i < currencies.length; i++) {
let currency = currencies[i];
let id = currency['coin'];
// todo: will need to rethink the fees
// to add support for multiple withdrawal/deposit methods and
// differentiated fees for each particular method
let code = this.commonCurrencyCode (id);
let precision = currency['tradePrecision'];
let deposit = currency['enableDeposit'];
let withdraw = currency['enableWithdraw'];
let active = (deposit && withdraw);
result[code] = {
'id': id,
'code': code,
'info': currency,
'name': currency['name'],
'active': active,
'status': 'ok',
'fee': currency['withdrawMinFee'], // 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['withdrawMinAmount'],
'max': Math.pow (10, precision),
},
},
};
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let response = await this.privateGetAccountBalance (this.extend ({
'limit': 20, // default 12, max 20
'page': 1,
}, params));
let balances = response['data'];
let result = { 'info': balances };
let indexed = this.indexBy (balances, 'coinType');
let keys = Object.keys (indexed);
for (let i = 0; i < keys.length; i++) {
let id = keys[i];
let currency = this.commonCurrencyCode (id);
let account = this.account ();
let balance = indexed[id];
let used = parseFloat (balance['freezeBalance']);
let free = parseFloat (balance['balance']);
let total = this.sum (free, used);
account['free'] = free;
account['used'] = used;
account['total'] = total;
result[currency] = account;
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.publicGetOpenOrders (this.extend ({
'symbol': market['id'],
}, params));
let orderbook = response['data'];
return this.parseOrderBook (orderbook, undefined, 'BUY', 'SELL');
}
parseOrder (order, market = undefined) {
let symbol = undefined;
if (market) {
symbol = market['symbol'];
} else {
symbol = order['coinType'] + '/' + order['coinTypePair'];
}
let timestamp = this.safeValue (order, 'createdAt');
let price = this.safeFloat (order, 'price');
if (typeof price === 'undefined')
price = this.safeFloat (order, 'dealPrice');
if (typeof price === 'undefined')
price = this.safeFloat (order, 'dealPriceAverage');
if (typeof price === 'undefined')
price = this.safeFloat (order, 'orderPrice');
let remaining = this.safeFloat (order, 'pendingAmount');
let status = this.safeValue (order, 'status');
let filled = this.safeFloat (order, 'dealAmount');
if (typeof status === 'undefined') {
if (typeof remaining !== 'undefined')
if (remaining > 0)
status = 'open';
else
status = 'closed';
}
if (typeof filled === 'undefined') {
if (typeof status !== 'undefined')
if (status === 'closed')
filled = this.safeFloat (order, 'amount');
}
let amount = this.safeFloat (order, 'amount');
let cost = this.safeFloat (order, 'dealValue');
if (typeof cost === 'undefined')
cost = this.safeFloat (order, 'dealValueTotal');
if (typeof filled !== 'undefined') {
if (typeof price !== 'undefined') {
if (typeof cost === 'undefined')
cost = price * filled;
}
if (typeof amount === 'undefined') {
if (typeof remaining !== 'undefined')
amount = this.sum (filled, remaining);
} else if (typeof remaining === 'undefined') {
remaining = amount - filled;
}
}
if ((status === 'open') && (typeof cost === 'undefined'))
cost = price * amount;
let side = this.safeValue (order, 'direction');
if (typeof side === 'undefined')
side = order['type'];
if (typeof side !== 'undefined')
side = side.toLowerCase ();
let feeCurrency = undefined;
if (market) {
feeCurrency = (side === 'sell') ? market['quote'] : market['base'];
} else {
let feeCurrencyField = (side === 'sell') ? 'coinTypePair' : 'coinType';
let feeCurrency = this.safeString (order, feeCurrencyField);
if (typeof feeCurrency !== 'undefined') {
if (feeCurrency in this.currencies_by_id)
feeCurrency = this.currencies_by_id[feeCurrency]['code'];
}
}
let feeCost = this.safeFloat (order, 'fee');
let fee = {
'cost': this.safeFloat (order, 'feeTotal', feeCost),
'rate': this.safeFloat (order, 'feeRate'),
'currency': feeCurrency,
};
// todo: parse order trades and fill fees from 'datas'
// do not confuse trades with orders
let orderId = this.safeString (order, 'orderOid');
if (typeof orderId === 'undefined')
orderId = this.safeString (order, 'oid');
let result = {
'info': order,
'id': orderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': 'limit',
'side': side,
'price': price,
'amount': amount,
'cost': cost,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': fee,
};
return result;
}
async fetchOrder (id, symbol = undefined, params = {}) {
if (typeof symbol === 'undefined')
throw new ExchangeError (this.id + ' fetchOrder requires a symbol argument');
let orderType = this.safeValue (params, 'type');
if (typeof orderType === 'undefined')
throw new ExchangeError (this.id + ' fetchOrder requires a type parameter ("BUY" or "SELL")');
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'symbol': market['id'],
'type': orderType,
'orderOid': id,
};
let response = await this.privateGetOrderDetail (this.extend (request, params));
let order = response['data'];
if (!order)
throw new OrderNotFound (this.id + ' ' + this.json (response));
return this.parseOrder (response['data'], market);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (!symbol)
throw new ExchangeError (this.id + ' fetchOpenOrders requires a symbol');
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'symbol': market['id'],
};
let response = await this.privateGetOrderActiveMap (this.extend (request, params));
let orders = this.arrayConcat (response['data']['SELL'], response['data']['BUY']);
let result = [];
for (let i = 0; i < orders.length; i++) {
result.push (this.extend (orders[i], { 'status': 'open' }));
}
return this.parseOrders (result, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let request = {};
await this.loadMarkets ();
let market = undefined;
if (typeof symbol !== 'undefined') {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (typeof since !== 'undefined')
request['since'] = since;
if (typeof limit !== 'undefined')
request['limit'] = limit;
let response = await this.privateGetOrderDealt (this.extend (request, params));
let orders = response['data']['datas'];
let result = [];
for (let i = 0; i < orders.length; i++) {
result.push (this.extend (orders[i], { 'status': 'closed' }));
}
return this.parseOrders (result, market, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
if (type !== 'limit')
throw new ExchangeError (this.id + ' allows limit orders only');
await this.loadMarkets ();
let market = this.market (symbol);
let base = market['base'];
let order = {
'symbol': market['id'],
'type': side.toUpperCase (),
'price': this.priceToPrecision (symbol, price),
'amount': this.truncate (amount, this.currencies[base]['precision']),
};
let response = await this.privatePostOrder (this.extend (order, params));
return {
'info': response,
'id': this.safeString (response['data'], 'orderOid'),
};
}
async cancelOrders (symbol = undefined, params = {}) {
// https://kucoinapidocs.docs.apiary.io/#reference/0/trading/cancel-all-orders
// docs say symbol is required, but it seems to be optional
// you can cancel all orders, or filter by symbol or type or both
let request = {};
if (symbol) {
await this.loadMarkets ();
let market = this.market (symbol);
request['symbol'] = market['id'];
}
if ('type' in params) {
request['type'] = params['type'].toUpperCase ();
params = this.omit (params, 'type');
}
let response = await this.privatePostOrderCancelAll (this.extend (request, params));
return response;
}
async cancelOrder (id, symbol = undefined, params = {}) {
if (!symbol)
throw new ExchangeError (this.id + ' cancelOrder requires a symbol');
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'symbol': market['id'],
'orderOid': id,
};
if ('type' in params) {
request['type'] = params['type'].toUpperCase ();
params = this.omit (params, 'type');
} else {
throw new ExchangeError (this.id + ' cancelOrder requires parameter type=["BUY"|"SELL"]');
}
let response = await this.privatePostCancelOrder (this.extend (request, params));
return response;
}
parseTicker (ticker, market = undefined) {
let timestamp = ticker['datetime'];
let symbol = undefined;
if (market) {
symbol = market['symbol'];
} else {
symbol = ticker['coinType'] + '/' + ticker['coinTypePair'];
}
// TNC coin doesn't have changerate for some reason
let change = this.safeFloat (ticker, 'changeRate');
if (typeof change !== 'undefined')
change *= 100;
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeFloat (ticker, 'high'),
'low': this.safeFloat (ticker, 'low'),
'bid': this.safeFloat (ticker, 'buy'),
'ask': this.safeFloat (ticker, 'sell'),
'vwap': undefined,
'open': undefined,
'close': undefined,
'first': undefined,
'last': this.safeFloat (ticker, 'lastDealPrice'),
'change': change,
'percentage': undefined,
'average': undefined,
'baseVolume': this.safeFloat (ticker, 'vol'),
'quoteVolume': this.safeFloat (ticker, 'volValue'),
'info': ticker,
};
}
async fetchTickers (symbols = undefined, params = {}) {
let response = await this.publicGetMarketOpenSymbols (params);
let tickers = response['data'];
let result = {};
for (let t = 0; t < tickers.length; t++) {
let ticker = this.parseTicker (tickers[t]);
let symbol = ticker['symbol'];
result[symbol] = ticker;
}
return result;
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.publicGetOpenTick (this.extend ({
'symbol': market['id'],
}, params));
let ticker = response['data'];
return this.parseTicker (ticker, market);
}
parseTrade (trade, market = undefined) {
let id = undefined;
let order = undefined;
let info = trade;
let timestamp = undefined;
let type = undefined;
let side = undefined;
let price = undefined;
let cost = undefined;
let amount = undefined;
let fee = undefined;
if (Array.isArray (trade)) {
timestamp = trade[0];
type = 'limit';
if (trade[1] === 'BUY') {
side = 'buy';
} else if (trade[1] === 'SELL') {
side = 'sell';
}
price = trade[2];
amount = trade[3];
} else {
timestamp = this.safeValue (trade, 'createdAt');
order = this.safeString (trade, 'orderOid');
if (typeof order === 'undefined')
order = this.safeString (trade, 'oid');
side = trade['dealDirection'].toLowerCase ();
price = this.safeFloat (trade, 'dealPrice');
amount = this.safeFloat (trade, 'amount');
cost = this.safeFloat (trade, 'dealValue');
let feeCurrency = undefined;
if ('coinType' in trade) {
feeCurrency = this.safeString (trade, 'coinType');
if (typeof feeCurrency !== 'undefined')
if (feeCurrency in this.currencies_by_id)
feeCurrency = this.currencies_by_id[feeCurrency]['code'];
}
fee = {
'cost': this.safeFloat (trade, 'fee'),
'currency': feeCurrency,
};
}
let symbol = undefined;
if (typeof market !== 'undefined')
symbol = market['symbol'];
return {
'id': id,
'order': order,
'info': info,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'cost': cost,
'amount': amount,
'fee': fee,
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.publicGetOpenDealOrders (this.extend ({
'symbol': market['id'],
}, params));
return this.parseTrades (response['data'], market, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (!symbol)
throw new ExchangeError (this.id + ' fetchMyTrades requires a symbol argument');
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'symbol': market['id'],
};
if (limit)
request['limit'] = limit;
let response = await this.privateGetDealOrders (this.extend (request, params));
return this.parseTrades (response['data']['datas'], market, since, limit);
}
parseTradingViewOHLCVs (ohlcvs, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
let result = [];
for (let i = 0; i < ohlcvs['t'].length; i++) {
result.push ([
ohlcvs['t'][i] * 1000,
ohlcvs['o'][i],
ohlcvs['h'][i],
ohlcvs['l'][i],
ohlcvs['c'][i],
ohlcvs['v'][i],
]);
}
return this.parseOHLCVs (result, market, timeframe, since, limit);
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let end = this.seconds ();
let resolution = this.timeframes[timeframe];
// convert 'resolution' to minutes in order to calculate 'from' later
let minutes = resolution;
if (minutes === 'D') {
if (typeof limit === 'undefined')
limit = 30; // 30 days, 1 month
minutes = 1440;
} else if (minutes === 'W') {
if (typeof limit === 'undefined')
limit = 52; // 52 weeks, 1 year
minutes = 10080;
} else if (typeof limit === 'undefined') {
// last 1440 periods, whatever the duration of the period is
// for 1m it equals 1 day (24 hours)
// for 5m it equals 5 days
// ...
limit = 1440;
}
let start = end - limit * minutes * 60;
// if 'since' has been supplied by user
if (typeof since !== 'undefined') {
start = parseInt (since / 1000); // convert milliseconds to seconds
end = Math.min (end, this.sum (start, limit * minutes * 60));
}
let request = {
'symbol': market['id'],
'resolution': resolution,
'from': start,
'to': end,
};
let response = await this.publicGetOpenChartHistory (this.extend (request, params));
return this.parseTradingViewOHLCVs (response, market, timeframe, since, limit);
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
await this.loadMarkets ();
let currency = this.currency (code);
let response = await this.privatePostAccountCoinWithdrawApply (this.extend ({
'coin': currency['id'],
'amount': amount,
'address': address,
}, params));
return {
'info': response,
'id': undefined,
};
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let endpoint = '/' + this.version + '/' + this.implodeParams (path, params);
let url = this.urls['api'][api] + endpoint;
let query = this.omit (params, this.extractParams (path));
if (api === 'private') {
this.checkRequiredCredentials ();
// their nonce is always a calibrated synched milliseconds-timestamp
let nonce = this.milliseconds ();
let queryString = '';
nonce = nonce.toString ();
if (Object.keys (query).length) {
queryString = this.rawencode (this.keysort (query));
url += '?' + queryString;
if (method !== 'GET') {
body = queryString;
}
}
let auth = endpoint + '/' + nonce + '/' + queryString;
let payload = this.stringToBase64 (this.encode (auth));
// payload should be "encoded" as returned from stringToBase64
let signature = this.hmac (payload, this.encode (this.secret), 'sha256');
headers = {
'KC-API-KEY': this.apiKey,
'KC-API-NONCE': nonce,
'KC-API-SIGNATURE': signature,
};
} else {
if (Object.keys (query).length)
url += '?' + this.urlencode (query);
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
throwExceptionOnError (response) {
//
// API endpoints return the following formats
// { success: false, code: "ERROR", msg: "Min price:100.0" }
// { success: true, code: "OK", msg: "Operation succeeded." }
//
// Web OHLCV endpoint returns this:
// { s: "ok", o: [], h: [], l: [], c: [], v: [] }
//
// This particular method handles API responses only
//
if (!('success' in response))
return;
if (response['success'] === true)
return; // not an error
if (!('code' in response) || !('msg' in response))
throw new ExchangeError (this.id + ': malformed response: ' + this.json (response));
const code = this.safeString (response, 'code');
const message = this.safeString (response, 'msg');
const feedback = this.id + ' ' + this.json (response);
if (code === 'UNAUTH') {
if (message === 'Invalid nonce')
throw new InvalidNonce (feedback);
throw new AuthenticationError (feedback);
} else if (code === 'ERROR') {
if (message.indexOf ('The precision of amount') >= 0)
throw new InvalidOrder (feedback); // amount violates precision.amount
if (message.indexOf ('Min amount each order') >= 0)
throw new InvalidOrder (feedback); // amount < limits.amount.min
if (message.indexOf ('Min price:') >= 0)
throw new InvalidOrder (feedback); // price < limits.price.min
if (message.indexOf ('The precision of price') >= 0)
throw new InvalidOrder (feedback); // price violates precision.price
} else if (code === 'NO_BALANCE') {
if (message.indexOf ('Insufficient balance') >= 0)
throw new InsufficientFunds (feedback);
}
throw new ExchangeError (this.id + ': unknown response: ' + this.json (response));
}
handleErrors (code, reason, url, method, headers, body, response = undefined) {
if (typeof response !== 'undefined') {
// JS callchain parses body beforehand
this.throwExceptionOnError (response);
} else if (body && (body[0] === '{')) {
// Python/PHP callchains don't have json available at this step
this.throwExceptionOnError (JSON.parse (body));
}
}
};