diff --git a/lib/auto-trade.ts b/lib/auto-trade.ts index 9fe8f72..2576e0b 100644 --- a/lib/auto-trade.ts +++ b/lib/auto-trade.ts @@ -326,7 +326,7 @@ export async function copyTrade() { // Find all accounts with open positions to determine direction + symbol let resolvedAction: 'Buy' | 'Sell' | null = null; - let resolvedSymbol: string | null = null; + let positionContractId: number | null = null; let positionedCount = 0; for (const firm of firms) { @@ -338,11 +338,7 @@ export async function copyTrade() { positionedCount++; if (!resolvedAction) { resolvedAction = pos.netPos > 0 ? 'Buy' : 'Sell'; - } - // Determine the symbol from the scheduler state (positions only have contractId) - if (!resolvedSymbol) { - const state = getState(); - resolvedSymbol = state.symbol === 'Auto' ? null : state.symbol; + positionContractId = pos.contractId; } } } @@ -352,11 +348,29 @@ export async function copyTrade() { return []; } - // Fall back to enabled instruments if symbol unknown + // Resolve symbol from the positioned contract's contractId + let resolvedSymbol: string | null = null; + const instruments = getInstruments(); + const enabledSymbols = instruments.filter(i => i.enabled).map(i => i.symbol); + + // Try each enabled symbol to find which one matches the positioned contractId + for (const firm of firms) { + const client = clients.get(firm.id); + if (!client) continue; + for (const sym of enabledSymbols) { + const contract = await client.findFrontMonthContract(sym); + if (contract && contract.id === positionContractId) { + resolvedSymbol = sym; + break; + } + } + if (resolvedSymbol) break; + } + + // Fall back to scheduler symbol or first enabled if (!resolvedSymbol) { - const instruments = getInstruments(); - const enabled = instruments.filter(i => i.enabled).map(i => i.symbol); - resolvedSymbol = enabled[0] ?? 'NQ'; + const state = getState(); + resolvedSymbol = state.symbol !== 'Auto' ? state.symbol : (enabledSymbols[0] ?? 'NQ'); } const pointValue = POINT_VALUES[resolvedSymbol];