import { BacktestEngine } from './src/backtest/BacktestEngine'; import { StrategyManager } from './src/strategies/StrategyManager'; import { StorageService } from './src/services/StorageService'; import { ModeManager } from './src/core/ModeManager'; import { MarketDataService } from './src/services/MarketDataService'; import { ExecutionService } from './src/services/ExecutionService'; import { IServiceContainer } from '@stock-bot/di'; async function debugPerformanceValues() { console.log('Debugging Performance Calculation Values...\n'); // Create minimal service container with more logging const container: IServiceContainer = { logger: { info: (msg: string, ...args: any[]) => { // Log everything related to P&L and portfolio if (msg.includes('P&L') || msg.includes('portfolio') || msg.includes('Portfolio') || msg.includes('equity') || msg.includes('Total') || msg.includes('pnl')) { console.log('[INFO]', msg, ...args); } }, error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args), warn: (msg: string, ...args: any[]) => console.warn('[WARN]', msg, ...args), debug: (msg: string, ...args: any[]) => { if (msg.includes('P&L') || msg.includes('portfolio') || msg.includes('pnl')) { console.log('[DEBUG]', msg, ...args); } }, } as any, custom: {} }; // Initialize services const storageService = new StorageService(); const marketDataService = new MarketDataService(container); const executionService = new ExecutionService(container); const modeManager = new ModeManager(container, marketDataService, executionService, storageService); const strategyManager = new StrategyManager(container); // Set services in container container.custom = { MarketDataService: marketDataService, ExecutionService: executionService, ModeManager: modeManager, StorageService: storageService }; // Initialize backtest mode await modeManager.initializeMode({ mode: 'backtest', startDate: '2023-01-01T00:00:00Z', endDate: '2023-01-15T00:00:00Z', // Just 15 days speed: 'max', symbols: ['TEST'], initialCapital: 100000, dataFrequency: '1d', strategy: 'sma-crossover' }); // Create backtest engine const backtestEngine = new BacktestEngine(container, storageService, strategyManager); // Run backtest const config = { mode: 'backtest', name: 'Debug Performance Values', strategy: 'sma-crossover', symbols: ['TEST'], startDate: '2023-01-01T00:00:00Z', endDate: '2023-01-15T00:00:00Z', initialCapital: 100000, commission: 0.001, slippage: 0.0001, dataFrequency: '1d', speed: 'max' }; console.log('Running backtest...'); const result = await backtestEngine.runBacktest(config); // Debug values console.log('\n=== RAW VALUES DEBUG ==='); console.log(`Initial Capital: $${config.initialCapital}`); console.log(`Reported Metrics:`); console.log(` - Total Return: ${result.metrics.totalReturn}%`); console.log(` - Sharpe Ratio: ${result.metrics.sharpeRatio}`); console.log(` - Max Drawdown: ${result.metrics.maxDrawdown}%`); console.log(` - Win Rate: ${result.metrics.winRate}%`); console.log(` - Total Trades: ${result.metrics.totalTrades}`); console.log('\n=== EQUITY CURVE VALUES ==='); console.log(`Equity Points: ${result.equity.length}`); if (result.equity.length > 0) { const first = result.equity[0]; const last = result.equity[result.equity.length - 1]; console.log(`First: ${first.date} => $${first.value}`); console.log(`Last: ${last.date} => $${last.value}`); // Manual calculation const manualReturn = ((last.value - first.value) / first.value) * 100; console.log(`\nManual Total Return: ${manualReturn.toFixed(2)}%`); console.log(`Difference from reported: ${Math.abs(manualReturn - result.metrics.totalReturn).toFixed(2)}%`); } console.log('\n=== TRADE ANALYSIS ==='); console.log(`Closed Trades: ${result.trades.length}`); if (result.trades.length > 0) { const wins = result.trades.filter(t => t.pnl > 0); const losses = result.trades.filter(t => t.pnl < 0); const manualWinRate = (wins.length / result.trades.length) * 100; console.log(`Wins: ${wins.length}`); console.log(`Losses: ${losses.length}`); console.log(`Manual Win Rate: ${manualWinRate.toFixed(2)}%`); // Show P&L values const totalPnL = result.trades.reduce((sum, t) => sum + t.pnl, 0); console.log(`\nTotal P&L from trades: $${totalPnL.toFixed(2)}`); // Show first few trades console.log('\nFirst 3 trades:'); result.trades.slice(0, 3).forEach((t, i) => { console.log(` ${i+1}. ${t.side} ${t.quantity} @ ${t.exitPrice} | P&L: $${t.pnl.toFixed(2)}`); }); } // Check trading engine P&L const tradingEngine = strategyManager.getTradingEngine(); if (tradingEngine) { try { const [realized, unrealized] = tradingEngine.getTotalPnl(); console.log('\n=== TRADING ENGINE P&L ==='); console.log(`Realized P&L: $${realized.toFixed(2)}`); console.log(`Unrealized P&L: $${unrealized.toFixed(2)}`); console.log(`Total P&L: $${(realized + unrealized).toFixed(2)}`); console.log(`Portfolio Value: $${(config.initialCapital + realized + unrealized).toFixed(2)}`); } catch (e) { console.error('Failed to get P&L from trading engine:', e); } } console.log('\n=== TEST COMPLETE ==='); process.exit(0); } debugPerformanceValues().catch(error => { console.error('Test failed:', error); process.exit(1); });