-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqryptos.js
421 lines (399 loc) · 15.4 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
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
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { InvalidNonce, OrderNotFound, InvalidOrder, InsufficientFunds, AuthenticationError } = 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,
'has': {
'CORS': false,
'fetchTickers': true,
'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',
'https://developers.quoine.com/v2',
],
'fees': 'https://qryptos.zendesk.com/hc/en-us/articles/115007858167-Fees',
},
'api': {
'public': {
'get': [
'products',
'products/{id}',
'products/{id}/price_levels',
'executions',
'ir_ladders/{currency}',
],
},
'private': {
'get': [
'accounts/balance',
'accounts/main_asset',
'crypto_accounts',
'executions/me',
'fiat_accounts',
'loan_bids',
'loans',
'orders',
'orders/{id}',
'orders/{id}/trades',
'orders/{id}/executions',
'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}',
],
},
},
'skipJsonOnStatusCodes': [401],
'exceptions': {
'messages': {
'API Authentication failed': AuthenticationError,
'Nonce is too small': InvalidNonce,
'Order not found': OrderNotFound,
'user': {
'not_enough_free_balance': InsufficientFunds,
},
'quantity': {
'less_than_order_size': InvalidOrder,
},
},
},
});
}
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, limit = undefined, 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 (typeof limit !== 'undefined')
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, 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 = this.safeValue (params, 'status');
if (status) {
params = this.omit (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 (this.extend (request, params));
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));
}
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 };
}
handleErrors (code, reason, url, method, headers, body, response = undefined) {
if (code >= 200 && code <= 299)
return;
const messages = this.exceptions['messages'];
if (code === 401) {
// expected non-json response
if (body in messages)
throw new messages[body] (this.id + ' ' + body);
else
return;
}
if (typeof response === 'undefined')
if ((body[0] === '{') || (body[0] === '['))
response = JSON.parse (body);
else
return;
const feedback = this.id + ' ' + this.json (response);
if (code === 404) {
// { "message": "Order not found" }
const message = this.safeString (response, 'message');
if (message in messages)
throw new messages[message] (feedback);
} else if (code === 422) {
// array of error messages is returned in 'user' or 'quantity' property of 'errors' object, e.g.:
// { "errors": { "user": ["not_enough_free_balance"] }}
// { "errors": { "quantity": ["less_than_order_size"] }}
if ('errors' in response) {
const errors = response['errors'];
const errorTypes = ['user', 'quantity'];
for (let i = 0; i < errorTypes.length; i++) {
const errorType = errorTypes[i];
if (errorType in errors) {
const errorMessages = errors[errorType];
for (let j = 0; j < errorMessages.length; j++) {
const message = errorMessages[j];
if (message in messages[errorType])
throw new messages[errorType][message] (feedback);
}
}
}
}
}
}
};