forked from ccxt/ccxt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgatecoin.js
701 lines (675 loc) · 32.7 KB
/
gatecoin.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
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, AuthenticationError, InvalidAddress, InsufficientFunds, OrderNotFound, InvalidOrder, PermissionDenied } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class gatecoin extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'gatecoin',
'name': 'Gatecoin',
'rateLimit': 2000,
'countries': [ 'HK' ], // Hong Kong
'comment': 'a regulated/licensed exchange',
'has': {
'CORS': false,
'createDepositAddress': true,
'fetchDepositAddress': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchTickers': true,
'withdraw': true,
},
'timeframes': {
'1m': '1m',
'15m': '15m',
'1h': '1h',
'6h': '6h',
'1d': '24h',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28646817-508457f2-726c-11e7-9eeb-3528d2413a58.jpg',
'api': 'https://api.gatecoin.com',
'www': 'https://gatecoin.com',
'doc': [
'https://gatecoin.com/api',
'https://github.com/Gatecoin/RESTful-API-Implementation',
'https://api.gatecoin.com/swagger-ui/index.html',
],
},
'api': {
'public': {
'get': [
'Public/ExchangeRate', // Get the exchange rates
'Public/LiveTicker', // Get live ticker for all currency
'Public/LiveTicker/{CurrencyPair}', // Get live ticker by currency
'Public/LiveTickers', // Get live ticker for all currency
'Public/MarketDepth/{CurrencyPair}', // Gets prices and market depth for the currency pair.
'Public/NetworkStatistics/{DigiCurrency}', // Get the network status of a specific digital currency
'Public/StatisticHistory/{DigiCurrency}/{Typeofdata}', // Get the historical data of a specific digital currency
'Public/TickerHistory/{CurrencyPair}/{Timeframe}', // Get ticker history
'Public/Transactions/{CurrencyPair}', // Gets recent transactions
'Public/TransactionsHistory/{CurrencyPair}', // Gets all transactions
'Reference/BusinessNatureList', // Get the business nature list.
'Reference/Countries', // Get the country list.
'Reference/Currencies', // Get the currency list.
'Reference/CurrencyPairs', // Get the currency pair list.
'Reference/CurrentStatusList', // Get the current status list.
'Reference/IdentydocumentTypes', // Get the different types of identity documents possible.
'Reference/IncomeRangeList', // Get the income range list.
'Reference/IncomeSourceList', // Get the income source list.
'Reference/VerificationLevelList', // Get the verif level list.
'Stream/PublicChannel', // Get the public pubnub channel list
],
'post': [
'Export/Transactions', // Request a export of all trades from based on currencypair, start date and end date
'Ping', // Post a string, then get it back.
'Public/Unsubscribe/{EmailCode}', // Lets the user unsubscribe from emails
'RegisterUser', // Initial trader registration.
],
},
'private': {
'get': [
'Account/CorporateData', // Get corporate account data
'Account/DocumentAddress', // Check if residence proof uploaded
'Account/DocumentCorporation', // Check if registered document uploaded
'Account/DocumentID', // Check if ID document copy uploaded
'Account/DocumentInformation', // Get Step3 Data
'Account/Email', // Get user email
'Account/FeeRate', // Get fee rate of logged in user
'Account/Level', // Get verif level of logged in user
'Account/PersonalInformation', // Get Step1 Data
'Account/Phone', // Get user phone number
'Account/Profile', // Get trader profile
'Account/Questionnaire', // Fill the questionnaire
'Account/Referral', // Get referral information
'Account/ReferralCode', // Get the referral code of the logged in user
'Account/ReferralNames', // Get names of referred traders
'Account/ReferralReward', // Get referral reward information
'Account/ReferredCode', // Get referral code
'Account/ResidentInformation', // Get Step2 Data
'Account/SecuritySettings', // Get verif details of logged in user
'Account/User', // Get all user info
'APIKey/APIKey', // Get API Key for logged in user
'Auth/ConnectionHistory', // Gets connection history of logged in user
'Balance/Balances', // Gets the available balance for each currency for the logged in account.
'Balance/Balances/{Currency}', // Gets the available balance for s currency for the logged in account.
'Balance/Deposits', // Get all account deposits, including wire and digital currency, of the logged in user
'Balance/Withdrawals', // Get all account withdrawals, including wire and digital currency, of the logged in user
'Bank/Accounts/{Currency}/{Location}', // Get internal bank account for deposit
'Bank/Transactions', // Get all account transactions of the logged in user
'Bank/UserAccounts', // Gets all the bank accounts related to the logged in user.
'Bank/UserAccounts/{Currency}', // Gets all the bank accounts related to the logged in user.
'ElectronicWallet/DepositWallets', // Gets all crypto currency addresses related deposits to the logged in user.
'ElectronicWallet/DepositWallets/{DigiCurrency}', // Gets all crypto currency addresses related deposits to the logged in user by currency.
'ElectronicWallet/Transactions', // Get all digital currency transactions of the logged in user
'ElectronicWallet/Transactions/{DigiCurrency}', // Get all digital currency transactions of the logged in user
'ElectronicWallet/UserWallets', // Gets all external digital currency addresses related to the logged in user.
'ElectronicWallet/UserWallets/{DigiCurrency}', // Gets all external digital currency addresses related to the logged in user by currency.
'Info/ReferenceCurrency', // Get user's reference currency
'Info/ReferenceLanguage', // Get user's reference language
'Notification/Messages', // Get from oldest unread + 3 read message to newest messages
'Trade/Orders', // Gets open orders for the logged in trader.
'Trade/Orders/{OrderID}', // Gets an order for the logged in trader.
'Trade/StopOrders', // Gets all stop orders for the logged in trader. Max 1000 record.
'Trade/StopOrdersHistory', // Gets all stop orders for the logged in trader. Max 1000 record.
'Trade/Trades', // Gets all transactions of logged in user
'Trade/UserTrades', // Gets all transactions of logged in user
],
'post': [
'Account/DocumentAddress', // Upload address proof document
'Account/DocumentCorporation', // Upload registered document document
'Account/DocumentID', // Upload ID document copy
'Account/Email/RequestVerify', // Request for verification email
'Account/Email/Verify', // Verification email
'Account/GoogleAuth', // Enable google auth
'Account/Level', // Request verif level of logged in user
'Account/Questionnaire', // Fill the questionnaire
'Account/Referral', // Post a referral email
'APIKey/APIKey', // Create a new API key for logged in user
'Auth/ChangePassword', // Change password.
'Auth/ForgotPassword', // Request reset password
'Auth/ForgotUserID', // Request user id
'Auth/Login', // Trader session log in.
'Auth/Logout', // Logout from the current session.
'Auth/LogoutOtherSessions', // Logout other sessions.
'Auth/ResetPassword', // Reset password
'Bank/Transactions', // Request a transfer from the traders account of the logged in user. This is only available for bank account
'Bank/UserAccounts', // Add an account the logged in user
'ElectronicWallet/DepositWallets/{DigiCurrency}', // Add an digital currency addresses to the logged in user.
'ElectronicWallet/Transactions/Deposits/{DigiCurrency}', // Get all internal digital currency transactions of the logged in user
'ElectronicWallet/Transactions/Withdrawals/{DigiCurrency}', // Get all external digital currency transactions of the logged in user
'ElectronicWallet/UserWallets/{DigiCurrency}', // Add an external digital currency addresses to the logged in user.
'ElectronicWallet/Withdrawals/{DigiCurrency}', // Request a transfer from the traders account to an external address. This is only available for crypto currencies.
'Notification/Messages', // Mark all as read
'Notification/Messages/{ID}', // Mark as read
'Trade/Orders', // Place an order at the exchange.
'Trade/StopOrders', // Place a stop order at the exchange.
],
'put': [
'Account/CorporateData', // Update user company data for corporate account
'Account/DocumentID', // Update ID document meta data
'Account/DocumentInformation', // Update Step3 Data
'Account/Email', // Update user email
'Account/PersonalInformation', // Update Step1 Data
'Account/Phone', // Update user phone number
'Account/Questionnaire', // update the questionnaire
'Account/ReferredCode', // Update referral code
'Account/ResidentInformation', // Update Step2 Data
'Account/SecuritySettings', // Update verif details of logged in user
'Account/User', // Update all user info
'Bank/UserAccounts', // Update the label of existing user bank accounnt
'ElectronicWallet/DepositWallets/{DigiCurrency}/{AddressName}', // Update the name of an address
'ElectronicWallet/UserWallets/{DigiCurrency}', // Update the name of an external address
'Info/ReferenceCurrency', // User's reference currency
'Info/ReferenceLanguage', // Update user's reference language
],
'delete': [
'APIKey/APIKey/{PublicKey}', // Remove an API key
'Bank/Transactions/{RequestID}', // Delete pending account withdraw of the logged in user
'Bank/UserAccounts/{Currency}/{Label}', // Delete an account of the logged in user
'ElectronicWallet/DepositWallets/{DigiCurrency}/{AddressName}', // Delete an digital currency addresses related to the logged in user.
'ElectronicWallet/UserWallets/{DigiCurrency}/{AddressName}', // Delete an external digital currency addresses related to the logged in user.
'Trade/Orders', // Cancels all existing order
'Trade/Orders/{OrderID}', // Cancels an existing order
'Trade/StopOrders', // Cancels all existing stop orders
'Trade/StopOrders/{ID}', // Cancels an existing stop order
],
},
},
'fees': {
'trading': {
'maker': 0.0025,
'taker': 0.0035,
},
},
'commonCurrencies': {
'BCP': 'BCPT',
'FLI': 'FLIXX',
'MAN': 'MANA',
'SLT': 'SALT',
'TRA': 'TRAC',
'WGS': 'WINGS',
},
'exceptions': {
'1005': InsufficientFunds,
'1008': OrderNotFound,
'1057': InvalidOrder,
'1044': OrderNotFound, // already canceled,
'1054': OrderNotFound, // already executed
},
});
}
async fetchMarkets () {
let response = await this.publicGetReferenceCurrencyPairs ();
let markets = response['currencyPairs'];
let result = [];
for (let i = 0; i < markets.length; i++) {
let market = markets[i];
let id = market['tradingCode'];
let baseId = market['baseCurrency'];
let quoteId = market['quoteCurrency'];
let base = this.commonCurrencyCode (baseId);
let quote = this.commonCurrencyCode (quoteId);
let symbol = base + '/' + quote;
let precision = {
'amount': 8,
'price': market['priceDecimalPlaces'],
};
let limits = {
'amount': {
'min': Math.pow (10, -precision['amount']),
'max': undefined,
},
'price': {
'min': Math.pow (10, -precision['amount']),
'max': undefined,
},
'cost': {
'min': undefined,
'max': undefined,
},
};
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': true,
'precision': precision,
'limits': limits,
'info': market,
});
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let response = await this.privateGetBalanceBalances ();
let balances = response['balances'];
let result = { 'info': balances };
for (let b = 0; b < balances.length; b++) {
let balance = balances[b];
let currencyId = balance['currency'];
let code = currencyId;
if (currencyId in this.currencies_by_id)
code = this.currencies_by_id[currencyId]['code'];
let account = {
'free': balance['availableBalance'],
'used': this.sum (
balance['pendingIncoming'],
balance['pendingOutgoing'],
balance['openOrder']
),
'total': balance['balance'],
};
result[code] = account;
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let orderbook = await this.publicGetPublicMarketDepthCurrencyPair (this.extend ({
'CurrencyPair': market['id'],
}, params));
return this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price', 'volume');
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let response = await this.privateGetTradeOrdersOrderID (this.extend ({
'OrderID': id,
}, params));
return this.parseOrder (response.order);
}
parseTicker (ticker, market = undefined) {
let timestamp = parseInt (ticker['createDateTime']) * 1000;
let symbol = undefined;
if (market)
symbol = market['symbol'];
let baseVolume = this.safeFloat (ticker, 'volume');
let vwap = this.safeFloat (ticker, 'vwap');
let quoteVolume = baseVolume * vwap;
let last = this.safeFloat (ticker, 'last');
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeFloat (ticker, 'high'),
'low': this.safeFloat (ticker, 'low'),
'bid': this.safeFloat (ticker, 'bid'),
'bidVolume': undefined,
'ask': this.safeFloat (ticker, 'ask'),
'askVolume': undefined,
'vwap': vwap,
'open': this.safeFloat (ticker, 'open'),
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
};
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
let response = await this.publicGetPublicLiveTickers (params);
let tickers = response['tickers'];
let result = {};
for (let t = 0; t < tickers.length; t++) {
let ticker = tickers[t];
let id = ticker['currencyPair'];
let market = this.markets_by_id[id];
let symbol = market['symbol'];
result[symbol] = this.parseTicker (ticker, market);
}
return result;
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.publicGetPublicLiveTickerCurrencyPair (this.extend ({
'CurrencyPair': market['id'],
}, params));
let ticker = response['ticker'];
return this.parseTicker (ticker, market);
}
parseTrade (trade, market = undefined) {
let side = undefined;
let orderId = undefined;
if ('way' in trade) {
side = (trade['way'] === 'bid') ? 'buy' : 'sell';
let orderIdField = trade['way'] + 'OrderId';
orderId = this.safeString (trade, orderIdField);
}
let timestamp = parseInt (trade['transactionTime']) * 1000;
if (market === undefined) {
let marketId = this.safeString (trade, 'currencyPair');
if (marketId !== undefined)
market = this.findMarket (marketId);
}
let fee = undefined;
let feeCost = this.safeFloat (trade, 'feeAmount');
let price = trade['price'];
let amount = trade['quantity'];
let cost = price * amount;
let feeCurrency = undefined;
let symbol = undefined;
if (market !== undefined) {
symbol = market['symbol'];
feeCurrency = market['quote'];
}
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': feeCurrency,
'rate': this.safeFloat (trade, 'feeRate'),
};
}
return {
'info': trade,
'id': this.safeString (trade, 'transactionId'),
'order': orderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'side': side,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.publicGetPublicTransactionsCurrencyPair (this.extend ({
'CurrencyPair': market['id'],
}, params));
return this.parseTrades (response['transactions'], market, since, limit);
}
parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
return [
parseInt (ohlcv['createDateTime']) * 1000,
ohlcv['open'],
ohlcv['high'],
ohlcv['low'],
ohlcv['last'],
ohlcv['volume'],
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'CurrencyPair': market['id'],
'Timeframe': this.timeframes[timeframe],
};
if (limit !== undefined)
request['Count'] = limit;
request = this.extend (request, params);
let response = await this.publicGetPublicTickerHistoryCurrencyPairTimeframe (request);
let ohlcvs = this.parseOHLCVs (response['tickers'], market, timeframe, since, limit);
return this.sortBy (ohlcvs, 0);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let order = {
'Code': this.marketId (symbol),
'Way': (side === 'buy') ? 'Bid' : 'Ask',
'Amount': amount,
};
if (type === 'limit')
order['Price'] = price;
if (this.twofa) {
if ('ValidationCode' in params)
order['ValidationCode'] = params['ValidationCode'];
else
throw new AuthenticationError (this.id + ' two-factor authentication requires a missing ValidationCode parameter');
}
let response = await this.privatePostTradeOrders (this.extend (order, params));
// At this point response['responseStatus']['message'] has been verified in handleErrors ()
// to be == 'OK', so we assume the order has indeed been opened
return {
'info': response,
'status': 'open',
'id': this.safeString (response, 'clOrderId'), // response['clOrderId'],
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.privateDeleteTradeOrdersOrderID ({ 'OrderID': id });
return response;
}
parseOrderStatus (status) {
const statuses = {
'1': 'open', // New
'2': 'open', // Filling
'4': 'canceled',
'6': 'closed',
};
if (status in statuses)
return statuses[status];
return status;
}
parseOrder (order, market = undefined) {
let side = (order['side'] === 0) ? 'buy' : 'sell';
let type = (order['type'] === 0) ? 'limit' : 'market';
let symbol = undefined;
if (market === undefined) {
let marketId = this.safeString (order, 'code');
if (marketId in this.markets_by_id)
market = this.markets_by_id[marketId];
}
if (market !== undefined)
symbol = market['symbol'];
let timestamp = parseInt (order['date']) * 1000;
let amount = order['initialQuantity'];
let remaining = order['remainingQuantity'];
let filled = amount - remaining;
let price = order['price'];
let cost = price * filled;
let id = order['clOrderId'];
let status = this.parseOrderStatus (this.safeString (order, 'status'));
let trades = undefined;
let fee = undefined;
if (status === 'closed') {
let tradesFilled = undefined;
let tradesCost = undefined;
trades = [];
let transactions = this.safeValue (order, 'trades');
let feeCost = undefined;
let feeCurrency = undefined;
let feeRate = undefined;
if (transactions !== undefined) {
if (Array.isArray (transactions)) {
for (let i = 0; i < transactions.length; i++) {
let trade = this.parseTrade (transactions[i]);
if (tradesFilled === undefined)
tradesFilled = 0.0;
if (tradesCost === undefined)
tradesCost = 0.0;
tradesFilled += trade['amount'];
tradesCost += trade['amount'] * trade['price'];
if ('fee' in trade) {
if (trade['fee']['cost'] !== undefined) {
if (feeCost === undefined)
feeCost = 0.0;
feeCost += trade['fee']['cost'];
}
feeCurrency = trade['fee']['currency'];
if (trade['fee']['rate'] !== undefined) {
if (feeRate === undefined)
feeRate = 0.0;
feeRate += trade['fee']['rate'];
}
}
trades.push (trade);
}
if ((tradesFilled !== undefined) && (tradesFilled > 0))
price = tradesCost / tradesFilled;
if (feeRate !== undefined) {
let numTrades = trades.length;
if (numTrades > 0)
feeRate = feeRate / numTrades;
}
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': feeCurrency,
'rate': feeRate,
};
}
}
}
}
let result = {
'id': id,
'datetime': this.iso8601 (timestamp),
'timestamp': timestamp,
'lastTradeTimestamp': undefined,
'status': status,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'amount': amount,
'filled': filled,
'remaining': remaining,
'cost': cost,
'trades': trades,
'fee': fee,
'info': order,
};
return result;
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let response = await this.privateGetTradeOrders ();
let orders = this.parseOrders (response['orders'], undefined, since, limit);
if (symbol !== undefined)
return this.filterBySymbol (orders, symbol);
return orders;
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.urls['api'] + '/' + this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path));
if (api === 'public') {
if (Object.keys (query).length)
url += '?' + this.urlencode (query);
} else {
this.checkRequiredCredentials ();
let nonce = this.nonce ();
let nonceString = nonce.toString ();
let contentType = (method === 'GET') ? '' : 'application/json';
let auth = method + url + contentType + nonceString;
auth = auth.toLowerCase ();
let signature = this.hmac (this.encode (auth), this.encode (this.secret), 'sha256', 'base64');
headers = {
'API_PUBLIC_KEY': this.apiKey,
'API_REQUEST_SIGNATURE': this.decode (signature),
'API_REQUEST_DATE': nonceString,
};
if (method !== 'GET') {
headers['Content-Type'] = contentType;
body = this.json (this.extend ({ 'nonce': nonce }, params));
}
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
this.checkAddress (address);
await this.loadMarkets ();
let currency = this.currency (code);
let request = {
'DigiCurrency': currency['id'],
'Address': address,
'Amount': amount,
};
let response = await this.privatePostElectronicWalletWithdrawalsDigiCurrency (this.extend (request, params));
return {
'info': response,
'id': this.safeString (response, 'id'),
};
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
let currency = this.currency (code);
let request = {
'DigiCurrency': currency['id'],
};
let response = await this.privateGetElectronicWalletDepositWalletsDigiCurrency (this.extend (request, params));
let result = response['addresses'];
let numResults = result.length;
if (numResults < 1)
throw new InvalidAddress (this.id + ' privateGetElectronicWalletDepositWalletsDigiCurrency() returned no addresses');
let address = this.safeString (result[0], 'address');
this.checkAddress (address);
return {
'currency': code,
'address': address,
'info': response,
};
}
async createDepositAddress (code, params = {}) {
await this.loadMarkets ();
let currency = this.currency (code);
let request = {
'DigiCurrency': currency['id'],
};
let response = await this.privatePostElectronicWalletDepositWalletsDigiCurrency (this.extend (request, params));
let address = response['address'];
this.checkAddress (address);
return {
'currency': code,
'address': address,
'info': response,
};
}
async createUserWallet (code, address, name, password, params = {}) {
await this.loadMarkets ();
let currency = this.currency (code);
let request = {
'DigiCurrency': currency['id'],
'AddressName': name,
'Address': address,
'Password': password,
};
// not unified yet
return await this.privatePostElectronicWalletUserWalletsDigiCurrency (this.extend (request, params));
}
handleErrors (code, reason, url, method, headers, body) {
if (typeof body !== 'string')
return; // fallback to default error handler
if (body.length < 2)
return; // fallback to default error handler
if (body.indexOf ('You are not authorized') >= 0) {
throw new PermissionDenied (body);
}
if (body[0] === '{') {
let response = JSON.parse (body);
if ('responseStatus' in response) {
let errorCode = this.safeString (response['responseStatus'], 'errorCode');
let message = this.safeString (response['responseStatus'], 'message');
const feedback = this.id + ' ' + body;
if (errorCode !== undefined) {
const exceptions = this.exceptions;
if (errorCode in exceptions) {
throw new exceptions[errorCode] (feedback);
}
throw new ExchangeError (feedback);
// Sometimes there isn't 'errorCode' but 'message' is present and is not 'OK'
} else if (message !== undefined && message !== 'OK') {
throw new ExchangeError (feedback);
}
}
}
}
};