-
Notifications
You must be signed in to change notification settings - Fork 55
/
app.js
1964 lines (1746 loc) · 75.8 KB
/
app.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pkg from 'bybit-api-gnome';
const { WebsocketClient, WS_KEY_MAP, LinearClient, AccountAssetClient, SpotClientV3} = pkg;
import { WebsocketClient as binanceWS } from 'binance';
import dotenv from 'dotenv';
import fetch from 'node-fetch';
import express from 'express';
import path from 'path';
import chalk from 'chalk';
import fs from 'fs';
import { Webhook, MessageBuilder } from 'discord-webhook-node';
import { env } from 'process';
import http from 'http';
import https from 'https';
import WebSocket from 'ws';
import { networkInterfaces } from 'os';
import moment from 'moment';
import * as cron from 'node-cron'
import bodyParser from 'body-parser'
import session from 'express-session';
import { Server } from 'socket.io'
import { newPosition, incrementPosition, closePosition, updatePosition } from './position.js';
import { loadJson, storeJson, traceTrade } from './utils.js';
import { createMarketOrder } from './order.js';
import { logIT, LOG_LEVEL } from './log.js';
dotenv.config();
// Discord report cron tasks
if (process.env.USE_DISCORD == "true") {
const cronTaskDiscordPositionReport = cron.schedule(process.env.DISCORD_REPORT_INTERVALL, () => {
logIT("Discord report send!");
reportWebhook();
});
}
// Update function
if (process.env.FIRST_START === 'false') {
updateLastDeploymentDateTime(new Date());
changeENV('FIRST_START', 'true');
dotenv.config();
}
// Check for updates
if (process.env.CHECK_FOR_UPDATE === 'true')
checkForUpdates()
// used to calculate bot runtime
const timestampBotStart = moment();
var hook;
var reporthook;
if (process.env.USE_DISCORD == "true") {
hook = new Webhook(process.env.DISCORD_URL);
if (process.env.SPLIT_DISCORD_LOG_AND_REPORT == "true") {
reporthook = new Webhook(process.env.DISCORD_URL_REPORT);
}
}
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const io = new Server(server);
const PORT = process.env.PORT || 3000;
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const key = process.env.API_KEY;
const secret = process.env.API_SECRET;
const stopLossCoins = new Map();
// keep tracks of opened positions
var openPositions = undefined;
// tradesStat store metric about current trade
const tradesHistory = new Map();
// globalTradesStats store global metric
const globalStatsPath = "./global_stats.json";
var globalTradesStats = {
trade_count: 0,
max_loss : 0,
losses_count: 0,
wins_count: 0,
consecutive_losses :0,
consecutive_wins :0,
max_consecutive_losses: 0,
max_consecutive_wins: 0
};
loadJson(globalStatsPath, globalTradesStats);
const TRACE_TRADES_LEVEL_OFF = "OFF";
const TRACE_TRADES_LEVEL_ON = "ON";
const TRACE_TRADES_LEVEL_MAX = "MAX";
const traceTradeFields = process.env.TRACE_TRADES_FIELDS.replace(/ /g,"").split(",")
var rateLimit = 2000;
var baseRateLimit = 2000;
var lastReport = 0;
var pairs = [];
var liquidationOrders = [];
var lastUpdate = 0;
var global_balance;
const drawdownThreshold = process.env.TIMEOUT_BLACKLIST_FOR_BIG_DRAWDOWN == "true" ? parseFloat(process.env.DRAWDOWN_THRESHOLD) : 0
// queue to sequentially execute scalp method
var tradeOrdersQueue = [];
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/css', express.static('gui/css'));
app.use('/img', express.static('gui/img'));
app.use('/node_modules', express.static('node_modules/socket.io/client-dist'));
app.use(session({
secret: process.env.GUI_SESSION_PASSWORD,
resave: false,
saveUninitialized: true
}));
app.get('/login', (req, res) => {
res.sendFile('login.html', { root: 'gui' });
});
app.post('/login', (req, res) => {
const password = req.body.password;
if (password === process.env.GUI_PASSWORD) {
req.session.isLoggedIn = true;
res.redirect('/');
} else {
res.status(401).send('Wrong password');
}
});
app.get('/', isAuthenticated, (req, res) => {
res.sendFile('index.html', { root: 'gui' });
});
app.get('/settings', isAuthenticated, (req, res) => {
res.sendFile('settings.html', { root: 'gui' });
});
app.get('/stats', isAuthenticated, (req, res) => {
res.sendFile('stats.html', { root: 'gui' });
});
const runningStatus_UNDEFINED = 0;
const runningStatus_RUN = 1;
const runningStatus_PAUSE = 2;
const runningStatus_Label = ["Undefined", "Running", "Paused"];
var runningStatus = runningStatus_UNDEFINED
app.get('/runningStatus', getRunningStatus, (req, res) => {
res.sendFile('index.html', { root: 'gui' });
});
io.on('connection', (socket) => {
socket.on('setting', (msg) => {
changeENV(msg.set, msg.val)
});
socket.on('sendsettings', (msg) => {
getSettings()
});
});
server.listen(PORT, () => {
const interfaces = networkInterfaces();
const addresses = [];
for (const iface of Object.values(interfaces)) {
for (const addr of iface) {
if (addr.family === 'IPv4' && !addr.internal) {
addresses.push(addr.address);
}
}
}
logIT(`GUI running on http://${addresses[0]}:${PORT}`)
});
//create ws client
const wsClient = new WebsocketClient({
key: key,
secret: secret,
market: 'linear',
livenet: true,
});
const binanceClient = new binanceWS({
beautify: true,
});
//create linear client
const linearClient = new LinearClient({
key: key,
secret: secret,
livenet: true,
});
//account client
if (process.env.WITHDRAW == "true" || process.env.TRANSFER_TO_SPOT == "true"){
const accountClient = new AccountAssetClient({
key: key,
secret: secret,
livenet: true,
});
}
function handleNewOrder(order, liquidity_trigger) {
// Add liquidity_trigger to order as list of liquidity to keep count of dca order i.e
// _liquidity_trigger: "liq1,liq2,...liqN"
const position = newPosition({...order, "liquidity_trigger": `\"${liquidity_trigger}\"`});
tradesHistory.set(order.symbol, position);
incOpenPosition();
}
function handleDcaOrder(order, liquidity_trigger) {
let trade_info = tradesHistory.get(order.symbol);
if (trade_info !== undefined) {
trade_info._dca_count++;
//remove "" before append a new liquidity item.
trade_info._liquidity_trigger = trade_info._liquidity_trigger.replace(/"/g, "");
trade_info._liquidity_trigger = `\"${trade_info._liquidity_trigger} ${liquidity_trigger}\"`;
if (process.env.TRACE_TRADES != TRACE_TRADES_LEVEL_OFF)
traceTrade("dca", trade_info, traceTradeFields);
}
}
function tradeOrdersQueue_enqueue(orderFnObj) {
let ordersInProgress = tradeOrdersQueue.filter(el => el.pair === orderFnObj.pair);
if (ordersInProgress.length == 0)
tradeOrdersQueue.push(orderFnObj);
}
wsClient.on('update', (data) => {
logIT(`raw message received ${JSON.stringify(data, null, 2)}`, LOG_LEVEL.DEBUG);
const topic = data.topic;
if (topic === "stop_order") {
const order_data = data.data;
//check for stoploss trigger
if (order_data[0].stop_order_type === "StopLoss" && order_data[0].order_status === "Triggered"){
//add coin to timeout
addCoinToTimeout(order_data[0].symbol, process.env.STOP_LOSS_TIMEOUT);
messageWebhook(order_data[0].symbol + " hit Stop Loss!\n Waiting " + process.env.STOP_LOSS_TIMEOUT + " ms for timeout...");
}
let trade_info = tradesHistory.get(order_data[0].symbol);
if (trade_info !== undefined && order_data[0].order_status === "Triggered" && (order_data[0].stop_order_type === "StopLoss" || order_data[0].stop_order_type === "TakeProfit")) {
trade_info._close_type = order_data[0].stop_order_type;
}
} else if (topic === "order") {
let close_position = false;
const filled_orders = data.data.filter(el => el.order_status == 'Filled');
filled_orders.forEach( order => {
let trade_info = tradesHistory.get(order.symbol);
// 26/05/2023 patch as ByBit change order.create_type
const order_type = trade_info._close_type ? trade_info._close_type : order.create_type;
switch(order_type) {
case 'CreateByUser':
// new trade
if (trade_info !== undefined) {
// update price with executed order price
// verify that it's starts order not dca
if (trade_info._start_price === 0) {
trade_info._start_price = order.last_exec_price;
traceTrade("start", trade_info, traceTradeFields);
}
}
break;
case 'StopLoss':
close_position = true;
globalTradesStats.consecutive_wins = 0;
globalTradesStats.consecutive_losses += 1;
globalTradesStats.max_consecutive_losses = Math.max(globalTradesStats.max_consecutive_losses, globalTradesStats.consecutive_losses);
globalTradesStats.losses_count += 1;
break;
case 'TakeProfit':
close_position = true;
globalTradesStats.consecutive_losses = 0;
globalTradesStats.consecutive_wins += 1;
globalTradesStats.max_consecutive_wins = Math.max(globalTradesStats.max_consecutive_wins, globalTradesStats.consecutive_wins);
globalTradesStats.wins_count += 1;
if (drawdownThreshold > 0 && trade_info._max_loss > drawdownThreshold) {
addCoinToTimeout(order.symbol, process.env.STOP_LOSS_TIMEOUT);
logIT(`handleTakeProfit::addCoinToTimeout for ${order.symbol} as during the trade have a loss greater than drawdownThreshold`);
}
break;
default:
// NOP
}
if (close_position) {
globalTradesStats.trade_count += 1;
globalTradesStats.max_loss = Math.min(globalTradesStats.max_loss, trade_info._max_loss);
closePosition(trade_info, order);
storeJson(globalStatsPath, globalTradesStats);
logIT(`#trade_stats:close# ${order.symbol}: ${JSON.stringify(trade_info)}`);
logIT(`#global_stats:close# ${JSON.stringify(globalTradesStats)}`);
if (process.env.TRACE_TRADES != TRACE_TRADES_LEVEL_OFF)
traceTrade(order_type, trade_info, traceTradeFields);
tradesHistory.delete(order.symbol);
decOpenPosition();
}
});
} else {
var pair = data.data.symbol;
var price = parseFloat(data.data.price);
var side = data.data.side;
//convert to float
var qty = parseFloat(data.data.qty) * price;
//create timestamp
var timestamp = Math.floor(Date.now() / 1000);
//find what index of liquidationOrders array is the pair
var index = liquidationOrders.findIndex(x => x.pair === pair);
var dir = "";
if (side === "Buy") {
dir = "Long";
} else {
dir = "Short";
}
//get blacklisted pairs
const blacklist = [];
var blacklist_all = process.env.BLACKLIST;
blacklist_all = blacklist_all.replaceAll(" ", "");
blacklist_all.split(',').forEach(item => {
blacklist.push(item);
});
// get whitelisted pairs
const whitelist = [];
var whitelist_all = process.env.WHITELIST;
whitelist_all = whitelist_all.replaceAll(" ", "");
whitelist_all.split(',').forEach(item => {
whitelist.push(item);
});
//if pair is not in liquidationOrders array and not in blacklist, add it
if (index === -1 && (!blacklist.includes(pair)) && (process.env.USE_WHITELIST == "false" || (process.env.USE_WHITELIST == "true" && whitelist.includes(pair)))) {
liquidationOrders.push({pair: pair, price: price, side: side, qty: qty, amount: 1, timestamp: timestamp});
index = liquidationOrders.findIndex(x => x.pair === pair);
}
//if pair is in liquidationOrders array, update it
else if ((!blacklist.includes(pair)) && (process.env.USE_WHITELIST == "false" || (process.env.USE_WHITELIST == "true" && whitelist.includes(pair)))) {
//check if timesstamp is withing 5 seconds of previous timestamp
if (timestamp - liquidationOrders[index].timestamp <= 5) {
liquidationOrders[index].price = price;
liquidationOrders[index].side = side;
//add qty to existing qty and round to 2 decimal places
liquidationOrders[index].qty = parseFloat((liquidationOrders[index].qty + qty).toFixed(2));
liquidationOrders[index].timestamp = timestamp;
liquidationOrders[index].amount = liquidationOrders[index].amount + 1;
}
//if timestamp is more than 5 seconds from previous timestamp, overwrite
else {
liquidationOrders[index].price = price;
liquidationOrders[index].side = side;
liquidationOrders[index].qty = qty;
liquidationOrders[index].timestamp = timestamp;
liquidationOrders[index].amount = 1;
}
if (liquidationOrders[index].qty > process.env.MIN_LIQUIDATION_VOLUME) {
if (stopLossCoins.has(pair) == true && process.env.USE_STOP_LOSS_TIMEOUT == "true") {
logIT(chalk.yellow(liquidationOrders[index].pair + " is not allowed to trade cause it is on timeout"));
} else {
if (process.env.PLACE_ORDERS_SEQUENTIALLY == "true")
tradeOrdersQueue_enqueue({'pair': pair, 'fn': scalp.bind(null, pair, {...liquidationOrders[index]}, 'Bybit', runningStatus != runningStatus_RUN)});
else
scalp(pair, {...liquidationOrders[index]}, 'Bybit', runningStatus != runningStatus_RUN);
}
}
else {
logIT(chalk.magenta("[" + liquidationOrders[index].amount + "] " + dir + " Liquidation order for " + liquidationOrders[index].pair + " @Bybit with a cumulative value of " + liquidationOrders[index].qty + " USDT"));
logIT(chalk.yellow("Not enough liquidations to trade " + liquidationOrders[index].pair));
}
}
else {
logIT(chalk.gray("Liquidation Found for Blacklisted pair: " + pair + " ignoring..."));
}
}
});
binanceClient.on('formattedMessage', (data) => {
//console.log('raw message received ', JSON.stringify(data, null, 2));
var pair = data.liquidationOrder.symbol;
var price = parseFloat(data.liquidationOrder.price);
var oside = data.liquidationOrder.side;
//convert to float
var qty = parseFloat(data.liquidationOrder.quantity) * price;
//create timestamp
var timestamp = Math.floor(Date.now() / 1000);
//find what index of liquidationOrders array is the pair
var index = liquidationOrders.findIndex(x => x.pair === pair);
var dir = "";
var side = "";
if (oside === "BUY") {
dir = "Long";
side = "Sell";
} else {
dir = "Short";
side = "Buy";
}
//get blacklisted pairs
const blacklist = [];
var blacklist_all = process.env.BLACKLIST;
blacklist_all = blacklist_all.replaceAll(" ", "");
blacklist_all.split(',').forEach(item => {
blacklist.push(item);
});
// get whitelisted pairs
const whitelist = [];
var whitelist_all = process.env.WHITELIST;
whitelist_all = whitelist_all.replaceAll(" ", "");
whitelist_all.split(',').forEach(item => {
whitelist.push(item);
});
//if pair is not in liquidationOrders array and not in blacklist, add it
if (index === -1 && (!blacklist.includes(pair)) && (process.env.USE_WHITELIST == "false" || (process.env.USE_WHITELIST == "true" && whitelist.includes(pair)))) {
liquidationOrders.push({pair: pair, price: price, side: side, qty: qty, amount: 1, timestamp: timestamp});
index = liquidationOrders.findIndex(x => x.pair === pair);
}
//if pair is in liquidationOrders array, update it
else if ((!blacklist.includes(pair)) && (process.env.USE_WHITELIST == "false" || (process.env.USE_WHITELIST == "true" && whitelist.includes(pair)))) {
//check if timesstamp is withing 5 seconds of previous timestamp
if (timestamp - liquidationOrders[index].timestamp <= 5) {
liquidationOrders[index].price = price;
liquidationOrders[index].side = side;
//add qty to existing qty and round to 2 decimal places
liquidationOrders[index].qty = parseFloat((liquidationOrders[index].qty + qty).toFixed(2));
liquidationOrders[index].timestamp = timestamp;
liquidationOrders[index].amount = liquidationOrders[index].amount + 1;
}
//if timestamp is more than 5 seconds from previous timestamp, overwrite
else {
liquidationOrders[index].price = price;
liquidationOrders[index].side = side;
liquidationOrders[index].qty = qty;
liquidationOrders[index].timestamp = timestamp;
liquidationOrders[index].amount = 1;
}
if (liquidationOrders[index].qty > process.env.MIN_LIQUIDATION_VOLUME) {
if (stopLossCoins.has(pair) == true && process.env.USE_STOP_LOSS_TIMEOUT == "true") {
logIT(chalk.yellow(liquidationOrders[index].pair + " is not allowed to trade cause it is on timeout"));
} else {
if (process.env.PLACE_ORDERS_SEQUENTIALLY == "true")
tradeOrdersQueue_enqueue({'pair': pair, 'fn': scalp.bind(null, pair, {...liquidationOrders[index]}, 'Binance', runningStatus != runningStatus_RUN)});
else
scalp(pair, {...liquidationOrders[index]}, 'Binance', runningStatus != runningStatus_RUN);
}
}
else {
logIT(chalk.magenta("[" + liquidationOrders[index].amount + "] " + dir + " Liquidation order for " + liquidationOrders[index].pair + " @Binance with a cumulative value of " + liquidationOrders[index].qty + " USDT"));
logIT(chalk.yellow("Not enough liquidations to trade " + liquidationOrders[index].pair));
}
}
else {
logIT(chalk.gray("Liquidation Found for Blacklisted pair: " + pair + " ignoring..."));
}
});
wsClient.on('open', (data,) => {
//console.log('connection opened open:', data.wsKey);
//catch error
if (data.wsKey === WS_KEY_MAP.WS_KEY_ERROR) {
logIT("Error: " + data)
return;
}
//logIT("Connection opened");
});
wsClient.on('response', (data) => {
if (data.wsKey === WS_KEY_MAP.WS_KEY_ERROR) {
logIT("Error: " + data)
return;
}
//logIT("Connection opened");
});
wsClient.on('reconnect', ({ wsKey }) => {
logIT('ws automatically reconnecting.... ', wsKey);
});
wsClient.on('reconnected', (data) => {
logIT('ws has reconnected ', data?.wsKey);
});
binanceClient.on('open', (data,) => {
//console.log('connection opened open:', data.wsKey);
});
binanceClient.on('reply', (data) => {
//console.log("Connection opened");
});
binanceClient.on('reconnecting', ({ wsKey }) => {
logIT('ws automatically reconnecting.... ', wsKey);
});
binanceClient.on('reconnected', (data) => {
logIT('ws has reconnected ', data?.wsKey);
});
binanceClient.on('error', (data) => {
logIT('ws saw error ', data?.wsKey);
});
//subscribe to stop_order to see when we hit stop-loss
wsClient.subscribe('stop_order')
//subscribe to order to see when orders where executed
wsClient.subscribe('order')
//run websocket
async function liquidationEngine(pairs) {
if (process.env.LIQ_SOURCE.toLowerCase() == 'both') {
wsClient.subscribe(pairs);
binanceClient.subscribeAllLiquidationOrders('usdm');
}
else if (process.env.LIQ_SOURCE.toLowerCase() == 'binance') {
binanceClient.subscribeAllLiquidationOrders('usdm');
}
else {
wsClient.subscribe(pairs);
}
}
async function transferFunds(amount) {
const transfer = await accountClient.createInternalTransfer(
{
transfer_id: await generateTransferId(),
coin: 'USDT',
amount: amount.toFixed(2),
from_account_type: 'CONTRACT',
to_account_type: 'SPOT',
}
);
}
async function withdrawFunds() {
const settings = JSON.parse(fs.readFileSync('account.json', 'utf8'));
if (process.env.WITHDRAW == "true"){
const withdraw = await accountClient.submitWithdrawal(
{
coin: process.env.WITHDRAW_COIN,
chain: process.env.WITHDRAW_CHAIN,
address: process.env.WITHDRAW_ADDRESS,
amount: String(process.env.AMOUNT_TO_WITHDRAW).toFixed(2),
account_type: process.env.WITHDRAW_ACCOUNT
}
);
logIT("Withdrawl completed!")
} else {
logIT("Would withdrawl, but it's not active..")
}
}
//Generate transferId
async function generateTransferId() {
const hexDigits = "0123456789abcdefghijklmnopqrstuvwxyz";
let transferId = "";
for (let i = 0; i < 32; i++) {
transferId += hexDigits.charAt(Math.floor(Math.random() * 16));
if (i === 7 || i === 11 || i === 15 || i === 19) {
transferId += "-";
}
}
return transferId;
}
//Get server time
async function getServerTime() {
const data = await linearClient.fetchServerTime();
var serverTime = new Date(data * 1000);
var serverTimeGmt = serverTime.toGMTString()+'\n' + serverTime.toLocaleString();
return serverTimeGmt;
}
//Get margin
async function getMargin() {
const data = await linearClient.getWalletBalance();
var usedBalance = data.result['USDT'].used_margin;
var balance = usedBalance;
return balance;
}
//get account balance
var getBalanceTryCount = 0;
async function getBalance() {
try{
// get ping
var started = Date.now();
const data = await linearClient.getWalletBalance();
var elapsed = (Date.now() - started);
if (data.ret_code != 0) {
logIT(chalk.redBright("Error fetching balance. err: " + data.ret_code + "; msg: " + data.ret_msg));
getBalanceTryCount++;
if (getBalanceTryCount == 3)
process.exit(1);
return;
}
getBalanceTryCount = 0
var availableBalance = data.result['USDT'].available_balance;
// save balance global to reduce api requests
global_balance = data.result['USDT'].available_balance;
var usedBalance = data.result['USDT'].used_margin;
var balance = availableBalance + usedBalance;
//load settings.json
const settings = JSON.parse(fs.readFileSync('account.json', 'utf8'));
//check if starting balance is set
if (settings.startingBalance === 0) {
settings.startingBalance = balance;
fs.writeFileSync('account.json', JSON.stringify(settings, null, 4));
var startingBalance = settings.startingBalance;
}
else {
var startingBalance = settings.startingBalance;
}
var diff = balance - startingBalance;
var percentGain = (diff / startingBalance) * 100;
//check for gain to safe amount to spot
if (diff >= process.env.AMOUNT_TO_SPOT && process.env.AMOUNT_TO_SPOT > 0 && process.env.TRANSFER_TO_SPOT == "true"){
transferFunds(diff)
logIT("Moved " + diff + " to SPOT")
}
//check spot balance to withdraw
//spot client
if (process.env.TRANSFER_TO_SPOT == "true" || process.env.WITHDRAW == "true"){
const spotClient = new SpotClientV3({
key: key,
secret: secret,
livenet: true,
});
const spotBal = await spotClient.getBalances();
if (spotBal.retCode != 0) {
logIT(chalk.redBright("Error fetching spot balance. err: " + spotBal.retCode + "; msg: " + spotBal.retMsg));
process.exit(1);
}
var withdrawCoin = spotBal.result.balances.find(item => item.coin === process.env.WITHDRAW_COIN);
if (withdrawCoin !== undefined && withdrawCoin.total >= process.env.AMOUNT_TO_WITHDRAW && process.env.WITHDRAW == "true"){
withdrawFunds();
logIT("Withdraw " + withdrawCoin.total + " to " + process.env.WITHDRAW_ADDRESS)
}
}
//if positive diff then log green
if (diff >= 0) {
logIT(chalk.greenBright.bold("Profit: " + diff.toFixed(4) + " USDT" + " (" + percentGain.toFixed(2) + "%)") + " | " + chalk.magentaBright.bold("Balance: " + balance.toFixed(4) + " USDT"));
}
else {
logIT(chalk.redBright.bold("Profit: " + diff.toFixed(4) + " USDT" + " (" + percentGain.toFixed(2) + "%)") + " " + chalk.magentaBright.bold("Balance: " + balance.toFixed(4) + " USDT"));
}
// create the gui data
var percentGain = percentGain.toFixed(6);
var diff = diff.toFixed(6);
//fetch positions
var positions = await linearClient.getPosition();
var positionList = [];
var openPositions = await totalOpenPositions();
if(openPositions === null) {
openPositions = 0;
}
var marg = await getMargin();
var time = await getServerTime();
//loop through positions.result[i].data get open symbols with size > 0 calculate pnl and to array
for (var i = 0; i < positions.result.length; i++) {
if (positions.result[i].data.size > 0) {
var pnl1 = positions.result[i].data.unrealised_pnl;
var pnl = pnl1.toFixed(6);
var symbol = positions.result[i].data.symbol;
var size = positions.result[i].data.size;
var liq = positions.result[i].data.liq_price;
var size = size.toFixed(4);
var ios = positions.result[i].data.is_isolated;
var priceFetch = await linearClient.getTickers({symbol: symbol});
var test = priceFetch.result[0].last_price;
let side = positions.result[i].data.side;
var dir = "";
if (side === "Buy") {
dir = "✅ Long / ❌ Short";
} else {
dir = "❌ Long / ✅ Short";
}
var stop_loss = positions.result[i].data.stop_loss;
var take_profit = positions.result[i].data.take_profit;
var price = positions.result[i].data.entry_price;
var fee = positions.result[i].data.occ_closing_fee;
var price = price.toFixed(4);
//calulate size in USDT
var usdValue = (positions.result[i].data.entry_price * size) / process.env.LEVERAGE;
var position = {
"symbol": symbol,
"size": size,
"side": dir,
"sizeUSD": usdValue.toFixed(3),
"pnl": pnl,
"liq": liq,
"price": price,
"stop_loss": stop_loss,
"take_profit": take_profit,
"iso": ios,
"test": test,
"fee": fee.toFixed(3),
}
let trade = tradesHistory.get(symbol);
// handle existing orders when app starts
if (trade === undefined) {
var usdValue = (positions.result[i].data.entry_price * size) / process.env.LEVERAGE;
const dca_count = Math.trunc( usdValue / (balance*process.env.PERCENT_ORDER_SIZE/100) );
tradesHistory.set(symbol, {...position, "_max_loss" : 0, "_dca_count" : dca_count, "_start_price" : positions.result[i].data.entry_price});
trade = tradesHistory.get(symbol);
} else {
updatePosition(trade, {"_max_loss": Math.min(pnl, trade._max_loss), "price": price, "stop_loss": stop_loss, "take_profit": take_profit});
}
positionList.push({...position, "dca_count": trade._dca_count, "max_loss": trade._max_loss.toFixed(3)});
if (process.env.TRACE_TRADES == TRACE_TRADES_LEVEL_MAX)
traceTrade("cont", trade, traceTradeFields);
}
}
//create data payload
const posidata = {
balance: balance.toFixed(2).toString(),
leverage: process.env.LEVERAGE.toString(),
totalUSDT: marg.toFixed(2).toString(),
profitUSDT: diff.toString(),
profit: percentGain.toString(),
servertime: time.toString(),
positioncount: openPositions.toString(),
ping: elapsed,
runningStatus: runningStatus_Label[runningStatus].toString(),
trade_count: globalTradesStats.trade_count,
max_loss: globalTradesStats.max_loss,
wins_count: globalTradesStats.wins_count,
loss_count: globalTradesStats.losses_count,
max_consecutive_wins: globalTradesStats.max_consecutive_wins,
max_consecutive_losses: globalTradesStats.max_consecutive_losses,
};
//send data to gui
io.sockets.emit("data", posidata);
const positionsData = [];
//for each position in positionList add field only 7 fields per embed
for(var i = 0; i < positionList.length; i++) {
positionsData.push({
symbol: positionList[i].symbol,
isolated: positionList[i].iso,
closing_fee: positionList[i].fee,
size: positionList[i].size,
sizeUSD: positionList[i].sizeUSD,
pnl: positionList[i].pnl,
side: positionList[i].side,
price: positionList[i].test,
entry_price: positionList[i].price,
stop_loss: positionList[i].stop_loss,
take_profit: positionList[i].take_profit,
liq_price: positionList[i].liq,
max_loss: positionList[i].max_loss,
dca_count: positionList[i].dca_count,
});
}
//send data to gui
io.sockets.emit("positions", positionsData);
return balance;
}
catch (e) {
return null;
}
}
//get position
async function getPosition(pair, side) {
//gor through all pairs and getPosition()
var positions = await linearClient.getPosition(pair);
const error_result = {side: null, entryPrice: null, size: null, percentGain: null};
if (positions.result == null)
logIT("Open positions response is null");
else if (!Array.isArray(positions.result))
logIT(`Open positions bad results: array type was expected: positions.result = ${positions.result}`);
else {
//look for pair in positions with the same side
var index = positions.result.findIndex(x => x.data.symbol === pair && x.data.side === side);
//make sure index is not -1
if (index == -1)
logIT(`Open positions bad response: symbol ${pair} not found`);
else {
if (positions.result[index].data.size >= 0) {
//console.log(positions.result[index].data);
if(positions.result[index].data.size > 0){
logIT(chalk.blueBright("Open position found for " + positions.result[index].data.symbol + " with a size of " + positions.result[index].data.size + " contracts" + " with profit of " + positions.result[index].data.realised_pnl + " USDT"));
var profit = positions.result[index ].data.unrealised_pnl;
//calculate the profit % change in USD
var margin = positions.result[index ].data.position_value/process.env.LEVERAGE;
var percentGain = (profit / margin) * 100;
return {side: positions.result[index].data.side, entryPrice: positions.result[index].data.entry_price, size: positions.result[index].data.size, percentGain: percentGain};
}
else{
//no open position
return {side: positions.result[index].data.side, entryPrice: positions.result[index].data.entry_price, size: positions.result[index].data.size, percentGain: 0};
}
}
else {
// adding this for debugging purposes
logIT("Error: getPostion invalid for " + pair + " size parameter is returning " + positions.result[index].data.size);
messageWebhook("Error: getPostion invalid for " + pair + " size parameter is returning " + positions.result[index].data.size);
return {side: null, entryPrice: null, size: null, percentGain: null};
}
}
}
// return on error
return {side: null, entryPrice: null, size: null, percentGain: null};
}
//take profit
async function takeProfit(symbol, position) {
//get entry price
var positions = await position;
if (positions.side === "Buy") {
var side = "Buy";
var takeProfit = positions.entry_price + (positions.entry_price * (process.env.TAKE_PROFIT_PERCENT/100) / process.env.LEVERAGE);
var stopLoss = positions.entry_price - (positions.entry_price * (process.env.STOP_LOSS_PERCENT/100) / process.env.LEVERAGE);
}
else {
var side = "Sell";
var takeProfit = positions.entry_price - (positions.entry_price * (process.env.TAKE_PROFIT_PERCENT/100) / process.env.LEVERAGE);
var stopLoss = positions.entry_price + (positions.entry_price * (process.env.STOP_LOSS_PERCENT/100) / process.env.LEVERAGE);
}
//load min order size json
const tickData = JSON.parse(fs.readFileSync('min_order_sizes.json', 'utf8'));
try {
var index = tickData.findIndex(x => x.pair === symbol);
var tickSize = tickData[index].tickSize;
var decimalPlaces = (tickSize.toString().split(".")[1] || []).length;
if (positions.size > 0 && positions.take_profit.toFixed(decimalPlaces) === 0 || takeProfit.toFixed(decimalPlaces) !== positions.take_profit.toFixed(decimalPlaces) || stopLoss.toFixed(decimalPlaces) !== positions.stop_loss.toFixed(decimalPlaces)) {
if(process.env.USE_STOPLOSS.toLowerCase() === "true") {
var cfg = {
symbol: symbol,
side: side,
stop_loss: stopLoss.toFixed(decimalPlaces),
};
if(process.env.USE_TAKE_PROFIT.toLowerCase() === "true")
cfg['take_profit'] = takeProfit.toFixed(decimalPlaces)
const order = await linearClient.setTradingStop(cfg);
//console.log(JSON.stringify(order, null, 4));
if (order.ret_msg === "OK" || order.ret_msg === "not modified" || order.ret_code === 10002) {
//console.log(chalk.red("TAKE PROFIT ERROR: ", JSON.stringify(order, null, 2)));
}
else if (order.ret_code === 130027 || order.ret_code === 130030 || order.ret_code === 130024) {
//find current price
var priceFetch = await linearClient.getTickers({symbol: symbol});
var price = priceFetch.result[0].last_price;
//if side is sell add 1 tick to price
if (side === "Sell") {
price = parseFloat(priceFetch.result[0].ask_price);
}
else {
price = parseFloat(priceFetch.result[0].bid_price);
}
var cfg = {
symbol: symbol,
side: side,
stop_loss: stopLoss.toFixed(decimalPlaces),
};
if(process.env.USE_TAKE_PROFIT.toLowerCase() === "true")
cfg['take_profit'] = price.toFixed(decimalPlaces)
const order = await linearClient.setTradingStop(cfg);
logIT(chalk.red("TAKE PROFIT FAILED FOR " + symbol + " WITH ERROR PRICE MOVING TOO FAST OR ORDER ALREADY CLOSED, TRYING TO FILL AT BID/ASK!!"));
}
else {
logIT(chalk.red("TAKE PROFIT ERROR: ", JSON.stringify(order, null, 4)));
}
}
else if (process.env.USE_TAKE_PROFIT.toLowerCase() === "true"){
const order = await linearClient.setTradingStop({
symbol: symbol,
side: side,
take_profit: takeProfit.toFixed(decimalPlaces),
});
//console.log(JSON.stringify(order, null, 2));
if(order.ret_msg === "OK" || order.ret_msg === "not modified" || order.ret_code === 130024) {
//console.log(chalk.red("TAKE PROFIT ERROR: ", JSON.stringify(order, null, 2)));
}
else if (order.ret_code === 130027 || order.ret_code === 130030) {
logIT(chalk.cyanBright("TAKE PROFIT FAILED PRICING MOVING FAST!! TRYING TO PLACE ABOVE CURRENT PRICE!!"));
//find current price
var priceFetch = await linearClient.getTickers({symbol: symbol});
logIT("Current price: " + JSON.stringify(priceFetch, null, 4));
var price = priceFetch.result[0].last_price;
//if side is sell add 1 tick to price
if (side === "Sell") {
price = priceFetch.result[0].ask_price
}
else {
price = priceFetch.result[0].bid_price
}
logIT("Price for symbol " + symbol + " is " + price);
const order = await linearClient.setTradingStop({
symbol: symbol,
side: side,
take_profit: price,
});
logIT(chalk.red("TAKE PROFIT FAILED FOR " + symbol + " WITH ERROR PRICE MOVING TOO FAST, TRYING TO FILL AT BID/ASK!!"));
}
else {
logIT(chalk.red("TAKE PROFIT ERROR: ", JSON.stringify(order, null, 2)));
}
}
}
else {
logIT("No take profit to set for " + symbol);
console.log("takeProfit " + takeProfit.toFixed(decimalPlaces))
console.log("positions.take_profit " + positions.take_profit.toFixed(decimalPlaces))
}
}
catch (e) {
logIT(chalk.red("Error setting take profit: " + e + " for symbol " + symbol));
}
}
function incOpenPosition() {
openPositions = (openPositions ?? 0) + 1;
}
function decOpenPosition() {
openPositions = (openPositions ?? 0) - 1;
if (openPositions < 0) {
logIT("decOpenPosition ERROR: open position < 0");
openPositions = undefined;
}
}
//fetch how how openPositions there are
async function totalOpenPositions() {
if (openPositions === undefined) {
try{
var positions = await linearClient.getPosition();
var open = 0;
for (var i = 0; i < positions.result.length; i++) {
if (positions.result[i].data.size > 0) {
open++;
}
}
openPositions = open;
}
catch (error) {
return null;
}
}
return openPositions;
}