forked from askmike/gekko
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gdax.js
346 lines (288 loc) · 11 KB
/
gdax.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
var Gdax = require('gdax');
var util = require('../core/util.js');
var _ = require('lodash');
var moment = require('moment');
var log = require('../core/log');
var batchSize = 100;
var Trader = function(config) {
_.bindAll(this);
this.post_only = true;
this.use_sandbox = false;
this.name = 'GDAX';
this.import = false;
this.scanback = false;
this.scanbackTid = 0;
this.scanbackResults = [];
this.asset = config.asset;
this.currency = config.currency;
if(_.isObject(config)) {
this.key = config.key;
this.secret = config.secret;
this.passphrase = config.passphrase;
this.pair = [config.asset, config.currency].join('-').toUpperCase();
this.post_only = (typeof config.post_only !== 'undefined') ? config.post_only : true;
}
this.gdax_public = new Gdax.PublicClient(this.pair, this.use_sandbox ? 'https://api-public.sandbox.gdax.com' : undefined);
this.gdax = new Gdax.AuthenticatedClient(this.key, this.secret, this.passphrase, this.use_sandbox ? 'https://api-public.sandbox.gdax.com' : undefined);
}
// if the exchange errors we try the same call again after
// waiting 10 seconds
Trader.prototype.retry = function(method, args) {
var wait = +moment.duration(10, 'seconds');
log.debug(this.name, 'returned an error, retrying..');
var self = this;
// make sure the callback (and any other fn)
// is bound to Trader
_.each(args, function(arg, i) {
if(_.isFunction(arg))
args[i] = _.bind(arg, self);
});
// run the failed method again with the same
// arguments after wait
setTimeout(
function() { method.apply(self, args) },
wait
);
}
Trader.prototype.getPortfolio = function(callback) {
var result = function(err, response, data) {
if(_.has(data, 'message')) {
if(data.message === 'Invalid API Key' || data.message === 'Invalid Passphrase')
util.die('GDAX said: ' + data.message);
return callback(data.message, []);
}
var portfolio = data.map(function (account) {
return {
name: account.currency.toUpperCase(),
amount: parseFloat(account.available)
}
}
);
callback(err, portfolio);
};
this.gdax.getAccounts(result);
}
Trader.prototype.getTicker = function(callback) {
var result = function(err, response, data) {
callback(err, {bid: +data.bid, ask: +data.ask})
};
this.gdax_public.getProductTicker(result);
}
Trader.prototype.getFee = function(callback) {
//https://www.gdax.com/fees
const fee = this.asset == 'BTC' ? 0.0025 : 0.003;
//There is no maker fee, not sure if we need taker fee here
//If post only is enabled, gdax only does maker trades which are free
callback(false, this.post_only ? 0 : fee);
}
Trader.prototype.normalizeResult = callback => {
return (err, resp, data) => {
if(err)
return callback(err);
if(!data)
return callback('No data');
if(data.message)
return callback(data);
callback(undefined, data);
}
}
Trader.prototype.buy = function(amount, price, callback) {
var args = _.toArray(arguments);
var buyParams = {
'price': this.getMaxDecimalsNumber(price, this.currency == 'BTC' ? 5 : 2),
'size': this.getMaxDecimalsNumber(amount),
'product_id': this.pair,
'post_only': this.post_only
};
var result = (err, data) => {
if(err) {
log.error('Error buying at GDAX:', err);
return this.retry(this.buy, args);
}
callback(err, data.id);
}
this.gdax.buy(buyParams, this.normalizeResult(result));
}
Trader.prototype.sell = function(amount, price, callback) {
var args = _.toArray(arguments);
var sellParams = {
'price': this.getMaxDecimalsNumber(price, this.currency == 'BTC' ? 5 : 2),
'size': this.getMaxDecimalsNumber(amount),
'product_id': this.pair,
'post_only': this.post_only
};
var result = function(err, data) {
if(err) {
log.error('Error selling at GDAX:', err);
return this.retry(this.sell, args);
}
callback(err, data.id);
}.bind(this);
this.gdax.sell(sellParams, this.normalizeResult(result));
}
Trader.prototype.checkOrder = function(order, callback) {
var args = _.toArray(arguments);
if (order == null) {
return callback('EMPTY ORDER_ID', false);
}
var result = function(err, data) {
if (err) {
log.error('GDAX ERROR:', err);
return this.retry(this.checkOrder, args);
}
var status = data.status;
if (status == 'done') {
return callback(err, true);
} else if (status == 'rejected') {
return callback(err, false);
} else if (status == 'pending') {
return callback(err, false);
}
callback(err, false);
}.bind(this);
this.gdax.getOrder(order, this.normalizeResult(result));
}
Trader.prototype.getOrder = function(order, callback) {
var args = _.toArray(arguments);
if (order == null) {
return callback('EMPTY ORDER_ID', false);
}
var result = function(err, data) {
if(err) {
if(err.message === 'NotFound') {
log.debug('GDAX NotFound error, spoofing order');
return callback(undefined, {
price: 0,
amount: 0,
date: moment.unix(0)
});
}
log.error('GDAX ERROR:', err);
return this.retry(this.checkOrder, args);
}
var price = parseFloat( data.price );
var amount = parseFloat( data.filled_size );
var date = moment( data.done_at );
callback(undefined, {price, amount, date});
}.bind(this);
this.gdax.getOrder(order, this.normalizeResult(result));
}
Trader.prototype.cancelOrder = function(order, callback) {
var args = _.toArray(arguments);
if (order == null) {
return;
}
var result = function(err, data) {
// todo, verify result..
callback();
};
this.gdax.cancelOrder(order, this.normalizeResult(result));
}
Trader.prototype.getTrades = function(since, callback, descending) {
var args = _.toArray(arguments);
var lastScan = 0;
var process = function(err, response, data) {
if(err)
return this.retry(this.getTrades, args);
var result = _.map(data, function(trade) {
return {
tid: trade.trade_id,
amount: parseFloat(trade.size),
date: moment.utc(trade.time).format('X'),
price: parseFloat(trade.price)
};
});
if (this.scanback) {
var last = _.last(data);
var first = _.first(data);
// Try to find trade id matching the since date
if (!this.scanbackTid) {
// either scan for new ones or we found it.
if (moment.utc(last.time) < moment.utc(since)) {
this.scanbackTid = last.trade_id;
} else {
log.debug('Scanning backwards...' + last.time);
this.gdax_public.getProductTrades({after: last.trade_id - (batchSize * lastScan) , limit: batchSize}, process);
lastScan++;
if (lastScan > 100) {
lastScan = 10;
}
}
}
if (this.scanbackTid) {
// if scanbackTid is set we need to move forward again
log.debug('Backwards: ' + last.time + ' (' + last.trade_id + ') to ' + first.time + ' (' + first.trade_id + ')');
if (this.import) {
this.scanbackTid = first.trade_id;
callback(null, result.reverse());
} else {
this.scanbackResults = this.scanbackResults.concat(result.reverse());
if (this.scanbackTid != first.trade_id) {
this.scanbackTid = first.trade_id;
this.gdax_public.getProductTrades({after: this.scanbackTid + batchSize + 1, limit: batchSize}, process);
} else {
this.scanback = false;
this.scanbackTid = 0;
if (!this.import) {
log.debug('Scan finished: data found:' + this.scanbackResults.length);
callback(null, this.scanbackResults);
}
this.scanbackResults = [];
}
}
}
} else {
callback(null, result.reverse());
}
}.bind(this);
if (since || this.scanback) {
this.scanback = true;
if (this.scanbackTid) {
this.gdax_public.getProductTrades({after: this.scanbackTid + batchSize + 1, limit: batchSize}, process);
} else {
log.debug('Scanning back in the history needed...');
log.debug(moment.utc(since).format());
this.gdax_public.getProductTrades({limit: batchSize}, process);
}
} else {
this.gdax_public.getProductTrades({limit: batchSize}, process);
}
}
Trader.prototype.getMaxDecimalsNumber = function (number, decimalLimit = 8) {
var decimalNumber = parseFloat(number);
// The ^-?\d*\. strips off any sign, integer portion, and decimal point
// leaving only the decimal fraction.
// The 0+$ strips off any trailing zeroes.
var decimalCount = ((+decimalNumber).toString()).replace(/^-?\d*\.?|0+$/g, '').length;
var decimalMultiplier = 1;
for (i = 0; i < decimalLimit; i++) {
decimalMultiplier *= 10;
}
return decimalCount <= decimalLimit ? decimalNumber.toString() : (Math.floor(decimalNumber * decimalMultiplier) / decimalMultiplier).toFixed(decimalLimit);
};
Trader.getCapabilities = function () {
return {
name: 'GDAX',
slug: 'gdax',
currencies: ['USD', 'EUR', 'GBP', 'BTC'],
assets: ['BTC', 'LTC', 'ETH'],
markets: [
{ pair: ['USD', 'BTC'], minimalOrder: { amount: 0.01, unit: 'asset' } },
{ pair: ['USD', 'LTC'], minimalOrder: { amount: 0.01, unit: 'asset' } },
{ pair: ['USD', 'ETH'], minimalOrder: { amount: 0.01, unit: 'asset' } },
{ pair: ['EUR', 'BTC'], minimalOrder: { amount: 0.01, unit: 'asset' } },
{ pair: ['EUR', 'ETH'], minimalOrder: { amount: 0.01, unit: 'asset' } },
{ pair: ['EUR', 'LTC'], minimalOrder: { amount: 0.01, unit: 'asset' } },
{ pair: ['GBP', 'BTC'], minimalOrder: { amount: 0.01, unit: 'asset' } },
{ pair: ['BTC', 'LTC'], minimalOrder: { amount: 0.01, unit: 'asset' } },
{ pair: ['BTC', 'ETH'], minimalOrder: { amount: 0.01, unit: 'asset' } }
],
requires: ['key', 'secret', 'passphrase'],
providesHistory: 'date',
providesFullHistory: true,
tid: 'tid',
tradable: true,
forceReorderDelay: true
};
}
module.exports = Trader;