critical: Fix exit order token sizing - TP/SL now use exact position size
BUG #92: Exit orders (TP1, TP2, SL) had different token sizes than position - Position: 142.91 SOL but TP1=140.87 SOL, SL=147.03 SOL (WRONG) - Root cause: usdToBase() calculated tokens as USD/price per order - Each exit order price produced different token amounts FIX: Pass actual token count via positionSizeTokens parameter - Added positionSizeTokens to PlaceExitOrdersOptions interface - Added tokensToBase() helper (tokens * 1e9 directly) - All exit sections now use token-based calculation when available Files updated to pass positionSizeTokens: - app/api/trading/execute/route.ts: openResult.fillSize - lib/trading/smart-entry-timer.ts: openResult.fillSize - lib/trading/sync-helper.ts: Math.abs(driftPos.size) - lib/trading/position-manager.ts: Math.abs(position.size) + fetch patterns - lib/startup/init-position-manager.ts: Math.abs(position.size) - lib/health/position-manager-health.ts: Drift position fetch + token size Result: When position = X tokens, ALL exit orders close portions of X tokens - TP1: X * tp1SizePercent / 100 tokens - TP2: remaining * tp2SizePercent / 100 tokens - SL: X tokens (full position) Backward compatible: Falls back to USD calculation if positionSizeTokens not provided
This commit is contained in:
@@ -280,6 +280,12 @@ async function restoreOrdersIfMissing(
|
||||
// Import order placement function
|
||||
const { placeExitOrders } = await import('../drift/orders')
|
||||
|
||||
// Get position size in tokens for accurate order sizing
|
||||
const positionSizeTokens = position && position.size ? Math.abs(position.size) : undefined
|
||||
if (positionSizeTokens) {
|
||||
logger.log(`📊 Position size for restored orders: ${positionSizeTokens.toFixed(4)} tokens`)
|
||||
}
|
||||
|
||||
// Place exit orders using trade's TP/SL prices
|
||||
const result = await placeExitOrders({
|
||||
symbol: trade.symbol,
|
||||
@@ -289,6 +295,7 @@ async function restoreOrdersIfMissing(
|
||||
tp2Price: trade.takeProfit2Price,
|
||||
stopLossPrice: trade.stopLossPrice,
|
||||
positionSizeUSD: trade.positionSizeUSD,
|
||||
positionSizeTokens: positionSizeTokens,
|
||||
tp1SizePercent: 75,
|
||||
tp2SizePercent: 0, // TP2-as-runner
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user