import { memo, useMemo, useState } from 'react'; import { browserLog } from '@/utils/browserLog'; import { Chart } from '../../../components/charts/Chart'; import type { PerformanceDataPoint } from '../types/backtest.types'; import { ChartContainer } from './ChartContainer'; interface ExtendedBacktestResult extends Pick { performanceData?: PerformanceDataPoint[]; runId?: string; id?: string; } interface ExtendedTrade { id: string; timestamp: string; symbol: string; side: 'buy' | 'sell'; quantity: number; price: number; commission: number; pnl?: number; positionAfter?: number; entryPrice?: number; entryDate?: string; date?: string; } interface BacktestChartProps { result: ExtendedBacktestResult | null; isLoading: boolean; } // Memoize the component to prevent unnecessary re-renders export const BacktestChart = memo(function BacktestChart({ result, isLoading, }: BacktestChartProps) { const [selectedSymbol, setSelectedSymbol] = useState(''); const chartData = useMemo(() => { if ( !result || (!result.equity && !result.performanceData) || (!result.ohlcData && !result.trades) ) { return null; } const symbols = result.ohlcData ? Object.keys(result.ohlcData) : result.trades ? [...new Set(result.trades.map(t => t.symbol))] : []; const symbol = selectedSymbol || symbols[0] || ''; const ohlcData = result.ohlcData?.[symbol] || []; // Remove excessive logging in production // Log only on significant changes if (process.env.NODE_ENV === 'development' && ohlcData.length > 0) { // Use a simple hash to detect actual data changes const dataHash = `${symbols.length}-${result.equity?.length || result.performanceData?.length}-${ohlcData.length}`; if ((window as Window & { __lastDataHash?: string }).__lastDataHash !== dataHash) { (window as Window & { __lastDataHash?: string }).__lastDataHash = dataHash; browserLog.log('BacktestChart data updated:', { symbols, selectedSymbol, symbol, ohlcDataKeys: result.ohlcData ? Object.keys(result.ohlcData) : [], equityLength: result.equity?.length || result.performanceData?.length, tradesLength: result.trades?.length, }); } } const equityData = result.equity ? result.equity .filter(e => e && e.date && e.value !== null && e.value !== undefined) .map(e => ({ time: new Date(e.date).getTime() / 1000, value: e.value, })) : result.performanceData ?.filter( p => p && p.timestamp && p.portfolioValue !== null && p.portfolioValue !== undefined ) .map(p => ({ time: new Date(p.timestamp).getTime() / 1000, value: p.portfolioValue, })) || []; // Find trades for this symbol const symbolTrades = result.trades?.filter(t => t.symbol === symbol) || []; browserLog.log('Symbol trades for', symbol, ':', symbolTrades); const tradeMarkers = symbolTrades .filter(trade => { // Check multiple possible field names const extTrade = trade as ExtendedTrade; const hasPrice = (extTrade.price !== null && extTrade.price !== undefined) || (extTrade.entryPrice !== null && extTrade.entryPrice !== undefined); const hasTime = (extTrade.timestamp !== null && extTrade.timestamp !== undefined) || (extTrade.entryDate !== null && extTrade.entryDate !== undefined) || (extTrade.date !== null && extTrade.date !== undefined); return hasPrice && hasTime; }) .map(trade => { // Use whatever field names are present const extTrade = trade as ExtendedTrade; const price = extTrade.price || extTrade.entryPrice || 0; const timestamp = extTrade.timestamp || extTrade.entryDate || extTrade.date || ''; const side = extTrade.side || (extTrade.quantity > 0 ? 'buy' : 'sell'); return { time: new Date(timestamp).getTime() / 1000, position: 'belowBar' as const, color: side === 'buy' ? '#10b981' : '#ef4444', shape: side === 'buy' ? ('arrowUp' as const) : ('arrowDown' as const), text: `${side === 'buy' ? 'Buy' : 'Sell'} @ $${price.toFixed(2)}`, price: price, }; }); browserLog.log('Trade markers:', tradeMarkers); const processedOhlcData = ohlcData .filter( d => d && d.timestamp !== null && d.timestamp !== undefined && d.open !== null && d.open !== undefined && d.high !== null && d.high !== undefined && d.low !== null && d.low !== undefined && d.close !== null && d.close !== undefined ) .map(d => ({ time: d.timestamp / 1000, // timestamp is already in milliseconds open: d.open, high: d.high, low: d.low, close: d.close, volume: d.volume || 0, })); return { ohlcData: processedOhlcData, equityData, tradeMarkers, symbols, }; }, [result, selectedSymbol]); if (isLoading) { return (
); } if (!result || !chartData) { return (

Run a backtest to see the equity curve and price chart.

); } return (
{chartData.symbols.length > 1 && (
)}
{height => ( )}
); });