critical: Fix breakeven SL using wrong entry price after TP1

- CRITICAL BUG: Drift SDK's position.entryPrice RECALCULATES after partial closes
- After TP1, Drift returns COST BASIS of remaining position, NOT original entry
- Example: SHORT @ 38.52 → TP1 @ 70% → Drift shows entry 40.01 (runner's basis)
- Result: Breakeven SL set .50 ABOVE actual entry = guaranteed loss if triggered

Fix:
- Always use database trade.entryPrice for breakeven calculations
- Drift's position.entryPrice = current state (runner cost basis)
- Database entryPrice = original entry (authoritative for breakeven)
- Added logging to show both values for verification

Impact:
- Every TP1 → breakeven transition was using WRONG price
- Locking in losses instead of true breakeven protection
- Financial loss bug affecting every trade with TP1

Files:
- lib/trading/position-manager.ts: Line 513 - use trade.entryPrice not position.entryPrice
- .github/copilot-instructions.md: Added Common Pitfall #43, deprecated old #44

Incident: Nov 16, 02:47 CET - SHORT entry 38.52, breakeven SL set at 40.01
Position closed by ghost detection before SL could trigger (lucky)
This commit is contained in:
mindesbunister
2025-11-16 03:00:22 +01:00
parent f505db4ac8
commit 673a49302a
3 changed files with 47 additions and 39 deletions

View File

@@ -508,13 +508,14 @@ export class PositionManager {
trade.tp1Hit = true
trade.currentSize = positionSizeUSD
// CRITICAL: Query Drift for ACTUAL entry price (more accurate than database)
// The position.entryPrice from Drift SDK is calculated from on-chain data
const actualEntryPrice = position.entryPrice || trade.entryPrice
console.log(`📊 Breakeven calculation: DB entry=$${trade.entryPrice.toFixed(4)}, Drift entry=$${actualEntryPrice.toFixed(4)}`)
// CRITICAL: Use DATABASE entry price for breakeven (Drift recalculates after partial closes)
// Drift's position.entryPrice is the COST BASIS of remaining position, NOT original entry
// For a true breakeven SL, we need the ORIGINAL entry price from when position opened
const breakevenPrice = trade.entryPrice
console.log(`📊 Breakeven SL: Using original entry price $${breakevenPrice.toFixed(4)} (Drift shows $${position.entryPrice.toFixed(4)} for remaining position)`)
// Move SL to TRUE breakeven after TP1
trade.stopLossPrice = actualEntryPrice
trade.stopLossPrice = breakevenPrice
trade.slMovedToBreakeven = true
console.log(`🛡️ Stop loss moved to breakeven: $${trade.stopLossPrice.toFixed(4)}`)