-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxbtce.js
341 lines (323 loc) · 12.9 KB
/
xbtce.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
"use strict";
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange')
const { ExchangeError, NotSupported, AuthenticationError } = require ('./base/errors')
// ---------------------------------------------------------------------------
module.exports = class xbtce extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'xbtce',
'name': 'xBTCe',
'countries': 'RU',
'rateLimit': 2000, // responses are cached every 2 seconds
'version': 'v1',
'hasPublicAPI': false,
'hasCORS': false,
'hasFetchTickers': true,
'hasFetchOHLCV': false,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28059414-e235970c-662c-11e7-8c3a-08e31f78684b.jpg',
'api': 'https://cryptottlivewebapi.xbtce.net:8443/api',
'www': 'https://www.xbtce.com',
'doc': [
'https://www.xbtce.com/tradeapi',
'https://support.xbtce.info/Knowledgebase/Article/View/52/25/xbtce-exchange-api',
],
},
'requiredCredentials': {
'apiKey': true,
'secret': true,
'uid': true,
},
'api': {
'public': {
'get': [
'currency',
'currency/{filter}',
'level2',
'level2/{filter}',
'quotehistory/{symbol}/{periodicity}/bars/ask',
'quotehistory/{symbol}/{periodicity}/bars/bid',
'quotehistory/{symbol}/level2',
'quotehistory/{symbol}/ticks',
'symbol',
'symbol/{filter}',
'tick',
'tick/{filter}',
'ticker',
'ticker/{filter}',
'tradesession',
],
},
'private': {
'get': [
'tradeserverinfo',
'tradesession',
'currency',
'currency/{filter}',
'level2',
'level2/{filter}',
'symbol',
'symbol/{filter}',
'tick',
'tick/{filter}',
'account',
'asset',
'asset/{id}',
'position',
'position/{id}',
'trade',
'trade/{id}',
'quotehistory/{symbol}/{periodicity}/bars/ask',
'quotehistory/{symbol}/{periodicity}/bars/ask/info',
'quotehistory/{symbol}/{periodicity}/bars/bid',
'quotehistory/{symbol}/{periodicity}/bars/bid/info',
'quotehistory/{symbol}/level2',
'quotehistory/{symbol}/level2/info',
'quotehistory/{symbol}/periodicities',
'quotehistory/{symbol}/ticks',
'quotehistory/{symbol}/ticks/info',
'quotehistory/cache/{symbol}/{periodicity}/bars/ask',
'quotehistory/cache/{symbol}/{periodicity}/bars/bid',
'quotehistory/cache/{symbol}/level2',
'quotehistory/cache/{symbol}/ticks',
'quotehistory/symbols',
'quotehistory/version',
],
'post': [
'trade',
'tradehistory',
],
'put': [
'trade',
],
'delete': [
'trade',
],
},
},
});
}
async fetchMarkets () {
let markets = await this.privateGetSymbol ();
let result = [];
for (let p = 0; p < markets.length; p++) {
let market = markets[p];
let id = market['Symbol'];
let base = market['MarginCurrency'];
let quote = market['ProfitCurrency'];
if (base == 'DSH')
base = 'DASH';
let symbol = base + '/' + quote;
symbol = market['IsTradeAllowed'] ? symbol : id;
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
});
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let balances = await this.privateGetAsset ();
let result = { 'info': balances };
for (let b = 0; b < balances.length; b++) {
let balance = balances[b];
let currency = balance['Currency'];
let uppercase = currency.toUpperCase ();
// xbtce names DASH incorrectly as DSH
if (uppercase == 'DSH')
uppercase = 'DASH';
let account = {
'free': balance['FreeAmount'],
'used': balance['LockedAmount'],
'total': balance['Amount'],
};
result[uppercase] = account;
}
return this.parseBalance (result);
}
async fetchOrderBook (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let orderbook = await this.privateGetLevel2Filter (this.extend ({
'filter': market['id'],
}, params));
orderbook = orderbook[0];
let timestamp = orderbook['Timestamp'];
return this.parseOrderBook (orderbook, timestamp, 'Bids', 'Asks', 'Price', 'Volume');
}
parseTicker (ticker, market = undefined) {
let timestamp = 0;
let last = undefined;
if ('LastBuyTimestamp' in ticker)
if (timestamp < ticker['LastBuyTimestamp']) {
timestamp = ticker['LastBuyTimestamp'];
last = ticker['LastBuyPrice'];
}
if ('LastSellTimestamp' in ticker)
if (timestamp < ticker['LastSellTimestamp']) {
timestamp = ticker['LastSellTimestamp'];
last = ticker['LastSellPrice'];
}
if (!timestamp)
timestamp = this.milliseconds ();
let symbol = undefined;
if (market)
symbol = market['symbol'];
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': ticker['DailyBestBuyPrice'],
'low': ticker['DailyBestSellPrice'],
'bid': ticker['BestBid'],
'ask': ticker['BestAsk'],
'vwap': undefined,
'open': undefined,
'close': undefined,
'first': undefined,
'last': last,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': ticker['DailyTradedTotalVolume'],
'quoteVolume': undefined,
'info': ticker,
};
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
let tickers = await this.publicGetTicker (params);
tickers = this.indexBy (tickers, 'Symbol');
let ids = Object.keys (tickers);
let result = {};
for (let i = 0; i < ids.length; i++) {
let id = ids[i];
let market = undefined;
let symbol = undefined;
if (id in this.markets_by_id) {
market = this.markets_by_id[id];
symbol = market['symbol'];
} else {
let base = id.slice (0, 3);
let quote = id.slice (3, 6);
if (base == 'DSH')
base = 'DASH';
if (quote == 'DSH')
quote = 'DASH';
symbol = base + '/' + quote;
}
let ticker = tickers[id];
result[symbol] = this.parseTicker (ticker, market);
}
return result;
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let tickers = await this.publicGetTickerFilter (this.extend ({
'filter': market['id'],
}, params));
let length = tickers.length;
if (length < 1)
throw new ExchangeError (this.id + ' fetchTicker returned empty response, xBTCe public API error');
tickers = this.indexBy (tickers, 'Symbol');
let ticker = tickers[market['id']];
return this.parseTicker (ticker, market);
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
// no method for trades?
return await this.privateGetTrade (params);
}
parseOHLCV (ohlcv, market = undefined, timeframe = '1m', since = undefined, limit = undefined) {
return [
ohlcv['Timestamp'],
ohlcv['Open'],
ohlcv['High'],
ohlcv['Low'],
ohlcv['Close'],
ohlcv['Volume'],
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
throw new NotSupported (this.id + ' fetchOHLCV is disabled by the exchange');
let minutes = parseInt (timeframe / 60); // 1 minute by default
let periodicity = minutes.toString ();
await this.loadMarkets ();
let market = this.market (symbol);
if (!since)
since = this.seconds () - 86400 * 7; // last day by defulat
if (!limit)
limit = 1000; // default
let response = await this.privateGetQuotehistorySymbolPeriodicityBarsBid (this.extend ({
'symbol': market['id'],
'periodicity': periodicity,
'timestamp': since,
'count': limit,
}, params));
return this.parseOHLCVs (response['Bars'], market, timeframe, since, limit);
}
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.tapiPostTrade (this.extend ({
'pair': this.marketId (symbol),
'type': side,
'amount': amount,
'rate': price,
}, params));
return {
'info': response,
'id': response['Id'].toString (),
};
}
async cancelOrder (id, symbol = undefined, params = {}) {
return await this.privateDeleteTrade (this.extend ({
'Type': 'Cancel',
'Id': id,
}, params));
}
nonce () {
return this.milliseconds ();
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
if (!this.apiKey)
throw new AuthenticationError (this.id + ' requires apiKey for all requests, their public API is always busy');
if (!this.uid)
throw new AuthenticationError (this.id + ' requires uid property for authentication and trading, their public API is always busy');
let url = this.urls['api'] + '/' + this.version;
if (api == 'public')
url += '/' + api;
url += '/' + this.implodeParams (path, params);
let query = this.omit (params, this.extractParams (path));
if (api == 'public') {
if (Object.keys (query).length)
url += '?' + this.urlencode (query);
} else {
this.checkRequiredCredentials ();
headers = { 'Accept-Encoding': 'gzip, deflate' };
let nonce = this.nonce ().toString ();
if (method == 'POST') {
if (Object.keys (query).length) {
headers['Content-Type'] = 'application/json';
body = this.json (query);
} else {
url += '?' + this.urlencode (query);
}
}
let auth = nonce + this.uid + this.apiKey + method + url;
if (body)
auth += body;
let signature = this.hmac (this.encode (auth), this.encode (this.secret), 'sha256', 'base64');
let credentials = this.uid + ':' + this.apiKey + ':' + nonce + ':' + this.binaryToString (signature);
headers['Authorization'] = 'HMAC ' + credentials;
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
}