forked from DitherAI/MeteorShower
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmain.js
More file actions
2076 lines (1826 loc) Β· 101 KB
/
main.js
File metadata and controls
2076 lines (1826 loc) Β· 101 KB
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
// βββββββββββββββββββββββββββββββββββββββββββββββ
// ~/main.js
// βββββββββββββββββββββββββββββββββββββββββββββββ
import BN from 'bn.js';
import { loadWalletKeypair, getMintDecimals, safeGetBalance } from './lib/solana.js';
import { openDlmmPosition, recenterPosition } from './lib/dlmm.js';
import 'dotenv/config';
import { getPrice } from './lib/price.js';
import { promptSolAmount, promptTokenRatio, promptBinSpan, promptPoolAddress, promptLiquidityStrategy, promptSwaplessRebalance, promptAutoCompound, promptTakeProfitStopLoss, promptFeeHandling, promptCompoundingMode, promptInitialReentryBins, promptMinSwapUsd, promptRebalanceStrategy } from './balance-prompt.js';
import { checkBinArrayInitializationFees } from './lib/bin-array-checker.js';
import { logger } from './lib/logger.js';
import readline from 'readline';
import dlmmPackage from '@meteora-ag/dlmm';
import {
Connection,
PublicKey,
ComputeBudgetProgram,
sendAndConfirmTransaction,
} from '@solana/web3.js';
import { getDynamicPriorityFee, PRIORITY_LEVELS, getFallbackPriorityFee } from './lib/priority-fee.js';
import { SOL_MINT, PREFLIGHT_SOL_BUFFER } from './lib/constants.js';
import { calculateTransactionOverhead } from './lib/fee-utils.js';
import { getSolBalanceBigInt } from './lib/balance-utils.js';
import { sendTransactionWithSenderIfEnabled } from './lib/sender.js';
import { PnLTracker } from './lib/pnl-tracker.js';
import { withRetry, withDynamicRetry } from './lib/retry.js';
// pull vars from the environment
const {
RPC_URL,
WALLET_PATH,
MONITOR_INTERVAL_SECONDS = 5,
PNL_CHECK_INTERVAL_SECONDS = 10,
} = process.env;
/**
* Closes a specific position and swaps its tokens to SOL (TP/SL trigger)
* @param {Connection} connection
* @param {Object} dlmmPool
* @param {Object} userKeypair
* @param {PublicKey} positionPubKey
* @param {Object} pos - The position object
*/
async function closeSpecificPosition(connection, dlmmPool, userKeypair, positionPubKey, pos) {
const { withRetry } = await import('./lib/retry.js');
const { unwrapWSOL } = await import('./lib/solana.js');
console.log(`π― Closing specific position: ${positionPubKey.toBase58()}`);
console.log(` Pool: ${dlmmPool.pubkey.toBase58()}`);
console.log(` Range: Bin ${pos.positionData.lowerBinId} to ${pos.positionData.upperBinId}`);
try {
await withRetry(async () => {
// Close the position using the same logic as close-position.js
const removeTxs = await dlmmPool.removeLiquidity({
position: positionPubKey,
user: userKeypair.publicKey,
fromBinId: pos.positionData.lowerBinId,
toBinId: pos.positionData.upperBinId,
bps: new BN(10_000), // 100% removal
shouldClaimAndClose: true,
});
// π§ FIX: Handle multiple transactions for extended positions in TP/SL
console.log(` π Processing ${removeTxs.length} transaction(s) to close position...`);
for (let i = 0; i < removeTxs.length; i++) {
const tx = removeTxs[i];
// Add dynamic priority fee to each transaction
try {
const dynamicFee = await getDynamicPriorityFee(connection, tx, PRIORITY_LEVELS.MEDIUM);
tx.instructions.unshift(
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: dynamicFee })
);
console.log(` π° Using dynamic priority fee: ${dynamicFee.toLocaleString()} micro-lamports`);
} catch (error) {
const fallbackFee = getFallbackPriorityFee(PRIORITY_LEVELS.MEDIUM);
console.warn(` β οΈ Dynamic priority fee failed, using fallback: ${fallbackFee}`);
tx.instructions.unshift(
ComputeBudgetProgram.setComputeUnitPrice({ microLamports: fallbackFee })
);
}
tx.feePayer = userKeypair.publicKey;
// Refresh blockhash for each transaction
const recent = await connection.getLatestBlockhash('confirmed');
tx.recentBlockhash = recent.blockhash;
tx.lastValidBlockHeight = recent.lastValidBlockHeight;
const sig = await sendTransactionWithSenderIfEnabled(connection, tx, [userKeypair], PRIORITY_LEVELS.MEDIUM);
console.log(` β
TP/SL close transaction ${i + 1}/${removeTxs.length} completed: ${sig}`);
}
await unwrapWSOL(connection, userKeypair);
console.log(` β
Position fully closed with ${removeTxs.length} transaction(s)`);
}, 'closeSpecificPosition');
// Swap the tokens from this specific pool to SOL
console.log(` π Swapping tokens from this position to SOL...`);
await swapPositionTokensToSol(connection, dlmmPool, userKeypair);
console.log(`β
Successfully closed position and swapped tokens to SOL`);
} catch (error) {
console.error(`β Error closing specific position: ${error.message}`);
throw error;
}
}
/**
* Swaps only the tokens from a specific DLMM pool to SOL
* @param {Connection} connection
* @param {Object} dlmmPool
* @param {Object} userKeypair
*/
async function swapPositionTokensToSol(connection, dlmmPool, userKeypair) {
const { safeGetBalance, getMintDecimals } = await import('./lib/solana.js');
const { swapTokensUltra } = await import('./lib/jupiter.js');
// Get the token mints from this specific pool
const tokenXMint = dlmmPool.tokenX.publicKey.toString();
const tokenYMint = dlmmPool.tokenY.publicKey.toString();
// SOL_MINT now imported from constants
// Determine which token is SOL and which is the alt token
const solMint = [tokenXMint, tokenYMint].find(mint => mint === SOL_MINT);
const altTokenMint = [tokenXMint, tokenYMint].find(mint => mint !== SOL_MINT);
if (!altTokenMint) {
console.log(` βΉοΈ Pool contains only SOL - no swapping needed`);
return;
}
console.log(` π TP/SL Swap Analysis:`);
console.log(` Pool: SOL + ${altTokenMint.substring(0, 8)}...${altTokenMint.substring(altTokenMint.length - 8)}`);
console.log(` Target: Swap alt token β SOL`);
// π JUPITER INDEX DELAY: Critical for TP/SL swaps after position closure
// This prevents "Taker has insufficient input" errors when tokens were just claimed
console.log(` β³ Waiting 1.5s for Jupiter balance index to update after position closure...`);
await new Promise(resolve => setTimeout(resolve, 1500));
console.log(` β
Ready to proceed with TP/SL Ultra API swap`);
try {
// Get current token balance (safeGetBalance returns BN in raw token units)
const { PublicKey } = await import('@solana/web3.js');
const altTokenBalanceRaw = await safeGetBalance(connection, new PublicKey(altTokenMint), userKeypair.publicKey);
console.log(` π Token balance analysis:`);
console.log(` Raw balance: ${altTokenBalanceRaw.toString()} (atomic units)`);
// Check if we have any tokens to swap
if (altTokenBalanceRaw.isZero() || altTokenBalanceRaw.lte(new BN(1000))) {
console.log(` βΉοΈ Alt token balance too low (${altTokenBalanceRaw.toString()}) - skipping swap`);
return;
}
// Get token decimals for UI display only
const decimals = await getMintDecimals(connection, new PublicKey(altTokenMint));
const uiAmount = parseFloat(altTokenBalanceRaw.toString()) / Math.pow(10, decimals);
console.log(` Decimals: ${decimals}`);
console.log(` UI amount: ${uiAmount.toFixed(6)} tokens`);
console.log(` Mint: ${altTokenMint}`);
// π§ CRITICAL FIX: safeGetBalance() already returns raw token amount in BN format
// No need to multiply by decimals - that was causing massively inflated amounts!
const swapAmount = BigInt(altTokenBalanceRaw.toString());
console.log(` π― Swap parameters:`);
console.log(` Amount (BigInt): ${swapAmount.toString()}`);
console.log(` From: ${altTokenMint}`);
console.log(` To: ${SOL_MINT}`);
const SLIPPAGE_BPS = Number(process.env.SLIPPAGE || 10);
const PRICE_IMPACT_PCT = Number(process.env.PRICE_IMPACT || 0.5);
console.log(` Slippage: ${SLIPPAGE_BPS} bps (${SLIPPAGE_BPS/100}%)`);
console.log(` Max price impact: ${PRICE_IMPACT_PCT}%`);
console.log(` π Executing TP/SL Ultra API swap...`);
const signature = await swapTokensUltra(
altTokenMint,
SOL_MINT,
swapAmount,
userKeypair,
connection,
dlmmPool,
SLIPPAGE_BPS,
20,
PRICE_IMPACT_PCT
);
if (signature) {
console.log(` π TP/SL swap completed successfully!`);
console.log(` β
Ultra API signature: ${signature}`);
console.log(` π View: https://solscan.io/tx/${signature}`);
} else {
console.log(` β TP/SL Ultra API swap failed - no signature returned`);
console.log(` This indicates Jupiter Ultra API backend issues or insufficient liquidity`);
}
} catch (swapError) {
console.log(` β TP/SL swap error: ${swapError.message}`);
console.log(` Error details for debugging:`);
console.log(` - Pool: ${dlmmPool.pubkey.toBase58()}`);
console.log(` - Alt token: ${altTokenMint}`);
console.log(` - Wallet: ${userKeypair.publicKey.toBase58()}`);
if (swapError.stack) {
console.log(` - Stack: ${swapError.stack.substring(0, 200)}...`);
}
}
}
async function monitorPositionLoop(
connection,
dlmmPool,
userKeypair,
sessionState,
positionPubKey,
intervalSeconds,
originalParams = {},
pnlTracker = null
) {
// Parse timer intervals
const pnlCheckSeconds = parseInt(PNL_CHECK_INTERVAL_SECONDS) || 10;
const rebalanceCheckSeconds = intervalSeconds;
console.log(`Starting monitoring:`);
console.log(` P&L updates: every ${pnlCheckSeconds}s`);
console.log(` Rebalance checks: every ${rebalanceCheckSeconds}s`);
console.log(`Tracking Position: ${positionPubKey.toBase58()}`);
// Timing tracking for dual intervals
let lastRebalanceCheck = 0;
const getTimestamp = () => Math.floor(Date.now() / 1000);
// Trailing stop tracking variables
let peakPnL = 0; // Highest P&L percentage since trail activation
let trailingActive = false; // Whether trailing is currently active
let dynamicStopLoss = null; // Current trailing stop level
console.log(`Rebalancing logic: Only triggers when price moves outside position range`);
// Initial-phase gate: suppress ANY rebalancing until price has moved OUTSIDE from the start by X bins
const initialReentryBins = originalParams.initialReentryBins ?? 2;
let initialRebalanceGateActive = initialReentryBins > 0;
let lastOutDirection = null; // 'UP' | 'DOWN' | null
// Outside-distance from START: capture start bin and initial direction based on single-sided side
let initialGateStartBinId = null;
let initialGateDirection = null; // 'UP' | 'DOWN' | null
// β‘ Add keyboard shortcuts for live control
console.log(`\nβ‘ LIVE CONTROLS:`);
console.log(` C = Close all positions & swap to SOL`);
console.log(` S = Show current status`);
console.log(` Q = Quit gracefully`);
console.log(` Ctrl+C twice = Emergency exit\n`);
// Setup keyboard input handling
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Enable raw mode for single key detection
if (process.stdin.isTTY) {
process.stdin.setRawMode(true);
}
let ctrlCCount = 0;
let isClosing = false;
const handleKeyPress = async (chunk) => {
if (isClosing) return; // Prevent multiple closures
const key = chunk.toString().toLowerCase();
switch (key) {
case 'c':
isClosing = true;
console.log('\nπ΄ CLOSING CURRENT POSITION...');
console.log('π This will close the current terminal position and swap its tokens to SOL...');
try {
// Lookup the currently monitored position by key
const { userPositions } = await dlmmPool.getPositionsByUserAndLbPair(userKeypair.publicKey);
const currentPosition = userPositions.find(p => p.publicKey.equals(positionPubKey));
if (!currentPosition) {
console.error('β No active position found to close.');
process.exit(1);
}
// Close only the current position; swapping to SOL is handled inside closeSpecificPosition
await closeSpecificPosition(connection, dlmmPool, userKeypair, positionPubKey, currentPosition);
console.log('β
Current position closed and swapped to SOL successfully!');
} catch (error) {
console.error('β Error during position closure:', error.message);
}
process.exit(0);
break;
case 's':
console.log('\nπ CURRENT STATUS:');
console.log(` Position: ${positionPubKey.toBase58()}`);
console.log(` Pool: ${dlmmPool.pubkey.toBase58()}`);
console.log(` Monitoring interval: ${intervalSeconds}s`);
console.log(` P&L tracking: Active`);
console.log(` Next update: ${intervalSeconds}s\n`);
break;
case 'q':
console.log('\nπ Graceful shutdown initiated...');
console.log('π Position will continue running - use "node cli.js close" later to close positions');
process.exit(0);
break;
case '\u0003': // Ctrl+C
ctrlCCount++;
if (ctrlCCount === 1) {
console.log('\nπ¨ EMERGENCY EXIT! Press Ctrl+C again within 3 seconds to confirm...');
setTimeout(() => { ctrlCCount = 0; }, 3000);
return;
}
if (ctrlCCount >= 2) {
isClosing = true;
console.log('\nπ΄ EMERGENCY POSITION CLOSURE ACTIVATED!');
console.log('π Closing all positions and swapping tokens to SOL...');
try {
const { closeAllPositions } = await import('./close-position.js');
await closeAllPositions();
console.log('β
Emergency closure completed successfully!');
} catch (error) {
console.error('β Error during emergency closure:', error.message);
}
process.exit(0);
}
break;
}
};
process.stdin.on('data', handleKeyPress);
// P&L Tracking Variables
let totalFeesEarnedUsd = 0;
let claimedFeesUsd = 0; // fees realized to wallet when not auto-compounded
let rebalanceCount = 0;
// Track accumulated X token fees in sol_only mode (fees that go to wallet instead of position)
let accumulatedXTokenFeesUsd = 0;
// Position-specific reserves (reset per position, not cumulative across session)
let feeReserveLamports = 0n;
// Reserve breakdown trackers (lamports)
let bufferReserveLamports = 0n; // buffer + headroom reserved during (re)open
let capReserveLamports = 0n; // capped amount reserved to keep under SOL limit
let haircutReserveLamports = 0n; // tiny bps trims reserved for safety
// Session reserves for token-side haircuts (raw token units)
let tokenXReserveLamports = 0n;
let tokenYReserveLamports = 0n;
// Session-tracked X fees accrued during swapless UP cycles (lamports)
let sessionAccruedFeeXLamports = 0n;
// Helper function to reset reserves when creating new positions
function resetReserveTracking() {
feeReserveLamports = 0n;
bufferReserveLamports = 0n;
capReserveLamports = 0n;
haircutReserveLamports = 0n;
tokenXReserveLamports = 0n;
tokenYReserveLamports = 0n;
sessionAccruedFeeXLamports = 0n;
}
// Expose a process-global aggregator so lower-level helpers can report reserve
globalThis.__MS_RESERVE_AGG__ = (lamports) => {
try { feeReserveLamports += BigInt(lamports.toString()); } catch {}
};
// Reserve breakdown aggregator used by lower-level helpers
globalThis.__MS_RESERVE_BREAKDOWN_ADD__ = (kind, lamports) => {
try {
const v = BigInt(lamports.toString());
if (kind === 'buffer') bufferReserveLamports += v;
else if (kind === 'cap') capReserveLamports += v;
else if (kind === 'haircut') haircutReserveLamports += v;
} catch {}
};
// Token-side reserve aggregators
globalThis.__MS_TOKEN_RESERVE_X_ADD__ = (lamports) => {
try { tokenXReserveLamports += BigInt(lamports.toString()); } catch {}
};
globalThis.__MS_TOKEN_RESERVE_Y_ADD__ = (lamports) => {
try { tokenYReserveLamports += BigInt(lamports.toString()); } catch {}
};
// Expose session X accrual helpers for cross-module reporting/consumption
globalThis.__MS_ACCRUED_X_ADD__ = (lamports) => {
try { sessionAccruedFeeXLamports += BigInt(lamports.toString()); } catch {}
};
globalThis.__MS_ACCRUED_X_PEEK__ = () => sessionAccruedFeeXLamports;
globalThis.__MS_ACCRUED_X_CONSUME__ = (lamports) => {
try {
const req = BigInt(lamports.toString());
const take = req <= sessionAccruedFeeXLamports ? req : sessionAccruedFeeXLamports;
sessionAccruedFeeXLamports -= take;
return take;
} catch { return 0n; }
};
console.log(`π P&L Tracking initialized - Initial deposit: $${sessionState.initialDepositUsd.toFixed(2)}`);
/* βββ 1. token-decimals βββββββββββββββββββββββββββββββ */
// Enhanced decimals fetching with retry logic for mint reliability
if (typeof dlmmPool.tokenX.decimal !== 'number')
dlmmPool.tokenX.decimal = await withRetry(
() => getMintDecimals(connection, dlmmPool.tokenX.publicKey),
'Token X decimals fetch',
3,
1000
);
if (typeof dlmmPool.tokenY.decimal !== 'number')
dlmmPool.tokenY.decimal = await withRetry(
() => getMintDecimals(connection, dlmmPool.tokenY.publicKey),
'Token Y decimals fetch',
3,
1000
);
const dx = dlmmPool.tokenX.decimal;
const dy = dlmmPool.tokenY.decimal;
console.log(`Token decimals: X=${dx}, Y=${dy}`);
console.log(`Token mints: X=${dlmmPool.tokenX.publicKey.toString()}, Y=${dlmmPool.tokenY.publicKey.toString()}`);
// Debug: Check for proper SOL/token pair detection
// SOL_MINT now imported from constants
const xIsSOL = dlmmPool.tokenX.publicKey.toString() === SOL_MINT.toString();
const yIsSOL = dlmmPool.tokenY.publicKey.toString() === SOL_MINT.toString();
console.log(`SOL Detection: X_IS_SOL=${xIsSOL}, Y_IS_SOL=${yIsSOL}`);
// Baseline for SOL-denominated PnL: lock at start of monitoring
// Enhanced initial price fetching with retry logic for session startup
const baseSolPx = yIsSOL
? await withRetry(() => getPrice(dlmmPool.tokenY.publicKey.toString()), 'Initial SOL price (Token Y)', 3, 1000)
: await withRetry(() => getPrice(dlmmPool.tokenX.publicKey.toString()), 'Initial SOL price (Token X)', 3, 1000);
const baselineSolUnits = baseSolPx ? (sessionState.initialDepositUsd / baseSolPx) : 0;
/* βββ 3. heading ββββββββββββββββββββββββββββββββββββββββββββββββββ */
console.log('');
console.log('β³ Waiting 5 seconds for RPC indexing to catch up before starting P&L monitoring...');
await new Promise(resolve => setTimeout(resolve, 5000));
console.log('π― Position Monitor Active');
// Grid helpers for clearer table output
const GRID_COLS = [
{ key: 'time', title: 'Time', w: 8, align: 'left' },
{ key: 'value', title: 'Value', w: 10, align: 'right' },
{ key: 'pnl', title: 'P&L', w: 11, align: 'right' },
{ key: 'pnlPct', title: 'P&L%', w: 9, align: 'right' },
{ key: 'fees', title: 'Fees', w: 9, align: 'right' },
{ key: 'rebal', title: 'Rebal', w: 5, align: 'right' },
{ key: 'tpslts', title: 'TP/SL/TS', w: 17, align: 'left' },
];
const fmtCell = (s, w, align) => {
const str = String(s);
if (str.length >= w) return str.slice(0, w);
const pad = ' '.repeat(w - str.length);
return align === 'right' ? pad + str : str + pad;
};
const printGridBorder = (type = 'top') => {
const join = (a, b, c) => a + GRID_COLS.map(c => 'β'.repeat(c.w)).join(b) + a;
if (type === 'top') console.log('β' + GRID_COLS.map(c => 'β'.repeat(c.w)).join('β¬') + 'β');
else if (type === 'mid') console.log('β' + GRID_COLS.map(c => 'β'.repeat(c.w)).join('βΌ') + 'β€');
else console.log('β' + GRID_COLS.map(c => 'β'.repeat(c.w)).join('β΄') + 'β');
};
const printGridHeader = () => {
printGridBorder('top');
const header = 'β' + GRID_COLS.map(c => fmtCell(c.title, c.w, 'left')).join('β') + 'β';
console.log(header);
printGridBorder('mid');
};
const printGridRow = (row) => {
const line = 'β' + GRID_COLS.map(c => fmtCell(row[c.key] ?? '', c.w, c.align)).join('β') + 'β';
console.log(line);
};
let gridRowCounter = 0;
printGridHeader();
/* βββ Keyboard Input Setup βββββββββββββββββββββββββββββββββββββββ */
// Setup keyboard input for debug toggle
if (process.stdin.setRawMode) {
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', (key) => {
if (key === 'd' || key === 'D') {
const newState = !logger.debugToConsole;
logger.setDebugToConsole(newState);
console.log(`\nπ§ Debug console output ${newState ? 'ENABLED' : 'DISABLED'} (logs still capture everything)\n`);
} else if (key === '\u0003') { // Ctrl+C
process.exit();
}
});
console.log('π‘ Press D to toggle debug output | Ctrl+C to exit\n');
}
/* βββ 4. loop βββββββββββββββββββββββββββββββββββββββββββββββββββββ */
while (true) {
try {
/* 4-A refresh on-chain state --------------------------------- */
// Enhanced state refresh with retry logic for blockchain reliability
await withRetry(
() => dlmmPool.refetchStates(),
'DLMM pool state refresh',
3,
1500
);
const { userPositions } = await withRetry(
() => dlmmPool.getPositionsByUserAndLbPair(userKeypair.publicKey),
'User positions fetch',
3,
1000
);
const activeBin = await withRetry(
() => dlmmPool.getActiveBin(),
'Active bin fetch',
3,
1000
);
const pos = userPositions.find(p => p.publicKey.equals(positionPubKey));
if (!activeBin) {
console.log('β Could not get active bin - retrying in next cycle');
await new Promise(r => setTimeout(r, pnlCheckSeconds * 1_000));
continue;
}
if (!pos) {
if (typeof globalThis.__MS_MISSING_POS_RETRIES__ !== 'number') globalThis.__MS_MISSING_POS_RETRIES__ = 0;
globalThis.__MS_MISSING_POS_RETRIES__ += 1;
const attempts = globalThis.__MS_MISSING_POS_RETRIES__;
console.log('β Position not found - may be indexing lag');
console.log(` Searching for position: ${positionPubKey.toBase58()}`);
console.log(` Found ${userPositions.length} positions:`);
userPositions.forEach((p, idx) => {
console.log(` [${idx}] ${p.publicKey.toBase58()} (bins: ${p.positionData?.lowerBinId} to ${p.positionData?.upperBinId})`);
});
// Extra debugging: Check if any position matches by transaction or timing
if (userPositions.length > 0) {
console.log(` π DEBUG: Found ${userPositions.length} position(s) for this specific pool:`);
console.log(` Pool: ${dlmmPool.pubkey.toBase58()}`);
console.log(` Token X: ${dlmmPool.tokenX.publicKey.toBase58()}`);
console.log(` Token Y: ${dlmmPool.tokenY.publicKey.toBase58()}`);
// AUTO-FIX: If we only have one position FOR THIS SPECIFIC POOL, use it
if (userPositions.length === 1) {
const onlyPosition = userPositions[0];
console.log(` π‘ Found exactly one position for this pool - AUTO-SWITCHING!`);
console.log(` Pool-specific position: ${onlyPosition.publicKey.toBase58()}`);
console.log(` Position range: Bin ${onlyPosition.positionData?.lowerBinId} to ${onlyPosition.positionData?.upperBinId}`);
console.log(` Switching from: ${positionPubKey.toBase58()}`);
console.log(` Switching to: ${onlyPosition.publicKey.toBase58()}`);
// Update the position we're tracking
positionPubKey = onlyPosition.publicKey;
globalThis.__MS_MISSING_POS_RETRIES__ = 0; // Reset retry count
console.log(` β
Auto-switched to correct pool-specific position - continuing monitor...`);
continue; // Retry the monitoring loop with correct position
} else if (userPositions.length > 1) {
console.log(` β οΈ Multiple positions found for this pool:`);
userPositions.forEach((p, idx) => {
console.log(` [${idx}] ${p.publicKey.toBase58()} (bins: ${p.positionData?.lowerBinId}-${p.positionData?.upperBinId})`);
});
console.log(` π‘ Cannot auto-switch with multiple positions - manual intervention needed`);
}
}
if (attempts < 5) {
console.log(` β³ Waiting to retry (${attempts}/5)...`);
await new Promise(r => setTimeout(r, pnlCheckSeconds * 1_000));
continue;
} else {
console.log(' β Still missing after retries β exiting monitor.');
break;
}
} else {
globalThis.__MS_MISSING_POS_RETRIES__ = 0;
}
/* 4-B amounts ------------------------------------------------- */
let lamX = new BN(0), lamY = new BN(0);
pos.positionData.positionBinData.forEach(b => {
lamX = lamX.add(new BN(b.positionXAmount));
lamY = lamY.add(new BN(b.positionYAmount));
});
const feeX = new BN(pos.positionData.feeX);
const feeY = new BN(pos.positionData.feeY);
const amtX = lamX.toNumber() / 10 ** dx;
const amtY = lamY.toNumber() / 10 ** dy;
const feeAmtX = feeX.toNumber() / 10 ** dx;
const feeAmtY = feeY.toNumber() / 10 ** dy;
// Enhanced price fetching with retry logic for network resilience
const pxX = await withRetry(
() => getPrice(dlmmPool.tokenX.publicKey.toString()),
'Price fetch Token X',
3,
1000
);
const pxY = await withRetry(
() => getPrice(dlmmPool.tokenY.publicKey.toString()),
'Price fetch Token Y',
3,
1000
);
const liqUsd = amtX * (pxX || 0) + amtY * (pxY || 0);
const feesUsd = feeAmtX * (pxX || 0) + feeAmtY * (pxY || 0);
// Include session reserve from haircuts (count only reserve, not full wallet)
// SOL_MINT now imported from constants
const xIsSOL = dlmmPool.tokenX.publicKey.toString() === SOL_MINT.toString();
const yIsSOL = dlmmPool.tokenY.publicKey.toString() === SOL_MINT.toString();
const solUsd = yIsSOL ? (pxY || 0) : xIsSOL ? (pxX || 0) : (pxY || 0);
const feeReserveUsd = Number(feeReserveLamports) / 1e9 * solUsd;
const bufferReserveUsd = Number(bufferReserveLamports) / 1e9 * solUsd;
const capReserveUsd = Number(capReserveLamports) / 1e9 * solUsd;
const haircutReserveUsd = Number(haircutReserveLamports) / 1e9 * solUsd;
// Token-side reserves valued in USD using their token prices
const tokenReserveUsd = (Number(tokenXReserveLamports) / 10 ** dx) * (pxX || 0) + (Number(tokenYReserveLamports) / 10 ** dy) * (pxY || 0);
// π§ FIX: Calculate total USD based on session configuration pathways
let totalUsd;
// Get configuration from originalParams
const autoCompoundMode = originalParams?.autoCompoundConfig?.mode || 'both';
const feeHandlingMode = originalParams?.feeHandlingMode || 'compound';
if (feeHandlingMode === 'compound') {
// Auto-compound mode: Some/all fees are reinvested in position
if (autoCompoundMode === 'both') {
// All fees compounded into position (wallet-claimed fees should not be included)
totalUsd = liqUsd + feesUsd;
} else if (autoCompoundMode === 'sol_only') {
// SOL_ONLY: SOL fees compounded, X token fees accumulate in wallet
totalUsd = liqUsd + feesUsd + accumulatedXTokenFeesUsd; // Include accumulated X tokens as gains
} else if (autoCompoundMode === 'token_only') {
// TOKEN_ONLY: Token fees compounded, SOL fees claimed to wallet
totalUsd = liqUsd + feesUsd; // Current position + current unclaimed
// Note: Claimed SOL fees tracked separately in sessionState.totalClaimedFeesUsd
} else {
// Mixed compounding fallback: Some fees in position, some claimed separately
totalUsd = liqUsd + feesUsd; // Current position + current unclaimed
// Note: Claimed fees tracked separately in sessionState.totalClaimedFeesUsd
}
} else {
// Claim-to-SOL mode: Position only (claimed fees separate)
totalUsd = liqUsd + feesUsd; // Current position + current unclaimed
// Note: Claimed fees tracked separately in sessionState.totalClaimedFeesUsd
}
// π― PRIORITY CHECK: TAKE PROFIT & STOP LOSS (BEFORE rebalancing)
// Calculate P&L using advanced P&L tracker
try {
const yDecimals = typeof dlmmPool.tokenY.decimal === 'number' ? dlmmPool.tokenY.decimal : await getMintDecimals(connection, dlmmPool.tokenY.publicKey);
const solPrice0 = await getPrice(SOL_MINT.toString());
const tokenPrice0 = (typeof tokenPrice === 'number' && tokenPrice > 0)
? tokenPrice
: (((await dlmmPool.getActiveBin())?.price) || 0) * solPrice0;
const initSolUsd = (Number(initialSolLamports.toString()) / 1e9) * solPrice0;
const initTokUnits = Number(initialTokenAmount.toString()) / Math.pow(10, yDecimals);
const initTokUsd = initTokUnits * (tokenPrice0 || 0);
console.log(`π― [P&L] Baseline Intent (resolved): ${initSolUsd.toFixed(2)} USD SOL + ${initTokUsd.toFixed(2)} USD Token`);
} catch { }
let currentPnL = 0;
let pnlPercentage = 0;
if (pnlTracker) {
try {
// Get current SOL and token prices
const solPrice = await getPrice(SOL_MINT.toString());
const activeBin = await dlmmPool.getActiveBin();
const tokenPrice = activeBin ? activeBin.price * solPrice : 0;
// Enhanced position fetch for bin-level analysis with retry logic
const position = await withRetry(
() => dlmmPool.getPosition(positionPubKey),
'Position fetch for analysis',
3,
1000
);
// Calculate comprehensive P&L with current baseline
const pnlData = await pnlTracker.calculatePnL(
position,
dlmmPool,
solPrice,
tokenPrice,
{ sol: new BN(0), token: new BN(0) }, // No new fees here
userKeypair.publicKey, // User public key for position lookup
sessionState.currentBaselineUsd // Pass current baseline to prevent false TP triggers
);
// Use absolute P&L for TP/SL decisions (most intuitive)
currentPnL = pnlData.absolutePnL;
pnlPercentage = pnlData.absolutePnLPercent;
// Update session state for compatibility
sessionState.sessionPnL = currentPnL;
sessionState.sessionPnLPercent = pnlPercentage;
sessionState.lifetimePnL = pnlData.absolutePnL;
sessionState.lifetimePnLPercent = pnlData.absolutePnLPercent;
} catch (error) {
console.log('β οΈ [P&L] Error calculating P&L, falling back to simple calculation:', error.message);
// Fallback to old calculation
sessionState.sessionPnL = totalUsd - sessionState.currentBaselineUsd;
const baselineUsd = Math.max(sessionState.currentBaselineUsd || 0, 1e-9);
sessionState.sessionPnLPercent = (sessionState.sessionPnL / baselineUsd) * 100;
const autoMode = originalParams?.autoCompoundConfig?.mode || 'both';
let lifetimeTotalValue = totalUsd;
if (feeHandlingMode !== 'compound') {
lifetimeTotalValue = totalUsd + sessionState.totalClaimedFeesUsd;
} else if (sessionState.autoCompound && autoMode === 'token_only') {
lifetimeTotalValue = totalUsd + sessionState.totalClaimedFeesUsd;
}
sessionState.lifetimePnL = lifetimeTotalValue - sessionState.initialDepositUsd;
sessionState.lifetimePnLPercent = (sessionState.lifetimePnL / sessionState.initialDepositUsd) * 100;
currentPnL = sessionState.sessionPnL;
pnlPercentage = sessionState.sessionPnLPercent;
}
} else {
// Fallback if no P&L tracker
sessionState.sessionPnL = totalUsd - sessionState.currentBaselineUsd;
const baselineUsd = Math.max(sessionState.currentBaselineUsd || 0, 1e-9);
sessionState.sessionPnLPercent = (sessionState.sessionPnL / baselineUsd) * 100;
const autoMode = originalParams?.autoCompoundConfig?.mode || 'both';
let lifetimeTotalValue = totalUsd;
if (feeHandlingMode !== 'compound') {
lifetimeTotalValue = totalUsd + sessionState.totalClaimedFeesUsd;
} else if (sessionState.autoCompound && autoMode === 'token_only') {
lifetimeTotalValue = totalUsd + sessionState.totalClaimedFeesUsd;
}
sessionState.lifetimePnL = lifetimeTotalValue - sessionState.initialDepositUsd;
sessionState.lifetimePnLPercent = (sessionState.lifetimePnL / sessionState.initialDepositUsd) * 100;
currentPnL = sessionState.sessionPnL;
pnlPercentage = sessionState.sessionPnLPercent;
}
// Show enhanced P&L information if available
if (pnlTracker) {
try {
const solPrice = await getPrice(SOL_MINT.toString());
const activeBin = dlmmPool.getActiveBin();
const tokenPrice = activeBin ? activeBin.price * solPrice : 0;
// Enhanced P&L calculation with retry logic for accurate tracking
const position = await withRetry(
() => dlmmPool.getPosition(positionPubKey),
'Position data fetch for P&L',
3,
1000
);
const pnlData = await withRetry(
() => pnlTracker.calculatePnL(position, dlmmPool, solPrice, tokenPrice, null, userKeypair.publicKey, sessionState.currentBaselineUsd),
'P&L calculation',
3,
1500
);
// Use comprehensive P&L data for TP/SL decisions (more accurate)
const comprehensivePnLPercent = pnlData.absolutePnLPercent;
// Show comprehensive P&L display every 60 seconds (to avoid spam)
const now = Date.now();
if (!sessionState.lastComprehensivePnL || (now - sessionState.lastComprehensivePnL) >= 60000) {
sessionState.lastComprehensivePnL = now;
pnlTracker.displayPnL(pnlData);
}
} catch (error) {
// Fallback to simple display
if (!sessionState.__legendPrinted) {
console.log('βΉοΈ P&L legend: session = since start, lifetime = since first position, SOL = lifetime in SOL; realized = claimed fees; unclaimed = in-position fees');
sessionState.__legendPrinted = true;
}
const ses = `${currentPnL >= 0 ? '+' : ''}${currentPnL.toFixed(2)} (${pnlPercentage >= 0 ? '+' : ''}${pnlPercentage.toFixed(1)}%)`;
const life = `${sessionState.lifetimePnL >= 0 ? '+' : ''}${sessionState.lifetimePnL.toFixed(2)} (${sessionState.lifetimePnLPercent >= 0 ? '+' : ''}${sessionState.lifetimePnLPercent.toFixed(1)}%)`;
const realized = (!sessionState.autoCompound && sessionState.totalClaimedFeesUsd > 0)
? ` | realized $${sessionState.totalClaimedFeesUsd.toFixed(2)}`
: '';
console.log(`π° P&L: session $${ses} | lifetime $${life}${realized}`);
}
} else {
// Original simple P&L display
if (!sessionState.__legendPrinted) {
console.log('βΉοΈ P&L legend: session = since start, lifetime = since first position, SOL = lifetime in SOL; realized = claimed fees; unclaimed = in-position fees');
sessionState.__legendPrinted = true;
}
const ses = `${currentPnL >= 0 ? '+' : ''}${currentPnL.toFixed(2)} (${pnlPercentage >= 0 ? '+' : ''}${pnlPercentage.toFixed(1)}%)`;
const life = `${sessionState.lifetimePnL >= 0 ? '+' : ''}${sessionState.lifetimePnL.toFixed(2)} (${sessionState.lifetimePnLPercent >= 0 ? '+' : ''}${sessionState.lifetimePnLPercent.toFixed(1)}%)`;
const realized = (!sessionState.autoCompound && sessionState.totalClaimedFeesUsd > 0)
? ` | realized $${sessionState.totalClaimedFeesUsd.toFixed(2)}`
: '';
console.log(`π° P&L: session $${ses} | lifetime $${life}${realized}`);
}
if (feeReserveUsd > 0.001) {
logger.debug(`π§ Reserve (off-position cash): +$${feeReserveUsd.toFixed(2)} [DEBUG ONLY - NOT part of P&L]`);
// Breakdown if any component is meaningful
const parts = [];
if (bufferReserveUsd > 0.001) parts.push(`buffer ~$${bufferReserveUsd.toFixed(2)}`);
if (capReserveUsd > 0.001) parts.push(`cap ~$${capReserveUsd.toFixed(2)}`);
if (haircutReserveUsd > 0.001) parts.push(`haircut ~$${haircutReserveUsd.toFixed(2)}`);
if (parts.length) logger.debug(` β³ Breakdown: ${parts.join(', ')}`);
}
// Note: Detailed P&L info now shown in comprehensive panel every 60s
// Removed duplicate π Unclaimed and πͺ P&L SOL lines to reduce clutter
/* Auto Fee Claiming during P&L monitoring */
// Check if fees exceed threshold and auto-claim/swap to SOL (only in claim-to-sol mode)
if (originalParams?.feeHandlingMode === 'claim_to_sol' &&
originalParams?.minSwapUsd &&
feesUsd >= originalParams.minSwapUsd) {
console.log(`π° Fees exceeded threshold ($${feesUsd.toFixed(4)} >= $${originalParams.minSwapUsd.toFixed(2)})`);
console.log('π Auto-claiming fees and analyzing SOL vs Token portions...');
try {
// Get wallet balances BEFORE claiming to calculate the difference
const { safeGetBalance } = await import('./lib/solana.js');
const { getPrice } = await import('./lib/price.js');
const { PublicKey } = await import('@solana/web3.js');
const tokenXMint = dlmmPool.tokenX.publicKey.toString();
const tokenYMint = dlmmPool.tokenY.publicKey.toString();
const balancesBefore = {
sol: await connection.getBalance(userKeypair.publicKey),
tokenX: await safeGetBalance(connection, new PublicKey(tokenXMint), userKeypair.publicKey),
tokenY: await safeGetBalance(connection, new PublicKey(tokenYMint), userKeypair.publicKey)
};
// Claim swap fees for this position using DLMM SDK (returns array of transactions)
const claimFeeTxs = await withRetry(
() => dlmmPool.claimSwapFee({
owner: userKeypair.publicKey,
position: pos
}),
'Fee claiming',
3,
1000
);
if (claimFeeTxs && claimFeeTxs.length > 0) {
// Execute claim transactions - DLMM SDK returns array of regular Transaction objects
const claimSigs = [];
for (let i = 0; i < claimFeeTxs.length; i++) {
const claimTx = claimFeeTxs[i];
const claimSig = await withRetry(
async () => {
const sig = await connection.sendTransaction(claimTx, [userKeypair]);
await connection.confirmTransaction(sig, 'confirmed');
return sig;
},
`Fee claim transaction ${i + 1}/${claimFeeTxs.length}`,
3,
1000
);
claimSigs.push(claimSig);
console.log(`β
Fees claimed (tx ${i + 1}/${claimFeeTxs.length}): ${claimSig}`);
}
// Get wallet balances AFTER claiming to see what we actually received
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for balance updates
const balancesAfter = {
sol: await connection.getBalance(userKeypair.publicKey),
tokenX: await safeGetBalance(connection, new PublicKey(tokenXMint), userKeypair.publicKey),
tokenY: await safeGetBalance(connection, new PublicKey(tokenYMint), userKeypair.publicKey)
};
// Calculate claimed amounts (difference between after and before)
const claimedAmounts = {
sol: balancesAfter.sol - balancesBefore.sol,
tokenX: balancesAfter.tokenX.sub(balancesBefore.tokenX),
tokenY: balancesAfter.tokenY.sub(balancesBefore.tokenY)
};
// Calculate USD values of claimed portions
const solPrice = await getPrice(SOL_MINT.toString());
const claimedSolUsd = (claimedAmounts.sol / 1e9) * (solPrice || 0);
let claimedAltTokenUsd = 0;
let altTokenAmount = 0;
let altTokenMint = null;
let altTokenSymbol = '';
// Determine which token is the alt token (non-SOL) and calculate its USD value
if (tokenXMint !== SOL_MINT && !claimedAmounts.tokenX.isZero()) {
altTokenMint = tokenXMint;
const decimals = dlmmPool.tokenX.decimal || 6; // Fallback to 6 if undefined
altTokenAmount = claimedAmounts.tokenX.toNumber() / Math.pow(10, decimals);
altTokenSymbol = dlmmPool.tokenX.symbol || 'TOKEN_X';
const tokenPrice = await getPrice(altTokenMint);
claimedAltTokenUsd = altTokenAmount * (tokenPrice || 0);
} else if (tokenYMint !== SOL_MINT && !claimedAmounts.tokenY.isZero()) {
altTokenMint = tokenYMint;
const decimals = dlmmPool.tokenY.decimal || 9; // Fallback to 9 if undefined
altTokenAmount = claimedAmounts.tokenY.toNumber() / Math.pow(10, decimals);
altTokenSymbol = dlmmPool.tokenY.symbol || 'TOKEN_Y';
const tokenPrice = await getPrice(altTokenMint);
claimedAltTokenUsd = altTokenAmount * (tokenPrice || 0);
}
const totalClaimedUsd = claimedSolUsd + claimedAltTokenUsd;
console.log(`π [CLAIM ANALYSIS] Claimed fee breakdown:`);
console.log(` β’ SOL portion: ${(claimedAmounts.sol / 1e9).toFixed(6)} SOL ($${claimedSolUsd.toFixed(4)})`);
if (altTokenAmount > 0) {
console.log(` β’ ${altTokenSymbol} portion: ${altTokenAmount.toFixed(6)} ${altTokenSymbol} ($${claimedAltTokenUsd.toFixed(4)})`);
}
console.log(` β’ Total claimed: $${totalClaimedUsd.toFixed(4)}`);
// Update claimed fees tracking with total USD value
totalFeesEarnedUsd += totalClaimedUsd;
claimedFeesUsd += totalClaimedUsd;
sessionState.totalClaimedFeesUsd += totalClaimedUsd;
// Only swap the alt token portion if it exists and exceeds minimum swap amount
if (altTokenAmount > 0 && altTokenMint) {
console.log(`π Swapping alt token portion (${altTokenSymbol}) to SOL...`);
const { swapTokensUltra } = await import('./lib/jupiter.js');
try {
await swapTokensUltra(
altTokenMint, // inputMint
SOL_MINT, // outputMint
claimedAmounts.tokenX.isZero() ? claimedAmounts.tokenY.toNumber() : claimedAmounts.tokenX.toNumber(), // amountRaw
userKeypair, // userKeypair
connection, // connection
dlmmPool, // dlmmPool (optional)
50, // slippageBps (0.5% = 50 bps)
20, // maxAttempts
0.5 // priceImpact
);
console.log(`β
Alt token portion swapped to SOL: $${claimedAltTokenUsd.toFixed(4)}`);
} catch (swapError) {
console.log(`β οΈ Failed to swap alt token portion: ${swapError.message}`);
}
} else {
console.log(`βΉοΈ No alt token portion to swap (fees were all SOL)`);
}
// Refresh position state after claiming
await withRetry(
() => dlmmPool.refetchStates(),
'Post-claim state refresh',
2,
1000
);
} else {
console.log('βΉοΈ No fees available to claim at this time');
}
} catch (error) {
console.error('β Error during fee claiming:', error.message);
console.log('β οΈ Continuing monitoring despite fee claim error...');
}
}
// Track peak P&L for trailing stop (using comprehensive P&L if available)
const currentPnLPercent = typeof comprehensivePnLPercent !== 'undefined' ? comprehensivePnLPercent : pnlPercentage;
if (originalParams.trailingStopEnabled) {
if (!trailingActive && currentPnLPercent >= originalParams.trailTriggerPercentage) {
trailingActive = true;
peakPnL = currentPnLPercent;
dynamicStopLoss = peakPnL - originalParams.trailingStopPercentage;
console.log(`π TRAILING STOP activated at +${currentPnLPercent.toFixed(1)}% (trigger: +${originalParams.trailTriggerPercentage}%)`);
console.log(` Initial trailing stop set at +${dynamicStopLoss.toFixed(1)}%`);
}
if (trailingActive && currentPnLPercent > peakPnL) {
peakPnL = currentPnLPercent;
const newDynamicStopLoss = peakPnL - originalParams.trailingStopPercentage;
if (newDynamicStopLoss > dynamicStopLoss) {
dynamicStopLoss = newDynamicStopLoss;
console.log(`π New peak: +${peakPnL.toFixed(1)}% β Trailing stop moved to +${dynamicStopLoss.toFixed(1)}%`);
}
}
}
if ((originalParams.takeProfitEnabled || originalParams.stopLossEnabled || originalParams.trailingStopEnabled) && !isNaN(currentPnLPercent)) {
let shouldClose = false;
let closeReason = '';