forked from askmike/gekko
-
Notifications
You must be signed in to change notification settings - Fork 1
/
portfolioManager.js
313 lines (265 loc) · 8.59 KB
/
portfolioManager.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
/*
The portfolio manager is responsible for making sure that
all decisions are turned into orders and make sure these orders
get executed. Besides the orders the manager also keeps track of
the client's portfolio.
*/
var _ = require('lodash');
// var EventEmitter = require('events').EventEmitter;
var Util = require("util");
var util = require('./util')
var events = require("events");
var log = require('./log');
var async = require('async');
var Manager = function(conf, checker) {
this.exchangeSlug = conf.exchange.toLowerCase();
// create an exchange
var Exchange = require('./exchanges/' + this.exchangeSlug);
this.exchange = new Exchange(conf);
// state
this.conf = conf;
this.portfolio = {};
this.fee;
this.order;
this.action;
this.currency = conf.currency || 'USD';
this.asset = conf.asset || 'BTC';
var error = this.checkExchange();
if(error && !checker)
throw error;
_.bindAll(this);
if(checker)
return;
log.debug('getting balance & fee from', this.exchange.name);
var prepare = function() {
this.starting = false;
log.info('trading at', this.exchange.name, 'ACTIVE');
log.info(this.exchange.name, 'trading fee will be:', this.fee * 100 + '%');
log.info('current', this.exchange.name, 'portfolio:');
_.each(this.portfolio, function(fund) {
log.info('\t', fund.name + ':', fund.amount);
});
this.emit('ready');
};
async.series([
this.setPortfolio,
this.setFee
], _.bind(prepare, this));
}
// teach our Manager events
Util.inherits(Manager, events.EventEmitter);
Manager.prototype.validCredentials = function() {
return !this.checkExchange();
}
Manager.prototype.checkExchange = function() {
// what kind of exchange are we dealing with?
//
// name: slug of exchange
// direct: does this exchange support MKT orders?
// infinityOrder: is this an exchange that supports infinity
// orders? (which means that it will accept orders bigger then
// the current balance and order at the full balance instead)
// currencies: all the currencies supported by the exchange
// implementation in gekko.
// assets: all the assets supported by the exchange implementation
// in gekko.
var exchanges = [
{
name: 'mtgox',
direct: true,
infinityOrder: true,
currencies: [
'USD', 'EUR', 'GBP', 'AUD', 'CAD', 'CHF', 'CNY',
'DKK', 'HKD', 'PLN', 'RUB', 'SGD', 'THB'
],
assets: ['BTC'],
requires: ['key', 'secret'],
minimalOrder: { amount: 0.01, unit: 'asset' }
},
{
name: 'btce',
direct: false,
infinityOrder: false,
currencies: ['USD', 'RUR', 'EUR'],
assets: ['BTC'],
requires: ['key', 'secret'],
minimalOrder: { amount: 0.01, unit: 'asset' }
},
{
name: 'bitstamp',
direct: false,
infinityOrder: false,
currencies: ['USD'],
assets: ['BTC'],
requires: ['user', 'password'],
minimalOrder: { amount: 1, unit: 'currency' }
},
{
name: 'cexio',
direct: false,
infinityOrder: false,
currencies: ['BTC'],
assets: ['GHS'],
requires: ['key', 'secret'],
minimalOrder: { amount: 0.000001, unit: 'currency' }
}
];
var exchange = _.find(exchanges, function(e) { return e.name === this.exchangeSlug }, this);
if(!exchange)
return 'Gekko does not support the exchange ' + this.exchangeSlug;
this.directExchange = exchange.direct;
this.infinityOrderExchange = exchange.infinityOrder;
if(_.indexOf(exchange.currencies, this.currency) === -1)
return 'Gekko does not support the currency ' + this.currency + ' at ' + this.exchange.name;
if(_.indexOf(exchange.assets, this.asset) === -1)
return 'Gekko does not support the asset ' + this.asset + ' at ' + this.exchange.name;
var ret;
_.each(exchange.requires, function(req) {
if(!this.conf[req])
ret = this.exchange.name + ' requires "' + req + '" to be set in the config';
}, this);
this.minimalOrder = exchange.minimalOrder;
return ret;
}
Manager.prototype.setPortfolio = function(callback) {
var set = function(err, portfolio) {
this.portfolio = portfolio;
callback();
};
this.exchange.getPortfolio(_.bind(set, this));
}
Manager.prototype.setFee = function(callback) {
var set = function(err, fee) {
this.fee = fee;
callback();
};
this.exchange.getFee(_.bind(set, this));
}
Manager.prototype.setTicker = function(callback) {
var set = function(err, ticker) {
this.ticker = ticker;
callback();
}
this.exchange.getTicker(_.bind(set, this));
}
// return the [fund] based on the data we have in memory
Manager.prototype.getFund = function(fund) {
return _.find(this.portfolio, function(f) { return f.name === fund});
}
Manager.prototype.getBalance = function(fund) {
return this.getFund(fund).amount;
}
// This function makes sure order get to the exchange
// and initiates follow up to make sure the orders will
// get executed. This is the backbone of the portfolio
// manager.
//
// How this is done depends on a couple of things:
//
// is this a directExchange? (does it support MKT orders)
// is this a infinityOrderExchange (does it support order
// requests bigger then the current balance?)
Manager.prototype.trade = function(what) {
if(what !== 'BUY' && what !== 'SELL')
return;
var act = function() {
var amount, price;
if(what === 'BUY') {
// do we need to specify the amount we want to buy?
if(this.infinityOrderExchange)
amount = 10000;
else
amount = this.getBalance(this.currency) / this.ticker.ask;
// can we just create a MKT order?
if(this.directExchange)
price = false;
else
price = this.ticker.ask;
this.buy(amount, price);
} else if(what === 'SELL') {
// do we need to specify the amount we want to sell?
if(this.infinityOrderExchange)
amount = 10000;
else
amount = this.getBalance(this.asset);
// can we just create a MKT order?
if(this.directExchange)
price = false;
else
price = this.ticker.bid;
this.sell(amount, price);
}
};
async.series([
this.setTicker,
this.setPortfolio
], _.bind(act, this));
}
Manager.prototype.getMinimum = function(price) {
if(this.minimalOrder.unit === 'currency')
return minimum = this.minimalOrder.amount / price;
else
return minimum = this.minimalOrder.amount;
}
// first do a quick check to see whether we can buy
// the asset, if so BUY and keep track of the order
// (amount is in asset quantity)
Manager.prototype.buy = function(amount, price) {
// sometimes cex.io specifies a price w/ > 8 decimals
price *= 100000000;
price = Math.ceil(price);
price /= 100000000;
var currency = this.getFund(this.currency);
var minimum = this.getMinimum(price);
if(amount > minimum) {
log.info('attempting to BUY',
amount, this.asset,
'at', this.exchange.name);
this.exchange.buy(amount, price, this.noteOrder);
this.action = 'BUY';
} else
log.info('wanted to buy but insufficient',
this.currency,
'(' + amount * price + ') at', this.exchange.name);
}
// first do a quick check to see whether we can sell
// the asset, if so SELL and keep track of the order
// (amount is in asset quantity)
Manager.prototype.sell = function(amount, price) {
// sometimes cex.io specifies a price w/ > 8 decimals
price *= 100000000;
price = Math.ceil(price);
price /= 100000000;
var asset = this.getFund(this.asset);
var minimum = this.getMinimum(price);
if(amount > minimum) {
log.info('attempting to SELL',
amount, this.asset,
'at', this.exchange.name);
this.exchange.sell(amount, price, this.noteOrder);
this.action = 'SELL';
} else
log.info('wanted to sell but insufficient',
this.asset,
'(' + amount + ') at', this.exchange.name);
}
Manager.prototype.noteOrder = function(order) {
this.order = order;
// if after 30 seconds the order is still there
// we cancel and calculate & make a new one
setTimeout(this.checkOrder, util.minToMs(0.5));
}
// check wether the order got fully filled
// if it is not: cancel & instantiate a new order
Manager.prototype.checkOrder = function() {
var finish = function(err, filled) {
if(!filled) {
log.info(this.action, 'order was not (fully) filled, canceling and creating new order');
this.exchange.cancelOrder(this.order);
return this.trade(this.action);
}
log.info(this.action, 'was succesfull');
}
this.exchange.checkOrder(this.order, _.bind(finish, this));
}
module.exports = Manager;