-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitflyer.js
487 lines (466 loc) · 17.8 KB
/
bitflyer.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
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, ArgumentsRequired, OrderNotFound } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class bitflyer extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'bitflyer',
'name': 'bitFlyer',
'countries': [ 'JP' ],
'version': 'v1',
'rateLimit': 1000, // their nonce-timestamp is in seconds...
'has': {
'CORS': false,
'withdraw': true,
'fetchMyTrades': true,
'fetchOrders': true,
'fetchOrder': 'emulated',
'fetchOpenOrders': 'emulated',
'fetchClosedOrders': 'emulated',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28051642-56154182-660e-11e7-9b0d-6042d1e6edd8.jpg',
'api': 'https://api.bitflyer.jp',
'www': 'https://bitflyer.jp',
'doc': 'https://lightning.bitflyer.com/docs?lang=en',
},
'api': {
'public': {
'get': [
'getmarkets/usa', // new (wip)
'getmarkets/eu', // new (wip)
'getmarkets', // or 'markets'
'getboard', // ...
'getticker',
'getexecutions',
'gethealth',
'getboardstate',
'getchats',
],
},
'private': {
'get': [
'getpermissions',
'getbalance',
'getbalancehistory',
'getcollateral',
'getcollateralhistory',
'getcollateralaccounts',
'getaddresses',
'getcoinins',
'getcoinouts',
'getbankaccounts',
'getdeposits',
'getwithdrawals',
'getchildorders',
'getparentorders',
'getparentorder',
'getexecutions',
'getpositions',
'gettradingcommission',
],
'post': [
'sendcoin',
'withdraw',
'sendchildorder',
'cancelchildorder',
'sendparentorder',
'cancelparentorder',
'cancelallchildorders',
],
},
},
'fees': {
'trading': {
'maker': 0.2 / 100,
'taker': 0.2 / 100,
},
'BTC/JPY': {
'maker': 0.15 / 100,
'taker': 0.15 / 100,
},
},
});
}
async fetchMarkets (params = {}) {
const jp_markets = await this.publicGetGetmarkets (params);
const us_markets = await this.publicGetGetmarketsUsa (params);
const eu_markets = await this.publicGetGetmarketsEu (params);
let markets = this.arrayConcat (jp_markets, us_markets);
markets = this.arrayConcat (markets, eu_markets);
const result = [];
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'product_code');
const currencies = id.split ('_');
let baseId = undefined;
let quoteId = undefined;
let base = undefined;
let quote = undefined;
const numCurrencies = currencies.length;
if (numCurrencies === 1) {
baseId = id.slice (0, 3);
quoteId = id.slice (3, 6);
} else if (numCurrencies === 2) {
baseId = currencies[0];
quoteId = currencies[1];
} else {
baseId = currencies[1];
quoteId = currencies[2];
}
base = this.safeCurrencyCode (baseId);
quote = this.safeCurrencyCode (quoteId);
const symbol = (numCurrencies === 2) ? (base + '/' + quote) : id;
const fees = this.safeValue (this.fees, symbol, this.fees['trading']);
let maker = this.safeValue (fees, 'maker', this.fees['trading']['maker']);
let taker = this.safeValue (fees, 'taker', this.fees['trading']['taker']);
let spot = true;
let future = false;
let type = 'spot';
if (('alias' in market) || (currencies[0] === 'FX')) {
type = 'future';
future = true;
spot = false;
maker = 0.0;
taker = 0.0;
}
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'maker': maker,
'taker': taker,
'type': type,
'spot': spot,
'future': future,
'info': market,
});
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
const response = await this.privateGetGetbalance (params);
//
// [
// {
// "currency_code": "JPY",
// "amount": 1024078,
// "available": 508000
// },
// {
// "currency_code": "BTC",
// "amount": 10.24,
// "available": 4.12
// },
// {
// "currency_code": "ETH",
// "amount": 20.48,
// "available": 16.38
// }
// ]
//
const result = { 'info': response };
for (let i = 0; i < response.length; i++) {
const balance = response[i];
const currencyId = this.safeString (balance, 'currency_code');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['total'] = this.safeFloat (balance, 'amount');
account['free'] = this.safeFloat (balance, 'available');
result[code] = account;
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'product_code': this.marketId (symbol),
};
const orderbook = await this.publicGetGetboard (this.extend (request, params));
return this.parseOrderBook (orderbook, undefined, 'bids', 'asks', 'price', 'size');
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const request = {
'product_code': this.marketId (symbol),
};
const ticker = await this.publicGetGetticker (this.extend (request, params));
const timestamp = this.parse8601 (this.safeString (ticker, 'timestamp'));
const last = this.safeFloat (ticker, 'ltp');
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': undefined,
'low': undefined,
'bid': this.safeFloat (ticker, 'best_bid'),
'bidVolume': undefined,
'ask': this.safeFloat (ticker, 'best_ask'),
'askVolume': undefined,
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': this.safeFloat (ticker, 'volume_by_product'),
'quoteVolume': undefined,
'info': ticker,
};
}
parseTrade (trade, market = undefined) {
let side = this.safeStringLower (trade, 'side');
if (side !== undefined) {
if (side.length < 1) {
side = undefined;
}
}
let order = undefined;
if (side !== undefined) {
const id = side + '_child_order_acceptance_id';
if (id in trade) {
order = trade[id];
}
}
if (order === undefined) {
order = this.safeString (trade, 'child_order_acceptance_id');
}
const timestamp = this.parse8601 (this.safeString (trade, 'exec_date'));
const price = this.safeFloat (trade, 'price');
const amount = this.safeFloat (trade, 'size');
let cost = undefined;
if (amount !== undefined) {
if (price !== undefined) {
cost = price * amount;
}
}
const id = this.safeString (trade, 'id');
let symbol = undefined;
if (market !== undefined) {
symbol = market['symbol'];
}
return {
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'order': order,
'type': undefined,
'side': side,
'takerOrMaker': undefined,
'price': price,
'amount': amount,
'cost': cost,
'fee': undefined,
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'product_code': market['id'],
};
const response = await this.publicGetGetexecutions (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const request = {
'product_code': this.marketId (symbol),
'child_order_type': type.toUpperCase (),
'side': side.toUpperCase (),
'price': price,
'size': amount,
};
const result = await this.privatePostSendchildorder (this.extend (request, params));
// { "status": - 200, "error_message": "Insufficient funds", "data": null }
const id = this.safeString (result, 'child_order_acceptance_id');
return {
'info': result,
'id': id,
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires a `symbol` argument');
}
await this.loadMarkets ();
const request = {
'product_code': this.marketId (symbol),
'child_order_acceptance_id': id,
};
return await this.privatePostCancelchildorder (this.extend (request, params));
}
parseOrderStatus (status) {
const statuses = {
'ACTIVE': 'open',
'COMPLETED': 'closed',
'CANCELED': 'canceled',
'EXPIRED': 'canceled',
'REJECTED': 'canceled',
};
return this.safeString (statuses, status, status);
}
parseOrder (order, market = undefined) {
const timestamp = this.parse8601 (this.safeString (order, 'child_order_date'));
const amount = this.safeFloat (order, 'size');
const remaining = this.safeFloat (order, 'outstanding_size');
const filled = this.safeFloat (order, 'executed_size');
const price = this.safeFloat (order, 'price');
const cost = price * filled;
const status = this.parseOrderStatus (this.safeString (order, 'child_order_state'));
const type = this.safeStringLower (order, 'child_order_type');
const side = this.safeStringLower (order, 'side');
let symbol = undefined;
if (market === undefined) {
const marketId = this.safeString (order, 'product_code');
if (marketId in this.markets_by_id) {
market = this.markets_by_id[marketId];
}
}
if (market !== undefined) {
symbol = market['symbol'];
}
let fee = undefined;
const feeCost = this.safeFloat (order, 'total_commission');
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': undefined,
'rate': undefined,
};
}
const id = this.safeString (order, 'child_order_acceptance_id');
return {
'id': id,
'info': order,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'status': status,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'fee': fee,
};
}
async fetchOrders (symbol = undefined, since = undefined, limit = 100, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrders() requires a `symbol` argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'product_code': market['id'],
'count': limit,
};
const response = await this.privateGetGetchildorders (this.extend (request, params));
let orders = this.parseOrders (response, market, since, limit);
if (symbol !== undefined) {
orders = this.filterBy (orders, 'symbol', symbol);
}
return orders;
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = 100, params = {}) {
const request = {
'child_order_state': 'ACTIVE',
};
return await this.fetchOrders (symbol, since, limit, this.extend (request, params));
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = 100, params = {}) {
const request = {
'child_order_state': 'COMPLETED',
};
return await this.fetchOrders (symbol, since, limit, this.extend (request, params));
}
async fetchOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrder() requires a `symbol` argument');
}
const orders = await this.fetchOrders (symbol);
const ordersById = this.indexBy (orders, 'id');
if (id in ordersById) {
return ordersById[id];
}
throw new OrderNotFound (this.id + ' No order found with id ' + id);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchMyTrades requires a `symbol` argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'product_code': market['id'],
};
if (limit !== undefined) {
request['count'] = limit;
}
const response = await this.privateGetGetexecutions (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
this.checkAddress (address);
await this.loadMarkets ();
if (code !== 'JPY' && code !== 'USD' && code !== 'EUR') {
throw new ExchangeError (this.id + ' allows withdrawing JPY, USD, EUR only, ' + code + ' is not supported');
}
const currency = this.currency (code);
const request = {
'currency_code': currency['id'],
'amount': amount,
// 'bank_account_id': 1234,
};
const response = await this.privatePostWithdraw (this.extend (request, params));
const id = this.safeString (response, 'message_id');
return {
'info': response,
'id': id,
};
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let request = '/' + this.version + '/';
if (api === 'private') {
request += 'me/';
}
request += path;
if (method === 'GET') {
if (Object.keys (params).length) {
request += '?' + this.urlencode (params);
}
}
const url = this.urls['api'] + request;
if (api === 'private') {
this.checkRequiredCredentials ();
const nonce = this.nonce ().toString ();
let auth = [ nonce, method, request ].join ('');
if (Object.keys (params).length) {
if (method !== 'GET') {
body = this.json (params);
auth += body;
}
}
headers = {
'ACCESS-KEY': this.apiKey,
'ACCESS-TIMESTAMP': nonce,
'ACCESS-SIGN': this.hmac (this.encode (auth), this.encode (this.secret)),
'Content-Type': 'application/json',
};
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
};