This repository has been archived by the owner on Feb 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
exchange.js
399 lines (381 loc) · 13.7 KB
/
exchange.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
var bittrex_authed = require('node-bittrex-api'),
bittrex_public = require('node-bittrex-api'),
n = require('numbro')
module.exports = function bittrex(conf) {
let recoverableErrors = new RegExp(/(ESOCKETTIMEOUT|ESOCKETTIMEDOUT|ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENOTFOUND|Invalid nonce|Rate limit exceeded|URL request error)/)
let shownWarning = false
let firstRun = true
let allowGetMarketCall = true
let marketRefresh = 15000
bittrex_authed.options({
'apikey': conf.bittrex.key.trim(),
'apisecret': conf.bittrex.secret.trim(),
'stream': false,
'cleartext': false,
'verbose': false
})
function joinProduct(product_id) {
return product_id.split('-')[1] + '-' + product_id.split('-')[0]
}
function retry(method, args, error) {
var timeout = 2500
if (error)
if (error.message)
if (error.message.match(/Rate limit exceeded/)) {
timeout = 10000
}
setTimeout(function () {
exchange[method].apply(exchange, args)
}, timeout)
return false
}
function handleErrors(command, err, data, args, callback) {
if (err) {
if (err.message && err.message.match(recoverableErrors)) {
return retry(command, args, err)
}
return callback(err, [])
}
if (typeof data !== 'object') {
console.log(`Bittrex API ${command} had an abnormal response, quitting.`)
return callback(null, [])
}
// generic error handler data was null and err was null
if (data == null) {
return retry(command, args, err)
}
// specific handlers
if ((command == 'getQuote' || command == 'getTrades') && data.result == null ) {
return retry(command, args, data)
}
if (!data.success) {
if (data.message && data.message.match(recoverableErrors)) {
return retry(command, args, data.message)
}
return callback(null, [])
}
return true
}
var orders = {}
var exchange = {
name: 'bittrex',
historyScan: 'forward',
makerFee: 0.25,
takerFee: 0.25,
getProducts: function() {
return require('./products.json')
},
getTrades: function (opts, cb) {
var func_args = [].slice.call(arguments)
var args = {
market:joinProduct(opts.product_id),
marketName: joinProduct(opts.product_id),
tickInterval: 'oneMin'
}
// accomplish back trades using 2 calls. ticks and getMarket and create a hybrid result.
var trades = []
// first run do the full deal. 2nd run only returns the last trades
if (allowGetMarketCall != true) {
cb(null, [])
return null
}
if (firstRun) {
bittrex_public.getticks(args, function(data, err) {
let res = handleErrors('getTrades', err, data, func_args, cb)
if (!shownWarning) {
console.log('Bittrex backfill is indirectly supported through the use of a hybrid system that combines a low resolution')
console.log('long term market of about 10 days and a short term high resolution market of the last 1-5 minutes.')
shownWarning = true
}
if (res) {
let lastVal = 0
for (const key in Object.keys(data.result)) {
var trade = data.result[key]
if (isNaN(opts.from) || new Date(trade.T).getTime() > new Date(opts.from).getTime()) {
let buySell = 'sell'
// todo: unsure about the >. if the price is greater than the last one should this one be a buy or sell. figure it out.
if (parseFloat(trade.C) > lastVal) buySell = 'buy'
trades.push({
trade_id: new Date(trade.T).getTime(),
time: new Date(trade.T).getTime(),
size: parseFloat(trade.V),
price: parseFloat(trade.C),
// selector should get overwritten by backfill, but was a point where it was missing in the backfill function so this was put in so it is never missed
selector: 'bittrex.'+opts.product_id,
side: buySell
})
lastVal = parseFloat(trade.C)
}
}
bittrex_public.getmarkethistory(args, function(data, err) {
let res2 = handleErrors('getTrades', err, data, func_args, cb)
if (res2) {
for (const key in Object.keys(data.result)) {
var trade = data.result[key]
if (isNaN(opts.from) || new Date(trade.TimeStamp).getTime() > new Date(opts.from).getTime()) {
trades.push({
// trade_id: trade.Id,
trade_id: trade.id,
time: new Date(trade.TimeStamp).getTime(),
size: parseFloat(trade.Quantity),
price: parseFloat(trade.Price),
// selector should get overwritten by backfill, but was a point where it was missing in the backfill function so this was put in so it is never missed
selector: 'bittrex.'+opts.product_id,
side: trade.OrderType || trade.OrderType == 'SELL' ? 'sell': 'buy'
// selector:
})
}
}
firstRun = false
allowGetMarketCall = false
setTimeout(()=>{allowGetMarketCall = true},marketRefresh)
// make sure all times come out sorted correctly. there is a chance they can appear in the array out of order otherwise.
trades = trades.sort((a, b) => {
if (a.time < b.time) return 1
if (a.time > b.time) return -1
return 0
}
)
cb(null, trades)
}
})
}
})
}
else {
bittrex_public.getmarkethistory(args, function(data, err) {
let res2 = handleErrors('getTrades', err, data, func_args, cb)
if (res2) {
for (const key in Object.keys(data.result)) {
var trade = data.result[key]
if (isNaN(opts.from) || new Date(trade.TimeStamp).getTime() > new Date(opts.from).getTime()) {
trades.push({
// trade_id: trade.Id,
trade_id: new Date(trade.TimeStamp).getTime(),
time: new Date(trade.TimeStamp).getTime(),
size: parseFloat(trade.Quantity),
price: parseFloat(trade.Price),
// selector should get overwritten by backfill, but was a point where it was missing in the backfill function so this was put in so it is never missed
selector: 'bittrex.'+opts.product_id,
side: trade.OrderType || trade.OrderType == 'SELL' ? 'sell': 'buy'
})
}
}
allowGetMarketCall = false
setTimeout(()=>{allowGetMarketCall = true},marketRefresh)
// Sorting at this point may be redundant.
trades = trades.sort((a, b) => {
if (a.time < b.time) return 1
if (a.time > b.time) return -1
return 0
}
)
cb(null, trades)
}
})
}
},
getBalance: function (opts, cb) {
var func_args = [].slice.call(arguments)
bittrex_authed.getbalances(function(data,err ) {
let res = handleErrors('getBalance', err, data, func_args, cb)
var balance = {
asset: 0,
currency: 0
}
if (res) {
for (const key in data.result) {
var _balance = data.result[key]
if (opts.last_signal === 'buy') {
if (_balance['Currency'] === opts.currency.toUpperCase()) {
balance.currency = n(_balance.Available).format('0.00000000'),
balance.currency_hold = 0
}
if (_balance['Currency'] === opts.asset.toUpperCase()) {
balance.asset = n(_balance.Available).format('0.00000000'),
balance.asset_hold = 0
}
}
else {
if (_balance['Currency'] === opts.asset.toUpperCase()) {
balance.asset = n(_balance.Available).format('0.00000000'),
balance.asset_hold = 0
}
if (_balance['Currency'] === opts.currency.toUpperCase()) {
balance.currency = n(_balance.Available).format('0.00000000'),
balance.currency_hold = 0
}
}
}
cb(null, balance)
}
})
},
getOrderBook: function (opts, cb) {
var args = {
market: joinProduct(opts.product_id),
type: 'both',
depth: 10
}
bittrex_public.getorderbook(args, function(data) {
if (typeof data !== 'object') {
console.log('Bittrex API (getorderbook) had an abnormal response, quitting.')
return cb(null, [])
}
if (!data.success) {
if (data.message && data.message.match(recoverableErrors)) {
return retry('getOrderBook', args, data.message)
}
console.log(data.message)
return cb(null, [])
}
if (typeof data.result.buy[0].Rate === 'undefined') {
console.log(data.message)
return cb(null, [])
}
cb(null, {
buyOrderRate: data.result.buy[0].Rate,
buyOrderAmount: data.result.buy[0].Quantity,
sellOrderRate: data.result.sell[0].Rate,
sellOrderAmount: data.result.sell[0].Quantity
})
})
},
getQuote: function (opts, cb) {
if (opts == null) return
if (opts.product_id == null) return
var func_args = [].slice.call(arguments)
var args = {
market: joinProduct(opts.product_id)
}
bittrex_public.getticker(args, function(data, err ) {
let res = handleErrors('getQuote', err, data, func_args, cb)
if (res)
cb(null, {
bid: data.result.Bid,
ask: data.result.Ask
})
})
},
cancelOrder: function (opts, cb) {
var func_args = [].slice.call(arguments)
let args = {
uuid: opts.order_id
}
bittrex_authed.cancel(args, function (data, err) {
if (err) {
return retry('cancelOrder', func_args, err)
}
cb()
})
},
trade: function (type, opts, cb) {
var func_args = [].slice.call(arguments)
var params = {
market: joinProduct(opts.product_id),
quantity: opts.size,
rate: opts.price
}
if (!('order_type' in opts) || !opts.order_type) {
opts.order_type = 'maker'
}
var fn = function(data,err) {
if (err != null ) {
if (data == null) {
data = {}
data.message = err.message
data.success = err.success
data.result = err.result
}
console.log('API Error')
console.log(JSON.stringify(err))
if (err.message && err.message.match(recoverableErrors)) {
return retry('trade', func_args, err.message)
}
}
if (err && err.message) {
if (err.message =='MIN_TRADE_REQUIREMENT_NOT_MET') {
let returnResult = {
reject_reason:'balance',
status:'rejected'
}
return cb(null, returnResult)
}
}
if (typeof data !== 'object') {
return cb(null, {})
}
if (!data.success) {
if (data.message && data.message.match(recoverableErrors)) {
return retry('trade', func_args, data.message)
}
console.log(data.message)
return cb(null, [])
}
var order = {
id: data && data.result ? data.result.uuid : null,
status: 'open',
price: opts.price,
size: opts.size,
post_only: !!opts.post_only,
created_at: new Date().getTime(),
filled_size: '0',
ordertype: opts.order_type
}
orders['~' + data.result.uuid] = order
cb(null, order)
}
if (type === 'buy') {
if (opts.order_type === 'maker') {
bittrex_authed.buylimit(params, fn)
}
if (opts.order_type === 'taker') {
bittrex_authed.buymarket(params, fn)
}
}
if (type === 'sell') {
if (opts.order_type === 'maker') {
bittrex_authed.selllimit(params, fn)
}
if (opts.order_type === 'taker') {
bittrex_authed.sellmarket(params, fn)
}
}
},
buy: function (opts, cb) {
exchange.trade('buy', opts, cb)
},
sell: function (opts, cb) {
exchange.trade('sell', opts, cb)
},
getOrder: function(opts, cb) {
var func_args = [].slice.call(arguments)
var order = orders['~' + opts.order_id]
if (!order) return cb(new Error('order not found in cache'))
var params = {
uuid: opts.order_id
}
bittrex_authed.getorder(params, function(data, err) {
let res = handleErrors('getOrder', err, data, func_args, cb)
if (res) {
var orderData = data.result
if (!orderData) {
return cb('Order not found')
}
if (orderData.QuantityRemaining == 0) {
order.status = 'done'
order.done_at = new Date().getTime()
order.filled_size = parseFloat(orderData.Quantity) - parseFloat(orderData.QuantityRemaining)
return cb(null, order)
}
cb(null, order)
}
})
},
// return the property used for range querying.
getCursor: function (trade) {
return (trade.time || trade)
}
}
return exchange
}