fix: Correct entry price when restoring orphaned positions from Drift
- Startup validation now updates entryPrice to match Drift's actual value - Prevents tracking with wrong entry price after container restarts - Also updates positionSizeUSD to reflect current position (runner after TP1) Bug: When reopening closed trades found on Drift, used stale DB entry price Result: Stop loss calculated from wrong entry (41.51 vs actual 41.31) Impact: 0.14% difference in SL placement (~$0.20 per SOL) Fix: Query Drift for real entry price and update DB during restoration Files: lib/startup/init-position-manager.ts
This commit is contained in:
@@ -120,9 +120,14 @@ async function validateOpenTrades() {
|
||||
// CRITICAL: If DB says closed but Drift shows open, restore tracking!
|
||||
if (trade.exitReason !== null) {
|
||||
console.log(`🔴 CRITICAL: ${trade.symbol} marked as CLOSED in DB but still OPEN on Drift!`)
|
||||
console.log(` DB entry: $${trade.entryPrice.toFixed(2)} | Drift entry: $${position.entryPrice.toFixed(2)}`)
|
||||
console.log(` DB exit: ${trade.exitReason} at ${trade.exitTime?.toISOString()}`)
|
||||
console.log(` Drift: ${position.size} ${trade.symbol} ${driftDirection} @ $${position.entryPrice.toFixed(2)}`)
|
||||
console.log(` 🔄 Reopening trade in DB to restore Position Manager tracking...`)
|
||||
console.log(` 🔄 Reopening trade and correcting entry price to match Drift...`)
|
||||
|
||||
// Calculate position size in USD using Drift's entry price
|
||||
const currentPrice = await driftService.getOraclePrice(marketConfig.driftMarketIndex)
|
||||
const positionSizeUSD = position.size * currentPrice
|
||||
|
||||
await prisma.trade.update({
|
||||
where: { id: trade.id },
|
||||
@@ -131,11 +136,13 @@ async function validateOpenTrades() {
|
||||
exitReason: null,
|
||||
exitTime: null,
|
||||
exitPrice: null,
|
||||
entryPrice: position.entryPrice, // CRITICAL: Use Drift's actual entry price, not DB value
|
||||
positionSizeUSD: positionSizeUSD, // Update to current size (may be runner after TP1)
|
||||
// Keep original realizedPnL from partial closes if any
|
||||
}
|
||||
})
|
||||
|
||||
console.log(` ✅ Trade restored - Position Manager will now monitor it`)
|
||||
console.log(` ✅ Trade restored with corrected entry: $${position.entryPrice.toFixed(2)} (was $${trade.entryPrice.toFixed(2)})`)
|
||||
} else {
|
||||
console.log(`✅ ${trade.symbol} ${trade.direction}: Position verified on Drift`)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user