From d4d2883af64858452badeedb59a33820f0d70106 Mon Sep 17 00:00:00 2001 From: mindesbunister Date: Wed, 29 Oct 2025 20:04:33 +0100 Subject: [PATCH] Fix: Prevent Position Manager from closing runner after on-chain TP2 - Detect on-chain TP2 fills in size mismatch logic and set tp2Hit flag - Position size thresholds: <30% = TP1, <10% = TP2 (prevents runner from being closed) - Ensures runner (5-20%) trails properly instead of being market-closed immediately --- lib/trading/position-manager.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/trading/position-manager.ts b/lib/trading/position-manager.ts index a158fcb..aa75903 100644 --- a/lib/trading/position-manager.ts +++ b/lib/trading/position-manager.ts @@ -347,12 +347,25 @@ export class PositionManager { return } - // Position exists but size mismatch (partial close by TP1?) + // Position exists but size mismatch (partial close by TP1 or TP2?) if (position.size < trade.currentSize * 0.95) { // 5% tolerance console.log(`⚠️ Position size mismatch: expected ${trade.currentSize}, got ${position.size}`) + + // Determine if this was TP1 or TP2 based on size + const remainingPercent = (position.size / trade.positionSize) * 100 + + if (!trade.tp1Hit && remainingPercent < 30) { + // First partial close, likely TP1 (should leave ~25%) + trade.tp1Hit = true + console.log(`✅ TP1 detected on-chain (${remainingPercent.toFixed(1)}% remaining)`) + } else if (trade.tp1Hit && !trade.tp2Hit && remainingPercent < 10) { + // Second partial close, likely TP2 (should leave ~5% runner) + trade.tp2Hit = true + console.log(`✅ TP2 detected on-chain (${remainingPercent.toFixed(1)}% runner remaining)`) + } + // Update current size to match reality trade.currentSize = position.size * (trade.positionSize / trade.currentSize) // Convert to USD - trade.tp1Hit = true await this.saveTradeState(trade) } @@ -468,7 +481,7 @@ export class PositionManager { } // 5. Take profit 2 (remaining position) - if (trade.tp1Hit && this.shouldTakeProfit2(currentPrice, trade)) { + if (trade.tp1Hit && !trade.tp2Hit && this.shouldTakeProfit2(currentPrice, trade)) { console.log(`🎊 TP2 HIT: ${trade.symbol} at ${profitPercent.toFixed(2)}%`) // Calculate how much to close based on TP2 size percent