-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqryptos.js
391 lines (368 loc) · 13.8 KB
/
qryptos.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
"use strict";
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange')
const { ExchangeError, OrderNotFound, InvalidOrder, InsufficientFunds } = require ('./base/errors')
// ---------------------------------------------------------------------------
module.exports = class qryptos extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'qryptos',
'name': 'QRYPTOS',
'countries': [ 'CN', 'TW' ],
'version': '2',
'rateLimit': 1000,
'hasFetchTickers': true,
'hasCORS': false,
'has': {
'fetchOrder': true,
'fetchOrders': true,
'fetchOpenOrders': true,
'fetchClosedOrders': true,
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/30953915-b1611dc0-a436-11e7-8947-c95bd5a42086.jpg',
'api': 'https://api.qryptos.com',
'www': 'https://www.qryptos.com',
'doc': 'https://developers.quoine.com',
},
'api': {
'public': {
'get': [
'products',
'products/{id}',
'products/{id}/price_levels',
'executions',
'ir_ladders/{currency}',
],
},
'private': {
'get': [
'accounts/balance',
'crypto_accounts',
'executions/me',
'fiat_accounts',
'loan_bids',
'loans',
'orders',
'orders/{id}',
'orders/{id}/trades',
'trades',
'trades/{id}/loans',
'trading_accounts',
'trading_accounts/{id}',
],
'post': [
'fiat_accounts',
'loan_bids',
'orders',
],
'put': [
'loan_bids/{id}/close',
'loans/{id}',
'orders/{id}',
'orders/{id}/cancel',
'trades/{id}',
'trades/{id}/close',
'trades/close_all',
'trading_accounts/{id}',
],
},
},
});
}
async fetchMarkets () {
let markets = await this.publicGetProducts ();
let result = [];
for (let p = 0; p < markets.length; p++) {
let market = markets[p];
let id = market['id'].toString ();
let base = market['base_currency'];
let quote = market['quoted_currency'];
let symbol = base + '/' + quote;
let maker = this.safeFloat (market, 'maker_fee');
let taker = this.safeFloat (market, 'taker_fee');
let active = !market['disabled'];
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'maker': maker,
'taker': taker,
'active': active,
'info': market,
});
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let balances = await this.privateGetAccountsBalance ();
let result = { 'info': balances };
for (let b = 0; b < balances.length; b++) {
let balance = balances[b];
let currency = balance['currency'];
let total = parseFloat (balance['balance']);
let account = {
'free': total,
'used': 0.0,
'total': total,
};
result[currency] = account;
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, params = {}) {
await this.loadMarkets ();
let orderbook = await this.publicGetProductsIdPriceLevels (this.extend ({
'id': this.marketId (symbol),
}, params));
return this.parseOrderBook (orderbook, undefined, 'buy_price_levels', 'sell_price_levels');
}
parseTicker (ticker, market = undefined) {
let timestamp = this.milliseconds ();
let last = undefined;
if ('last_traded_price' in ticker) {
if (ticker['last_traded_price']) {
let length = ticker['last_traded_price'].length;
if (length > 0)
last = parseFloat (ticker['last_traded_price']);
}
}
let symbol = undefined;
if (market)
symbol = market['symbol'];
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeFloat (ticker, 'high_market_ask'),
'low': this.safeFloat (ticker, 'low_market_bid'),
'bid': this.safeFloat (ticker, 'market_bid'),
'ask': this.safeFloat (ticker, 'market_ask'),
'vwap': undefined,
'open': undefined,
'close': undefined,
'first': undefined,
'last': last,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': this.safeFloat (ticker, 'volume_24h'),
'quoteVolume': undefined,
'info': ticker,
};
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
let tickers = await this.publicGetProducts (params);
let result = {};
for (let t = 0; t < tickers.length; t++) {
let ticker = tickers[t];
let base = ticker['base_currency'];
let quote = ticker['quoted_currency'];
let symbol = base + '/' + quote;
let market = this.markets[symbol];
result[symbol] = this.parseTicker (ticker, market);
}
return result;
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let ticker = await this.publicGetProductsId (this.extend ({
'id': market['id'],
}, params));
return this.parseTicker (ticker, market);
}
parseTrade (trade, market) {
let timestamp = trade['created_at'] * 1000;
return {
'info': trade,
'id': trade['id'].toString (),
'order': undefined,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': market['symbol'],
'type': undefined,
'side': trade['taker_side'],
'price': parseFloat (trade['price']),
'amount': parseFloat (trade['quantity']),
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'product_id': market['id'],
};
if (limit)
request['limit'] = limit;
let response = await this.publicGetExecutions (this.extend (request, params));
return this.parseTrades (response['models'], market, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let order = {
'order_type': type,
'product_id': this.marketId (symbol),
'side': side,
'quantity': amount,
};
if (type == 'limit')
order['price'] = price;
let response = await this.privatePostOrders (this.extend ({
'order': order,
}, params));
return this.parseOrder(response);
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let result = await this.privatePutOrdersIdCancel (this.extend ({
'id': id,
}, params));
let order = this.parseOrder (result);
if (order['status'] == 'closed')
throw new OrderNotFound (this.id + ' ' + this.json (order));
return order;
}
parseOrder (order) {
let timestamp = order['created_at'] * 1000;
let marketId = order['product_id'].toString ();
let market = this.marketsById[marketId];
let status = undefined;
if ('status' in order) {
if (order['status'] == 'live') {
status = 'open';
} else if (order['status'] == 'filled') {
status = 'closed';
} else if (order['status'] == 'cancelled') { // 'll' intended
status = 'canceled';
}
}
let amount = parseFloat (order['quantity']);
let filled = parseFloat (order['filled_quantity']);
let symbol = undefined;
if (market) {
symbol = market['symbol'];
}
return {
'id': order['id'].toString (),
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'type': order['order_type'],
'status': status,
'symbol': symbol,
'side': order['side'],
'price': order['price'],
'amount': amount,
'filled': filled,
'remaining': amount - filled,
'trades': undefined,
'fee': {
'currency': undefined,
'cost': parseFloat (order['order_fee']),
},
'info': order,
};
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let order = await this.privateGetOrdersId (this.extend ({
'id': id,
}, params));
return this.parseOrder (order);
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params={}) {
await this.loadMarkets ();
let market = undefined;
let request = {};
if (symbol) {
market = this.market (symbol);
request['product_id'] = market['id'];
}
let status = params['status'];
if (status == 'open') {
request['status'] = 'live';
} else if (status == 'closed') {
request['status'] = 'filled';
} else if (status == 'canceled') {
request['status'] = 'cancelled';
}
let result = await this.privateGetOrders (request);
let orders = result['models'];
return this.parseOrders (orders, market, since, limit);
}
fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
return this.fetchOrders (symbol, since, limit, this.extend ({ 'status': 'open' }, params));
}
fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
return this.fetchOrders (symbol, since, limit, this.extend ({ 'status': 'closed' }, params));
}
handleErrors (code, reason, url, method, headers, body) {
let response = undefined;
if (code == 200 || code == 404 || code == 422) {
if ((body[0] == '{') || (body[0] == '[')) {
response = JSON.parse (body);
} else {
// if not a JSON response
throw new ExchangeError (this.id + ' returned a non-JSON reply: ' + body);
}
}
if (code == 404) {
if ('message' in response) {
if (response['message'] == 'Order not found') {
throw new OrderNotFound (this.id + ' ' + body);
}
}
} else if (code == 422) {
if ('errors' in response) {
let errors = response['errors'];
if ('user' in errors) {
let messages = errors['user'];
if (messages.indexOf ('not_enough_free_balance') >= 0) {
throw new InsufficientFunds (this.id + ' ' + body);
}
} else if ('quantity' in errors) {
let messages = errors['quantity'];
if (messages.indexOf ('less_than_order_size') >= 0) {
throw new InvalidOrder (this.id + ' ' + body);
}
}
}
}
}
nonce () {
return this.milliseconds ();
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = '/' + this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path));
headers = {
'X-Quoine-API-Version': this.version,
'Content-Type': 'application/json',
};
if (api == 'public') {
if (Object.keys (query).length)
url += '?' + this.urlencode (query);
} else {
this.checkRequiredCredentials ();
if (method == 'GET') {
if (Object.keys (query).length)
url += '?' + this.urlencode (query);
} else if (Object.keys (query).length) {
body = this.json (query);
}
let nonce = this.nonce ();
let request = {
'path': url,
'nonce': nonce,
'token_id': this.apiKey,
'iat': Math.floor (nonce / 1000), // issued at
};
headers['X-Quoine-Auth'] = this.jwt (request, this.secret);
}
url = this.urls['api'] + url;
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
}