-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfcoin.js
538 lines (513 loc) · 19.7 KB
/
fcoin.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
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, ExchangeNotAvailable, InsufficientFunds, InvalidOrder, DDoSProtection, InvalidNonce, AuthenticationError, NotSupported } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class fcoin extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'fcoin',
'name': 'FCoin',
'countries': 'CN',
'rateLimit': 2000,
'userAgent': this.userAgents['chrome39'],
'version': 'v2',
'accounts': undefined,
'accountsById': undefined,
'hostname': 'api.fcoin.com',
'has': {
'CORS': false,
'fetchDepositAddress': false,
'fetchOHCLV': false,
'fetchOpenOrders': true,
'fetchClosedOrders': true,
'fetchOrder': true,
'fetchOrders': true,
'fetchOrderBook': true,
'fetchOrderBooks': false,
'fetchTradingLimits': false,
'withdraw': false,
'fetchCurrencies': false,
},
'timeframes': {
'1m': 'M1',
'3m': 'M3',
'5m': 'M5',
'15m': 'M15',
'30m': 'M30',
'1h': 'H1',
'1d': 'D1',
'1w': 'W1',
'1M': 'MN',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/42244210-c8c42e1e-7f1c-11e8-8710-a5fb63b165c4.jpg',
'api': 'https://api.fcoin.com',
'www': 'https://www.fcoin.com',
'referral': 'https://www.fcoin.com/i/Z5P7V',
'doc': 'https://developer.fcoin.com',
'fees': 'https://support.fcoin.com/hc/en-us/articles/360003715514-Trading-Rules',
},
'api': {
'market': {
'get': [
'ticker/{symbol}',
'depth/{level}/{symbol}',
'trades/{symbol}',
'candles/{timeframe}/{symbol}',
],
},
'public': {
'get': [
'symbols',
'currencies',
'server-time',
],
},
'private': {
'get': [
'accounts/balance',
'orders',
'orders/{order_id}',
'orders/{order_id}/match-results', // check order result
],
'post': [
'orders',
'orders/{order_id}/submit-cancel', // cancel order
],
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'maker': 0.001,
'taker': 0.001,
},
},
'limits': {
'amount': { 'min': 0.01, 'max': 100000 },
},
'options': {
'limits': {
'BTM/USDT': { 'amount': { 'min': 0.1, 'max': 10000000 }},
'ETC/USDT': { 'amount': { 'min': 0.001, 'max': 400000 }},
'ETH/USDT': { 'amount': { 'min': 0.001, 'max': 10000 }},
'LTC/USDT': { 'amount': { 'min': 0.001, 'max': 40000 }},
'BCH/USDT': { 'amount': { 'min': 0.001, 'max': 5000 }},
'BTC/USDT': { 'amount': { 'min': 0.001, 'max': 1000 }},
'ICX/ETH': { 'amount': { 'min': 0.01, 'max': 3000000 }},
'OMG/ETH': { 'amount': { 'min': 0.01, 'max': 500000 }},
'FT/USDT': { 'amount': { 'min': 1, 'max': 10000000 }},
'ZIL/ETH': { 'amount': { 'min': 1, 'max': 10000000 }},
'ZIP/ETH': { 'amount': { 'min': 1, 'max': 10000000 }},
'FT/BTC': { 'amount': { 'min': 1, 'max': 10000000 }},
'FT/ETH': { 'amount': { 'min': 1, 'max': 10000000 }},
},
},
'exceptions': {
'400': NotSupported, // Bad Request
'401': AuthenticationError,
'405': NotSupported,
'429': DDoSProtection, // Too Many Requests, exceed api request limit
'1002': ExchangeNotAvailable, // System busy
'1016': InsufficientFunds,
'3008': InvalidOrder,
'6004': InvalidNonce,
'6005': AuthenticationError, // Illegal API Signature
},
});
}
async fetchMarkets () {
let response = await this.publicGetSymbols ();
let result = [];
let markets = response['data'];
for (let i = 0; i < markets.length; i++) {
let market = markets[i];
let id = market['name'];
let baseId = market['base_currency'];
let quoteId = market['quote_currency'];
let base = baseId.toUpperCase ();
base = this.commonCurrencyCode (base);
let quote = quoteId.toUpperCase ();
quote = this.commonCurrencyCode (quote);
let symbol = base + '/' + quote;
let precision = {
'price': market['price_decimal'],
'amount': market['amount_decimal'],
};
let limits = {
'price': {
'min': Math.pow (10, -precision['price']),
'max': Math.pow (10, precision['price']),
},
};
if (symbol in this.options['limits']) {
limits = this.extend (this.options['limits'][symbol], limits);
}
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.privateGetAccountsBalance (params);
let result = { 'info': response };
let balances = response['data'];
for (let i = 0; i < balances.length; i++) {
let balance = balances[i];
let currencyId = balance['currency'];
let code = currencyId.toUpperCase ();
if (currencyId in this.currencies_by_id) {
code = this.currencies_by_id[currencyId]['code'];
} else {
code = this.commonCurrencyCode (code);
}
let account = this.account ();
account['free'] = parseFloat (balance['available']);
account['total'] = parseFloat (balance['balance']);
account['used'] = parseFloat (balance['frozen']);
result[code] = account;
}
return this.parseBalance (result);
}
parseBidsAsks (orders, priceKey = 0, amountKey = 1) {
let result = [];
let length = orders.length;
let halfLength = parseInt (length / 2);
// += 2 in the for loop below won't transpile
for (let i = 0; i < halfLength; i++) {
let index = i * 2;
let priceField = this.sum (index, priceKey);
let amountField = this.sum (index, amountKey);
result.push ([
orders[priceField],
orders[amountField],
]);
}
return result;
}
async fetchOrderBook (symbol = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
if (typeof limit !== 'undefined') {
if ((limit === 20) || (limit === 100)) {
limit = 'L' + limit.toString ();
} else {
throw new ExchangeError (this.id + ' fetchOrderBook supports limit of 20, 100 or no limit. Other values are not accepted');
}
} else {
limit = 'full';
}
let request = this.extend ({
'symbol': this.marketId (symbol),
'level': limit, // L20, L100, full
}, params);
let response = await this.marketGetDepthLevelSymbol (request);
let orderbook = response['data'];
return this.parseOrderBook (orderbook, orderbook['ts'], 'bids', 'asks', 0, 1);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let ticker = await this.marketGetTickerSymbol (this.extend ({
'symbol': market['id'],
}, params));
return this.parseTicker (ticker['data'], market);
}
parseTicker (ticker, market = undefined) {
let timestamp = undefined;
let symbol = undefined;
if (typeof market === 'undefined') {
let tickerType = this.safeString (ticker, 'type');
if (typeof tickerType !== 'undefined') {
let parts = tickerType.split ('.');
let id = parts[1];
if (id in this.markets_by_id) {
market = this.markets_by_id[id];
}
}
}
let values = ticker['ticker'];
let last = values[0];
if (typeof market !== 'undefined') {
symbol = market['symbol'];
}
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': values[7],
'low': values[8],
'bid': values[2],
'bidVolume': values[3],
'ask': values[4],
'askVolume': values[5],
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': values[9],
'quoteVolume': values[10],
'info': ticker,
};
}
parseTrade (trade, market = undefined) {
let symbol = undefined;
if (typeof market !== 'undefined') {
symbol = market['symbol'];
}
let timestamp = parseInt (trade['ts']);
let side = trade['side'].toLowerCase ();
let orderId = this.safeString (trade, 'id');
let price = this.safeFloat (trade, 'price');
let amount = this.safeFloat (trade, 'amount');
let cost = price * amount;
let fee = undefined;
return {
'id': orderId,
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'order': orderId,
'side': side,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
};
}
async fetchTrades (symbol, since = undefined, limit = 50, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'symbol': market['id'],
'limit': limit,
};
if (typeof since !== 'undefined') {
request['timestamp'] = parseInt (since / 1000);
}
let response = await this.marketGetTradesSymbol (this.extend (request, params));
return this.parseTrades (response['data'], market, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let orderType = type;
amount = this.amountToPrecision (symbol, amount);
let order = {
'symbol': this.marketId (symbol),
'amount': amount,
'side': side,
'type': orderType,
};
if (type === 'limit') {
order['price'] = this.priceToPrecision (symbol, price);
}
let result = await this.privatePostOrders (this.extend (order, params));
return result['data'];
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
return await this.privatePostOrdersOrderIdSubmitCancel (this.extend ({
'order_id': id,
}, params));
}
parseOrderStatus (status) {
const statuses = {
'submitted': 'open',
'canceled': 'canceled',
'partial_filled': 'open',
'partial_canceled': 'canceled',
'filled': 'closed',
'pending_cancel': 'canceled',
};
if (status in statuses) {
return statuses[status];
}
return status;
}
parseOrder (order, market = undefined) {
let id = order['id'];
let side = order['side'];
let status = this.parseOrderStatus (order['state']);
let symbol = undefined;
if (typeof market === 'undefined') {
let marketId = order['symbol'];
if (marketId in this.markets_by_id) {
market = this.markets_by_id[marketId];
}
}
let orderType = order['type'];
let timestamp = parseInt (order['created_at']);
let amount = this.safeFloat (order, 'amount');
let filled = this.safeFloat (order, 'filled_amount');
let remaining = undefined;
let price = this.safeFloat (order, 'price');
let cost = undefined;
if (typeof filled !== 'undefined') {
if (typeof amount !== 'undefined') {
remaining = amount - filled;
}
if (typeof price !== 'undefined') {
cost = price * filled;
}
}
let feeCurrency = undefined;
if (typeof market !== 'undefined') {
symbol = market['symbol'];
feeCurrency = (side === 'buy') ? market['base'] : market['quote'];
}
let feeCost = this.safeFloat (order, 'fill_fees');
let result = {
'info': order,
'id': id,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': orderType,
'side': side,
'price': price,
'cost': cost,
'amount': amount,
'remaining': remaining,
'filled': filled,
'average': undefined,
'status': status,
'fee': {
'cost': feeCost,
'currency': feeCurrency,
},
'trades': undefined,
};
return result;
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let request = this.extend ({
'order_id': id,
}, params);
let response = await this.privateGetOrdersOrderId (request);
return this.parseOrder (response['data']);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let result = await this.fetchOrders (symbol, since, limit, { 'states': 'submitted' });
return result;
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
let result = await this.fetchOrders (symbol, since, limit, { 'states': 'filled' });
return result;
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'symbol': market['id'],
'states': 'submitted',
};
if (typeof limit !== 'undefined')
request['limit'] = limit;
let response = await this.privateGetOrders (this.extend (request, params));
return this.parseOrders (response['data'], market, since, limit);
}
parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
return [
ohlcv['seq'],
ohlcv['open'],
ohlcv['high'],
ohlcv['low'],
ohlcv['close'],
ohlcv['base_vol'],
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = 100, params = {}) {
await this.loadMarkets ();
if (typeof limit === 'undefined') {
throw new ExchangeError (this.id + ' fetchOHLCV requires a limit argument');
}
let market = this.market (symbol);
let request = this.extend ({
'symbol': market['id'],
'timeframe': this.timeframes[timeframe],
'limit': limit,
}, params);
let response = await this.marketGetCandlesTimeframeSymbol (request);
return this.parseOHLCVs (response['data'], market, timeframe, since, limit);
}
nonce () {
return this.milliseconds ();
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let request = '/' + this.version + '/';
request += (api === 'private') ? '' : (api + '/');
request += this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path));
let url = this.urls['api'] + request;
if ((api === 'public') || (api === 'market')) {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
} else if (api === 'private') {
this.checkRequiredCredentials ();
let timestamp = this.nonce ().toString ();
query = this.keysort (query);
if (method === 'GET') {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
}
// HTTP_METHOD + HTTP_REQUEST_URI + TIMESTAMP + POST_BODY
let auth = method + url + timestamp;
if (method === 'POST') {
if (Object.keys (query).length) {
body = this.json (query);
auth += this.urlencode (query);
}
}
let payload = this.stringToBase64 (this.encode (auth));
let signature = this.hmac (payload, this.encode (this.secret), 'sha1', 'binary');
signature = this.decode (this.stringToBase64 (signature));
headers = {
'FC-ACCESS-KEY': this.apiKey,
'FC-ACCESS-SIGNATURE': signature,
'FC-ACCESS-TIMESTAMP': timestamp,
'Content-Type': 'application/json',
};
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
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[0] === '{') || (body[0] === '[')) {
const response = JSON.parse (body);
let status = this.safeString (response, 'status');
if (status !== '0') {
const feedback = this.id + ' ' + body;
if (status in this.exceptions) {
const exceptions = this.exceptions;
throw new exceptions[status] (feedback);
}
throw new ExchangeError (feedback);
}
}
}
};