forked from yura505/robinbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
positions.js
76 lines (65 loc) · 2.25 KB
/
positions.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
var n = require('numbro');
var instruments = require('./instruments.js');
var quotes = require('./quotes.js');
module.exports = {
download: function(cb) {
console.log("Downloading nonzero positions...");
global.Robinhood.nonzero_positions(
function(err, response, body){
if (err) return cb(err);
nonzero_positions = body.results;
cb();
})
},
quantity: function(symbol) {
for (let pos of nonzero_positions) {
let ticker = instruments.getSymbol(pos.url);
if (ticker == symbol) {
return n(pos.quantity).value();
}
}
return 0;
},
exists: function(symbol) {
for (let pos of nonzero_positions) {
if (symbol == instruments.getSymbol(pos.url)) return pos;
}
},
sum: function() {
return this.value;
},
/* backtest methods */
add: function(symbol, price, count) {
var pos = this.exists(symbol);
if (pos === undefined) {
let url = instruments.addSymbol(symbol);
nonzero_positions.push({ url: url, quantity: count, average_buy_price: price });
} else {
pos.quantity += count;
}
console.log("BUY: "+count+" "+symbol+" at "+price+" ("+(price*count)+")");
return price * count;
},
remove: function(symbol, price, count) {
var pos = this.exists(symbol);
if (pos !== undefined) {
if (pos.quantity == count) {
nonzero_positions = nonzero_positions.filter(item => item !== pos);
} else {
pos.quantity -= count;
}
console.log("SELL: "+count+" "+symbol+" at "+price+" ("+(price*count)+")");
return price * count;
} else {
console.error("Trying to sell zero position: "+symbol+" "+count);
}
return 0;
},
get value() {
return nonzero_positions.reduce(function(total, pos) {
let symbol = instruments.getSymbol(pos.url);
return total + ((symbol !== undefined) ? n(pos.quantity).multiply(quotes.get(symbol)[0].close).value() : 0);
}, 0);
}
}
var nonzero_positions = [ ];