From bcd1cd0c76fd95284a16ae969e5fd57562868c4e Mon Sep 17 00:00:00 2001 From: mindesbunister Date: Sun, 2 Nov 2025 20:34:59 +0100 Subject: [PATCH] fix(position-manager): correctly handle partial close size conversions to USD - Convert closePosition.closedSize (base asset) to USD when updating trade.currentSize - Fix conversion when position.size detected from Drift: set currentSize = position.size * currentPrice - Prevent trade.currentSize from being reduced to tiny values due to unit mismatch --- lib/trading/position-manager.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/trading/position-manager.ts b/lib/trading/position-manager.ts index 51977f8..95f74ea 100644 --- a/lib/trading/position-manager.ts +++ b/lib/trading/position-manager.ts @@ -450,8 +450,8 @@ export class PositionManager { // Position exists but size mismatch (partial close by TP1?) if (position.size < trade.currentSize * 0.95) { // 5% tolerance console.log(`⚠️ Position size mismatch: expected ${trade.currentSize}, got ${position.size}`) - // Update current size to match reality - trade.currentSize = position.size * (trade.positionSize / trade.currentSize) // Convert to USD + // Update current size to match reality (convert base asset size to USD using current price) + trade.currentSize = position.size * currentPrice trade.tp1Hit = true await this.saveTradeState(trade) } @@ -687,9 +687,13 @@ export class PositionManager { } else { // Partial close (TP1) trade.realizedPnL += result.realizedPnL || 0 - trade.currentSize -= result.closedSize || 0 - - console.log(`✅ 50% closed | Realized: $${result.realizedPnL?.toFixed(2)} | Remaining: ${trade.currentSize}`) + // result.closedSize is returned in base asset units (e.g., SOL), convert to USD using closePrice + const closePriceForCalc = result.closePrice || currentPrice + const closedSizeBase = result.closedSize || 0 + const closedUSD = closedSizeBase * closePriceForCalc + trade.currentSize = Math.max(0, trade.currentSize - closedUSD) + + console.log(`✅ Partial close executed | Realized: $${(result.realizedPnL || 0).toFixed(2)} | Closed (base): ${closedSizeBase.toFixed(6)} | Closed (USD): $${closedUSD.toFixed(2)} | Remaining USD: $${trade.currentSize.toFixed(2)}`) } // TODO: Send notification