diff --git a/lib/drift/orders.ts b/lib/drift/orders.ts index 396721b..47a593b 100644 --- a/lib/drift/orders.ts +++ b/lib/drift/orders.ts @@ -486,9 +486,12 @@ export async function closePosition( if (isDryRun) { console.log('๐Ÿงช DRY RUN MODE: Simulating close order (not executing on blockchain)') - // Calculate realized P&L - const pnlPerUnit = oraclePrice - position.entryPrice - const realizedPnL = pnlPerUnit * sizeToClose * (position.side === 'long' ? 1 : -1) + // Calculate realized P&L with leverage + const profitPercent = ((oraclePrice - position.entryPrice) / position.entryPrice) * 100 * (position.side === 'long' ? 1 : -1) + const leverage = position.leverage || 10 + const accountPnLPercent = profitPercent * leverage + const closedNotional = sizeToClose * oraclePrice + const realizedPnL = (closedNotional * accountPnLPercent) / 100 const mockTxSig = `DRY_RUN_CLOSE_${Date.now()}_${Math.random().toString(36).substring(7)}` @@ -534,12 +537,20 @@ export async function closePosition( console.log('โœ… Transaction confirmed on-chain') - // Calculate realized P&L - const pnlPerUnit = oraclePrice - position.entryPrice - const realizedPnL = pnlPerUnit * sizeToClose * (position.side === 'long' ? 1 : -1) + // Calculate realized P&L with leverage + // CRITICAL: P&L must account for leverage and be calculated on USD notional, not base asset size + const profitPercent = ((oraclePrice - position.entryPrice) / position.entryPrice) * 100 * (position.side === 'long' ? 1 : -1) + const leverage = position.leverage || 10 // Fallback to 10x if not available + const accountPnLPercent = profitPercent * leverage + + // Calculate closed notional value (USD) + const closedNotional = sizeToClose * oraclePrice + const realizedPnL = (closedNotional * accountPnLPercent) / 100 console.log(`๐Ÿ’ฐ Close details:`) console.log(` Close price: $${oraclePrice.toFixed(4)}`) + console.log(` Profit %: ${profitPercent.toFixed(3)}% | Account P&L (${leverage}x): ${accountPnLPercent.toFixed(2)}%`) + console.log(` Closed notional: $${closedNotional.toFixed(2)}`) console.log(` Realized P&L: $${realizedPnL.toFixed(2)}`) // If closing 100%, cancel all remaining orders for this market