429 lines
14 KiB
TypeScript
429 lines
14 KiB
TypeScript
import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
|
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
import { useNavigate, useParams } from 'react-router-dom';
|
|
import { useWebSocket } from '@/hooks/useWebSocket';
|
|
import { BacktestConfiguration } from './components/BacktestConfiguration';
|
|
import { BacktestPlayback } from './components/BacktestPlayback';
|
|
import { BacktestTrades } from './components/BacktestTrades';
|
|
import { RunControlsCompact } from './components/RunControlsCompact';
|
|
import { RunsListWithMetrics } from './components/RunsListWithMetrics';
|
|
import { useBacktestV2 } from './hooks/useBacktestV2';
|
|
import type { BacktestConfig } from './types/backtest.types';
|
|
|
|
const baseTabs = [
|
|
{ id: 'runs', name: 'Runs' },
|
|
{ id: 'settings', name: 'Settings' },
|
|
];
|
|
|
|
const runTabs = [
|
|
{ id: 'details', name: 'Details' },
|
|
{ id: 'trades', name: 'Trades' },
|
|
];
|
|
|
|
export function BacktestDetailPageV2() {
|
|
const { id, runId } = useParams<{ id: string; runId?: string }>();
|
|
const navigate = useNavigate();
|
|
const [activeTab, setActiveTab] = useState('details');
|
|
const [showNewRun, setShowNewRun] = useState(false);
|
|
const navigationGeneration = useRef(0);
|
|
|
|
const {
|
|
backtest,
|
|
runs,
|
|
currentRun,
|
|
runResults,
|
|
isLoading,
|
|
error,
|
|
submissionError,
|
|
isSubmitting,
|
|
hasPendingSubmission,
|
|
loadBacktest,
|
|
updateBacktest,
|
|
createRun,
|
|
cancelRun,
|
|
cancelRequested,
|
|
selectRun,
|
|
refreshRun,
|
|
} = useBacktestV2();
|
|
|
|
// Notifications invalidate the same persisted-state reader used by polling.
|
|
useWebSocket({
|
|
runId:
|
|
currentRun && ['pending', 'running', 'paused'].includes(currentRun.status)
|
|
? currentRun.id
|
|
: null,
|
|
onMessage: message => {
|
|
if (message.type !== 'pong') {
|
|
void refreshRun(message.runId);
|
|
}
|
|
},
|
|
});
|
|
|
|
useEffect(() => {
|
|
navigationGeneration.current++;
|
|
setShowNewRun(false);
|
|
return () => {
|
|
navigationGeneration.current++;
|
|
};
|
|
}, [id, runId]);
|
|
|
|
useEffect(() => {
|
|
if (id) {
|
|
void loadBacktest(id);
|
|
}
|
|
}, [id, loadBacktest]);
|
|
|
|
// URL selection is immediate; a new selection invalidates every old continuation.
|
|
useEffect(() => {
|
|
void selectRun(runId);
|
|
setActiveTab(previous => (runId ? (previous === 'runs' ? 'details' : previous) : 'runs'));
|
|
}, [runId, selectRun]);
|
|
|
|
// Handle configuration save
|
|
const handleConfigSubmit = useCallback(
|
|
async (config: BacktestConfig) => {
|
|
if (!id) {
|
|
return;
|
|
}
|
|
|
|
await updateBacktest(id, {
|
|
name: config.name,
|
|
strategy: config.strategy,
|
|
symbols: config.symbols,
|
|
startDate: config.startDate.toISOString().split('T')[0],
|
|
endDate: config.endDate.toISOString().split('T')[0],
|
|
initialCapital: config.initialCapital,
|
|
config: {
|
|
...backtest?.config,
|
|
commission: config.commission,
|
|
slippage: config.slippage,
|
|
speedMultiplier: config.speedMultiplier,
|
|
dataPolicy: {
|
|
adjustment: config.priceAdjustment ?? 'raw',
|
|
timestamp:
|
|
!backtest?.config?.dataFrequency || backtest.config.dataFrequency === '1d'
|
|
? 'utc-session-date'
|
|
: 'utc-instant',
|
|
},
|
|
},
|
|
});
|
|
},
|
|
[id, updateBacktest, backtest]
|
|
);
|
|
|
|
// Handle new run creation
|
|
const handleCreateRun = useCallback(async () => {
|
|
const generation = navigationGeneration.current;
|
|
const newRun = await createRun(null);
|
|
if (newRun && id && generation === navigationGeneration.current) {
|
|
setShowNewRun(false);
|
|
navigate(`/backtests/${id}/run/${newRun.id}`);
|
|
}
|
|
}, [createRun, navigate, id]);
|
|
|
|
// Handle rerun
|
|
const handleRerun = useCallback(
|
|
async (speedMultiplier: number | null) => {
|
|
const generation = navigationGeneration.current;
|
|
const newRun = await createRun(speedMultiplier);
|
|
if (newRun && id && generation === navigationGeneration.current) {
|
|
navigate(`/backtests/${id}/run/${newRun.id}`);
|
|
}
|
|
},
|
|
[createRun, navigate, id]
|
|
);
|
|
|
|
// Convert backtest to config format for the form
|
|
const backtestConfig: BacktestConfig | undefined = backtest
|
|
? {
|
|
name: backtest.name,
|
|
startDate: new Date(backtest.startDate),
|
|
endDate: new Date(backtest.endDate),
|
|
initialCapital: backtest.initialCapital,
|
|
symbols: backtest.symbols,
|
|
strategy: backtest.strategy,
|
|
speedMultiplier: 1,
|
|
commission: Number(backtest.config?.commission ?? 0.001),
|
|
slippage: Number(backtest.config?.slippage ?? 0.0001),
|
|
priceAdjustment:
|
|
backtest.config?.dataPolicy &&
|
|
typeof backtest.config.dataPolicy === 'object' &&
|
|
'adjustment' in backtest.config.dataPolicy &&
|
|
backtest.config.dataPolicy.adjustment === 'provider-adjusted'
|
|
? 'provider-adjusted'
|
|
: 'raw',
|
|
}
|
|
: undefined;
|
|
|
|
const renderTabContent = () => {
|
|
if (['details', 'trades'].includes(activeTab)) {
|
|
if (isLoading) {
|
|
return (
|
|
<div role="status" className="p-8 text-text-secondary">
|
|
Loading run data...
|
|
</div>
|
|
);
|
|
}
|
|
if (currentRun?.status === 'failed' || currentRun?.status === 'cancelled') {
|
|
return (
|
|
<div role="status" className="p-8 text-text-secondary">
|
|
{currentRun.status === 'failed'
|
|
? `Run failed: ${currentRun.error || 'No error details were saved.'}`
|
|
: 'Run cancelled. No completed results are available.'}
|
|
</div>
|
|
);
|
|
}
|
|
if (currentRun && currentRun.status !== 'completed') {
|
|
return (
|
|
<div role="status" className="p-8 text-text-secondary">
|
|
{cancelRequested || currentRun.cancelRequested
|
|
? 'Cancellation requested. Waiting for the worker to stop.'
|
|
: 'Run is not complete. Results will appear when saved.'}
|
|
</div>
|
|
);
|
|
}
|
|
if (currentRun && !runResults) {
|
|
return (
|
|
<div className="p-8 text-text-secondary">
|
|
<p>Run completed, but saved results are unavailable.</p>
|
|
<button className="mt-2 text-primary-500" onClick={() => void refreshRun()}>
|
|
Retry results
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|
|
}
|
|
// A missing result is not a successful run with zero trades.
|
|
if (!currentRun && ['details', 'trades'].includes(activeTab)) {
|
|
return (
|
|
<div className="flex items-center justify-center h-full">
|
|
<div className="text-center">
|
|
<p className="text-text-secondary mb-4">Please select a run to view {activeTab}</p>
|
|
<button
|
|
onClick={() => setActiveTab('runs')}
|
|
className="text-primary-500 hover:text-primary-600 font-medium"
|
|
>
|
|
Go to Runs
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
switch (activeTab) {
|
|
case 'runs':
|
|
return (
|
|
<div className="space-y-4">
|
|
<div className="flex justify-between items-center">
|
|
<h3 className="text-lg font-medium text-text-primary">Run History</h3>
|
|
<button
|
|
onClick={() => setShowNewRun(true)}
|
|
className="inline-flex items-center px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
|
>
|
|
<PlusIcon className="w-4 h-4 mr-2" />
|
|
New Run
|
|
</button>
|
|
</div>
|
|
|
|
{showNewRun && (
|
|
<div className="bg-surface-secondary rounded-lg border border-border p-4 space-y-4">
|
|
<h4 className="text-base font-medium text-text-primary">Run current settings</h4>
|
|
<p className="text-sm text-text-secondary">
|
|
Submit the current configuration, not a reproduction of a previous run. A retry
|
|
recovers the original submission if it was already accepted.
|
|
</p>
|
|
<div className="flex space-x-2">
|
|
<button
|
|
onClick={() => {
|
|
void handleCreateRun();
|
|
}}
|
|
disabled={isSubmitting}
|
|
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
|
>
|
|
{isSubmitting
|
|
? 'Submitting...'
|
|
: hasPendingSubmission
|
|
? 'Retry submission'
|
|
: 'Run current settings'}
|
|
</button>
|
|
<button
|
|
onClick={() => {
|
|
navigationGeneration.current++;
|
|
setShowNewRun(false);
|
|
}}
|
|
className="px-4 py-2 bg-surface-tertiary text-text-primary rounded-md text-sm font-medium hover:bg-surface-secondary transition-colors"
|
|
>
|
|
Cancel
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<RunsListWithMetrics
|
|
runs={runs}
|
|
currentRunId={currentRun?.id}
|
|
onSelectRun={selectRun}
|
|
/>
|
|
</div>
|
|
);
|
|
case 'settings':
|
|
return (
|
|
<div className="max-w-4xl mx-auto">
|
|
<BacktestConfiguration
|
|
onSubmit={handleConfigSubmit}
|
|
disabled={false}
|
|
initialConfig={backtestConfig}
|
|
/>
|
|
</div>
|
|
);
|
|
case 'details':
|
|
// Only render if we have matching results or no results yet
|
|
if (runResults && currentRun && runResults.runId !== currentRun.id) {
|
|
return (
|
|
<div className="h-full flex items-center justify-center">
|
|
<div className="text-text-secondary">Loading run data...</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="h-full overflow-hidden">
|
|
<BacktestPlayback
|
|
key={currentRun?.id || 'no-run'} // Force remount on run change
|
|
result={runResults}
|
|
isLoading={isLoading}
|
|
/>
|
|
</div>
|
|
);
|
|
case 'trades':
|
|
return (
|
|
<div className="h-full overflow-y-auto">
|
|
<BacktestTrades result={runResults} isLoading={isLoading} />
|
|
</div>
|
|
);
|
|
default:
|
|
return null;
|
|
}
|
|
};
|
|
|
|
if (!backtest && !isLoading) {
|
|
return (
|
|
<div className="h-full flex items-center justify-center">
|
|
<div className="text-center">
|
|
<p className="text-text-secondary mb-4">{error || 'Backtest not found'}</p>
|
|
{error && id && (
|
|
<button className="mr-4 text-primary-500" onClick={() => void loadBacktest(id)}>
|
|
Retry backtest
|
|
</button>
|
|
)}
|
|
<button
|
|
onClick={() => navigate('/backtests')}
|
|
className="text-primary-500 hover:text-primary-600"
|
|
>
|
|
Back to Backtests
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="h-full flex flex-col">
|
|
{/* Header with Tabs */}
|
|
<div className="flex-shrink-0 border-b border-border">
|
|
<div className="flex items-center justify-between">
|
|
<div className="flex items-center flex-1">
|
|
<button
|
|
onClick={() => navigate('/backtests')}
|
|
className="p-2 hover:bg-surface-tertiary transition-colors"
|
|
aria-label="Back to backtests"
|
|
>
|
|
<ArrowLeftIcon className="h-5 w-5 text-text-secondary" />
|
|
</button>
|
|
<div className="px-2">
|
|
<h1 className="text-sm font-bold text-text-primary flex items-center gap-1">
|
|
{backtest?.name || 'Loading...'}
|
|
{currentRun && (
|
|
<span className="text-text-secondary font-normal">
|
|
- Run #{currentRun.runNumber}
|
|
</span>
|
|
)}
|
|
</h1>
|
|
<p className="text-xs text-text-secondary">
|
|
Current definition: {backtest?.strategy || ''} •{' '}
|
|
{backtest?.symbols.join(', ') || ''}
|
|
</p>
|
|
</div>
|
|
|
|
{/* Tabs */}
|
|
<nav className="flex ml-4" aria-label="Tabs">
|
|
{(currentRun ? runTabs : []).concat(baseTabs).map(tab => (
|
|
<button
|
|
key={tab.id}
|
|
onClick={() => setActiveTab(tab.id)}
|
|
className={`
|
|
whitespace-nowrap py-2 px-3 border-b-2 font-medium text-sm
|
|
${
|
|
activeTab === tab.id
|
|
? 'border-primary-500 text-primary-500'
|
|
: 'border-transparent text-text-secondary hover:text-text-primary hover:border-border'
|
|
}
|
|
`}
|
|
>
|
|
{tab.name}
|
|
</button>
|
|
))}
|
|
</nav>
|
|
</div>
|
|
|
|
{/* Run Controls */}
|
|
{currentRun && (
|
|
<div className="px-4">
|
|
<RunControlsCompact
|
|
run={currentRun}
|
|
onCancel={cancelRun}
|
|
cancelRequested={cancelRequested}
|
|
onRerun={handleRerun}
|
|
isSubmitting={isSubmitting}
|
|
hasPendingSubmission={hasPendingSubmission}
|
|
/>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Tab Content */}
|
|
<div className="flex-1 overflow-hidden py-4">
|
|
{submissionError && (
|
|
<div className="mb-4 p-4 bg-error/10 border border-error/20 rounded-lg">
|
|
<p role="alert" className="text-sm text-error">
|
|
Run submission failed: {submissionError}. Retry to recover the same submission.
|
|
</p>
|
|
{!showNewRun && (
|
|
<button
|
|
disabled={isSubmitting}
|
|
className="mt-2 text-primary-500"
|
|
onClick={() => void handleCreateRun()}
|
|
>
|
|
Retry submission
|
|
</button>
|
|
)}
|
|
</div>
|
|
)}
|
|
{error && (
|
|
<div className="mb-4 p-4 bg-error/10 border border-error/20 rounded-lg">
|
|
<p role="alert" className="text-sm text-error">
|
|
{error}
|
|
</p>
|
|
{runId && (
|
|
<button className="mt-2 text-primary-500" onClick={() => void refreshRun()}>
|
|
Retry run
|
|
</button>
|
|
)}
|
|
</div>
|
|
)}
|
|
{renderTabContent()}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|