-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzaif.js
358 lines (338 loc) · 12.6 KB
/
zaif.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
"use strict";
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange')
const { ExchangeError } = require ('./base/errors')
// ---------------------------------------------------------------------------
module.exports = class zaif extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'zaif',
'name': 'Zaif',
'countries': 'JP',
'rateLimit': 2000,
'version': '1',
'hasCORS': false,
'hasFetchOpenOrders': true,
'hasFetchClosedOrders': true,
'hasWithdraw': true,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766927-39ca2ada-5eeb-11e7-972f-1b4199518ca6.jpg',
'api': 'https://api.zaif.jp',
'www': 'https://zaif.jp',
'doc': [
'http://techbureau-api-document.readthedocs.io/ja/latest/index.html',
'https://corp.zaif.jp/api-docs',
'https://corp.zaif.jp/api-docs/api_links',
'https://www.npmjs.com/package/zaif.jp',
'https://github.com/you21979/node-zaif',
],
},
'api': {
'public': {
'get': [
'depth/{pair}',
'currencies/{pair}',
'currencies/all',
'currency_pairs/{pair}',
'currency_pairs/all',
'last_price/{pair}',
'ticker/{pair}',
'trades/{pair}',
],
},
'private': {
'post': [
'active_orders',
'cancel_order',
'deposit_history',
'get_id_info',
'get_info',
'get_info2',
'get_personal_info',
'trade',
'trade_history',
'withdraw',
'withdraw_history',
],
},
'ecapi': {
'post': [
'createInvoice',
'getInvoice',
'getInvoiceIdsByOrderNumber',
'cancelInvoice',
],
},
'tlapi': {
'post': [
'get_positions',
'position_history',
'active_positions',
'create_position',
'change_position',
'cancel_position',
],
},
'fapi': {
'get': [
'groups/{group_id}',
'last_price/{group_id}/{pair}',
'ticker/{group_id}/{pair}',
'trades/{group_id}/{pair}',
'depth/{group_id}/{pair}',
],
},
},
});
}
async fetchMarkets () {
let markets = await this.publicGetCurrencyPairsAll ();
let result = [];
for (let p = 0; p < markets.length; p++) {
let market = markets[p];
let id = market['currency_pair'];
let symbol = market['name'];
let [ base, quote ] = symbol.split ('/');
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
});
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let response = await this.privatePostGetInfo ();
let balances = response['return'];
let result = { 'info': balances };
let currencies = Object.keys (balances['funds']);
for (let c = 0; c < currencies.length; c++) {
let currency = currencies[c];
let balance = balances['funds'][currency];
let uppercase = currency.toUpperCase ();
let account = {
'free': balance,
'used': 0.0,
'total': balance,
};
if ('deposit' in balances) {
if (currency in balances['deposit']) {
account['total'] = balances['deposit'][currency];
account['used'] = account['total'] - account['free'];
}
}
result[uppercase] = account;
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, params = {}) {
await this.loadMarkets ();
let orderbook = await this.publicGetDepthPair (this.extend ({
'pair': this.marketId (symbol),
}, params));
return this.parseOrderBook (orderbook);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let ticker = await this.publicGetTickerPair (this.extend ({
'pair': this.marketId (symbol),
}, params));
let timestamp = this.milliseconds ();
let vwap = ticker['vwap'];
let baseVolume = ticker['volume'];
let quoteVolume = baseVolume * vwap;
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': ticker['high'],
'low': ticker['low'],
'bid': ticker['bid'],
'ask': ticker['ask'],
'vwap': vwap,
'open': undefined,
'close': undefined,
'first': undefined,
'last': ticker['last'],
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
};
}
parseTrade (trade, market = undefined) {
let side = (trade['trade_type'] == 'bid') ? 'buy' : 'sell';
let timestamp = trade['date'] * 1000;
let id = this.safeString (trade, 'id');
id = this.safeString (trade, 'tid', id);
if (!market)
market = this.markets_by_id[trade['currency_pair']];
return {
'id': id.toString (),
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market['symbol'],
'type': undefined,
'side': side,
'price': trade['price'],
'amount': trade['amount'],
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let response = await this.publicGetTradesPair (this.extend ({
'pair': market['id'],
}, params));
return this.parseTrades (response, market);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
if (type == 'market')
throw new ExchangeError (this.id + ' allows limit orders only');
let response = await this.privatePostTrade (this.extend ({
'currency_pair': this.marketId (symbol),
'action': (side == 'buy') ? 'bid' : 'ask',
'amount': amount,
'price': price,
}, params));
return {
'info': response,
'id': response['return']['order_id'].toString (),
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
return await this.privatePostCancelOrder (this.extend ({
'order_id': id,
}, params));
}
parseOrder (order, market = undefined) {
let side = (order['action'] == 'bid') ? 'buy' : 'sell';
let timestamp = parseInt (order['timestamp']) * 1000;
if (!market)
market = this.markets_by_id[order['currency_pair']];
let price = order['price'];
let amount = order['amount'];
return {
'id': order['id'].toString (),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'status': 'open',
'symbol': market['symbol'],
'type': 'limit',
'side': side,
'price': price,
'cost': price * amount,
'amount': amount,
'filled': undefined,
'remaining': undefined,
'trades': undefined,
'fee': undefined,
};
}
parseOrders (orders, market = undefined) {
let ids = Object.keys (orders);
let result = [];
for (let i = 0; i < ids.length; i++) {
let id = ids[i];
let order = orders[id];
let extended = this.extend (order, { 'id': id });
result.push (this.parseOrder (extended, market));
}
return result;
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
let request = {
// 'is_token': false,
// 'is_token_both': false,
};
if (symbol) {
market = this.market (symbol);
request['currency_pair'] = market['id'];
}
let response = await this.privatePostActiveOrders (this.extend (request, params));
return this.parseOrders (response['return'], market);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
let request = {
// 'from': 0,
// 'count': 1000,
// 'from_id': 0,
// 'end_id': 1000,
// 'order': 'DESC',
// 'since': 1503821051,
// 'end': 1503821051,
// 'is_token': false,
};
if (symbol) {
market = this.market (symbol);
request['currency_pair'] = market['id'];
}
let response = await this.privatePostTradeHistory (this.extend (request, params));
return this.parseOrders (response['return'], market);
}
async withdraw (currency, amount, address, params = {}) {
await this.loadMarkets ();
if (currency == 'JPY')
throw new ExchangeError (this.id + ' does not allow ' + currency + ' withdrawals');
let result = await this.privatePostWithdraw (this.extend ({
'currency': currency,
'amount': amount,
'address': address,
// 'message': 'Hi!', // XEM only
// 'opt_fee': 0.003, // BTC and MONA only
}, params));
return {
'info': result,
'id': result['return']['txid'],
'fee': result['return']['fee'],
};
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = this.urls['api'] + '/';
if (api == 'public') {
url += 'api/' + this.version + '/' + this.implodeParams (path, params);
} else if (api == 'fapi') {
url += 'fapi/' + this.version + '/' + this.implodeParams (path, params);
} else {
this.checkRequiredCredentials ();
if (api == 'ecapi') {
url += 'ecapi';
} else if (api == 'tlapi') {
url += 'tlapi';
} else {
url += 'tapi';
}
let nonce = this.nonce ();
body = this.urlencode (this.extend ({
'method': path,
'nonce': nonce,
}, params));
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 };
}
async request (path, api = 'api', method = 'GET', params = {}, headers = undefined, body = undefined) {
let response = await this.fetch2 (path, api, method, params, headers, body);
if ('error' in response)
throw new ExchangeError (this.id + ' ' + response['error']);
if ('success' in response)
if (!response['success'])
throw new ExchangeError (this.id + ' ' + this.json (response));
return response;
}
}