forked from askmike/gekko
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kraken.js
262 lines (207 loc) · 6.06 KB
/
kraken.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
var Kraken = require('kraken-api');
var moment = require('moment');
var util = require('../core/util');
var _ = require('lodash');
var log = require('../core/log');
var crypto_currencies = [
"LTC",
"XBT",
"XRP",
"DAO",
"ETH",
"XDG",
"XLM",
"XRP"
];
var fiat_currencies = [
"EUR",
"GBP",
"USD",
"JPY"
];
// Method to check if asset/currency is a crypto currency
var isCrypto = function(value) {
return _.contains(crypto_currencies, value);
};
// Method to check if asset/currency is a fiat currency
var isFiat = function(value) {
return _.contains(fiat_currencies, value);
};
var Trader = function(config) {
_.bindAll(this);
// Default currency / asset
this.currency = "EUR";
this.asset = "XBT";
if(_.isObject(config)) {
this.key = config.key;
this.secret = config.secret;
this.currency = config.currency.toUpperCase();
this.asset = config.asset.toUpperCase();
}
this.setAssetPair();
this.name = 'kraken';
this.since = null;
this.kraken = new Kraken(this.key, this.secret);
}
Trader.prototype.setAssetPair = function() {
var assetPrefix = "X";
var currencyPrefix = "Z";
if (isFiat(this.asset))
assetPrefix = "Z";
else if(isCrypto(this.currency))
assetPrefix = "X";
if (isFiat(this.currency))
currencyPrefix = "Z";
else if(isCrypto(this.currency))
currencyPrefix = "X";
this.pair = assetPrefix + this.asset + currencyPrefix + this.currency;
};
Trader.prototype.retry = function(method, args, err) {
var wait = +moment.duration(10, 'seconds');
log.debug(this.name, 'returned an error, retrying..', err);
if(!_.isFunction(method)) {
log.error(this.name, 'failed to retry, no method supplied.');
return;
}
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.getTrades = function(since, callback, descending) {
var args = _.toArray(arguments);
var process = function(err, trades) {
if (err || !trades || trades.length === 0)
return this.retry(this.getTrades, args, err);
var parsedTrades = [];
_.each(trades.result[this.pair], function(trade) {
parsedTrades.push({
date: parseInt(Math.round(trade[2]), 10),
price: parseFloat(trade[0]),
amount: parseFloat(trade[1])
});
}, this);
if(descending)
callback(null, parsedTrades.reverse());
else
callback(null, parsedTrades);
};
var reqData = {
pair: this.pair
};
// This appears to not work correctly
// skipping for now so we have the same
// behaviour cross exchange.
//
// if(!_.isNull(this.since))
// reqData.since = this.since;
this.kraken.api('Trades', reqData, _.bind(process, this));
};
Trader.prototype.getPortfolio = function(callback) {
var args = _.toArray(arguments);
var set = function(err, data) {
if(_.isEmpty(data))
err = 'no data';
if(!_.isEmpty(data.error))
err = data.error;
if (err)
return this.retry(this.getPortfolio, args, JSON.stringify(err));
var portfolio = [];
_.each(data.result, function(amount, asset) {
portfolio.push({name: asset.substr(1), amount: parseFloat(amount)});
});
callback(err, portfolio);
};
this.kraken.api('Balance', {}, _.bind(set, this));
};
Trader.prototype.getFee = function(callback) {
callback(false, 0.002);
};
Trader.prototype.getTicker = function(callback) {
var set = function(err, data) {
if(_.isEmpty(data))
err = 'no data';
if(!_.isEmpty(data.error))
err = data.error;
if (err)
return log.error('unable to get ticker', JSON.stringify(err));
var result = data.result[this.pair];
var ticker = {
ask: result.a[0],
bid: result.b[0]
};
callback(err, ticker);
};
this.kraken.api('Ticker', {pair: this.pair}, _.bind(set, this));
};
var roundAmount = function(amount) {
// Prevent "You incorrectly entered one of fields."
// because of more than 8 decimals.
amount *= 100000000;
amount = Math.floor(amount);
amount /= 100000000;
return amount;
};
Trader.prototype.addOrder = function(tradeType, amount, price, callback) {
amount = roundAmount(amount);
log.debug(tradeType.toUpperCase(), amount, this.asset, '@', price, this.currency);
var set = function(err, data) {
if(_.isEmpty(data))
err = 'no data';
if(!_.isEmpty(data.error))
err = data.error;
if (err)
return log.error('unable to', tradeType.toLowerCase(), JSON.stringify(err));
var txid = data.result.txid[0];
log.debug('added order with txid:', txid);
callback(err, txid);
};
this.kraken.api('AddOrder', {
pair: this.pair,
type: tradeType.toLowerCase(),
ordertype: 'limit',
price: price,
volume: amount.toString()
}, _.bind(set, this));
};
Trader.prototype.buy = function(amount, price, callback) {
this.addOrder('buy', amount, price, callback);
};
Trader.prototype.sell = function(amount, price, callback) {
this.addOrder('sell', amount, price, callback);
};
Trader.prototype.checkOrder = function(order, callback) {
var check = function(err, data) {
if(_.isEmpty(data))
err = 'no data';
if(!_.isEmpty(data.error))
err = data.error;
if(err)
return log.error('Unable to check order', order, JSON.stringify(err));
var result = data.result[order];
var stillThere = result.status === 'open' || result.status === 'pending';
callback(err, !stillThere);
};
this.kraken.api('QueryOrders', {txid:order}, _.bind(check, this));
};
Trader.prototype.cancelOrder = function(order) {
var cancel = function(err, data) {
if(_.isEmpty(data))
err = 'no data';
if(!_.isEmpty(data.error))
err = data.error;
if(err)
log.error('unable to cancel order', order, '(', err, JSON.stringify(err), ')');
};
this.kraken.api('CancelOrder', {txid: order}, _.bind(cancel, this));
};
module.exports = Trader;