import { BacktestEngine } from '../src/backtest/BacktestEngine'; import { createExampleRuntime } from './example-runtime'; async function debugPositionTracking() { // Create service container with detailed logging const { container, storageService, marketDataService: _marketDataService, modeManager, strategyManager, } = await createExampleRuntime(); // Initialize backtest mode with full config await modeManager.initializeMode({ mode: 'backtest', startDate: '2023-06-01T00:00:00Z', endDate: '2023-09-01T00:00:00Z', // Just 3 months for debugging speed: 'max', symbols: ['AAPL.US'], initialCapital: 100000, dataFrequency: '1d', strategy: 'sma-crossover', }); // Create backtest engine const backtestEngine = new BacktestEngine(container, storageService, strategyManager); // Listen to strategy events for debugging strategyManager.on('order', (orderEvent: unknown) => { console.log('\nšŸ“Š STRATEGY ORDER EVENT:', orderEvent); }); // Configure backtest const config = { mode: 'backtest' as const, name: 'Position Tracking Debug', strategy: 'sma-crossover', symbols: ['AAPL.US'], startDate: '2023-06-01T00:00:00Z', endDate: '2023-09-01T00:00:00Z', initialCapital: 100000, commission: 0.001, slippage: 0.0001, dataFrequency: '1d' as const, speed: 'max' as const, }; console.log('Starting position tracking debug...\n'); try { const result = await backtestEngine.runBacktest(config); console.log('\n=== FINAL RESULTS ==='); console.log(`Total Trades: ${result.metrics.totalTrades}`); console.log(`Win Rate: ${result.metrics.winRate.toFixed(2)}%`); console.log('\n=== TRADE DETAILS ==='); let buyCount = 0; let sellCount = 0; result.trades.forEach((trade, i) => { console.log(`\nTrade ${i + 1}:`); console.log(` Symbol: ${trade.symbol}`); console.log(` Side: ${trade.side}`); console.log(` Entry: ${trade.entryDate} @ $${trade.entryPrice.toFixed(2)}`); console.log(` Exit: ${trade.exitDate} @ $${trade.exitPrice.toFixed(2)}`); console.log(` Quantity: ${trade.quantity}`); console.log(` P&L: $${trade.pnl.toFixed(2)}`); if (trade.side === 'buy') { buyCount++; } else if (trade.side === 'sell') { sellCount++; } }); console.log(`\n=== TRADE SIDE SUMMARY ===`); console.log(`Buy trades: ${buyCount}`); console.log(`Sell trades: ${sellCount}`); // Check final positions console.log('\n=== FINAL POSITIONS ==='); result.positions.forEach(pos => { console.log(`${pos.symbol}: ${pos.quantity} shares @ avg $${pos.averagePrice.toFixed(2)}`); }); } catch (error) { console.error('Debug failed:', error); } } // Run the debug debugPositionTracking().catch(console.error);