-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
202 lines (191 loc) · 9.71 KB
/
index.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
#!/usr/bin/env node
const Request = require('request-promise');
const dotenv = require('dotenv');
const express = require('express');
dotenv.config();
let notification_def = [
{"NEW": 1, "CANCELED": 1, "TRADE": 1}, {"LIMIT": 1, "MARKET": 1, "STOP_LOSS": 1}, {"BUY": 1, "SELL": 1}
]
let token = process.env['TELEGRAM_TOKEN'];
let chat_id = process.env['TELEGRAM_CHAT_ID'];
let api_key = process.env['BINANCE_API_KEY'];
let secret_key = process.env['BINANCE_SECRET_KEY'];
let NODE_ENV = process.env.NODE_ENV || "development";
let port = process.env.PORT || 3000;
let notification_settings = process.env['NOTIFICATION_SETTINGS'];
if (typeof notification_settings == "undefined") {
notification_settings = notification_def
} else {
notification_settings = JSON.parse(process.env['NOTIFICATION_SETTINGS'].replace(/'/g, '"'))
}
let timeZone = process.env.TIME_ZONE_STRING || 'Asia/Kolkata';
if (NODE_ENV === "development") {
console.log("NODE_ENV development")
} else {
console.log("NODE_ENV production")
}
console.log(`Your Notification Settings is - ${notification_settings}`);
//Indian time string
const event = new Date().toLocaleString('en-IN', {
timeZone: timeZone,
timeZoneName: 'short'
});
console.log(`Your TimeZone is - ${timeZone}`);
const app = express();
app.all('/', (req, res) => res.send('Bot is Running'));
app.listen(port, () => console.log(`${event} - Server started on ${port} port`));
//BinanceWS
const binanceApi = require('binance');
const binanceWS = new binanceApi.BinanceWS(false);
try {
let binanceRest;
binanceRest = new binanceApi.BinanceRest({
key: api_key,
secret: secret_key,
recvWindow: 10000
})
binanceWS.onUserData(binanceRest, data => {
console.log(`${event} - Session Message: `, data);
process_data(data);
}, 60000).then(() => {
console.log(`${event} - Monitoring Spot User Order Data for binance.com`);
sendMessage(`<b>Binance Spot Order Monitor Started</b>\nthis message shows that you or heroku(if your are using) restart the bot.`)
})
} catch (err) {
console.error(`${event} - ${err}`)
sendMessage(err.toString())
}
function fixFloat(floatNum, Precision = 8) {
let num = Number.parseFloat(floatNum).toFixed(Precision);
let str = num.toString();
return str.replace(/(\.\d+?)0+\b/g, "$1") //fix 20.000 to 20.0 or 0.0000000120 to 0.000000012
}
//[{"NEW": 1, "CANCELED": 1, "TRADE": 1},{"LIMIT": 1, "MARKET": 1, "STOP_LOSS": 1},{"BUY": 1, "SELL": 1}]
let notification_orderStatus = notification_settings[0] //{"NEW": 1, "CANCELED": 1, "TRADE": 1}
let notification_orderType = notification_settings[1] //{"LIMIT": 1, "MARKET": 1, "STOP_LOSS": 1}
let notification_side = notification_settings[2] //{"BUY": 1, "SELL": 1}
function process_data(data) {
let {
e: eventType,
} = data;
let txt;
if (eventType === 'executionReport') {
let {
x: executionType,
s: symbol,
p: price,
q: quantity,
S: side,
o: orderType,
i: orderId,
X: orderStatus,
l: lastTradeQuantity,
z: Cumulative_filled_quantity,
L: Last_price,
r: Order_reject_reason
} = data;
let str4 = Trim(symbol, 4)
let str3 = Trim(symbol, 3)
let sy;
if (["USDT", "BUSD", "TUSD", "USDC", "BIDR", "IDRT", "BVND"].includes(str4)) {
sy = str4
}
if (["BNB", "BTC", "XRP", "TRX", "ETH", "AUD", "BRL", "EUR", "GBP", "RUB", "TRY", "PAX", "DAI", "UAH", "NGN", "VAI"].includes(str3)) {
sy = str3
}
let total = ``;
if (orderType === "MARKET") {
price = Last_price
} else {
total = `\n<b>Total:</b> ${fixFloat(Number(price) * Number(quantity))} ${sy}`
}
if (executionType === 'NEW' && notification_orderStatus['NEW'] === 1) {
if (side === 'BUY' && notification_side['BUY'] === 1 || side === 'SELL' && notification_side['SELL'] === 1) {
if (orderStatus === 'NEW') {
if (orderType === "MARKET" && notification_orderType['MARKET'] === 1) {
txt = `✅ ✅ ✅\n<b>Spot ${orderType} ${side} Order CREATED</b>\n<b>Symbol:</b> #${symbol}\n<b>Quantity:</b> ${fixFloat(quantity)}\n<b>Order ID:</b> #ID${orderId}`
} else if (
((orderType === "LIMIT" || orderType === "LIMIT_MAKER") && notification_orderType['LIMIT'] === 1) ||
((orderType === "STOP_LOSS" || orderType === "STOP_LOSS_LIMIT" || orderType === "TAKE_PROFIT" || orderType === "TAKE_PROFIT_LIMIT") && notification_orderType['STOP_LOSS'] === 1)
) {
txt = `✅ ✅ ✅\n<b>Spot ${orderType} ${side} Order CREATED</b>\n<b>Symbol:</b> #${symbol}\n<b>Price:</b> ${price}\n<b>Quantity:</b> ${fixFloat(quantity)}${total}\n<b>Order ID:</b> #ID${orderId}`
}
} else if (orderStatus === 'REJECTED') {
if (orderType === "MARKET" && notification_orderType['MARKET'] === 1) {
txt = `🚫 🚫 🚫\n<b>Spot ${orderType} ${side} Order REJECTED</b>\n<b>Symbol:</b> #${symbol}\n<b>Quantity:</b> ${fixFloat(quantity)}\n<b>Order ID:</b> #ID${orderId}\n<b>Order reject reason:</b> #ID${Order_reject_reason}`
} else if (
((orderType === "LIMIT" || orderType === "LIMIT_MAKER") && notification_orderType['LIMIT'] === 1) ||
((orderType === "STOP_LOSS" || orderType === "STOP_LOSS_LIMIT" || orderType === "TAKE_PROFIT" || orderType === "TAKE_PROFIT_LIMIT") && notification_orderType['STOP_LOSS'] === 1)
) {
txt = `🚫 🚫 🚫\n<b>Spot ${orderType} ${side} Order REJECTED</b>\n<b>Symbol:</b> #${symbol}\n<b>Price:</b> ${price}\n<b>Quantity:</b> ${fixFloat(quantity)}${total}\n<b>Order ID:</b> #ID${orderId}\n<b>Order reject reason:</b> #ID${Order_reject_reason}`
}
}
}
} else if (executionType === 'CANCELED' && notification_orderStatus['CANCELED'] === 1) {
if (side === 'BUY' && notification_side['BUY'] === 1 || side === 'SELL' && notification_side['SELL'] === 1) {
if (orderStatus === 'CANCELED') {
if (
((orderType === "LIMIT" || orderType === "LIMIT_MAKER") && notification_orderType['LIMIT'] === 1) ||
((orderType === "STOP_LOSS" || orderType === "STOP_LOSS_LIMIT" || orderType === "TAKE_PROFIT" || orderType === "TAKE_PROFIT_LIMIT") && notification_orderType['STOP_LOSS'] === 1)
) {
txt = `❎ ❎ ❎\n<b>Spot ${orderType} ${side} Order CANCELED</b>\n<b>Symbol:</b> #${symbol}\n<b>Price:</b> ${price}\n<b>Quantity:</b> ${fixFloat(quantity)}${total}\n<b>Order ID:</b> #ID${orderId}`
}
}
}
} else if (executionType === 'TRADE' && notification_orderStatus['TRADE'] === 1) {
if (side === 'BUY' && notification_side['BUY'] === 1 || side === 'SELL' && notification_side['SELL'] === 1) {
if ((orderType === "MARKET" && notification_orderType['MARKET'] === 1) ||
((orderType === "LIMIT" || orderType === "LIMIT_MAKER") && notification_orderType['LIMIT'] === 1) ||
((orderType === "STOP_LOSS" || orderType === "STOP_LOSS_LIMIT" || orderType === "TAKE_PROFIT" || orderType === "TAKE_PROFIT_LIMIT") && notification_orderType['STOP_LOSS'] === 1)
) {
if (orderStatus === 'PARTIALLY_FILLED') {
txt = `⌛ ⌛ ⌛\n<b>Spot ${orderType} ${side} Order PARTIALLY FILLED</b>\n<b>Symbol:</b> #${symbol}\n<b>Price:</b> ${Last_price}\n<b>Last Filled:</b> ${fixFloat(lastTradeQuantity)}\n<b>Total Filled:</b> ${fixFloat(Cumulative_filled_quantity)}\n<b>Remaining:</b> ${fixFloat(Number(quantity) - Number(Cumulative_filled_quantity))}\n<b>Order ID:</b> #ID${orderId}`
} else if (orderStatus === 'FILLED') {
txt = `💰 💰 💰\n<b>Spot ${orderType} ${side} Order FULLY FILLED</b>\n<b>Symbol:</b> #${symbol}\n<b>Price:</b> ${Last_price}\n<b>Filled:</b> ${fixFloat(Cumulative_filled_quantity)}${total}\n<b>Order ID:</b> #ID${orderId}`
}
}
}
}
if (txt) {
sendMessage(txt)
}
}
}
//sending telegram message
function sendMessage(text) {
let params = {
chat_id: chat_id,
text: text,
parse_mode: 'html'
};
let options = {
uri: 'https://api.telegram.org/bot' + token + '/' + 'sendMessage',
qs: params,
simple: false,
resolveWithFullResponse: true,
forever: true
};
return Request(options).then(resp => {
if (resp.statusCode !== 200) {
throw new Error(resp.statusCode + ':\n' + resp.body);
}
let updates = JSON.parse(resp.body);
if (updates.ok) {
console.log("Message send via Telegram")
return updates;
} else {
console.log(`something went wrong while sending message to telegram see detailed error below.`)
console.error(updates)
return null;
}
}).catch(error => {
throw error;
});
}
function Trim(input, last_n_chr) {
if (!input || !input.length) {
return;
}
let l = input.length - last_n_chr
return input.slice(l);
}