-
Notifications
You must be signed in to change notification settings - Fork 3
/
bot2.js
365 lines (312 loc) · 18.3 KB
/
bot2.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var _ = require('lodash');
var math = require('mathjs');
var moment = require('moment');
var colors = require('colors');
var SMA = require('technicalindicators').SMA;
var RSI = require('technicalindicators').RSI;
var ROC = require('technicalindicators').ROC;
var BB = require('technicalindicators').BollingerBands;
var bullish = require('technicalindicators').bullish;
var bearish = require('technicalindicators').bearish;
var asyncData = require("./asyncData.js");
var mongoose = require('mongoose');
var Data15m = require('./models/data15m.js');
var BalanceHist = require('./models/balanceHist.js');
var Data15mLast500 = require('./models/data15mLast500.js');
var numeral = require('numeral');
//===============================================================================================================================
// MLAB DATABASE CONFIG
//===============================================================================================================================
const dbRoute = process.env.MLAB;
mongoose.connect(dbRoute, { useNewUrlParser: true});
let db = mongoose.connection;
db.once('open', () => console.log('db connected'));
db.on('error', console.error.bind(console, 'monogdb connection error:'));
//===============================================================================================================================
// Binance CONFIG
//===============================================================================================================================
const binance = require('node-binance-api')().options({
APIKEY: process.env.APIKEY,
APISECRET: process.env.APISECRET,
useServerTime: true, // If you get timestamp errors, synchronize to server time at startup
test: false // If you want to use sandbox mode where orders are simulated
});
//===============================================================================================================================
// Binance API - IOTA ETH BOT
//===============================================================================================================================
let tradePair = 'IOTAETH'; // Pair you want to trade.
let tradeQty = 10; // Qty you want to trade.
let timeFrame = '15m'; // Trading Period: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M
let decimalPlaces = 0.00000001; // Number of decimal places on tradingPair
let tradeInterval = 10000; // Interval of milliseconds bot will analyse price changes. Needs to be > 1000, due to Exchange API limits.
let totalETHInvested = 4.1; // Total invested.
let sinceInception = moment("20190618", "YYYYMMDD").fromNow(); // Date you started investing.
// Function to eliminate fl
function strip(number) {
return (parseFloat(number).toPrecision(6));
}
setInterval(function() {
binance.candlesticks(tradePair, timeFrame, (error, ticks, symbol) => {
let last_tick = ticks[ticks.length - 1];
let [time, open, high, low, close, volume, closeTime, assetVolume, trades, buyBaseVolume, buyAssetVolume, ignored] = last_tick;
var array200Period = [];
var arrayVolume = [];
for (var i = 0; i < 200; i++) {
array200Period.push(Number(ticks[i][4]));
arrayVolume.push(+ticks[i][5]);
}
// Available parameters to use with Trading strategy (RSI, BolingerBand, SMA, etc...) Google npm technical indicators library for more indicators.
var fivePeriodCandlestickInput = {
open: [+ticks[194][1], +ticks[195][1], +ticks[196][1], +ticks[197][1], +ticks[198][1]],
high: [+ticks[194][2], +ticks[195][2], +ticks[196][2], +ticks[197][2], +ticks[198][2]],
low: [+ticks[194][3], +ticks[195][3], +ticks[196][3], +ticks[197][3], +ticks[198][3]],
close: [+ticks[194][4], +ticks[195][4], +ticks[196][4], +ticks[197][4], +ticks[198][4]]
};
var inputRSI = {
values: array200Period,
period: 14
};
var inputBB1 = {
period : 20,
values : array200Period,
stdDev : 1
};
var inputBB2 = {
period: 20,
values: array200Period,
stdDev: 2
};
var inputBB3 = {
period: 20,
values: array200Period,
stdDev: 3
};
//Calculate RSI (Relative Strength Index), BollingerBands, SMA (Simple Moving Average), ROC (Rate of Change).
var rsi = RSI.calculate(inputRSI)[RSI.calculate(inputRSI).length - 1];
var bollingerBands1 = BB.calculate(inputBB1);
var bollingerBands2 = BB.calculate(inputBB2);
var bollingerBands3 = BB.calculate(inputBB3);
var bollingerSpread = bollingerBands2[bollingerBands2.length - 1].upper / bollingerBands2[bollingerBands2.length - 1].lower;
var upper = bollingerBands2[bollingerBands2.length - 1].upper;
var middle = bollingerBands2[bollingerBands2.length - 1].middle;
var lower = bollingerBands2[bollingerBands2.length - 1].lower;
var simpleMovingAverage200 = SMA.calculate({
period: 200,
values: array200Period
});
var roc3 = ROC.calculate({period : 3, values : array200Period})[ROC.calculate({period : 3, values : array200Period}).length - 1];
var roc5 = ROC.calculate({period : 5, values : array200Period})[ROC.calculate({period : 5, values : array200Period}).length - 1];
var roc8 = ROC.calculate({period : 8, values : array200Period})[ROC.calculate({period : 8, values : array200Period}).length - 1];
var roc13 = ROC.calculate({period : 13, values : array200Period})[ROC.calculate({period : 13, values : array200Period}).length - 1];
var roc21 = ROC.calculate({period : 21, values : array200Period})[ROC.calculate({period : 21, values : array200Period}).length - 1];
var lastVolume = arrayVolume[arrayVolume.length -1];
var averageVolume = math.mean(arrayVolume);
var lastPrice = +ticks[199][4];
(async function data() {
let tradeHistoryData = await asyncData.tradeHistoryData.IOTA();
let balances = await asyncData.getBalances();
let prices = await asyncData.getPriceData();
let bidAsk = await asyncData.getBidAsk.IOTA();
let result = {
tradeHistoryData: tradeHistoryData,
balances: balances,
prices: prices,
bidAsk: bidAsk
};
return result;
})().then((result) => {
// Optimal Buy & Sell Prices.
var optimalBuyPrice = strip(math.max(lastPrice, +result.bidAsk.bidPrice + +decimalPlaces));
var optimalSellPrice = strip(math.min(lastPrice, +result.bidAsk.askPrice - +decimalPlaces));
// STRATEGY STARTS HERE! Once condition is met, current order is canceled and new order is placed.
if (lastPrice < lower && rsi < 38) {
setTimeout(function() {
binance.cancelOrders(tradePair, (error, response, symbol) => {
console.log(symbol + " cancel response:", response);
});
console.log(colors.cyan('Buy: last price < lower limit @ 2sigma'));
binance.buy(tradePair, tradeQty, optimalBuyPrice);
}, 500);
} else if (lastPrice < bollingerBands3[bollingerBands3.length - 1].lower && rsi < 30) {
setTimeout(function() {
binance.cancelOrders(tradePair, (error, response, symbol) => {
console.log(symbol + " cancel response:", response);
});
console.log(colors.cyan('Buy: last price < lower limit @ 3sigma'));
binance.buy(tradePair, tradeQty, optimalBuyPrice);
}, 500);
} else if (rsi < 20) {
setTimeout(function() {
binance.cancelOrders(tradePair, (error, response, symbol) => {
console.log(symbol + " cancel response:", response);
});
console.log(colors.cyan('Strong Buy: RSI < 20'));
binance.buy(tradePair, tradeQty * 3, strip(+result.bidAsk.askPrice));
}, 500);
} else if (lastPrice > upper && rsi > 60) {
setTimeout(function() {
binance.cancelOrders(tradePair, (error, response, symbol) => {
console.log(symbol + " cancel response:", response);
});
console.log(colors.cyan('Sell: last price > upper limit @ 2sigma'));
binance.sell(tradePair, tradeQty, optimalSellPrice);
}, 500);
} else if (rsi > 80) {
setTimeout(function() {
binance.cancelOrders(tradePair, (error, response, symbol) => {
console.log(symbol + " cancel response:", response);
});
console.log(colors.cyan('Strong Sell: RSI > 80'));
binance.sell(tradePair, tradeQty * 3, strip(+result.bidAsk.bidPrice));
}, 500);
} else if (+result.balances.ETH.available < 0.02 ) {
setTimeout(function() {
binance.cancelOrders(tradePair, (error, response, symbol) => {
console.log(symbol + " cancel response:", response);
});
console.log(colors.cyan('Sell: reduce risk, overbought'));
binance.sell(tradePair, +(+result.balances.IOTA.available * 0.25).toFixed(0), strip(+result.bidAsk.askPrice - +decimalPlaces));
}, 500);
// STRATEGY ENDS HERE.
// Place BNB order for exchange fees.
} else if (+result.balances.BNB.available < 0.5 ) {
setTimeout(function() {
binance.cancelOrders(tradePair, (error, response, symbol) => {
console.log(symbol + " cancel response:", response);
});
console.log(colors.cyan('Buying more BNB for fees.'));
binance.buy('BNBETH', 0.5, +result.bidAsk.askPrice - +decimalPlaces);
}, 500);
// Logs all information to the console.
} else {
console.log('============================================================');
console.log(new Date().toLocaleString());
console.log(colors.cyan('Waiting for trade... => ' + symbol).bold);
}
console.log('------------------------------------------------------------');
if (+close > +simpleMovingAverage200[simpleMovingAverage200.length - 1]) {
console.log('^^^^^^^^^^^^^^^^^^^^^^^^ Trend is UP ^^^^^^^^^^^^^^^^^^^^^^^^'.bgGreen + "\n");
} else {
console.log('________________________ Trend is DOWN ________________________'.bgRed + "\n");
}
console.log(colors.underline.cyan(`Price Data =>`).bgBlack.bold);
if (Number(close) > bollingerBands2[bollingerBands2.length - 1].upper) {
console.log("Last Close: " + colors.green(close));
} else if (Number(close) < bollingerBands2[bollingerBands2.length - 1].lower) {
console.log("Last Close: " + colors.red(close));
} else {
console.log("Last Close: " + Number(ticks[199][4]).toFixed(8));
}
if (bullish(fivePeriodCandlestickInput) === true) {
console.log(`Candlestick Pattern Bullish?: ${colors.green(bullish(fivePeriodCandlestickInput)).bold}`);
} else {
console.log(`Candlestick Pattern Bullish?: ${colors.red(bullish(fivePeriodCandlestickInput)).bold}`);
}
console.log("SMA 200 Period: " + (simpleMovingAverage200[simpleMovingAverage200.length - 1]).toFixed(8));
console.log("Upper Limit @Sigma Lvl. " + inputBB2.stdDev + " = " + upper.toFixed(8));
console.log("Lower Limit @Sigma Lvl. " + inputBB2.stdDev + " = " + lower.toFixed(8));
console.log("Bollinger Bands Spread: " + colors.yellow((((bollingerSpread) - 1) * 100).toFixed(2) + " %"));
console.log('RSI: ' + colors.yellow(rsi));
console.log("ROC 3,5,8,13,21 period: " + colors.yellow(`${roc3.toFixed(2)}, ${roc5.toFixed(2)}, ${roc8.toFixed(2)}, ${roc13.toFixed(2)}, ${roc21.toFixed(2)} %`));
console.log(`Last Volume: ${colors.yellow(lastVolume)}, Average Volume: ${colors.yellow(averageVolume.toFixed(0))}`);
console.log('------------------------------------------------------------' + "\n");
console.log(colors.underline.cyan(`${symbol} Trade History Last 500 trades => `).bgBlack.bold + "\n" +
`Count Buy Trades: ${result.tradeHistoryData[2]} \n` +
`Count Sell Trades: ${result.tradeHistoryData[5]} \n` +
`Total Qty Bought: ${result.tradeHistoryData[1]} \n` +
`Total Qty Sold: ${result.tradeHistoryData[4]} \n` +
`Weighted Buy Price: ${result.tradeHistoryData[0]} \n` +
`Weighted Sell Price: ${result.tradeHistoryData[3]} \n` +
'Total Profit/Loss: Ξ ' + ((+result.tradeHistoryData[3] - +result.tradeHistoryData[0]) * Math.min(Number(math.sum(+result.tradeHistoryData[4])), Number(math.sum(+result.tradeHistoryData[1])))).toFixed(4));
var mktMakerProfitOrLoss = Number((((((result.tradeHistoryData[3]) / result.tradeHistoryData[0]) - 1) * 100) - 0.2).toFixed(2));
if (mktMakerProfitOrLoss > 0) {
console.log("Avg MKT_Maker Spread: " + colors.green(mktMakerProfitOrLoss + ' %').bold);
} else {
console.log("Avg MKT_Maker Spread: " + colors.red(mktMakerProfitOrLoss + ' %').bold);
}
console.log('------------------------------------------------------------' + "\n");
console.log(colors.underline.cyan('Account Data =>').bgBlack.bold);
console.log(`ETH balance: Ξ ${numeral(result.balances.ETH.available).format('0.000')}`);
console.log(`IOTA balance: ${numeral(result.balances.IOTA.available).format('0.0')} miota || Ξ ${(result.balances.IOTA.available*lastPrice).toFixed(2)}`);
console.log(`Total Invested: Ξ ${totalETHInvested}`);
var totalETHBalance = (+result.balances.ETH.available + +result.balances.IOTA.available*lastPrice).toFixed(3);
console.log(`Total balance: Ξ ${totalETHBalance} || $ ${(totalETHBalance * result.prices.ETHUSDT).toFixed(0)} USD`);
console.log(`Total BNB balance: ${numeral(+result.balances.BNB.available).format('0.00')}`);
if(((+totalETHBalance/+totalETHInvested)-1) < 0) {
console.log(`ROI: ${colors.red(numeral((+totalETHBalance/+totalETHInvested)-1).format('%0.000')).bold}`);
} else {
console.log(`ROI: ${colors.green(numeral((+totalETHBalance/+totalETHInvested)-1).format('%0.000')).bold}`);
}
console.log(`Since Inception: ${sinceInception}`);
console.log('------------------------------------------------------------' + "\n");
binance.openOrders(false, (error, openOrders) => {
console.log("openOrders()", openOrders);
});
});
}, {
limit: 200,
endTime: Date.now()
});
}, tradeInterval);
//===============================================================================================================================
// COLLECT DATA - NOT IN USE
//===============================================================================================================================
// setInterval(()=> {
// // Intervals: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M
// binance.candlesticks(tradePair, timeFrame, (error, ticks, symbol) => {
// let last_tick = ticks[ticks.length - 1];
// let [time, open, high, low, close, volume, closeTime, assetVolume, trades, buyBaseVolume, buyAssetVolume, ignored] = last_tick;
// var newData = new Data15m();
// newData.date = moment.unix(+time/1000).format("YYYY-MM-DD");
// newData.time = moment.unix(+time/1000).format('LTS');
// newData.closeTime = moment.unix(+closeTime/1000).format('LTS');
// newData.open = open;
// newData.high = high;
// newData.low = low;
// newData.close = close;
// newData.assetVolume = assetVolume;
// newData.trades = trades;
// newData.buyBaseVolume = buyBaseVolume;
// newData.buyAssetVolume = buyAssetVolume;
// // newData.data = ticks;
// newData.save((err, docs) => {
// if(err) {
// console.log(err);
// } else {
// return docs;
// }
// });
// }, {limit: 500, endTime: Date.now() });
// }, 1000*60*15);
// Data15mLast500.deleteMany({}, (err, result)=>{
// if(err) {
// console.log(err);
// } else {
// console.log(result);
// }
// });
// // Intervals: 1m,3m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,3d,1w,1M
// binance.candlesticks(tradePair, timeFrame, (error, ticks, symbol) => {
// let last_tick = ticks[ticks.length - 1];
// let [time, open, high, low, close, volume, closeTime, assetVolume, trades, buyBaseVolume, buyAssetVolume, ignored] = last_tick;
// var newData = new Data15mLast500();
// newData.data = ticks;
// newData.save((err, docs) => {
// if(err) {
// console.log(err);
// } else {
// return docs;
// }
// });
// }, {limit: 500, endTime: Date.now() });
//===============================================================================================================================
// SERVER START
//===============================================================================================================================
app.listen(8082, process.env.IP, function() {
console.log('server start...' + process.env.IP + ":" + 8082);
});