-
Notifications
You must be signed in to change notification settings - Fork 0
/
trader.js
171 lines (142 loc) · 5.51 KB
/
trader.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
'use strict'
// IMPORT SCRIPTS
const Config = require('./config');
const MergeAlgo = require('./strategies/MergeAlgo');
const Bot = require('./bot');
const BitMEXClient = require('./index');
// DEFINE Trading Algo
let algorithm = new MergeAlgo(
{
name: 'TradingMergeAlgo',
algorithm: Config.algorithm,
}
);
// SET UP CLIENT
const client = new BitMEXClient({testnet: Config.testnet});
client.on('error', console.error);
client.on('open', () => console.log('Connection opened.'));
client.on('close', () => console.log('Connection closed.'));
client.on('initialize', () => console.log('Client initialized, data is flowing.'));
// stream in latest data
let current = {askPrice: null, askPriceAvarage: null, lastAction: '', time: null};
let decisionNumber = 0;
let finalWorkedData = [];
let workeddata = [];
let minutedata = [];
let nextDecisionTime = Date.now() + 1000 * Config.timeStepDecisionInSeconds;
let nextBatchTime = Date.now() + 1000 * Config.batchTimeInSeconds;
let avarage = 0;
let avarageForDecision = 0;
Bot.getHistoricalTrades({binSize: '1h', count: '1000'}).then(res => {
for(let i = res.length-1; i >= 0; i--){
workeddata.push({askPriceAvarage: res[i].close});
if(workeddata.length >= 12){
runDecider(workeddata);
}
}
});
return;
client.addStream('XBTUSD', 'quote', function(data, symbol, table) {
current.askPrice = data[data.length - 1].askPrice;
current.timestamp = new Date(data[data.length - 1].timestamp);
// console.log(".");
if(Date.now() < nextBatchTime){
// Secure that the askPrice is not identical
if(data.length > 0 && minutedata.length > 0 && current.askPrice == minutedata[minutedata.length-1].askPrice){
return;
}
minutedata.push(data[data.length-1]);
console.log("new data: " + minutedata[minutedata.length -1].askPrice);
// FIND BEST TIME TO SHORT / LONG
current.lastAction = decideAndOrder(decisionNumber, current.lastAction, minutedata[minutedata.length -1].askPrice, 0.5, current.askPriceAvarage);
return;
}
// get minute avarage taking into account timestamp
let sum = 0;
for(let el of minutedata){
sum += el.askPrice;
}
if(minutedata.length > 0){
avarage = sum / minutedata.length;
}
workeddata.push({askPriceAvarage: avarage});
nextBatchTime = Date.now() + 1000 * Config.batchTimeInSeconds;
console.log("added avarage of: " + workeddata[workeddata.length -1].askPriceAvarage + " from " + minutedata.length + " values.");
minutedata = [];
if(Date.now < nextDecisionTime){
return;
}
runDecider(workeddata);
});
function runDecider(decideData){
// get decision time avarage
let sumForDecision = 0;
for(let el of decideData){
sumForDecision += el.askPriceAvarage;
}
if(decideData.length > 0){
avarageForDecision = sumForDecision / decideData.length;
}else{
console.log("no new data for decision!");
}
finalWorkedData.push({askPriceAvarage: avarageForDecision});
nextDecisionTime = Date.now() + 1000 * Config.timeStepDecisionInSeconds;
console.log("Making decision on value: " + finalWorkedData[finalWorkedData.length -1].askPriceAvarage + " from " + workeddata.length + " values.");
workeddata = [];
current.askPriceAvarage = finalWorkedData[finalWorkedData.length-1].askPriceAvarage;
// Secure that enough finalWorkedData is collected
if(finalWorkedData.length > Config.minDataBeforeTrade){
decisionNumber = algorithm.getDecisionNumber(current.askPriceAvarage);
console.log(decisionNumber + ' / ' + current.lastAction);
}else{
decisionNumber = algorithm.getDecisionNumber(current.askPriceAvarage);
console.log('Gathering data: ' + finalWorkedData.length + ' / ' + Config.minDataBeforeTrade + ' / ' + decisionNumber);
}
}
function placeOrder(price, decision){
//check minDataBeforeTrade
if(finalWorkedData.length < Config.minDataBeforeTrade){
console.log("Failed placeOrder. Missing (" + (Config.minDataBeforeTrade - finalWorkedData.length) + ") datapoints.");
return;
}
// get orders
Bot.getOrders()
.then(orders => {
let orderIDs = orders.map(order => order.orderID);
// cancel active orders
Bot.cancelOrders({orderID: orderIDs})
.then(() => {
// Calculate amount based on current open position
Bot.getPositions()
.then(positions => {
let qty = positions[0].currentQty;
let purchaseAmount = Config.positionQuantity + Math.abs(qty);
if(decision == 'short'){
purchaseAmount *= -1;
}
// Place the order
if(decision == 'short' && purchaseAmount < 0 || decision == 'long' && purchaseAmount > 0){
Bot.placeOrder({orderQty: purchaseAmount, price: price})
.then(() => console.log('placed order for ' + purchaseAmount + ' / ' + decision))
.catch(e => console.log(e));
}
else{
console.log('could not place order. Perhaps last order did not go through.');
}
});
});
});
}
function decideAndOrder(decisionNumber, lastaction, price, pricePadding, avarageprice){
let action = '';
if(decisionNumber >= Config.algorithm.triggers.long && lastaction !== 'long' && price <= avarageprice){
placeOrder(price + pricePadding, 'long');
action = 'long';
}
else if(decisionNumber <= Config.algorithm.triggers.short && lastaction !== 'short' && price >= avarageprice){
placeOrder(price - pricePadding, 'short');
action = 'short';
}
let result = action || lastaction;
return result;
}