220 lines
7.1 KiB
TypeScript
220 lines
7.1 KiB
TypeScript
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<import('../services/backtestApiV2').RunResult, 'equity' | 'ohlcData' | 'trades'> {
|
|
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<string>('');
|
|
|
|
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 (
|
|
<div className="bg-surface-secondary rounded-lg border border-border p-4 h-full animate-pulse">
|
|
<div className="h-full bg-surface rounded"></div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (!result || !chartData) {
|
|
return (
|
|
<div className="bg-surface-secondary rounded-lg border border-border p-8 text-center h-full flex items-center justify-center">
|
|
<p className="text-text-secondary">
|
|
Run a backtest to see the equity curve and price chart.
|
|
</p>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="h-full flex flex-col">
|
|
{chartData.symbols.length > 1 && (
|
|
<div className="flex space-x-2 mb-4">
|
|
<label className="text-sm text-text-secondary">Symbol:</label>
|
|
<select
|
|
value={selectedSymbol || chartData.symbols[0]}
|
|
onChange={e => setSelectedSymbol(e.target.value)}
|
|
className="px-2 py-1 bg-background border border-border rounded text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
|
>
|
|
{chartData.symbols.map(symbol => (
|
|
<option key={symbol} value={symbol}>
|
|
{symbol}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
)}
|
|
|
|
<div className="flex-1 min-h-0">
|
|
<ChartContainer>
|
|
{height => (
|
|
<Chart
|
|
data={chartData.ohlcData}
|
|
overlayData={[
|
|
{
|
|
name: 'Equity',
|
|
data: chartData.equityData,
|
|
color: '#3b82f6',
|
|
lineWidth: 2,
|
|
},
|
|
]}
|
|
tradeMarkers={chartData.tradeMarkers}
|
|
height={height}
|
|
chartId={`backtest-${result?.runId || result?.id || 'default'}`}
|
|
key={result?.runId || result?.id || 'default'}
|
|
/>
|
|
)}
|
|
</ChartContainer>
|
|
</div>
|
|
</div>
|
|
);
|
|
});
|