-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.mjs
544 lines (520 loc) · 17.2 KB
/
main.mjs
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
// Dependencies
import chalk from "chalk";
import dotenv from "dotenv";
import Taapi from "taapi";
import { exec } from "child_process";
dotenv.config();
function logger(level, message) {
const timestamp = new Date().toISOString();
let color = chalk.hex("#15B5B0");
if (level == "error") {
color = chalk.red;
} else if (level == "warn") {
color = chalk.hex("#FFA500");
} else if (level == "finance") {
color = chalk.hex("#3EAB76");
} else if (level == "finance-profit") {
color = chalk.hex("#FF00DD");
}
console.log(color(`${timestamp} - ${message}`));
}
function sendTelegramMessage(message) {
exec(`telegram-send "${message}"`, (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
if (stderr) {
console.error(`Stderr: ${stderr}`);
return;
}
// console.log(`Stdout: ${stdout}`);
});
}
// Dynamically import the ES Module '@ln-markets/api'
async function loadModules() {
// Function to validate the presence of required environment variables
function validateEnvVariables() {
const requiredEnv = [
"LNM_API_KEY",
"LNM_API_SECRET",
"LNM_PASSPHRASE",
"TAAPI_API_KEY",
];
const missingEnv = requiredEnv.filter((envVar) => !process.env[envVar]);
if (missingEnv.length > 0) {
throw new Error(
`Missing required environment variables: ${missingEnv.join(", ")}`
);
}
}
// Validate environment variables before creating Taapi client
validateEnvVariables();
const { createRestClient, createWebsocketClient } = await import(
"@ln-markets/api"
);
// Configuration
const apiConfig = {
key: process.env.LNM_API_KEY,
secret: process.env.LNM_API_SECRET,
passphrase: process.env.LNM_PASSPHRASE,
};
const taapiClient = new Taapi.default(process.env.TAAPI_API_KEY);
// RestClient Initialization
const restClient = createRestClient(apiConfig);
// Retry
let retryCount = 0;
const maxRetries = 5;
// Trading State
let lastTradeTime = 0;
let lastPrice = null;
let indexPrice = null;
const fetchInterval = 60000;
let lastCalledTime = Date.now() - fetchInterval;
let lastTradeLogicCall = 0;
let rsiData = [];
let lastTickDirection = '';
let minusTickCounter = 0;
let plusTickDetected = false;
const period = 15;
const tradeLogicCooldown = 60 * 1000;
const canMakeTrade = () => Date.now() - lastTradeTime > 1000;
function calculateMovingAverage(data, period) {
let movingAverages = [];
for (let i = period - 1; i < data.length; i++) {
let sum = 0;
for (let j = 0; j < period; j++) {
if (isNaN(data[i - j])) {
logger("error", `Non-numeric data encountered: ${data[i - j]}`);
return NaN; // Or handle this case as appropriate
}
sum += data[i - j];
}
let average = sum / period;
movingAverages.push(average);
}
// logger('debug', `Calculated moving averages: ${movingAverages}`);
return movingAverages.length > 0
? movingAverages[movingAverages.length - 1]
: NaN;
}
function addRsiSample(sample) {
if (rsiData.length > 15) {
// Remove the oldest sample to make room for the new one
rsiData.shift();
}
// Add the new RSI sample
rsiData.push(sample);
}
async function fetchRSI(timeframe) {
const currentTime = Date.now();
if (currentTime - lastCalledTime < 15000) {
return Promise.reject("RSI call is on cooldown");
}
try {
// Call the RSI function and update the last called time
const rsiResponse = await taapiClient.getIndicator(
"rsi",
"BTC/USDT",
timeframe
);
lastCalledTime = currentTime;
return rsiResponse;
} catch (error) {
console.error(`Failed to fetch RSI: ${error.message}`);
return Promise.reject(error);
}
}
async function fetchBbands(timeframe) {
const currentTime = Date.now();
if (currentTime - lastCalledTime < 15000) {
return Promise.reject("RSI call is on cooldown");
}
try {
// Call the RSI function and update the last called time
const bbandsResponse = await taapiClient.getIndicator(
"bbands",
"BTC/USDT",
timeframe
);
lastCalledTime = currentTime;
return bbandsResponse;
} catch (error) {
console.error(`Failed to fetch Bbands: ${error.message}`);
return Promise.reject(error);
}
}
async function fetchUltosc(timeframe) {
const currentTime = Date.now();
if (currentTime - lastCalledTime < 15000) {
return Promise.reject("Ultosc call is on cooldown");
}
try {
const ultoscResponse = await taapiClient.getIndicator(
"ultosc",
"BTC/USDT",
timeframe
);
lastCalledTime = currentTime;
return ultoscResponse;
} catch (error) {
console.error(`Failed to fetch ultosc: ${error.message}`);
return Promise.reject(error);
}
}
async function fetchStddev(timeframe) {
const currentTime = Date.now();
if (currentTime - lastCalledTime < 15000) {
return Promise.reject("Stddev call is on cooldown");
}
try {
const stddevResponse = await taapiClient.getIndicator(
"stddev",
"BTC/USDT",
timeframe
);
lastCalledTime = currentTime;
return stddevResponse;
} catch (error) {
console.error(`Failed to fetch stddev: ${error.message}`);
return Promise.reject(error);
}
}
async function fetchMacd(timeframe) {
const currentTime = Date.now();
if (currentTime - lastCalledTime < 15000) {
return Promise.reject("Macd call is on cooldown");
}
try {
const macdResponse = await taapiClient.getIndicator(
"macd",
"BTC/USDT",
timeframe
);
lastCalledTime = currentTime;
return macdResponse;
} catch (error) {
console.error(`Failed to fetch macd: ${error.message}`);
return Promise.reject(error);
}
}
function shouldCallTradeLogic() {
const now = Date.now();
return now - lastTradeLogicCall >= tradeLogicCooldown;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Trading logic
async function tradeLogic() {
if (!canMakeTrade()) {
logger(
"error",
"Trade not possible: Cooling down period has not elapsed."
);
return;
}
if (lastPrice === null || indexPrice === null) {
return;
}
let sellBypass = false;
// Fetch positions
let totalSellExposure = 0;
let totalBuyExposure = 0;
try {
let runningPositions = await restClient.futuresGetTrades({
type: "running",
});
// Calculate total exposure for both sides
let profitableSells = 0;
let profitableBuys = 0;
let sellPl = 0;
let buyPl = 0;
let buyOrders = 0;
let sellOrders = 0;
let buyAvgPl = 0;
let sellAvgPl = 0;
runningPositions.forEach((position) => {
if (position.side === "s") {
sellOrders++;
sellPl += position.pl;
totalSellExposure += position.quantity;
if (position.pl > 30) {
logger(
"finance-profit",
`CLOSING SHORT POSITION ${JSON.stringify(position)}`
);
restClient.futuresCloseTrade(position.id);
profitableSells += position.quantity;
sendTelegramMessage(
`Closed profitable short on LNM: fee ${position.opening_fee}, price ${position.price}, pl ${position.pl}`
);
} else if (position.pl < -10) {
logger(
"error",
`CLOSING SHORT POSITION AT LOSS ${JSON.stringify(position)}`
);
restClient.futuresCloseTrade(position.id);
sendTelegramMessage(
`Closed short at a loss on LNM: fee ${position.opening_fee}, price ${position.price}, pl ${position.pl}`
);
}
} else if (position.side === "b") {
buyOrders++;
buyPl += position.pl;
totalBuyExposure += position.quantity;
if (position.pl > 30) {
logger(
"finance-profit",
`CLOSING LONG POSITION ${JSON.stringify(position)}`
);
restClient.futuresCloseTrade(position.id);
profitableBuys += position.quantity;
sendTelegramMessage(
`Closed profitable long on LNM: fee ${position.opening_fee}, price ${position.price}, pl ${position.pl}`
);
} else if (position.pl < -10) {
logger(
"error",
`CLOSING LONG POSITION AT LOSS ${JSON.stringify(position)}`
);
restClient.futuresCloseTrade(position.id);
sendTelegramMessage(
`Closed long at a loss on LNM: fee ${position.opening_fee}, price ${position.price}, pl ${position.pl}`
);
}
}
});
if (buyOrders > 2) {
buyAvgPl = buyPl / buyOrders;
}
if (sellOrders > 2) {
sellAvgPl = sellPl / sellOrders;
}
logger("info", `BuyAvgPl: ${buyAvgPl}, SellAvgPl: ${sellAvgPl}`);
// Reread positions
totalSellExposure = 0;
totalBuyExposure = 0;
await sleep(1000);
runningPositions = await restClient.futuresGetTrades({
type: "running",
});
runningPositions.forEach((position) => {
if (position.side === "s") {
totalSellExposure += position.quantity;
if (sellAvgPl > 5 && position.pl > sellAvgPl) {
logger(
"finance-profit",
`CLOSING SHORT POSITION ${JSON.stringify(position)}`
);
restClient.futuresCloseTrade(position.id);
sendTelegramMessage(
`Closed profitable short on LNM: fee ${position.opening_fee}, price ${position.price}, pl ${position.pl}`
);
} else {
logger("info", `Short position with pl ${position.pl}`);
}
} else if (position.side === "b") {
totalBuyExposure += position.quantity;
if (buyAvgPl > 5 && position.pl > buyAvgPl) {
logger(
"finance-profit",
`CLOSING LONG POSITION ${JSON.stringify(position)}`
);
restClient.futuresCloseTrade(position.id);
sendTelegramMessage(
`Closed profitable long on LNM: fee ${position.opening_fee}, price ${position.price}, pl ${position.pl}`
);
}
logger("info", `Long position with pl ${position.pl}`);
}
});
// }
logger(
"info",
`Profitable sells: $${profitableSells} (exp $${totalSellExposure} pl ${sellPl} sats), profitable buys: $${profitableBuys} (exp $${totalBuyExposure} pl ${buyPl} sats)`
);
if (buyPl >= 70) {
logger("info", "[DRY-RUN] triggered synthetic exit");
//sellBypass = true;
}
// logger('info', `Sell exposure: $${totalSellExposure}, Buy exposure: $${totalBuyExposure}, Position: $${totalBuyExposure-totalSellExposure}`);
} catch (error) {
logger("error", `Fetching positions failed: ${JSON.stringify(error)}`);
logger(error.stack);
}
logger("info", `Last tick direction: ${lastTickDirection}, price ${lastPrice}`);
if (lastTickDirection) {
if (lastTickDirection === 'MinusTick') {
minusTickCounter++;
plusTickDetected = false;
} else if (lastTickDirection === 'PlusTick') {
if (minusTickCounter >= 5) {
plusTickDetected = true;
}
minusTickCounter = 0;
}
}
try {
let action = "none";
let rsi = await fetchRSI("15m");
await sleep(15000);
let bbands = await fetchBbands("15m");
await sleep(15000);
// let ultosc = await fetchUltosc('15m');
// await sleep(15000);
let adjustedSellRsiThreshold = 75;
let adjustedBuyRsiThreshold = 45;
addRsiSample(rsi.value);
// Keep consuming RSI samples until we have `period` number of samples
// logger('finance', rsiData);
// logger('finance', `Ultosc: ${ultosc.value}`);
if (rsiData.length >= period) {
// Get moving average and print calculated thresholds
const movingAverageRSI = Number(
calculateMovingAverage(rsiData, period)
);
logger(
"finance",
`RSI_movAvg: ${movingAverageRSI}, RSI_mBuy: ${movingAverageRSI - 3}, RSI_mSell: ${
movingAverageRSI + 3
}`
);
adjustedSellRsiThreshold = movingAverageRSI + 3;
adjustedBuyRsiThreshold = movingAverageRSI - 3;
} else {
return;
}
logger(
"finance",
`RSI: ${rsi.value}, Bands: ${bbands.valueLowerBand} / ${bbands.valueUpperBand}`
);
logger("finance", `Price ${lastPrice}, Index price ${indexPrice}`);
if (totalSellExposure > 19 || totalBuyExposure > 19) {
// logger('info', 'Exposure on one side is greater than $9, returning early.');
return;
}
let sellPriceThreshold = bbands.valueLowerBand * 1.03;
let buyPriceThreshold = bbands.valueUpperBand * 0.9960;
logger(
"info",
`Sell thresh $${sellPriceThreshold}, Buy thresh $${buyPriceThreshold}`
);
// Check for sell conditions
if (
sellBypass ||
(rsi.value >= adjustedSellRsiThreshold &&
lastPrice > sellPriceThreshold)
) {
action = "sell";
if (sellBypass) {
logger("warn", "Condition met for selling: synthetic exit");
} else {
logger(
"warn",
`Condition met for selling: RSI ${rsi.value} is above ${adjustedSellRsiThreshold} and price is 3% higher than Bollinger Lower Band. Attempting to sell at ${lastPrice}.`
);
}
await restClient.futuresNewTrade({
side: "s",
type: "m",
leverage: 1,
quantity: 2,
});
sendTelegramMessage(`Shorted on LNM at ${lastPrice}`);
} else if (
plusTickDetected ||
(rsi.value <= adjustedBuyRsiThreshold &&
lastPrice < buyPriceThreshold)
) {
action = "buy";
logger(
"warn",
`Condition met for buying: RSI ${rsi.value} is below ${adjustedBuyRsiThreshold} and price is 0.40% lower than Bollinger Higher Band. Attempting to buy at ${lastPrice}.`
);
await restClient.futuresNewTrade({
side: "b",
type: "m",
leverage: 1,
quantity: 2,
});
sendTelegramMessage(`Longed on LNM at ${lastPrice}`);
}
// Update the timestamp of the last trade
lastTradeTime = Date.now();
if (action !== "none") {
logger("finance", `Trade action executed: ${action}`);
}
} catch (error) {
const errorLog = {
message: error.message,
stack: error.stack,
name: error.name,
};
logger("error", `Trade execution failed: ${errorLog.message}`);
logger("error", errorLog.stack);
const errorDetails = JSON.stringify(
error,
Object.getOwnPropertyNames(error)
);
logger("error", `Error details: ${errorDetails}`);
}
}
// WebSocket client for live data
async function setupWebSocket() {
logger("info", "Setting up websocket");
try {
const wsClient = await createWebsocketClient(apiConfig);
await wsClient.publicSubscribe([
"futures:btc_usd:last-price",
"futures:btc_usd:index",
]);
logger("info", "Subscribed to websocket topics");
wsClient.ws.on("futures:btc_usd:last-price", (data) => {
// logger("info", `Received price data: ${JSON.stringify(data, null, 2)}`);
if (data?.lastPrice !== undefined) {
lastPrice = data.lastPrice;
lastTickDirection = data.lastTickDirection;
// console.log(`Updated last price: ${lastPrice}`);
if (shouldCallTradeLogic()) {
tradeLogic();
lastTradeLogicCall = Date.now();
}
} else {
logger("error", "Last price data is undefined in the received data");
}
});
wsClient.ws.on("futures:btc_usd:index", (data) => {
// logger("info", `Received index data: ${JSON.stringify(data, null, 2)}`);
if (data?.index !== undefined) {
indexPrice = data.index;
if (shouldCallTradeLogic()) {
tradeLogic();
lastTradeLogicCall = Date.now();
}
} else {
logger("error", "Index price data is undefined in the received data");
}
});
wsClient.ws.on("open", () => (retryCount = 0));
wsClient.ws.on("close", () => {
logger("info", "WebSocket closed");
if (retryCount < maxRetries) {
let delay = Math.min(1000 * 2 ** retryCount, 30000);
logger("info", "Reconnecting websocket");
setTimeout(setupWebSocket, delay);
retryCount++;
} else {
logger("error", "Max retries reached for reconnect");
}
});
wsClient.ws.on("error", (error) =>
console.error(`WebSocket error: ${error.message}`)
);
} catch (error) {
logger("error", `WebSocket setup failed: ${error.message}`);
}
}
setupWebSocket();
}
loadModules().catch(console.error);