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:
@@ -128,9 +128,28 @@ async function ensureExitOrdersForTrade(
|
||||
|
||||
const { placeExitOrders } = await import('../drift/orders')
|
||||
|
||||
// Fetch current position size in tokens for accurate order sizing
|
||||
let positionSizeTokens: number | undefined
|
||||
try {
|
||||
const { getDriftService } = await import('../drift/client')
|
||||
const { getMarketConfig } = await import('../../config/trading')
|
||||
const driftService = getDriftService()
|
||||
if (driftService && (driftService as any).isInitialized) {
|
||||
const marketConfig = getMarketConfig(trade.symbol)
|
||||
const position = await driftService.getPosition(marketConfig.driftMarketIndex)
|
||||
if (position && Math.abs(position.size) > 0.01) {
|
||||
positionSizeTokens = Math.abs(position.size)
|
||||
console.log(`📊 Position size for health monitor orders: ${positionSizeTokens.toFixed(4)} tokens`)
|
||||
}
|
||||
}
|
||||
} catch (posError) {
|
||||
console.warn('⚠️ Could not fetch position for health monitor token size, using USD fallback')
|
||||
}
|
||||
|
||||
const placeResult = await placeExitOrders({
|
||||
symbol: trade.symbol,
|
||||
positionSizeUSD,
|
||||
positionSizeTokens,
|
||||
entryPrice: trade.entryPrice,
|
||||
tp1Price,
|
||||
tp2Price,
|
||||
|
||||
Reference in New Issue
Block a user