forked from askmike/gekko
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathportfolioManager.js
321 lines (264 loc) · 7.94 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
314
315
316
317
318
319
320
321
/*
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 util = require('./util');
var events = require("events");
var log = require('./log');
var async = require('async');
var checker = require('./exchangeChecker.js');
var Manager = function(conf) {
_.bindAll(this);
var error = checker.cantTrade(conf)
if(error)
util.die(error);
var exchangeMeta = checker.settings(conf);
this.exchangeSlug = exchangeMeta.slug;
// create an exchange
var Exchange = require('../exchanges/' + this.exchangeSlug);
this.exchange = new Exchange(conf);
this.conf = conf;
this.portfolio = {};
this.fee;
this.order;
this.action;
this.directExchange = exchangeMeta.direct;
this.infinityOrderExchange = exchangeMeta.infinityOrder;
this.marketConfig = _.find(exchangeMeta.markets, function(p) {
return p.pair[0] === conf.currency && p.pair[1] === conf.asset;
});
this.minimalOrder = this.marketConfig.minimalOrder;
this.currency = conf.currency;
this.asset = conf.asset;
}
Manager.prototype.init = function(callback) {
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 + '%');
this.logPortfolio();
callback();
};
async.series([
this.setPortfolio,
this.setFee
], _.bind(prepare, this));
// Because on cex.io your asset grows refresh and
// display portfolio stats every 5 minutes
if(this.exchange.name === 'cex.io')
setInterval(this.recheckPortfolio, util.minToMs(5));
}
Manager.prototype.setPortfolio = function(callback) {
var set = function(err, portfolio) {
this.portfolio = portfolio;
if(_.isFunction(callback))
callback();
};
this.exchange.getPortfolio(_.bind(set, this));
}
Manager.prototype.setFee = function(callback) {
var set = function(err, fee) {
this.fee = fee;
if(_.isFunction(callback))
callback();
};
this.exchange.getFee(_.bind(set, this));
}
Manager.prototype.setTicker = function(callback) {
var set = function(err, ticker) {
this.ticker = ticker;
if(_.isFunction(callback))
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;
this.action = what;
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.floor(price);
price /= 100000000;
var currency = this.getFund(this.currency);
var minimum = this.getMinimum(price);
var availabe = this.getBalance(this.currency) / price;
// if not suficient funds
if(amount > availabe) {
return log.info(
'Wanted to buy but insufficient',
this.currency,
'(' + availabe + ')',
'at',
this.exchange.name
);
}
// if order to small
if(amount < minimum) {
return log.info(
'Wanted to buy',
this.asset,
'but the amount is too small',
'(' + amount + ')',
'at',
this.exchange.name
);
}
log.info(
'Attempting too BUY',
amount,
this.asset,
'at',
this.exchange.name
);
this.exchange.buy(amount, price, this.noteOrder);
}
// 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 minimum = this.getMinimum(price);
var availabe = this.getBalance(this.asset);
// if not suficient funds
if(amount < availabe) {
return log.info(
'Wanted to buy but insufficient',
this.asset,
'(' + availabe + ')',
'at',
this.exchange.name
);
}
// if order to small
if(amount < minimum) {
return log.info(
'Wanted to buy',
this.currency,
'but the amount is too small',
'(' + amount + ')',
'at',
this.exchange.name
);
}
log.info(
'Attempting to SELL',
amount,
this.asset,
'at',
this.exchange.name
);
this.exchange.sell(amount, price, this.noteOrder);
}
Manager.prototype.noteOrder = function(err, 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, cancelling and creating new order');
this.exchange.cancelOrder(this.order);
// Delay the trade, as cancel -> trade can trigger
// an error on cex.io if they happen on the same
// unix timestamp second (nonce will not increment).
var self = this;
setTimeout(function() { self.trade(self.action); }, 1000);
return;
}
log.info(this.action, 'was successfull');
}
this.exchange.checkOrder(this.order, _.bind(finish, this));
}
Manager.prototype.logPortfolio = function() {
log.info(this.exchange.name, 'portfolio:');
_.each(this.portfolio, function(fund) {
log.info('\t', fund.name + ':', fund.amount);
});
}
// On cex.io the portfolio gets updated as new blocks
// come in when we are holding the asset.
Manager.prototype.recheckPortfolio = function() {
this.setPortfolio(this.enforcePosition);
}
// If we are in a long position we are bullish
// and thus want to reinvest earnings back into
// the asset (GHS) as we are assuming the value
// of the asset will go up.
Manager.prototype.enforcePosition = function() {
if(this.action !== 'BUY')
return;
this.trade('BUY');
}
module.exports = Manager;