commit 2 refactor

This commit is contained in:
Boki 2026-10-20 14:35:45 -04:00
parent 588f666943
commit 32e43c9243
310 changed files with 33318 additions and 31189 deletions

View file

@ -1,375 +1,387 @@
import { useWebSocket } from '@/hooks/useWebSocket';
import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
import { useCallback, useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
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 {
backtest,
runs,
currentRun,
runResults,
isLoading,
error,
loadBacktest,
updateBacktest,
createRun,
pauseRun,
resumeRun,
updateRunSpeed,
selectRun,
} = useBacktestV2();
// WebSocket connection for real-time updates
useWebSocket({
runId: currentRun?.id || null,
onProgress: (progress, currentDate) => {
// Update the run progress in the UI
if (currentRun) {
// This will trigger a re-render with updated progress
console.log('Progress update:', progress, currentDate);
}
},
onError: (error) => {
console.error('Run error:', error);
// Reload runs to get updated status
if (id) {
loadBacktest(id);
}
},
onCompleted: async () => {
// When run completes, reload to get the final results
if (currentRun?.id) {
try {
// Small delay to ensure the results are persisted
await new Promise(resolve => setTimeout(resolve, 500));
// Force re-select the run to load its results
await selectRun(currentRun.id);
} catch (err) {
console.error('Failed to load completed run results:', err);
}
}
}
});
// Load backtest on mount
useEffect(() => {
if (id) {
loadBacktest(id);
}
}, [id, loadBacktest]);
// Clear mismatched results immediately
useEffect(() => {
if (runResults && currentRun && runResults.runId !== currentRun.id) {
console.warn('Run results mismatch:', {
runResultsId: runResults.runId,
currentRunId: currentRun.id
});
// Clear the mismatched results immediately to prevent rendering wrong data
// The selectRun effect will load the correct results
}
}, [runResults?.runId, currentRun?.id]);
// We don't need this effect anymore - it's causing unnecessary re-renders
// The selectRun function already handles clearing mismatched results
// Select run based on URL parameter with debounce
useEffect(() => {
const timeoutId = setTimeout(() => {
if (runId) {
// If the current run already matches, don't re-select
if (currentRun?.id === runId) {
return;
}
// Always try to select the run - selectRun will fetch it if not found
selectRun(runId);
// Show details tab by default when a run is selected
if (activeTab === 'runs') {
setActiveTab('details');
}
} else if (!runId && currentRun) {
// Clear run selection when navigating away from run URL
selectRun(undefined);
setActiveTab('runs');
}
}, 50); // Small debounce to prevent rapid switching
return () => clearTimeout(timeoutId);
}, [runId, currentRun?.id, selectRun, activeTab]);
// 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: {
commission: config.commission,
slippage: config.slippage,
speedMultiplier: config.speedMultiplier,
},
});
}, [id, updateBacktest]);
// Handle new run creation
const handleCreateRun = useCallback(async (speedMultiplier: number) => {
const newRun = await createRun(speedMultiplier);
setShowNewRun(false);
// Navigate to the new run
if (newRun && id) {
navigate(`/backtests/${id}/run/${newRun.id}`);
}
}, [createRun, navigate, id]);
// Handle rerun
const handleRerun = useCallback(async (speedMultiplier: number | null) => {
// Pass null for max speed (no limit)
const newRun = await createRun(speedMultiplier ?? undefined);
// Navigate to the new run's URL
if (newRun && id) {
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: backtest.config?.commission ?? 0.001,
slippage: backtest.config?.slippage ?? 0.0001,
} : undefined;
const renderTabContent = () => {
// Show message if trying to view run-specific tabs without a run selected
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">Start New Run</h4>
<p className="text-sm text-text-secondary">
This will start a new backtest run with the current configuration.
</p>
<div className="flex space-x-2">
<button
onClick={() => {
handleCreateRun(1000); // Always use max speed
}}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
Start Run
</button>
<button
onClick={() => 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">Backtest not found</p>
<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">
{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}
onPause={pauseRun}
onResume={resumeRun}
onRerun={handleRerun}
onSpeedChange={updateRunSpeed}
/>
</div>
)}
</div>
</div>
{/* Tab Content */}
<div className="flex-1 overflow-hidden py-4">
{error && (
<div className="mb-4 p-4 bg-error/10 border border-error/20 rounded-lg">
<p className="text-sm text-error">{error}</p>
</div>
)}
{renderTabContent()}
</div>
</div>
);
}
import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
import { useCallback, useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useWebSocket } from '@/hooks/useWebSocket';
import { browserLog } from '@/utils/browserLog';
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 {
backtest,
runs,
currentRun,
runResults,
isLoading,
error,
loadBacktest,
updateBacktest,
createRun,
pauseRun,
resumeRun,
updateRunSpeed,
selectRun,
} = useBacktestV2();
// WebSocket connection for real-time updates
useWebSocket({
runId: currentRun?.id || null,
onProgress: (progress, currentDate) => {
// Update the run progress in the UI
if (currentRun) {
// This will trigger a re-render with updated progress
browserLog.log('Progress update:', progress, currentDate);
}
},
onError: error => {
browserLog.error('Run error:', error);
// Reload runs to get updated status
if (id) {
loadBacktest(id);
}
},
onCompleted: async () => {
// When run completes, reload to get the final results
if (currentRun?.id) {
try {
// Small delay to ensure the results are persisted
await new Promise(resolve => setTimeout(resolve, 500));
// Force re-select the run to load its results
await selectRun(currentRun.id);
} catch (err) {
browserLog.error('Failed to load completed run results:', err);
}
}
},
});
// Load backtest on mount
useEffect(() => {
if (id) {
loadBacktest(id);
}
}, [id, loadBacktest]);
// Clear mismatched results immediately
useEffect(() => {
if (runResults && currentRun && runResults.runId !== currentRun.id) {
browserLog.warn('Run results mismatch:', {
runResultsId: runResults.runId,
currentRunId: currentRun.id,
});
// Clear the mismatched results immediately to prevent rendering wrong data
// The selectRun effect will load the correct results
}
}, [runResults?.runId, currentRun?.id]);
// We don't need this effect anymore - it's causing unnecessary re-renders
// The selectRun function already handles clearing mismatched results
// Select run based on URL parameter with debounce
useEffect(() => {
const timeoutId = setTimeout(() => {
if (runId) {
// If the current run already matches, don't re-select
if (currentRun?.id === runId) {
return;
}
// Always try to select the run - selectRun will fetch it if not found
selectRun(runId);
// Show details tab by default when a run is selected
if (activeTab === 'runs') {
setActiveTab('details');
}
} else if (!runId && currentRun) {
// Clear run selection when navigating away from run URL
selectRun(undefined);
setActiveTab('runs');
}
}, 50); // Small debounce to prevent rapid switching
return () => clearTimeout(timeoutId);
}, [runId, currentRun?.id, selectRun, activeTab]);
// 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: {
commission: config.commission,
slippage: config.slippage,
speedMultiplier: config.speedMultiplier,
},
});
},
[id, updateBacktest]
);
// Handle new run creation
const handleCreateRun = useCallback(
async (speedMultiplier: number) => {
const newRun = await createRun(speedMultiplier);
setShowNewRun(false);
// Navigate to the new run
if (newRun && id) {
navigate(`/backtests/${id}/run/${newRun.id}`);
}
},
[createRun, navigate, id]
);
// Handle rerun
const handleRerun = useCallback(
async (speedMultiplier: number | null) => {
// Pass null for max speed (no limit)
const newRun = await createRun(speedMultiplier ?? undefined);
// Navigate to the new run's URL
if (newRun && id) {
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),
}
: undefined;
const renderTabContent = () => {
// Show message if trying to view run-specific tabs without a run selected
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">Start New Run</h4>
<p className="text-sm text-text-secondary">
This will start a new backtest run with the current configuration.
</p>
<div className="flex space-x-2">
<button
onClick={() => {
handleCreateRun(1000); // Always use max speed
}}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
Start Run
</button>
<button
onClick={() => 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">Backtest not found</p>
<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">
{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}
onPause={pauseRun}
onResume={resumeRun}
onRerun={handleRerun}
onSpeedChange={updateRunSpeed}
/>
</div>
)}
</div>
</div>
{/* Tab Content */}
<div className="flex-1 overflow-hidden py-4">
{error && (
<div className="mb-4 p-4 bg-error/10 border border-error/20 rounded-lg">
<p className="text-sm text-error">{error}</p>
</div>
)}
{renderTabContent()}
</div>
</div>
);
}

View file

@ -1,151 +1,143 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { DataTable } from '@/components/ui/DataTable/DataTable';
import type { ColumnDef } from '@tanstack/react-table';
import { PlusIcon } from '@heroicons/react/24/solid';
import { backtestApiV2, type Backtest } from './services/backtestApiV2';
import { CreateBacktestDialog } from './components/CreateBacktestDialog';
export function BacktestListPageV2() {
const navigate = useNavigate();
const [backtests, setBacktests] = useState<Backtest[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [showCreateDialog, setShowCreateDialog] = useState(false);
const loadBacktests = async () => {
setIsLoading(true);
setError(null);
try {
const data = await backtestApiV2.listBacktests();
setBacktests(data);
} catch (err) {
setError('Failed to load backtests');
console.error(err);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadBacktests();
}, []);
const handleCreateBacktest = async (config: Omit<Backtest, 'id' | 'createdAt' | 'updatedAt'>) => {
try {
const newBacktest = await backtestApiV2.createBacktest(config);
await loadBacktests();
setShowCreateDialog(false);
navigate(`/backtests/${newBacktest.id}`);
} catch (err) {
setError('Failed to create backtest');
console.error(err);
}
};
const columns: ColumnDef<Backtest>[] = [
{
accessorKey: 'name',
header: 'Name',
size: 200,
cell: ({ row }) => (
<div className="font-medium text-text-primary">
{row.original.name}
</div>
),
},
{
accessorKey: 'strategy',
header: 'Strategy',
size: 150,
cell: ({ row }) => (
<span className="capitalize text-text-primary">
{row.original.strategy}
</span>
),
},
{
accessorKey: 'symbols',
header: 'Symbols',
size: 200,
cell: ({ row }) => (
<div className="text-sm text-text-secondary">
{row.original.symbols.join(', ')}
</div>
),
},
{
accessorKey: 'dateRange',
header: 'Date Range',
size: 200,
cell: ({ row }) => (
<div className="text-sm text-text-secondary">
{new Date(row.original.startDate).toLocaleDateString()} - {new Date(row.original.endDate).toLocaleDateString()}
</div>
),
},
{
accessorKey: 'initialCapital',
header: 'Initial Capital',
size: 150,
cell: ({ row }) => (
<div className="text-sm text-text-primary font-mono">
${row.original.initialCapital.toLocaleString()}
</div>
),
},
{
accessorKey: 'createdAt',
header: 'Created',
size: 180,
cell: ({ row }) => (
<div className="text-sm text-text-secondary">
{new Date(row.original.createdAt).toLocaleString()}
</div>
),
},
];
return (
<div className="flex flex-col h-full space-y-6">
<div className="flex-shrink-0 flex justify-between items-center">
<div>
<h1 className="text-lg font-bold text-text-primary mb-2">Backtests</h1>
<p className="text-text-secondary text-sm">
Create and manage backtest configurations
</p>
</div>
<button
onClick={() => setShowCreateDialog(true)}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors flex items-center space-x-2"
>
<PlusIcon className="w-4 h-4" />
<span>New Backtest</span>
</button>
</div>
{error && (
<div className="bg-error/10 border border-error text-error px-4 py-3 rounded-lg text-sm">
{error}
</div>
)}
<div className="flex-1 min-h-0">
<DataTable
data={backtests}
columns={columns}
loading={isLoading}
onRowClick={(row) => navigate(`/backtests/${row.id}`)}
height={600}
/>
</div>
{showCreateDialog && (
<CreateBacktestDialog
onClose={() => setShowCreateDialog(false)}
onCreate={handleCreateBacktest}
/>
)}
</div>
);
}
import { PlusIcon } from '@heroicons/react/24/solid';
import type { ColumnDef } from '@tanstack/react-table';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { DataTable } from '@/components/ui/DataTable/DataTable';
import { browserLog } from '@/utils/browserLog';
import { CreateBacktestDialog } from './components/CreateBacktestDialog';
import { backtestApiV2, type Backtest } from './services/backtestApiV2';
export function BacktestListPageV2() {
const navigate = useNavigate();
const [backtests, setBacktests] = useState<Backtest[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [showCreateDialog, setShowCreateDialog] = useState(false);
const loadBacktests = async () => {
setIsLoading(true);
setError(null);
try {
const data = await backtestApiV2.listBacktests();
setBacktests(data);
} catch (err) {
setError('Failed to load backtests');
browserLog.error(err);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
loadBacktests();
}, []);
const handleCreateBacktest = async (config: Omit<Backtest, 'id' | 'createdAt' | 'updatedAt'>) => {
try {
const newBacktest = await backtestApiV2.createBacktest(config);
await loadBacktests();
setShowCreateDialog(false);
navigate(`/backtests/${newBacktest.id}`);
} catch (err) {
setError('Failed to create backtest');
browserLog.error(err);
}
};
const columns: ColumnDef<Backtest>[] = [
{
accessorKey: 'name',
header: 'Name',
size: 200,
cell: ({ row }) => <div className="font-medium text-text-primary">{row.original.name}</div>,
},
{
accessorKey: 'strategy',
header: 'Strategy',
size: 150,
cell: ({ row }) => (
<span className="capitalize text-text-primary">{row.original.strategy}</span>
),
},
{
accessorKey: 'symbols',
header: 'Symbols',
size: 200,
cell: ({ row }) => (
<div className="text-sm text-text-secondary">{row.original.symbols.join(', ')}</div>
),
},
{
accessorKey: 'dateRange',
header: 'Date Range',
size: 200,
cell: ({ row }) => (
<div className="text-sm text-text-secondary">
{new Date(row.original.startDate).toLocaleDateString()} -{' '}
{new Date(row.original.endDate).toLocaleDateString()}
</div>
),
},
{
accessorKey: 'initialCapital',
header: 'Initial Capital',
size: 150,
cell: ({ row }) => (
<div className="text-sm text-text-primary font-mono">
${row.original.initialCapital.toLocaleString()}
</div>
),
},
{
accessorKey: 'createdAt',
header: 'Created',
size: 180,
cell: ({ row }) => (
<div className="text-sm text-text-secondary">
{new Date(row.original.createdAt).toLocaleString()}
</div>
),
},
];
return (
<div className="flex flex-col h-full space-y-6">
<div className="flex-shrink-0 flex justify-between items-center">
<div>
<h1 className="text-lg font-bold text-text-primary mb-2">Backtests</h1>
<p className="text-text-secondary text-sm">Create and manage backtest configurations</p>
</div>
<button
onClick={() => setShowCreateDialog(true)}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors flex items-center space-x-2"
>
<PlusIcon className="w-4 h-4" />
<span>New Backtest</span>
</button>
</div>
{error && (
<div className="bg-error/10 border border-error text-error px-4 py-3 rounded-lg text-sm">
{error}
</div>
)}
<div className="flex-1 min-h-0">
<DataTable
data={backtests}
columns={columns}
loading={isLoading}
onRowClick={row => navigate(`/backtests/${row.id}`)}
height={600}
/>
</div>
{showCreateDialog && (
<CreateBacktestDialog
onClose={() => setShowCreateDialog(false)}
onCreate={handleCreateBacktest}
/>
)}
</div>
);
}

View file

@ -1,188 +1,220 @@
import type { BacktestResult } from '../types/backtest.types';
import { useState, useMemo, memo } from 'react';
import { Chart } from '../../../components/charts/Chart';
import { ChartContainer } from './ChartContainer';
interface ExtendedBacktestResult extends BacktestResult {
equity?: Array<{ date: string; value: number }>;
ohlcData?: Record<string, Array<{
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume?: number;
}>>;
runId?: 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 any).__lastDataHash !== dataHash) {
(window as any).__lastDataHash = dataHash;
console.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)
.map(e => ({
time: new Date(e.date).getTime() / 1000,
value: e.value
}))
: result.performanceData
?.filter(p => p && p.timestamp && p.portfolioValue != null)
.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) || [];
console.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.entryPrice != null;
const hasTime = extTrade.timestamp != null || extTrade.entryDate != null || extTrade.date != null;
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' : 'arrowDown') as const,
text: `${side === 'buy' ? 'Buy' : 'Sell'} @ $${price.toFixed(2)}`,
price: price
};
});
console.log('Trade markers:', tradeMarkers);
const processedOhlcData = ohlcData
.filter(d => d && d.timestamp != null && d.open != null && d.high != null && d.low != null && d.close != null)
.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>
);
});
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>
);
});

View file

@ -1,228 +1,258 @@
import { useState, memo } from 'react';
import { BacktestChart } from './BacktestChart';
import { ErrorBoundary } from '../../../components/ErrorBoundary';
import { CompactPerformanceMetrics } from './CompactPerformanceMetrics';
import { PositionsSummary } from './PositionsSummary';
interface BacktestPlaybackProps {
result: any | null;
isLoading: boolean;
}
export const BacktestPlayback = memo(function BacktestPlayback({ result, isLoading }: BacktestPlaybackProps) {
const [showPositions, setShowPositions] = useState(false);
if (isLoading) {
return (
<div className="h-full flex items-center justify-center">
<div className="text-text-secondary">Loading playback data...</div>
</div>
);
}
if (!result) {
return (
<div className="h-full flex items-center justify-center">
<div className="text-text-secondary">No data available</div>
</div>
);
}
// Get positions from the result
let openPositions: any[] = [];
let closedPositions: any[] = [];
if (result.positions) {
if (Array.isArray(result.positions)) {
result.positions.forEach((p: any) => {
if (p.quantity !== 0) {
openPositions.push(p);
} else if (p.realizedPnl !== 0) {
closedPositions.push(p);
}
});
} else if (typeof result.positions === 'object') {
// Convert positions object to array
Object.entries(result.positions).forEach(([symbol, position]: [string, any]) => {
const pos = { symbol, ...position };
if (position.quantity !== 0) {
openPositions.push(pos);
} else if (position.realizedPnl !== 0) {
closedPositions.push(pos);
}
});
}
}
return (
<div className="h-full flex flex-col gap-4">
{/* Chart Section */}
<div className="flex-1 min-h-0">
<ErrorBoundary
fallback={
<div className="h-full flex items-center justify-center bg-surface-secondary rounded-lg border border-border">
<div className="text-center p-4">
<p className="text-text-secondary mb-4">Chart failed to load</p>
<button
onClick={() => window.location.reload()}
className="text-primary-500 hover:text-primary-600 font-medium"
>
Reload Page
</button>
</div>
</div>
}
>
<BacktestChart
result={result}
isLoading={isLoading}
/>
</ErrorBoundary>
</div>
{/* Performance Metrics and Positions - Fixed height section */}
<div className="flex-shrink-0 grid grid-cols-1 lg:grid-cols-2 gap-4">
<CompactPerformanceMetrics result={result} isLoading={isLoading} />
<PositionsSummary
openPositions={openPositions}
closedPositions={closedPositions}
onExpand={() => setShowPositions(true)}
/>
</div>
{/* Detailed Positions View - Optional expanded view */}
{showPositions && (openPositions.length > 0 || closedPositions.length > 0) && (
<div className="flex-shrink-0">
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<div className="flex justify-between items-center mb-3">
<h3 className="text-sm font-medium text-text-primary">
All Positions
</h3>
<button
onClick={() => setShowPositions(!showPositions)}
className="text-xs text-text-secondary hover:text-text-primary"
>
Close
</button>
</div>
<div className="space-y-4">
{openPositions.length > 0 && (
<div>
<h4 className="text-sm font-medium text-text-secondary mb-2">Open Positions ({openPositions.length})</h4>
<div className="space-y-2">
<div className="grid grid-cols-6 gap-2 text-xs font-medium text-text-secondary pb-2 border-b border-border">
<div>Symbol</div>
<div>Side</div>
<div className="text-right">Quantity</div>
<div className="text-right">Entry Price</div>
<div className="text-right">Current Price</div>
<div className="text-right">P&L</div>
</div>
{openPositions.map((position, index) => {
const quantity = position.quantity || 0;
const avgPrice = position.averagePrice || position.avgPrice || 0;
const currentPrice = position.currentPrice || position.lastPrice || avgPrice;
const side = quantity > 0 ? 'long' : 'short';
const absQuantity = Math.abs(quantity);
const pnl = (currentPrice - avgPrice) * quantity;
const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0;
return (
<div key={index} className="grid grid-cols-6 gap-2 text-sm">
<div className="font-medium text-text-primary">{position.symbol}</div>
<div className={side === 'long' ? 'text-success' : 'text-error'}>
{side.toUpperCase()}
</div>
<div className="text-right text-text-primary">{absQuantity}</div>
<div className="text-right text-text-primary">
${avgPrice.toFixed(2)}
</div>
<div className="text-right text-text-primary">
${currentPrice.toFixed(2)}
</div>
<div className={`text-right font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}>
${pnl.toFixed(2)} ({pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(2)}%)
</div>
</div>
);
})}
</div>
</div>
)}
{closedPositions.length > 0 && (
<div>
<h4 className="text-sm font-medium text-text-secondary mb-2">Closed Positions ({closedPositions.length})</h4>
<div className="space-y-1">
{closedPositions.map((position, index) => (
<div key={index} className="flex items-center justify-between py-2 px-3 bg-surface rounded">
<div className="flex items-center space-x-3">
<span className="font-medium text-text-primary">{position.symbol}</span>
<span className="text-sm text-text-secondary">Closed</span>
</div>
<div className="text-right">
<div className={`text-sm font-medium ${position.realizedPnl >= 0 ? 'text-success' : 'text-error'}`}>
Realized P&L: ${position.realizedPnl.toFixed(2)}
</div>
</div>
</div>
))}
</div>
</div>
)}
<div className="pt-3 mt-3 border-t border-border grid grid-cols-3 gap-4 text-sm">
<div className="text-center">
<div className="text-text-secondary text-xs">Unrealized P&L</div>
<div className={`font-medium ${
openPositions.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + ((currentPrice - avgPrice) * quantity);
}, 0) >= 0 ? 'text-success' : 'text-error'
}`}>
${openPositions.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + ((currentPrice - avgPrice) * quantity);
}, 0).toFixed(2)}
</div>
</div>
<div className="text-center">
<div className="text-text-secondary text-xs">Realized P&L</div>
<div className={`font-medium ${
closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0) >= 0 ? 'text-success' : 'text-error'
}`}>
${closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0).toFixed(2)}
</div>
</div>
<div className="text-center">
<div className="text-text-secondary text-xs">Total P&L</div>
<div className={`font-medium ${
(openPositions.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + ((currentPrice - avgPrice) * quantity);
}, 0) + closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0)) >= 0 ? 'text-success' : 'text-error'
}`}>
${(openPositions.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + ((currentPrice - avgPrice) * quantity);
}, 0) + closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0)).toFixed(2)}
</div>
</div>
</div>
</div>
</div>
</div>
)}
</div>
);
});
import { memo, useState } from 'react';
import { ErrorBoundary } from '../../../components/ErrorBoundary';
import type { RunResult } from '../services/backtestApiV2';
import type { Position } from '../types/backtest.types';
import { BacktestChart } from './BacktestChart';
import { CompactPerformanceMetrics } from './CompactPerformanceMetrics';
import { PositionsSummary } from './PositionsSummary';
interface BacktestPlaybackProps {
result: RunResult | null;
isLoading: boolean;
}
export const BacktestPlayback = memo(function BacktestPlayback({
result,
isLoading,
}: BacktestPlaybackProps) {
const [showPositions, setShowPositions] = useState(false);
if (isLoading) {
return (
<div className="h-full flex items-center justify-center">
<div className="text-text-secondary">Loading playback data...</div>
</div>
);
}
if (!result) {
return (
<div className="h-full flex items-center justify-center">
<div className="text-text-secondary">No data available</div>
</div>
);
}
// Get positions from the result
const openPositions: Position[] = [];
const closedPositions: Position[] = [];
if (result.positions) {
if (Array.isArray(result.positions)) {
result.positions.forEach(p => {
if (p.quantity !== 0) {
openPositions.push(p);
} else if (p.realizedPnl !== 0) {
closedPositions.push(p);
}
});
} else if (typeof result.positions === 'object') {
// Convert positions object to array
Object.entries(result.positions).forEach(([symbol, position]) => {
const pos = { symbol, ...position };
if (position.quantity !== 0) {
openPositions.push(pos);
} else if (position.realizedPnl !== 0) {
closedPositions.push(pos);
}
});
}
}
return (
<div className="h-full flex flex-col gap-4">
{/* Chart Section */}
<div className="flex-1 min-h-0">
<ErrorBoundary
fallback={
<div className="h-full flex items-center justify-center bg-surface-secondary rounded-lg border border-border">
<div className="text-center p-4">
<p className="text-text-secondary mb-4">Chart failed to load</p>
<button
onClick={() => window.location.reload()}
className="text-primary-500 hover:text-primary-600 font-medium"
>
Reload Page
</button>
</div>
</div>
}
>
<BacktestChart result={result} isLoading={isLoading} />
</ErrorBoundary>
</div>
{/* Performance Metrics and Positions - Fixed height section */}
<div className="flex-shrink-0 grid grid-cols-1 lg:grid-cols-2 gap-4">
<CompactPerformanceMetrics result={result} isLoading={isLoading} />
<PositionsSummary
openPositions={openPositions}
closedPositions={closedPositions}
onExpand={() => setShowPositions(true)}
/>
</div>
{/* Detailed Positions View - Optional expanded view */}
{showPositions && (openPositions.length > 0 || closedPositions.length > 0) && (
<div className="flex-shrink-0">
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<div className="flex justify-between items-center mb-3">
<h3 className="text-sm font-medium text-text-primary">All Positions</h3>
<button
onClick={() => setShowPositions(!showPositions)}
className="text-xs text-text-secondary hover:text-text-primary"
>
Close
</button>
</div>
<div className="space-y-4">
{openPositions.length > 0 && (
<div>
<h4 className="text-sm font-medium text-text-secondary mb-2">
Open Positions ({openPositions.length})
</h4>
<div className="space-y-2">
<div className="grid grid-cols-6 gap-2 text-xs font-medium text-text-secondary pb-2 border-b border-border">
<div>Symbol</div>
<div>Side</div>
<div className="text-right">Quantity</div>
<div className="text-right">Entry Price</div>
<div className="text-right">Current Price</div>
<div className="text-right">P&L</div>
</div>
{openPositions.map((position, index) => {
const quantity = position.quantity || 0;
const avgPrice = position.averagePrice || position.avgPrice || 0;
const currentPrice = position.currentPrice || position.lastPrice || avgPrice;
const side = quantity > 0 ? 'long' : 'short';
const absQuantity = Math.abs(quantity);
const pnl = (currentPrice - avgPrice) * quantity;
const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0;
return (
<div key={index} className="grid grid-cols-6 gap-2 text-sm">
<div className="font-medium text-text-primary">{position.symbol}</div>
<div className={side === 'long' ? 'text-success' : 'text-error'}>
{side.toUpperCase()}
</div>
<div className="text-right text-text-primary">{absQuantity}</div>
<div className="text-right text-text-primary">${avgPrice.toFixed(2)}</div>
<div className="text-right text-text-primary">
${currentPrice.toFixed(2)}
</div>
<div
className={`text-right font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}
>
${pnl.toFixed(2)} ({pnlPercent >= 0 ? '+' : ''}
{pnlPercent.toFixed(2)}%)
</div>
</div>
);
})}
</div>
</div>
)}
{closedPositions.length > 0 && (
<div>
<h4 className="text-sm font-medium text-text-secondary mb-2">
Closed Positions ({closedPositions.length})
</h4>
<div className="space-y-1">
{closedPositions.map((position, index) => (
<div
key={index}
className="flex items-center justify-between py-2 px-3 bg-surface rounded"
>
<div className="flex items-center space-x-3">
<span className="font-medium text-text-primary">{position.symbol}</span>
<span className="text-sm text-text-secondary">Closed</span>
</div>
<div className="text-right">
<div
className={`text-sm font-medium ${position.realizedPnl >= 0 ? 'text-success' : 'text-error'}`}
>
Realized P&L: ${position.realizedPnl.toFixed(2)}
</div>
</div>
</div>
))}
</div>
</div>
)}
<div className="pt-3 mt-3 border-t border-border grid grid-cols-3 gap-4 text-sm">
<div className="text-center">
<div className="text-text-secondary text-xs">Unrealized P&L</div>
<div
className={`font-medium ${
openPositions.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + (currentPrice - avgPrice) * quantity;
}, 0) >= 0
? 'text-success'
: 'text-error'
}`}
>
$
{openPositions
.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + (currentPrice - avgPrice) * quantity;
}, 0)
.toFixed(2)}
</div>
</div>
<div className="text-center">
<div className="text-text-secondary text-xs">Realized P&L</div>
<div
className={`font-medium ${
closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0) >= 0
? 'text-success'
: 'text-error'
}`}
>
${closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0).toFixed(2)}
</div>
</div>
<div className="text-center">
<div className="text-text-secondary text-xs">Total P&L</div>
<div
className={`font-medium ${
openPositions.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + (currentPrice - avgPrice) * quantity;
}, 0) +
closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0) >=
0
? 'text-success'
: 'text-error'
}`}
>
$
{(
openPositions.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + (currentPrice - avgPrice) * quantity;
}, 0) + closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0)
).toFixed(2)}
</div>
</div>
</div>
</div>
</div>
</div>
)}
</div>
);
});

View file

@ -1,246 +1,251 @@
import type { BacktestResult } from '../types/backtest.types';
import { DataTable } from '@/components/ui/DataTable';
import type { ColumnDef } from '@tanstack/react-table';
interface BacktestTradesProps {
result: any | null;
isLoading: boolean;
}
export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
if (isLoading) {
return (
<div className="bg-surface-secondary rounded-lg border border-border p-4 animate-pulse">
<div className="space-y-3">
{[...Array(5)].map((_, i) => (
<div key={i} className="h-16 bg-surface rounded"></div>
))}
</div>
</div>
);
}
if (!result || !result.trades || result.trades.length === 0) {
return (
<div className="bg-surface-secondary rounded-lg border border-border p-8 text-center">
<p className="text-text-secondary">No trades executed in this backtest.</p>
</div>
);
}
// Add debug logging
console.log('Trades data:', result.trades);
const columns: ColumnDef<any>[] = [
{
accessorKey: 'symbol',
header: 'Symbol',
size: 100,
cell: ({ getValue }) => (
<span className="text-sm font-medium text-text-primary">{getValue() as string}</span>
),
},
{
id: 'side',
header: 'Side',
size: 80,
cell: ({ row }) => {
const trade = row.original;
const side = trade.side || (trade.quantity > 0 ? 'buy' : 'sell');
return (
<span className={`inline-flex px-2 py-1 text-xs font-medium rounded-md ${
side === 'buy'
? 'bg-success/10 text-success'
: 'bg-error/10 text-error'
}`}>
{side.toUpperCase()}
</span>
);
},
},
{
id: 'date',
header: 'Date',
size: 180,
cell: ({ row }) => {
const trade = row.original;
const date = trade.timestamp || trade.entryDate || trade.date;
return (
<span className="text-sm text-text-secondary">
{date ? new Date(date).toLocaleString() : '-'}
</span>
);
},
},
{
id: 'price',
header: 'Price',
size: 100,
cell: ({ row }) => {
const trade = row.original;
const price = trade.price || trade.entryPrice;
return (
<span className="text-sm text-text-primary">
${price != null ? price.toFixed(2) : '0.00'}
</span>
);
},
},
{
accessorKey: 'quantity',
header: 'Quantity',
size: 80,
cell: ({ getValue }) => {
const qty = Math.abs(getValue() as number || 0);
return <span className="text-sm text-text-primary">{qty}</span>;
},
},
{
accessorKey: 'commission',
header: 'Commission',
size: 100,
cell: ({ getValue }) => {
const commission = getValue() as number || 0;
return (
<span className="text-sm text-text-secondary">
${commission.toFixed(2)}
</span>
);
},
},
{
id: 'pnl',
header: 'P&L',
size: 100,
cell: ({ row }) => {
const trade = row.original;
const pnl = trade.pnl || trade.realizedPnl || 0;
return (
<span className={`text-sm font-medium ${
pnl >= 0 ? 'text-success' : 'text-error'
}`}>
${pnl.toFixed(2)}
</span>
);
},
},
];
// Calculate trade statistics
const tradeStats = result.trades.reduce((stats: any, trade: any) => {
const pnl = trade.pnl || trade.realizedPnl || 0;
if (pnl > 0) {
stats.wins++;
stats.totalWin += pnl;
} else if (pnl < 0) {
stats.losses++;
stats.totalLoss += Math.abs(pnl);
}
stats.totalPnL += pnl;
return stats;
}, { wins: 0, losses: 0, totalWin: 0, totalLoss: 0, totalPnL: 0 });
const winRate = result.trades.length > 0 ? (tradeStats.wins / result.trades.length) * 100 : 0;
return (
<div>
<div className="mb-4 grid grid-cols-1 md:grid-cols-5 gap-4">
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Total Trades</p>
<p className="text-lg font-medium text-text-primary">{result.trades.length}</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Win Rate</p>
<p className="text-lg font-medium text-text-primary">{winRate.toFixed(1)}%</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Wins</p>
<p className="text-lg font-medium text-success">{tradeStats.wins}</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Losses</p>
<p className="text-lg font-medium text-error">{tradeStats.losses}</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Total P&L</p>
<p className={`text-lg font-medium ${tradeStats.totalPnL >= 0 ? 'text-success' : 'text-error'}`}>
${tradeStats.totalPnL.toFixed(2)}
</p>
</div>
</div>
<DataTable
data={result.trades}
columns={columns}
className="bg-surface-secondary rounded-lg border border-border"
height={400}
/>
{result.positions && Object.keys(result.positions).length > 0 && (() => {
const positionsArray = Object.entries(result.positions).map(([symbol, position]) => ({
symbol,
...position
}));
const positionColumns: ColumnDef<typeof positionsArray[0]>[] = [
{
accessorKey: 'symbol',
header: 'Symbol',
size: 100,
cell: ({ getValue }) => (
<span className="text-sm font-medium text-text-primary">{getValue() as string}</span>
),
},
{
accessorKey: 'quantity',
header: 'Quantity',
size: 100,
cell: ({ getValue }) => (
<span className="text-sm text-text-primary">{getValue() as number || 0}</span>
),
},
{
accessorKey: 'averagePrice',
header: 'Avg Price',
size: 120,
cell: ({ getValue }) => {
const price = getValue() as number;
return (
<span className="text-sm text-text-primary">
${price != null ? price.toFixed(2) : '0.00'}
</span>
);
},
},
{
accessorKey: 'unrealizedPnl',
header: 'Unrealized P&L',
size: 150,
cell: ({ getValue }) => {
const pnl = getValue() as number || 0;
return (
<span className={`text-sm font-medium ${
pnl >= 0 ? 'text-success' : 'text-error'
}`}>
${pnl != null ? pnl.toFixed(2) : '0.00'}
</span>
);
},
},
];
return (
<div className="mt-6">
<h4 className="text-base font-medium text-text-primary mb-3">Open Positions</h4>
<DataTable
data={positionsArray}
columns={positionColumns}
className="bg-surface-secondary rounded-lg border border-border"
height={200}
/>
</div>
);
})()}
</div>
);
}
import type { ColumnDef } from '@tanstack/react-table';
import { DataTable } from '@/components/ui/DataTable';
import { browserLog } from '@/utils/browserLog';
import type { RunResult } from '../services/backtestApiV2';
import type { Trade } from '../types/backtest.types';
interface BacktestTradesProps {
result: RunResult | null;
isLoading: boolean;
}
export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
if (isLoading) {
return (
<div className="bg-surface-secondary rounded-lg border border-border p-4 animate-pulse">
<div className="space-y-3">
{[...Array(5)].map((_, i) => (
<div key={i} className="h-16 bg-surface rounded"></div>
))}
</div>
</div>
);
}
if (!result || !result.trades || result.trades.length === 0) {
return (
<div className="bg-surface-secondary rounded-lg border border-border p-8 text-center">
<p className="text-text-secondary">No trades executed in this backtest.</p>
</div>
);
}
// Add debug logging
browserLog.log('Trades data:', result.trades);
const columns: ColumnDef<Trade>[] = [
{
accessorKey: 'symbol',
header: 'Symbol',
size: 100,
cell: ({ getValue }) => (
<span className="text-sm font-medium text-text-primary">{getValue() as string}</span>
),
},
{
id: 'side',
header: 'Side',
size: 80,
cell: ({ row }) => {
const trade = row.original;
const side = trade.side || (trade.quantity > 0 ? 'buy' : 'sell');
return (
<span
className={`inline-flex px-2 py-1 text-xs font-medium rounded-md ${
side === 'buy' ? 'bg-success/10 text-success' : 'bg-error/10 text-error'
}`}
>
{side.toUpperCase()}
</span>
);
},
},
{
id: 'date',
header: 'Date',
size: 180,
cell: ({ row }) => {
const trade = row.original;
const date = trade.timestamp || trade.entryDate || trade.date;
return (
<span className="text-sm text-text-secondary">
{date ? new Date(date).toLocaleString() : '-'}
</span>
);
},
},
{
id: 'price',
header: 'Price',
size: 100,
cell: ({ row }) => {
const trade = row.original;
const price = trade.price || trade.entryPrice;
return (
<span className="text-sm text-text-primary">
${price !== null && price !== undefined ? price.toFixed(2) : '0.00'}
</span>
);
},
},
{
accessorKey: 'quantity',
header: 'Quantity',
size: 80,
cell: ({ getValue }) => {
const qty = Math.abs((getValue() as number) || 0);
return <span className="text-sm text-text-primary">{qty}</span>;
},
},
{
accessorKey: 'commission',
header: 'Commission',
size: 100,
cell: ({ getValue }) => {
const commission = (getValue() as number) || 0;
return <span className="text-sm text-text-secondary">${commission.toFixed(2)}</span>;
},
},
{
id: 'pnl',
header: 'P&L',
size: 100,
cell: ({ row }) => {
const trade = row.original;
const pnl = trade.pnl || trade.realizedPnl || 0;
return (
<span className={`text-sm font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}>
${pnl.toFixed(2)}
</span>
);
},
},
];
// Calculate trade statistics
const tradeStats = result.trades.reduce(
(stats, trade) => {
const pnl = trade.pnl || trade.realizedPnl || 0;
if (pnl > 0) {
stats.wins++;
stats.totalWin += pnl;
} else if (pnl < 0) {
stats.losses++;
stats.totalLoss += Math.abs(pnl);
}
stats.totalPnL += pnl;
return stats;
},
{ wins: 0, losses: 0, totalWin: 0, totalLoss: 0, totalPnL: 0 }
);
const winRate = result.trades.length > 0 ? (tradeStats.wins / result.trades.length) * 100 : 0;
return (
<div>
<div className="mb-4 grid grid-cols-1 md:grid-cols-5 gap-4">
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Total Trades</p>
<p className="text-lg font-medium text-text-primary">{result.trades.length}</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Win Rate</p>
<p className="text-lg font-medium text-text-primary">{winRate.toFixed(1)}%</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Wins</p>
<p className="text-lg font-medium text-success">{tradeStats.wins}</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Losses</p>
<p className="text-lg font-medium text-error">{tradeStats.losses}</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Total P&L</p>
<p
className={`text-lg font-medium ${tradeStats.totalPnL >= 0 ? 'text-success' : 'text-error'}`}
>
${tradeStats.totalPnL.toFixed(2)}
</p>
</div>
</div>
<DataTable
data={result.trades}
columns={columns}
className="bg-surface-secondary rounded-lg border border-border"
height={400}
/>
{result.positions &&
Object.keys(result.positions).length > 0 &&
(() => {
const positionsArray = Object.entries(result.positions).map(([symbol, position]) => ({
symbol,
...position,
}));
const positionColumns: ColumnDef<(typeof positionsArray)[0]>[] = [
{
accessorKey: 'symbol',
header: 'Symbol',
size: 100,
cell: ({ getValue }) => (
<span className="text-sm font-medium text-text-primary">
{getValue() as string}
</span>
),
},
{
accessorKey: 'quantity',
header: 'Quantity',
size: 100,
cell: ({ getValue }) => (
<span className="text-sm text-text-primary">{(getValue() as number) || 0}</span>
),
},
{
accessorKey: 'averagePrice',
header: 'Avg Price',
size: 120,
cell: ({ getValue }) => {
const price = getValue() as number;
return (
<span className="text-sm text-text-primary">
${price !== null && price !== undefined ? price.toFixed(2) : '0.00'}
</span>
);
},
},
{
accessorKey: 'unrealizedPnl',
header: 'Unrealized P&L',
size: 150,
cell: ({ getValue }) => {
const pnl = (getValue() as number) || 0;
return (
<span
className={`text-sm font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}
>
${pnl !== null && pnl !== undefined ? pnl.toFixed(2) : '0.00'}
</span>
);
},
},
];
return (
<div className="mt-6">
<h4 className="text-base font-medium text-text-primary mb-3">Open Positions</h4>
<DataTable
data={positionsArray}
columns={positionColumns}
className="bg-surface-secondary rounded-lg border border-border"
height={200}
/>
</div>
);
})()}
</div>
);
}

View file

@ -1,42 +1,44 @@
import { useRef, useEffect, useState, ReactNode } from 'react';
interface ChartContainerProps {
children: (height: number) => ReactNode;
className?: string;
}
export function ChartContainer({ children, className = '' }: ChartContainerProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(500); // Default height
useEffect(() => {
if (!containerRef.current) return;
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const { height } = entry.contentRect;
if (height > 0) {
setHeight(Math.floor(height));
}
}
});
resizeObserver.observe(containerRef.current);
// Initial measurement
const initialHeight = containerRef.current.clientHeight;
if (initialHeight > 0) {
setHeight(initialHeight);
}
return () => {
resizeObserver.disconnect();
};
}, []);
return (
<div ref={containerRef} className={`h-full w-full ${className}`}>
{children(height)}
</div>
);
}
import { useEffect, useRef, useState, type ReactNode } from 'react';
interface ChartContainerProps {
children: (height: number) => ReactNode;
className?: string;
}
export function ChartContainer({ children, className = '' }: ChartContainerProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(500); // Default height
useEffect(() => {
if (!containerRef.current) {
return;
}
const resizeObserver = new ResizeObserver(entries => {
for (const entry of entries) {
const { height } = entry.contentRect;
if (height > 0) {
setHeight(Math.floor(height));
}
}
});
resizeObserver.observe(containerRef.current);
// Initial measurement
const initialHeight = containerRef.current.clientHeight;
if (initialHeight > 0) {
setHeight(initialHeight);
}
return () => {
resizeObserver.disconnect();
};
}, []);
return (
<div ref={containerRef} className={`h-full w-full ${className}`}>
{children(height)}
</div>
);
}

View file

@ -1,297 +1,350 @@
import type { BacktestResult } from '../types/backtest.types';
interface ExtendedMetrics {
// Core metrics
totalReturn?: number;
sharpeRatio?: number;
maxDrawdown?: number;
winRate?: number;
totalProfit?: number;
profitFactor?: number;
totalTrades?: number;
avgWin?: number;
avgLoss?: number;
expectancy?: number;
sortinoRatio?: number;
calmarRatio?: number;
profitableTrades?: number;
// Extended metrics from orchestrator
annualizedReturn?: number;
volatility?: number;
avgHoldingPeriod?: number;
maxConsecutiveLosses?: number;
maxConsecutiveWins?: number;
payoffRatio?: number;
largestWin?: number;
largestLoss?: number;
avgWinLoss?: number;
skewness?: number;
kurtosis?: number;
tailRatio?: number;
kellyFraction?: number;
informationRatio?: number;
avgTradesPerDay?: number;
}
interface CompactPerformanceMetricsProps {
result: any | null;
isLoading: boolean;
}
export function CompactPerformanceMetrics({ result, isLoading }: CompactPerformanceMetricsProps) {
if (isLoading || !result) {
return null;
}
const metrics = result.metrics as ExtendedMetrics;
const analytics = result.analytics || {};
// Merge metrics from both sources
const allMetrics = {
...metrics,
...analytics,
// Override with metrics values if they exist
...metrics
};
// Calculate totalProfit if not provided
const totalProfit = allMetrics.totalProfit ??
(allMetrics.totalReturn && result.config?.initialCapital ?
allMetrics.totalReturn * result.config.initialCapital :
undefined);
const formatValue = (value: number | undefined, format: 'percent' | 'number' | 'currency', decimals = 2) => {
if (value === undefined || value === null) return '-';
switch (format) {
case 'percent':
return `${(value * 100).toFixed(decimals)}%`;
case 'currency':
const prefix = value < 0 ? '-$' : '$';
return `${prefix}${Math.abs(value).toFixed(decimals)}`;
case 'number':
return value.toFixed(decimals);
}
};
const getColorClass = (value: number | undefined, thresholds: { good: number; warning?: number }) => {
if (value === undefined || value === null) return 'text-text-secondary';
if (thresholds.warning !== undefined) {
if (value >= thresholds.good) return 'text-success';
if (value >= thresholds.warning) return 'text-warning';
return 'text-error';
}
return value >= thresholds.good ? 'text-success' : 'text-error';
};
return (
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<h3 className="text-sm font-medium text-text-primary mb-3">Performance Analytics</h3>
<div className="grid grid-cols-3 gap-3">
{/* Column 1 - Return Metrics */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Total Return</span>
<span className={`text-sm font-medium ${getColorClass(allMetrics.totalReturn, { good: 0 })}`}>
{formatValue(allMetrics.totalReturn, 'percent')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Sharpe Ratio</span>
<span className={`text-sm font-medium ${getColorClass(allMetrics.sharpeRatio, { good: 1, warning: 0 })}`}>
{formatValue(allMetrics.sharpeRatio, 'number')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Max Drawdown</span>
<span className={`text-sm font-medium ${getColorClass(allMetrics.maxDrawdown, { good: -0.1, warning: -0.2 })}`}>
{formatValue(allMetrics.maxDrawdown, 'percent')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Win Rate</span>
<span className={`text-sm font-medium ${getColorClass(allMetrics.winRate, { good: 0.5 })}`}>
{formatValue(allMetrics.winRate, 'percent', 1)}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Total Profit</span>
<span className={`text-sm font-medium ${getColorClass(totalProfit, { good: 0 })}`}>
{formatValue(totalProfit, 'currency')}
</span>
</div>
</div>
{/* Column 2 - Risk Metrics */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Profit Factor</span>
<span className={`text-sm font-medium ${getColorClass(allMetrics.profitFactor, { good: 1.5, warning: 1 })}`}>
{formatValue(allMetrics.profitFactor, 'number')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Total Trades</span>
<span className="text-sm font-medium text-text-primary">
{allMetrics.totalTrades ?? '-'}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Avg Win/Loss</span>
<span className="text-sm font-medium text-text-primary">
<span className="text-success">{formatValue(allMetrics.avgWin, 'currency')}</span>
<span className="text-text-secondary mx-1">/</span>
<span className="text-error">{formatValue(allMetrics.avgLoss, 'currency')}</span>
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Expectancy</span>
<span className={`text-sm font-medium ${getColorClass(allMetrics.expectancy, { good: 0 })}`}>
{formatValue(allMetrics.expectancy, 'currency')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Sortino Ratio</span>
<span className={`text-sm font-medium ${getColorClass(allMetrics.sortinoRatio, { good: 1, warning: 0 })}`}>
{formatValue(allMetrics.sortinoRatio, 'number')}
</span>
</div>
</div>
{/* Column 3 - Additional Metrics */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Annual Return</span>
<span className={`text-sm font-medium ${getColorClass(allMetrics.annualizedReturn, { good: 0.1, warning: 0 })}`}>
{formatValue(allMetrics.annualizedReturn, 'percent')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Volatility</span>
<span className={`text-sm font-medium ${getColorClass(-(allMetrics.volatility ?? 0), { good: -15, warning: -25 })}`}>
{formatValue(allMetrics.volatility ? allMetrics.volatility / 100 : undefined, 'percent', 1)}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Avg Holding</span>
<span className="text-sm font-medium text-text-primary">
{allMetrics.avgHoldingPeriod ? `${(allMetrics.avgHoldingPeriod / 60).toFixed(1)}h` : '-'}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Max Consec Loss</span>
<span className={`text-sm font-medium ${allMetrics.maxConsecutiveLosses > 5 ? 'text-error' : 'text-text-primary'}`}>
{allMetrics.maxConsecutiveLosses ?? '-'}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Payoff Ratio</span>
<span className={`text-sm font-medium ${getColorClass(allMetrics.payoffRatio, { good: 1.5, warning: 1 })}`}>
{formatValue(allMetrics.payoffRatio, 'number')}
</span>
</div>
</div>
</div>
{/* Advanced Metrics - Show only if available */}
{(allMetrics.skewness !== undefined || allMetrics.kurtosis !== undefined ||
allMetrics.informationRatio !== undefined || allMetrics.kellyFraction !== undefined) && (
<div className="mt-2 pt-2 border-t border-border">
<div className="grid grid-cols-4 gap-2 text-xs">
{allMetrics.informationRatio !== undefined && (
<div className="text-center">
<span className="text-text-secondary">Info Ratio</span>
<div className={`font-medium ${getColorClass(allMetrics.informationRatio, { good: 0.5, warning: 0 })}`}>
{formatValue(allMetrics.informationRatio, 'number')}
</div>
</div>
)}
{allMetrics.skewness !== undefined && (
<div className="text-center">
<span className="text-text-secondary">Skewness</span>
<div className={`font-medium ${getColorClass(allMetrics.skewness, { good: 0 })}`}>
{formatValue(allMetrics.skewness, 'number')}
</div>
</div>
)}
{allMetrics.kurtosis !== undefined && (
<div className="text-center">
<span className="text-text-secondary">Kurtosis</span>
<div className="font-medium text-text-primary">
{formatValue(allMetrics.kurtosis, 'number')}
</div>
</div>
)}
{allMetrics.kellyFraction !== undefined && (
<div className="text-center">
<span className="text-text-secondary">Kelly %</span>
<div className="font-medium text-text-primary">
{formatValue(allMetrics.kellyFraction, 'percent')}
</div>
</div>
)}
</div>
</div>
)}
{/* Additional Metrics Row */}
<div className="mt-2 pt-2 border-t border-border">
<div className="grid grid-cols-5 gap-2 text-xs">
<div className="text-center">
<span className="text-text-secondary">Calmar</span>
<div className={`font-medium ${getColorClass(allMetrics.calmarRatio, { good: 1, warning: 0.5 })}`}>
{formatValue(allMetrics.calmarRatio, 'number')}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Profitable</span>
<div className="font-medium text-text-primary">
{allMetrics.profitableTrades ?? '-'}/{allMetrics.totalTrades ?? '-'}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Exposure</span>
<div className="font-medium text-text-primary">
{result.analytics?.exposureTime ? formatValue(result.analytics.exposureTime, 'percent', 1) : '-'}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Largest Win</span>
<div className={`font-medium text-success`}>
{formatValue(allMetrics.largestWin, 'currency')}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Largest Loss</span>
<div className={`font-medium text-error`}>
{formatValue(allMetrics.largestLoss, 'currency')}
</div>
</div>
</div>
</div>
</div>
);
}
import type { RunResult } from '../services/backtestApiV2';
interface ExtendedMetrics {
// Core metrics
totalReturn?: number;
sharpeRatio?: number;
maxDrawdown?: number;
winRate?: number;
totalProfit?: number;
profitFactor?: number;
totalTrades?: number;
avgWin?: number;
avgLoss?: number;
expectancy?: number;
sortinoRatio?: number;
calmarRatio?: number;
profitableTrades?: number;
// Extended metrics from orchestrator
annualizedReturn?: number;
volatility?: number;
avgHoldingPeriod?: number;
maxConsecutiveLosses?: number;
maxConsecutiveWins?: number;
payoffRatio?: number;
largestWin?: number;
largestLoss?: number;
avgWinLoss?: number;
skewness?: number;
kurtosis?: number;
tailRatio?: number;
kellyFraction?: number;
informationRatio?: number;
avgTradesPerDay?: number;
}
interface CompactPerformanceMetricsProps {
result: RunResult | null;
isLoading: boolean;
}
export function CompactPerformanceMetrics({ result, isLoading }: CompactPerformanceMetricsProps) {
if (isLoading || !result) {
return null;
}
const metrics = result.metrics as ExtendedMetrics;
const analytics = result.analytics || {};
// Merge metrics from both sources
const allMetrics = {
...metrics,
...analytics,
// Override with metrics values if they exist
...metrics,
};
// Calculate totalProfit if not provided
const totalProfit =
allMetrics.totalProfit ??
(allMetrics.totalReturn && result.config?.initialCapital
? allMetrics.totalReturn * result.config.initialCapital
: undefined);
const formatValue = (
value: number | undefined,
format: 'percent' | 'number' | 'currency',
decimals = 2
) => {
if (value === undefined || value === null) {
return '-';
}
switch (format) {
case 'percent':
return `${(value * 100).toFixed(decimals)}%`;
case 'currency': {
const prefix = value < 0 ? '-$' : '$';
return `${prefix}${Math.abs(value).toFixed(decimals)}`;
}
case 'number':
return value.toFixed(decimals);
}
};
const getColorClass = (
value: number | undefined,
thresholds: { good: number; warning?: number }
) => {
if (value === undefined || value === null) {
return 'text-text-secondary';
}
if (thresholds.warning !== undefined) {
if (value >= thresholds.good) {
return 'text-success';
}
if (value >= thresholds.warning) {
return 'text-warning';
}
return 'text-error';
}
return value >= thresholds.good ? 'text-success' : 'text-error';
};
return (
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<h3 className="text-sm font-medium text-text-primary mb-3">Performance Analytics</h3>
<div className="grid grid-cols-3 gap-3">
{/* Column 1 - Return Metrics */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Total Return</span>
<span
className={`text-sm font-medium ${getColorClass(allMetrics.totalReturn, { good: 0 })}`}
>
{formatValue(allMetrics.totalReturn, 'percent')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Sharpe Ratio</span>
<span
className={`text-sm font-medium ${getColorClass(allMetrics.sharpeRatio, { good: 1, warning: 0 })}`}
>
{formatValue(allMetrics.sharpeRatio, 'number')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Max Drawdown</span>
<span
className={`text-sm font-medium ${getColorClass(allMetrics.maxDrawdown, { good: -0.1, warning: -0.2 })}`}
>
{formatValue(allMetrics.maxDrawdown, 'percent')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Win Rate</span>
<span
className={`text-sm font-medium ${getColorClass(allMetrics.winRate, { good: 0.5 })}`}
>
{formatValue(allMetrics.winRate, 'percent', 1)}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Total Profit</span>
<span className={`text-sm font-medium ${getColorClass(totalProfit, { good: 0 })}`}>
{formatValue(totalProfit, 'currency')}
</span>
</div>
</div>
{/* Column 2 - Risk Metrics */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Profit Factor</span>
<span
className={`text-sm font-medium ${getColorClass(allMetrics.profitFactor, { good: 1.5, warning: 1 })}`}
>
{formatValue(allMetrics.profitFactor, 'number')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Total Trades</span>
<span className="text-sm font-medium text-text-primary">
{allMetrics.totalTrades ?? '-'}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Avg Win/Loss</span>
<span className="text-sm font-medium text-text-primary">
<span className="text-success">{formatValue(allMetrics.avgWin, 'currency')}</span>
<span className="text-text-secondary mx-1">/</span>
<span className="text-error">{formatValue(allMetrics.avgLoss, 'currency')}</span>
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Expectancy</span>
<span
className={`text-sm font-medium ${getColorClass(allMetrics.expectancy, { good: 0 })}`}
>
{formatValue(allMetrics.expectancy, 'currency')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Sortino Ratio</span>
<span
className={`text-sm font-medium ${getColorClass(allMetrics.sortinoRatio, { good: 1, warning: 0 })}`}
>
{formatValue(allMetrics.sortinoRatio, 'number')}
</span>
</div>
</div>
{/* Column 3 - Additional Metrics */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Annual Return</span>
<span
className={`text-sm font-medium ${getColorClass(allMetrics.annualizedReturn, { good: 0.1, warning: 0 })}`}
>
{formatValue(allMetrics.annualizedReturn, 'percent')}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Volatility</span>
<span
className={`text-sm font-medium ${getColorClass(-(allMetrics.volatility ?? 0), { good: -15, warning: -25 })}`}
>
{formatValue(
allMetrics.volatility ? allMetrics.volatility / 100 : undefined,
'percent',
1
)}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Avg Holding</span>
<span className="text-sm font-medium text-text-primary">
{allMetrics.avgHoldingPeriod
? `${(allMetrics.avgHoldingPeriod / 60).toFixed(1)}h`
: '-'}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Max Consec Loss</span>
<span
className={`text-sm font-medium ${(allMetrics.maxConsecutiveLosses ?? 0) > 5 ? 'text-error' : 'text-text-primary'}`}
>
{allMetrics.maxConsecutiveLosses ?? '-'}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-xs text-text-secondary">Payoff Ratio</span>
<span
className={`text-sm font-medium ${getColorClass(allMetrics.payoffRatio, { good: 1.5, warning: 1 })}`}
>
{formatValue(allMetrics.payoffRatio, 'number')}
</span>
</div>
</div>
</div>
{/* Advanced Metrics - Show only if available */}
{(allMetrics.skewness !== undefined ||
allMetrics.kurtosis !== undefined ||
allMetrics.informationRatio !== undefined ||
allMetrics.kellyFraction !== undefined) && (
<div className="mt-2 pt-2 border-t border-border">
<div className="grid grid-cols-4 gap-2 text-xs">
{allMetrics.informationRatio !== undefined && (
<div className="text-center">
<span className="text-text-secondary">Info Ratio</span>
<div
className={`font-medium ${getColorClass(allMetrics.informationRatio, { good: 0.5, warning: 0 })}`}
>
{formatValue(allMetrics.informationRatio, 'number')}
</div>
</div>
)}
{allMetrics.skewness !== undefined && (
<div className="text-center">
<span className="text-text-secondary">Skewness</span>
<div className={`font-medium ${getColorClass(allMetrics.skewness, { good: 0 })}`}>
{formatValue(allMetrics.skewness, 'number')}
</div>
</div>
)}
{allMetrics.kurtosis !== undefined && (
<div className="text-center">
<span className="text-text-secondary">Kurtosis</span>
<div className="font-medium text-text-primary">
{formatValue(allMetrics.kurtosis, 'number')}
</div>
</div>
)}
{allMetrics.kellyFraction !== undefined && (
<div className="text-center">
<span className="text-text-secondary">Kelly %</span>
<div className="font-medium text-text-primary">
{formatValue(allMetrics.kellyFraction, 'percent')}
</div>
</div>
)}
</div>
</div>
)}
{/* Additional Metrics Row */}
<div className="mt-2 pt-2 border-t border-border">
<div className="grid grid-cols-5 gap-2 text-xs">
<div className="text-center">
<span className="text-text-secondary">Calmar</span>
<div
className={`font-medium ${getColorClass(allMetrics.calmarRatio, { good: 1, warning: 0.5 })}`}
>
{formatValue(allMetrics.calmarRatio, 'number')}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Profitable</span>
<div className="font-medium text-text-primary">
{allMetrics.profitableTrades ?? '-'}/{allMetrics.totalTrades ?? '-'}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Exposure</span>
<div className="font-medium text-text-primary">
{result.analytics?.exposureTime
? formatValue(result.analytics.exposureTime, 'percent', 1)
: '-'}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Largest Win</span>
<div className={`font-medium text-success`}>
{formatValue(allMetrics.largestWin, 'currency')}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Largest Loss</span>
<div className={`font-medium text-error`}>
{formatValue(allMetrics.largestLoss, 'currency')}
</div>
</div>
</div>
</div>
</div>
);
}

View file

@ -1,228 +1,228 @@
import { useState } from 'react';
import { XMarkIcon } from '@heroicons/react/24/solid';
import type { Backtest } from '../services/backtestApiV2';
interface CreateBacktestDialogProps {
onClose: () => void;
onCreate: (config: Omit<Backtest, 'id' | 'createdAt' | 'updatedAt'>) => void;
}
export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialogProps) {
const [formData, setFormData] = useState({
name: '',
strategy: 'moving-average',
symbols: ['AAPL'],
startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
endDate: new Date().toISOString().split('T')[0],
initialCapital: 100000,
commission: 0,
slippage: 0,
});
const [symbolInput, setSymbolInput] = useState('');
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!formData.name.trim()) {
alert('Please enter a backtest name');
return;
}
onCreate({
...formData,
metadata: {},
});
};
const addSymbol = () => {
const symbol = symbolInput.trim().toUpperCase();
if (symbol && !formData.symbols.includes(symbol)) {
setFormData({ ...formData, symbols: [...formData.symbols, symbol] });
setSymbolInput('');
}
};
const removeSymbol = (symbol: string) => {
setFormData({
...formData,
symbols: formData.symbols.filter(s => s !== symbol),
});
};
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-surface-secondary rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-center mb-6">
<h2 className="text-lg font-bold text-text-primary">Create New Backtest</h2>
<button
onClick={onClose}
className="p-1 hover:bg-surface-tertiary rounded transition-colors"
>
<XMarkIcon className="w-5 h-5 text-text-secondary" />
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Backtest Name
</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
placeholder="My Strategy Backtest"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Strategy
</label>
<select
value={formData.strategy}
onChange={(e) => setFormData({ ...formData, strategy: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
>
<option value="moving-average">Moving Average</option>
<option value="momentum">Momentum</option>
<option value="mean-reversion">Mean Reversion</option>
<option value="pairs-trading">Pairs Trading</option>
<option value="custom">Custom</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Symbols
</label>
<div className="flex gap-2 mb-2">
<input
type="text"
value={symbolInput}
onChange={(e) => setSymbolInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addSymbol())}
className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
placeholder="Enter symbol (e.g., AAPL)"
/>
<button
type="button"
onClick={addSymbol}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
Add
</button>
</div>
<div className="flex flex-wrap gap-2">
{formData.symbols.map(symbol => (
<span
key={symbol}
className="inline-flex items-center gap-1 px-3 py-1 bg-background border border-border rounded-full text-sm text-text-primary"
>
{symbol}
<button
type="button"
onClick={() => removeSymbol(symbol)}
className="hover:text-error transition-colors"
>
<XMarkIcon className="w-4 h-4" />
</button>
</span>
))}
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Start Date
</label>
<input
type="date"
value={formData.startDate}
onChange={(e) => setFormData({ ...formData, startDate: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
End Date
</label>
<input
type="date"
value={formData.endDate}
onChange={(e) => setFormData({ ...formData, endDate: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
required
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Initial Capital
</label>
<input
type="number"
value={formData.initialCapital}
onChange={(e) => setFormData({ ...formData, initialCapital: parseFloat(e.target.value) || 0 })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
min="0"
step="1000"
required
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Commission (per trade)
</label>
<input
type="number"
value={formData.commission}
onChange={(e) => setFormData({ ...formData, commission: parseFloat(e.target.value) || 0 })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
min="0"
step="0.01"
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Slippage (%)
</label>
<input
type="number"
value={formData.slippage}
onChange={(e) => setFormData({ ...formData, slippage: parseFloat(e.target.value) || 0 })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
min="0"
step="0.01"
/>
</div>
</div>
<div className="flex justify-end gap-3 pt-4">
<button
type="button"
onClick={onClose}
className="px-4 py-2 border border-border text-text-secondary rounded-md text-sm font-medium hover:bg-surface-tertiary transition-colors"
>
Cancel
</button>
<button
type="submit"
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
Create Backtest
</button>
</div>
</form>
</div>
</div>
);
}
import { XMarkIcon } from '@heroicons/react/24/solid';
import { useState } from 'react';
import type { Backtest } from '../services/backtestApiV2';
interface CreateBacktestDialogProps {
onClose: () => void;
onCreate: (config: Omit<Backtest, 'id' | 'createdAt' | 'updatedAt'>) => void;
}
export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialogProps) {
const [formData, setFormData] = useState({
name: '',
strategy: 'moving-average',
symbols: ['AAPL'],
startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10),
endDate: new Date().toISOString().slice(0, 10),
initialCapital: 100000,
commission: 0,
slippage: 0,
});
const [symbolInput, setSymbolInput] = useState('');
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!formData.name.trim()) {
alert('Please enter a backtest name');
return;
}
onCreate({
...formData,
config: { commission: formData.commission, slippage: formData.slippage },
});
};
const addSymbol = () => {
const symbol = symbolInput.trim().toUpperCase();
if (symbol && !formData.symbols.includes(symbol)) {
setFormData({ ...formData, symbols: [...formData.symbols, symbol] });
setSymbolInput('');
}
};
const removeSymbol = (symbol: string) => {
setFormData({
...formData,
symbols: formData.symbols.filter(s => s !== symbol),
});
};
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-surface-secondary rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
<div className="flex justify-between items-center mb-6">
<h2 className="text-lg font-bold text-text-primary">Create New Backtest</h2>
<button
onClick={onClose}
className="p-1 hover:bg-surface-tertiary rounded transition-colors"
>
<XMarkIcon className="w-5 h-5 text-text-secondary" />
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Backtest Name
</label>
<input
type="text"
value={formData.name}
onChange={e => setFormData({ ...formData, name: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
placeholder="My Strategy Backtest"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">Strategy</label>
<select
value={formData.strategy}
onChange={e => setFormData({ ...formData, strategy: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
>
<option value="moving-average">Moving Average</option>
<option value="momentum">Momentum</option>
<option value="mean-reversion">Mean Reversion</option>
<option value="pairs-trading">Pairs Trading</option>
<option value="custom">Custom</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">Symbols</label>
<div className="flex gap-2 mb-2">
<input
type="text"
value={symbolInput}
onChange={e => setSymbolInput(e.target.value)}
onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), addSymbol())}
className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
placeholder="Enter symbol (e.g., AAPL)"
/>
<button
type="button"
onClick={addSymbol}
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
Add
</button>
</div>
<div className="flex flex-wrap gap-2">
{formData.symbols.map(symbol => (
<span
key={symbol}
className="inline-flex items-center gap-1 px-3 py-1 bg-background border border-border rounded-full text-sm text-text-primary"
>
{symbol}
<button
type="button"
onClick={() => removeSymbol(symbol)}
className="hover:text-error transition-colors"
>
<XMarkIcon className="w-4 h-4" />
</button>
</span>
))}
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Start Date
</label>
<input
type="date"
value={formData.startDate}
onChange={e => setFormData({ ...formData, startDate: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
required
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">End Date</label>
<input
type="date"
value={formData.endDate}
onChange={e => setFormData({ ...formData, endDate: e.target.value })}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
required
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Initial Capital
</label>
<input
type="number"
value={formData.initialCapital}
onChange={e =>
setFormData({ ...formData, initialCapital: parseFloat(e.target.value) || 0 })
}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
min="0"
step="1000"
required
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Commission (per trade)
</label>
<input
type="number"
value={formData.commission}
onChange={e =>
setFormData({ ...formData, commission: parseFloat(e.target.value) || 0 })
}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
min="0"
step="0.01"
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Slippage (%)
</label>
<input
type="number"
value={formData.slippage}
onChange={e =>
setFormData({ ...formData, slippage: parseFloat(e.target.value) || 0 })
}
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
min="0"
step="0.01"
/>
</div>
</div>
<div className="flex justify-end gap-3 pt-4">
<button
type="button"
onClick={onClose}
className="px-4 py-2 border border-border text-text-secondary rounded-md text-sm font-medium hover:bg-surface-tertiary transition-colors"
>
Cancel
</button>
<button
type="submit"
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
>
Create Backtest
</button>
</div>
</form>
</div>
</div>
);
}

View file

@ -1,134 +1,157 @@
interface Position {
symbol: string;
quantity: number;
averagePrice?: number;
avgPrice?: number;
currentPrice?: number;
lastPrice?: number;
realizedPnl?: number;
unrealizedPnl?: number;
}
interface PositionsSummaryProps {
openPositions: Position[];
closedPositions: Position[];
onExpand?: () => void;
}
export function PositionsSummary({ openPositions, closedPositions, onExpand }: PositionsSummaryProps) {
const totalRealizedPnL = closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0);
const totalUnrealizedPnL = openPositions.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + ((currentPrice - avgPrice) * quantity);
}, 0);
const totalPnL = totalRealizedPnL + totalUnrealizedPnL;
return (
<div className="bg-surface-secondary rounded-lg border border-border p-4 h-full flex flex-col">
<h3 className="text-sm font-medium text-text-primary mb-3">Positions Summary</h3>
<div className="flex-1">
{openPositions.length > 0 && (
<div className="mb-3">
<h4 className="text-xs font-medium text-text-secondary mb-2">Open Positions ({openPositions.length})</h4>
<div className="space-y-1">
{openPositions.slice(0, 3).map((position, index) => {
const quantity = position.quantity || 0;
const avgPrice = position.averagePrice || position.avgPrice || 0;
const currentPrice = position.currentPrice || position.lastPrice || avgPrice;
const side = quantity > 0 ? 'long' : 'short';
const absQuantity = Math.abs(quantity);
const pnl = (currentPrice - avgPrice) * quantity;
const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0;
return (
<div key={index} className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-surface-tertiary transition-colors">
<div className="flex items-center space-x-2">
<span className="text-sm font-medium text-text-primary">{position.symbol}</span>
<span className={`text-xs px-1.5 py-0.5 rounded ${
side === 'long' ? 'bg-success/20 text-success' : 'bg-error/20 text-error'
}`}>
{side.toUpperCase()}
</span>
<span className="text-xs text-text-secondary">
{absQuantity} @ ${avgPrice.toFixed(2)}
</span>
</div>
<div className="flex items-center space-x-2">
<span className="text-xs text-text-secondary">
${currentPrice.toFixed(2)}
</span>
<span className={`text-xs font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}>
{pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(1)}%
</span>
</div>
</div>
);
})}
</div>
</div>
)}
{closedPositions.length > 0 && openPositions.length === 0 && (
<div className="mb-3">
<h4 className="text-xs font-medium text-text-secondary mb-2">
Closed Positions ({closedPositions.length})
</h4>
<div className="space-y-1">
{closedPositions.slice(0, 3).map((position, index) => (
<div key={index} className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-surface-tertiary transition-colors">
<span className="text-sm font-medium text-text-primary">{position.symbol}</span>
<span className={`text-sm font-medium ${position.realizedPnl >= 0 ? 'text-success' : 'text-error'}`}>
${position.realizedPnl.toFixed(2)}
</span>
</div>
))}
</div>
</div>
)}
{openPositions.length === 0 && closedPositions.length === 0 && (
<p className="text-sm text-text-secondary text-center">No positions to display</p>
)}
</div>
{/* Summary metrics at bottom - similar to performance metrics */}
<div className="mt-3 pt-3 border-t border-border">
<div className="grid grid-cols-3 gap-2 text-xs">
<div className="text-center">
<span className="text-text-secondary">Unrealized</span>
<div className={`font-medium ${totalUnrealizedPnL >= 0 ? 'text-success' : 'text-error'}`}>
${totalUnrealizedPnL.toFixed(2)}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Realized</span>
<div className={`font-medium ${totalRealizedPnL >= 0 ? 'text-success' : 'text-error'}`}>
${totalRealizedPnL.toFixed(2)}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Total P&L</span>
<div className={`font-medium ${totalPnL >= 0 ? 'text-success' : 'text-error'}`}>
${totalPnL.toFixed(2)}
</div>
</div>
</div>
{((openPositions.length > 3) ||
(closedPositions.length > 3 && openPositions.length === 0)) && onExpand && (
<button
onClick={onExpand}
className="w-full text-xs text-primary-500 hover:text-primary-600 text-center pt-2 font-medium"
>
View all {openPositions.length + closedPositions.length} positions
</button>
)}
</div>
</div>
);
}
interface Position {
symbol: string;
quantity: number;
averagePrice?: number;
avgPrice?: number;
currentPrice?: number;
lastPrice?: number;
realizedPnl?: number;
unrealizedPnl?: number;
}
interface PositionsSummaryProps {
openPositions: Position[];
closedPositions: Position[];
onExpand?: () => void;
}
export function PositionsSummary({
openPositions,
closedPositions,
onExpand,
}: PositionsSummaryProps) {
const totalRealizedPnL = closedPositions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0);
const totalUnrealizedPnL = openPositions.reduce((sum, p) => {
const quantity = p.quantity || 0;
const avgPrice = p.averagePrice || p.avgPrice || 0;
const currentPrice = p.currentPrice || p.lastPrice || avgPrice;
return sum + (currentPrice - avgPrice) * quantity;
}, 0);
const totalPnL = totalRealizedPnL + totalUnrealizedPnL;
return (
<div className="bg-surface-secondary rounded-lg border border-border p-4 h-full flex flex-col">
<h3 className="text-sm font-medium text-text-primary mb-3">Positions Summary</h3>
<div className="flex-1">
{openPositions.length > 0 && (
<div className="mb-3">
<h4 className="text-xs font-medium text-text-secondary mb-2">
Open Positions ({openPositions.length})
</h4>
<div className="space-y-1">
{openPositions.slice(0, 3).map((position, index) => {
const quantity = position.quantity || 0;
const avgPrice = position.averagePrice || position.avgPrice || 0;
const currentPrice = position.currentPrice || position.lastPrice || avgPrice;
const side = quantity > 0 ? 'long' : 'short';
const absQuantity = Math.abs(quantity);
const pnl = (currentPrice - avgPrice) * quantity;
const pnlPercent = avgPrice > 0 ? (pnl / (avgPrice * absQuantity)) * 100 : 0;
return (
<div
key={index}
className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-surface-tertiary transition-colors"
>
<div className="flex items-center space-x-2">
<span className="text-sm font-medium text-text-primary">
{position.symbol}
</span>
<span
className={`text-xs px-1.5 py-0.5 rounded ${
side === 'long' ? 'bg-success/20 text-success' : 'bg-error/20 text-error'
}`}
>
{side.toUpperCase()}
</span>
<span className="text-xs text-text-secondary">
{absQuantity} @ ${avgPrice.toFixed(2)}
</span>
</div>
<div className="flex items-center space-x-2">
<span className="text-xs text-text-secondary">
${currentPrice.toFixed(2)}
</span>
<span
className={`text-xs font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}
>
{pnlPercent >= 0 ? '+' : ''}
{pnlPercent.toFixed(1)}%
</span>
</div>
</div>
);
})}
</div>
</div>
)}
{closedPositions.length > 0 && openPositions.length === 0 && (
<div className="mb-3">
<h4 className="text-xs font-medium text-text-secondary mb-2">
Closed Positions ({closedPositions.length})
</h4>
<div className="space-y-1">
{closedPositions.slice(0, 3).map((position, index) => (
<div
key={index}
className="flex items-center justify-between py-1.5 px-2 rounded hover:bg-surface-tertiary transition-colors"
>
<span className="text-sm font-medium text-text-primary">{position.symbol}</span>
<span
className={`text-sm font-medium ${(position.realizedPnl ?? 0) >= 0 ? 'text-success' : 'text-error'}`}
>
${(position.realizedPnl ?? 0).toFixed(2)}
</span>
</div>
))}
</div>
</div>
)}
{openPositions.length === 0 && closedPositions.length === 0 && (
<p className="text-sm text-text-secondary text-center">No positions to display</p>
)}
</div>
{/* Summary metrics at bottom - similar to performance metrics */}
<div className="mt-3 pt-3 border-t border-border">
<div className="grid grid-cols-3 gap-2 text-xs">
<div className="text-center">
<span className="text-text-secondary">Unrealized</span>
<div
className={`font-medium ${totalUnrealizedPnL >= 0 ? 'text-success' : 'text-error'}`}
>
${totalUnrealizedPnL.toFixed(2)}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Realized</span>
<div className={`font-medium ${totalRealizedPnL >= 0 ? 'text-success' : 'text-error'}`}>
${totalRealizedPnL.toFixed(2)}
</div>
</div>
<div className="text-center">
<span className="text-text-secondary">Total P&L</span>
<div className={`font-medium ${totalPnL >= 0 ? 'text-success' : 'text-error'}`}>
${totalPnL.toFixed(2)}
</div>
</div>
</div>
{(openPositions.length > 3 || (closedPositions.length > 3 && openPositions.length === 0)) &&
onExpand && (
<button
onClick={onExpand}
className="w-full text-xs text-primary-500 hover:text-primary-600 text-center pt-2 font-medium"
>
View all {openPositions.length + closedPositions.length} positions
</button>
)}
</div>
</div>
);
}

View file

@ -1,201 +1,196 @@
import { useState } from 'react';
import type { Run } from '../services/backtestApiV2';
import {
PlayIcon,
PauseIcon,
StopIcon,
ForwardIcon,
BackwardIcon,
} from '@heroicons/react/24/solid';
interface RunControlsProps {
run: Run;
onPause: () => void;
onResume: () => void;
onCancel: () => void;
onSpeedChange: (speed: number) => void;
}
export function RunControls({
run,
onPause,
onResume,
onCancel,
onSpeedChange,
}: RunControlsProps) {
const [speedMultiplier, setSpeedMultiplier] = useState(run.speedMultiplier);
const handleSpeedChange = (speed: number) => {
setSpeedMultiplier(speed);
onSpeedChange(speed);
};
const speedOptions = [
{ value: 0.1, label: '0.1x' },
{ value: 0.5, label: '0.5x' },
{ value: 1, label: '1x' },
{ value: 2, label: '2x' },
{ value: 5, label: '5x' },
{ value: 10, label: '10x' },
{ value: 50, label: '50x' },
{ value: 100, label: '100x' },
{ value: 1000, label: 'Max' },
];
const formatDate = (date?: string) => {
if (!date) return '-';
return new Date(date).toLocaleString();
};
const formatDuration = () => {
if (!run.startedAt) return '00:00';
const start = new Date(run.startedAt).getTime();
const current = Date.now();
const duration = current - start;
const seconds = Math.floor(duration / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
return `${hours.toString().padStart(2, '0')}:${(minutes % 60).toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
} else {
return `${minutes.toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
}
};
return (
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<h3 className="text-base font-medium text-text-primary mb-4">Run Control</h3>
<div className="space-y-4">
{/* Progress Bar */}
<div>
<div className="flex justify-between text-sm text-text-secondary mb-1">
<span>Progress</span>
<span>{run.progress.toFixed(1)}%</span>
</div>
<div className="w-full bg-background rounded-full h-3 overflow-hidden">
<div
className="bg-primary-500 h-3 transition-all duration-300 relative"
style={{ width: `${run.progress}%` }}
>
<div className="absolute inset-0 bg-gradient-to-r from-primary-500 to-primary-400 opacity-50"></div>
</div>
</div>
</div>
{/* Control Buttons */}
<div className="flex items-center space-x-2">
{run.status === 'running' ? (
<button
onClick={onPause}
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-warning text-white rounded-md text-sm font-medium hover:bg-warning/90 transition-colors"
>
<PauseIcon className="w-4 h-4" />
Pause
</button>
) : run.status === 'paused' ? (
<button
onClick={onResume}
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-success text-white rounded-md text-sm font-medium hover:bg-success/90 transition-colors"
>
<PlayIcon className="w-4 h-4" />
Resume
</button>
) : null}
{(run.status === 'running' || run.status === 'paused') && (
<button
onClick={onCancel}
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-error text-white rounded-md text-sm font-medium hover:bg-error/90 transition-colors"
>
<StopIcon className="w-4 h-4" />
Cancel
</button>
)}
</div>
{/* Speed Control */}
{run.status === 'running' && (
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Playback Speed
</label>
<div className="flex items-center space-x-2">
<button
onClick={() => {
const currentIndex = speedOptions.findIndex(s => s.value === speedMultiplier);
if (currentIndex > 0) {
handleSpeedChange(speedOptions[currentIndex - 1].value);
}
}}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
disabled={speedMultiplier <= 0.1}
>
<BackwardIcon className="w-4 h-4 text-text-secondary" />
</button>
<select
value={speedMultiplier}
onChange={(e) => handleSpeedChange(parseFloat(e.target.value))}
className="flex-1 px-3 py-1.5 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
>
{speedOptions.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
<button
onClick={() => {
const currentIndex = speedOptions.findIndex(s => s.value === speedMultiplier);
if (currentIndex < speedOptions.length - 1) {
handleSpeedChange(speedOptions[currentIndex + 1].value);
}
}}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
disabled={speedMultiplier >= 1000}
>
<ForwardIcon className="w-4 h-4 text-text-secondary" />
</button>
</div>
</div>
)}
{/* Run Info */}
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-text-secondary">Status:</span>
<span className="ml-2 text-text-primary font-medium">
{run.status.charAt(0).toUpperCase() + run.status.slice(1)}
</span>
</div>
<div>
<span className="text-text-secondary">Duration:</span>
<span className="ml-2 text-text-primary font-medium">
{formatDuration()}
</span>
</div>
{run.currentSimulationDate && (
<div className="col-span-2">
<span className="text-text-secondary">Current Date:</span>
<span className="ml-2 text-text-primary font-medium">
{formatDate(run.currentSimulationDate)}
</span>
</div>
)}
{run.error && (
<div className="col-span-2">
<span className="text-text-secondary">Error:</span>
<span className="ml-2 text-error text-xs">
{run.error}
</span>
</div>
)}
</div>
</div>
</div>
);
}
import {
BackwardIcon,
ForwardIcon,
PauseIcon,
PlayIcon,
StopIcon,
} from '@heroicons/react/24/solid';
import { useState } from 'react';
import { at } from '@stock-bot/invariants';
import type { Run } from '../services/backtestApiV2';
interface RunControlsProps {
run: Run;
onPause: () => void;
onResume: () => void;
onCancel: () => void;
onSpeedChange: (speed: number) => void;
}
export function RunControls({ run, onPause, onResume, onCancel, onSpeedChange }: RunControlsProps) {
const [speedMultiplier, setSpeedMultiplier] = useState(run.speedMultiplier ?? 1000);
const handleSpeedChange = (speed: number) => {
setSpeedMultiplier(speed);
onSpeedChange(speed);
};
const speedOptions = [
{ value: 0.1, label: '0.1x' },
{ value: 0.5, label: '0.5x' },
{ value: 1, label: '1x' },
{ value: 2, label: '2x' },
{ value: 5, label: '5x' },
{ value: 10, label: '10x' },
{ value: 50, label: '50x' },
{ value: 100, label: '100x' },
{ value: 1000, label: 'Max' },
];
const formatDate = (date?: string) => {
if (!date) {
return '-';
}
return new Date(date).toLocaleString();
};
const formatDuration = () => {
if (!run.startedAt) {
return '00:00';
}
const start = new Date(run.startedAt).getTime();
const current = Date.now();
const duration = current - start;
const seconds = Math.floor(duration / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
return `${hours.toString().padStart(2, '0')}:${(minutes % 60).toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
} else {
return `${minutes.toString().padStart(2, '0')}:${(seconds % 60).toString().padStart(2, '0')}`;
}
};
return (
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<h3 className="text-base font-medium text-text-primary mb-4">Run Control</h3>
<div className="space-y-4">
{/* Progress Bar */}
<div>
<div className="flex justify-between text-sm text-text-secondary mb-1">
<span>Progress</span>
<span>{run.progress.toFixed(1)}%</span>
</div>
<div className="w-full bg-background rounded-full h-3 overflow-hidden">
<div
className="bg-primary-500 h-3 transition-all duration-300 relative"
style={{ width: `${run.progress}%` }}
>
<div className="absolute inset-0 bg-gradient-to-r from-primary-500 to-primary-400 opacity-50"></div>
</div>
</div>
</div>
{/* Control Buttons */}
<div className="flex items-center space-x-2">
{run.status === 'running' ? (
<button
onClick={onPause}
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-warning text-white rounded-md text-sm font-medium hover:bg-warning/90 transition-colors"
>
<PauseIcon className="w-4 h-4" />
Pause
</button>
) : run.status === 'paused' ? (
<button
onClick={onResume}
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-success text-white rounded-md text-sm font-medium hover:bg-success/90 transition-colors"
>
<PlayIcon className="w-4 h-4" />
Resume
</button>
) : null}
{(run.status === 'running' || run.status === 'paused') && (
<button
onClick={onCancel}
className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-2 bg-error text-white rounded-md text-sm font-medium hover:bg-error/90 transition-colors"
>
<StopIcon className="w-4 h-4" />
Cancel
</button>
)}
</div>
{/* Speed Control */}
{run.status === 'running' && (
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Playback Speed
</label>
<div className="flex items-center space-x-2">
<button
onClick={() => {
const currentIndex = speedOptions.findIndex(s => s.value === speedMultiplier);
if (currentIndex > 0) {
handleSpeedChange(at(speedOptions, currentIndex - 1).value);
}
}}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
disabled={speedMultiplier <= 0.1}
>
<BackwardIcon className="w-4 h-4 text-text-secondary" />
</button>
<select
value={speedMultiplier}
onChange={e => handleSpeedChange(parseFloat(e.target.value))}
className="flex-1 px-3 py-1.5 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
>
{speedOptions.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
<button
onClick={() => {
const currentIndex = speedOptions.findIndex(s => s.value === speedMultiplier);
if (currentIndex < speedOptions.length - 1) {
handleSpeedChange(at(speedOptions, currentIndex + 1).value);
}
}}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
disabled={speedMultiplier >= 1000}
>
<ForwardIcon className="w-4 h-4 text-text-secondary" />
</button>
</div>
</div>
)}
{/* Run Info */}
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-text-secondary">Status:</span>
<span className="ml-2 text-text-primary font-medium">
{run.status.charAt(0).toUpperCase() + run.status.slice(1)}
</span>
</div>
<div>
<span className="text-text-secondary">Duration:</span>
<span className="ml-2 text-text-primary font-medium">{formatDuration()}</span>
</div>
{run.currentSimulationDate && (
<div className="col-span-2">
<span className="text-text-secondary">Current Date:</span>
<span className="ml-2 text-text-primary font-medium">
{formatDate(run.currentSimulationDate)}
</span>
</div>
)}
{run.error && (
<div className="col-span-2">
<span className="text-text-secondary">Error:</span>
<span className="ml-2 text-error text-xs">{run.error}</span>
</div>
)}
</div>
</div>
</div>
);
}

View file

@ -1,100 +1,102 @@
import type { Run } from '../services/backtestApiV2';
import {
ArrowPathIcon,
} from '@heroicons/react/24/solid';
interface RunControlsCompactProps {
run: Run;
onPause: () => void;
onResume: () => void;
onRerun: (speed: number | null) => void;
onNext?: () => void;
onSpeedChange: (speed: number | null) => void;
}
export function RunControlsCompact({
run,
onPause,
onResume,
onRerun,
onNext,
}: RunControlsCompactProps) {
const isRunning = run.status === 'running';
const isPaused = run.status === 'paused';
const isCompleted = run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled';
return (
<div className="flex items-center space-x-3">
{/* Progress */}
<div className="flex items-center space-x-2">
<span className="text-xs text-text-secondary">Progress:</span>
<div className="w-24 bg-background rounded-full h-2 overflow-hidden">
<div
className="bg-primary-500 h-2 transition-all duration-300 relative"
style={{ width: `${run.progress}%` }}
>
<div className="absolute inset-0 bg-gradient-to-r from-primary-500 to-primary-400 opacity-50"></div>
</div>
</div>
<span className="text-xs text-text-primary font-medium">{run.progress.toFixed(0)}%</span>
</div>
{/* Control Buttons */}
<div className="flex items-center space-x-1">
{isRunning ? (
<button
onClick={onPause}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Pause"
>
<PauseIcon className="w-4 h-4 text-text-primary" />
</button>
) : isPaused ? (
<button
onClick={onResume}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Resume"
>
<PlayIcon className="w-4 h-4 text-text-primary" />
</button>
) : null}
{onNext && (
<button
onClick={onNext}
className="p-1 rounded hover:bg-surface-tertiary transition-colors disabled:opacity-50"
disabled={!isRunning && !isPaused}
title="Next"
>
<ForwardIcon className="w-4 h-4 text-text-primary" />
</button>
)}
<button
onClick={() => onRerun(null)} // Always use max speed
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Rerun"
>
<ArrowPathIcon className="w-4 h-4 text-text-primary" />
</button>
</div>
{/* Status Indicator */}
{run.status !== 'running' && run.status !== 'paused' && (
<>
<div className="h-6 w-px bg-border"></div>
<span className={`text-xs font-medium ${
run.status === 'completed' ? 'text-success' :
run.status === 'failed' ? 'text-error' :
run.status === 'cancelled' ? 'text-text-secondary' :
'text-text-primary'
}`}>
{run.status.charAt(0).toUpperCase() + run.status.slice(1)}
</span>
</>
)}
</div>
);
}
import { ArrowPathIcon, ForwardIcon, PauseIcon, PlayIcon } from '@heroicons/react/24/solid';
import type { Run } from '../services/backtestApiV2';
interface RunControlsCompactProps {
run: Run;
onPause: () => void;
onResume: () => void;
onRerun: (speed: number | null) => void;
onNext?: () => void;
onSpeedChange: (speed: number | null) => void;
}
export function RunControlsCompact({
run,
onPause,
onResume,
onRerun,
onNext,
}: RunControlsCompactProps) {
const isRunning = run.status === 'running';
const isPaused = run.status === 'paused';
const _isCompleted =
run.status === 'completed' || run.status === 'failed' || run.status === 'cancelled';
return (
<div className="flex items-center space-x-3">
{/* Progress */}
<div className="flex items-center space-x-2">
<span className="text-xs text-text-secondary">Progress:</span>
<div className="w-24 bg-background rounded-full h-2 overflow-hidden">
<div
className="bg-primary-500 h-2 transition-all duration-300 relative"
style={{ width: `${run.progress}%` }}
>
<div className="absolute inset-0 bg-gradient-to-r from-primary-500 to-primary-400 opacity-50"></div>
</div>
</div>
<span className="text-xs text-text-primary font-medium">{run.progress.toFixed(0)}%</span>
</div>
{/* Control Buttons */}
<div className="flex items-center space-x-1">
{isRunning ? (
<button
onClick={onPause}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Pause"
>
<PauseIcon className="w-4 h-4 text-text-primary" />
</button>
) : isPaused ? (
<button
onClick={onResume}
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Resume"
>
<PlayIcon className="w-4 h-4 text-text-primary" />
</button>
) : null}
{onNext && (
<button
onClick={onNext}
className="p-1 rounded hover:bg-surface-tertiary transition-colors disabled:opacity-50"
disabled={!isRunning && !isPaused}
title="Next"
>
<ForwardIcon className="w-4 h-4 text-text-primary" />
</button>
)}
<button
onClick={() => onRerun(null)} // Always use max speed
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
title="Rerun"
>
<ArrowPathIcon className="w-4 h-4 text-text-primary" />
</button>
</div>
{/* Status Indicator */}
{run.status !== 'running' && run.status !== 'paused' && (
<>
<div className="h-6 w-px bg-border"></div>
<span
className={`text-xs font-medium ${
run.status === 'completed'
? 'text-success'
: run.status === 'failed'
? 'text-error'
: run.status === 'cancelled'
? 'text-text-secondary'
: 'text-text-primary'
}`}
>
{run.status.charAt(0).toUpperCase() + run.status.slice(1)}
</span>
</>
)}
</div>
);
}

View file

@ -1,290 +1,336 @@
import { DataTable } from '@/components/ui/DataTable';
import type { ColumnDef } from '@tanstack/react-table';
import type { Run, RunResult } from '../services/backtestApiV2';
import { useNavigate, useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { backtestApiV2 } from '../services/backtestApiV2';
import {
CheckCircleIcon,
XCircleIcon,
PauseIcon,
PlayIcon,
ClockIcon,
} from '@heroicons/react/24/outline';
interface RunsListProps {
runs: Run[];
currentRunId?: string;
onSelectRun: (runId: string) => void;
}
interface RunWithMetrics extends Run {
metrics?: RunResult['metrics'];
initialCapital?: number;
}
export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsListProps) {
const navigate = useNavigate();
const { id: backtestId } = useParams<{ id: string }>();
const [runsWithMetrics, setRunsWithMetrics] = useState<RunWithMetrics[]>([]);
const [loadingMetrics, setLoadingMetrics] = useState(false);
// Fetch metrics for completed runs
useEffect(() => {
const fetchMetrics = async () => {
setLoadingMetrics(true);
const updatedRuns: RunWithMetrics[] = await Promise.all(
runs.map(async (run) => {
if (run.status === 'completed') {
try {
const results = await backtestApiV2.getRunResults(run.id);
return {
...run,
metrics: results.metrics,
initialCapital: results.config?.initialCapital
};
} catch (error) {
console.error(`Failed to fetch metrics for run ${run.id}:`, error);
return run;
}
}
return run;
})
);
setRunsWithMetrics(updatedRuns);
setLoadingMetrics(false);
};
if (runs.length > 0) {
fetchMetrics();
}
}, [runs]);
const getStatusIcon = (status: Run['status']) => {
switch (status) {
case 'completed':
return <CheckCircleIcon className="w-4 h-4 text-success" />;
case 'failed':
return <XCircleIcon className="w-4 h-4 text-error" />;
case 'cancelled':
return <XCircleIcon className="w-4 h-4 text-text-secondary" />;
case 'running':
return <PlayIcon className="w-4 h-4 text-primary-500" />;
case 'paused':
return <PauseIcon className="w-4 h-4 text-warning" />;
case 'pending':
return <ClockIcon className="w-4 h-4 text-text-secondary" />;
}
};
const getStatusLabel = (status: Run['status']) => {
return status.charAt(0).toUpperCase() + status.slice(1);
};
const formatPercentage = (value: number | undefined, decimals = 2) => {
if (value === undefined || value === null) return '-';
return `${(value * 100).toFixed(decimals)}%`;
};
const formatNumber = (value: number | undefined, decimals = 2) => {
if (value === undefined || value === null) return '-';
return value.toFixed(decimals);
};
const formatCurrency = (value: number | undefined) => {
if (value === undefined || value === null) return '-';
const prefix = value < 0 ? '-$' : '$';
return `${prefix}${Math.abs(value).toFixed(2)}`;
};
const columns: ColumnDef<RunWithMetrics>[] = [
{
accessorKey: 'runNumber',
header: 'Run #',
size: 60,
cell: ({ getValue, row }) => (
<span className={`text-sm font-medium ${row.original.id === currentRunId ? 'text-primary-500' : 'text-text-primary'}`}>
#{getValue() as number}
</span>
),
},
{
accessorKey: 'status',
header: 'Status',
size: 100,
cell: ({ getValue }) => {
const status = getValue() as Run['status'];
return (
<div className="flex items-center space-x-2">
{getStatusIcon(status)}
<span className="text-sm text-text-primary">{getStatusLabel(status)}</span>
</div>
);
},
},
{
accessorKey: 'progress',
header: 'Progress',
size: 120,
cell: ({ row }) => {
const progress = row.original.progress;
const status = row.original.status;
if (status === 'pending') return <span className="text-sm text-text-secondary">-</span>;
if (status === 'completed') return <span className="text-sm text-success">Complete</span>;
return (
<div className="flex items-center space-x-2">
<div className="flex-1 bg-surface-tertiary rounded-full h-2 overflow-hidden">
<div
className="bg-primary-500 h-2 transition-all duration-300"
style={{ width: `${progress}%` }}
/>
</div>
<span className="text-xs text-text-secondary">{progress.toFixed(0)}%</span>
</div>
);
},
},
{
id: 'totalReturn',
header: 'Return',
size: 80,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.totalReturn;
return (
<span className={`text-sm font-medium ${
value === undefined ? 'text-text-secondary' :
value >= 0 ? 'text-success' : 'text-error'
}`}>
{formatPercentage(value)}
</span>
);
},
},
{
id: 'sharpeRatio',
header: 'Sharpe',
size: 80,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.sharpeRatio;
return (
<span className={`text-sm font-medium ${
value === undefined ? 'text-text-secondary' :
value > 1 ? 'text-success' :
value > 0 ? 'text-warning' : 'text-error'
}`}>
{formatNumber(value)}
</span>
);
},
},
{
id: 'maxDrawdown',
header: 'Max DD',
size: 80,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.maxDrawdown;
return (
<span className={`text-sm font-medium ${
value === undefined ? 'text-text-secondary' :
value > -0.1 ? 'text-success' :
value > -0.2 ? 'text-warning' : 'text-error'
}`}>
{formatPercentage(value)}
</span>
);
},
},
{
id: 'winRate',
header: 'Win Rate',
size: 80,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.winRate;
return (
<span className={`text-sm font-medium ${
value === undefined ? 'text-text-secondary' :
value > 0.5 ? 'text-success' : 'text-warning'
}`}>
{formatPercentage(value, 1)}
</span>
);
},
},
{
id: 'profitFactor',
header: 'Profit Factor',
size: 100,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.profitFactor;
return (
<span className={`text-sm font-medium ${
value === undefined ? 'text-text-secondary' :
value > 1.5 ? 'text-success' :
value > 1 ? 'text-warning' : 'text-error'
}`}>
{formatNumber(value)}
</span>
);
},
},
{
id: 'totalProfit',
header: 'Total Profit',
size: 100,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.totalProfit;
return (
<span className={`text-sm font-medium ${
value === undefined ? 'text-text-secondary' :
value >= 0 ? 'text-success' : 'text-error'
}`}>
{formatCurrency(value)}
</span>
);
},
},
{
accessorKey: 'startedAt',
header: 'Started',
size: 160,
cell: ({ getValue }) => {
const date = getValue() as string | undefined;
return (
<span className="text-sm text-text-secondary">
{date ? new Date(date).toLocaleString() : '-'}
</span>
);
},
},
];
if (runs.length === 0) {
return (
<div className="bg-surface-secondary rounded-lg border border-border p-8 text-center">
<p className="text-text-secondary">No runs yet. Create a new run to get started.</p>
</div>
);
}
return (
<DataTable
data={runsWithMetrics}
columns={columns}
onRowClick={(run) => {
navigate(`/backtests/${backtestId}/run/${run.id}`);
onSelectRun(run.id);
}}
className="bg-surface-secondary rounded-lg border border-border"
height={400}
loading={loadingMetrics}
/>
);
}
import {
CheckCircleIcon,
ClockIcon,
PauseIcon,
PlayIcon,
XCircleIcon,
} from '@heroicons/react/24/outline';
import type { ColumnDef } from '@tanstack/react-table';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { DataTable } from '@/components/ui/DataTable';
import { browserLog } from '@/utils/browserLog';
import type { Run, RunResult } from '../services/backtestApiV2';
import { backtestApiV2 } from '../services/backtestApiV2';
interface RunsListProps {
runs: Run[];
currentRunId?: string;
onSelectRun: (runId: string) => void;
}
interface RunWithMetrics extends Run {
metrics?: RunResult['metrics'];
initialCapital?: number;
}
export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsListProps) {
const navigate = useNavigate();
const { id: backtestId } = useParams<{ id: string }>();
const [runsWithMetrics, setRunsWithMetrics] = useState<RunWithMetrics[]>([]);
const [loadingMetrics, setLoadingMetrics] = useState(false);
// Fetch metrics for completed runs
useEffect(() => {
const fetchMetrics = async () => {
setLoadingMetrics(true);
const updatedRuns: RunWithMetrics[] = await Promise.all(
runs.map(async run => {
if (run.status === 'completed') {
try {
const results = await backtestApiV2.getRunResults(run.id);
return {
...run,
metrics: results.metrics,
initialCapital: results.config?.initialCapital,
};
} catch (error) {
browserLog.error(`Failed to fetch metrics for run ${run.id}:`, error);
return run;
}
}
return run;
})
);
setRunsWithMetrics(updatedRuns);
setLoadingMetrics(false);
};
if (runs.length > 0) {
fetchMetrics();
}
}, [runs]);
const getStatusIcon = (status: Run['status']) => {
switch (status) {
case 'completed':
return <CheckCircleIcon className="w-4 h-4 text-success" />;
case 'failed':
return <XCircleIcon className="w-4 h-4 text-error" />;
case 'cancelled':
return <XCircleIcon className="w-4 h-4 text-text-secondary" />;
case 'running':
return <PlayIcon className="w-4 h-4 text-primary-500" />;
case 'paused':
return <PauseIcon className="w-4 h-4 text-warning" />;
case 'pending':
return <ClockIcon className="w-4 h-4 text-text-secondary" />;
}
};
const getStatusLabel = (status: Run['status']) => {
return status.charAt(0).toUpperCase() + status.slice(1);
};
const formatPercentage = (value: number | undefined, decimals = 2) => {
if (value === undefined || value === null) {
return '-';
}
return `${(value * 100).toFixed(decimals)}%`;
};
const formatNumber = (value: number | undefined, decimals = 2) => {
if (value === undefined || value === null) {
return '-';
}
return value.toFixed(decimals);
};
const formatCurrency = (value: number | undefined) => {
if (value === undefined || value === null) {
return '-';
}
const prefix = value < 0 ? '-$' : '$';
return `${prefix}${Math.abs(value).toFixed(2)}`;
};
const columns: ColumnDef<RunWithMetrics>[] = [
{
accessorKey: 'runNumber',
header: 'Run #',
size: 60,
cell: ({ getValue, row }) => (
<span
className={`text-sm font-medium ${row.original.id === currentRunId ? 'text-primary-500' : 'text-text-primary'}`}
>
#{getValue() as number}
</span>
),
},
{
accessorKey: 'status',
header: 'Status',
size: 100,
cell: ({ getValue }) => {
const status = getValue() as Run['status'];
return (
<div className="flex items-center space-x-2">
{getStatusIcon(status)}
<span className="text-sm text-text-primary">{getStatusLabel(status)}</span>
</div>
);
},
},
{
accessorKey: 'progress',
header: 'Progress',
size: 120,
cell: ({ row }) => {
const progress = row.original.progress;
const status = row.original.status;
if (status === 'pending') {
return <span className="text-sm text-text-secondary">-</span>;
}
if (status === 'completed') {
return <span className="text-sm text-success">Complete</span>;
}
return (
<div className="flex items-center space-x-2">
<div className="flex-1 bg-surface-tertiary rounded-full h-2 overflow-hidden">
<div
className="bg-primary-500 h-2 transition-all duration-300"
style={{ width: `${progress}%` }}
/>
</div>
<span className="text-xs text-text-secondary">{progress.toFixed(0)}%</span>
</div>
);
},
},
{
id: 'totalReturn',
header: 'Return',
size: 80,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.totalReturn;
return (
<span
className={`text-sm font-medium ${
value === undefined
? 'text-text-secondary'
: value >= 0
? 'text-success'
: 'text-error'
}`}
>
{formatPercentage(value)}
</span>
);
},
},
{
id: 'sharpeRatio',
header: 'Sharpe',
size: 80,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.sharpeRatio;
return (
<span
className={`text-sm font-medium ${
value === undefined
? 'text-text-secondary'
: value > 1
? 'text-success'
: value > 0
? 'text-warning'
: 'text-error'
}`}
>
{formatNumber(value)}
</span>
);
},
},
{
id: 'maxDrawdown',
header: 'Max DD',
size: 80,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.maxDrawdown;
return (
<span
className={`text-sm font-medium ${
value === undefined
? 'text-text-secondary'
: value > -0.1
? 'text-success'
: value > -0.2
? 'text-warning'
: 'text-error'
}`}
>
{formatPercentage(value)}
</span>
);
},
},
{
id: 'winRate',
header: 'Win Rate',
size: 80,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.winRate;
return (
<span
className={`text-sm font-medium ${
value === undefined
? 'text-text-secondary'
: value > 0.5
? 'text-success'
: 'text-warning'
}`}
>
{formatPercentage(value, 1)}
</span>
);
},
},
{
id: 'profitFactor',
header: 'Profit Factor',
size: 100,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.profitFactor;
return (
<span
className={`text-sm font-medium ${
value === undefined
? 'text-text-secondary'
: value > 1.5
? 'text-success'
: value > 1
? 'text-warning'
: 'text-error'
}`}
>
{formatNumber(value)}
</span>
);
},
},
{
id: 'totalProfit',
header: 'Total Profit',
size: 100,
cell: ({ row }) => {
const metrics = row.original.metrics;
const value = metrics?.totalProfit;
return (
<span
className={`text-sm font-medium ${
value === undefined
? 'text-text-secondary'
: value >= 0
? 'text-success'
: 'text-error'
}`}
>
{formatCurrency(value)}
</span>
);
},
},
{
accessorKey: 'startedAt',
header: 'Started',
size: 160,
cell: ({ getValue }) => {
const date = getValue() as string | undefined;
return (
<span className="text-sm text-text-secondary">
{date ? new Date(date).toLocaleString() : '-'}
</span>
);
},
},
];
if (runs.length === 0) {
return (
<div className="bg-surface-secondary rounded-lg border border-border p-8 text-center">
<p className="text-text-secondary">No runs yet. Create a new run to get started.</p>
</div>
);
}
return (
<DataTable
data={runsWithMetrics}
columns={columns}
onRowClick={run => {
navigate(`/backtests/${backtestId}/run/${run.id}`);
onSelectRun(run.id);
}}
className="bg-surface-secondary rounded-lg border border-border"
height={400}
loading={loadingMetrics}
/>
);
}

View file

@ -1,389 +1,411 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { backtestApiV2 } from '../services/backtestApiV2';
import type { Backtest, Run, RunResult, CreateBacktestRequest } from '../services/backtestApiV2';
interface UseBacktestV2Return {
// State
backtest: Backtest | null;
runs: Run[];
currentRun: Run | null;
runResults: RunResult | null;
isLoading: boolean;
error: string | null;
// Actions
loadBacktest: (id: string) => Promise<void>;
createBacktest: (request: CreateBacktestRequest) => Promise<Backtest>;
updateBacktest: (id: string, updates: Partial<CreateBacktestRequest>) => Promise<void>;
deleteBacktest: (id: string) => Promise<void>;
createRun: (speedMultiplier?: number | null) => Promise<Run | undefined>;
pauseRun: () => Promise<void>;
resumeRun: () => Promise<void>;
cancelRun: () => Promise<void>;
updateRunSpeed: (speedMultiplier: number | null) => Promise<void>;
selectRun: (runId: string | undefined) => Promise<void>;
}
export function useBacktestV2(): UseBacktestV2Return {
const [backtest, setBacktest] = useState<Backtest | null>(null);
const [runs, setRuns] = useState<Run[]>([]);
const [currentRun, setCurrentRun] = useState<Run | null>(null);
const [runResults, setRunResults] = useState<RunResult | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);
// Load a specific backtest and its runs
const loadBacktest = useCallback(async (id: string) => {
setIsLoading(true);
setError(null);
try {
const [loadedBacktest, loadedRuns] = await Promise.all([
backtestApiV2.getBacktest(id),
backtestApiV2.listRuns(id)
]);
setBacktest(loadedBacktest);
setRuns(loadedRuns);
// Don't auto-select runs here - let the URL parameter drive the selection
} catch (err) {
console.error('Failed to load backtest:', err);
setError(err instanceof Error ? err.message : 'Failed to load backtest');
} finally {
setIsLoading(false);
}
}, []);
// Create a new backtest
const createBacktest = useCallback(async (request: CreateBacktestRequest): Promise<Backtest> => {
setIsLoading(true);
setError(null);
try {
const newBacktest = await backtestApiV2.createBacktest(request);
setBacktest(newBacktest);
setRuns([]);
setCurrentRun(null);
setRunResults(null);
return newBacktest;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create backtest');
throw err;
} finally {
setIsLoading(false);
}
}, []);
// Update backtest configuration
const updateBacktest = useCallback(async (id: string, updates: Partial<CreateBacktestRequest>) => {
setIsLoading(true);
setError(null);
try {
const updatedBacktest = await backtestApiV2.updateBacktest(id, updates);
setBacktest(updatedBacktest);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update backtest');
throw err;
} finally {
setIsLoading(false);
}
}, []);
// Delete backtest
const deleteBacktest = useCallback(async (id: string) => {
setIsLoading(true);
setError(null);
try {
await backtestApiV2.deleteBacktest(id);
setBacktest(null);
setRuns([]);
setCurrentRun(null);
setRunResults(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete backtest');
throw err;
} finally {
setIsLoading(false);
}
}, []);
// Create a new run
const createRun = useCallback(async (speedMultiplier?: number | null) => {
if (!backtest) return;
setIsLoading(true);
setError(null);
setRunResults(null);
try {
// Pass speedMultiplier as-is, null means max speed
const newRun = await backtestApiV2.createRun(backtest.id, {
speedMultiplier: speedMultiplier === undefined ? null : speedMultiplier
});
// Add to runs array first
setRuns(prevRuns => [newRun, ...prevRuns]);
// Clear previous results immediately
setRunResults(null);
// Set as current run
setCurrentRun(newRun);
// Small delay to ensure the run is properly created in the database
await new Promise(resolve => setTimeout(resolve, 100));
// Check if the run is completed (it might complete instantly)
let finalRun = newRun;
// If status is pending, check again after a short delay
if (newRun.status === 'pending') {
await new Promise(resolve => setTimeout(resolve, 500));
try {
finalRun = await backtestApiV2.getRun(newRun.id);
// Update the current run with the latest status
setCurrentRun(finalRun);
setRuns(prevRuns =>
prevRuns.map(r => r.id === finalRun.id ? finalRun : r)
);
} catch (err) {
console.error('Failed to re-check run status:', err);
}
}
// If the run is completed, load results
if (finalRun.status === 'completed') {
try {
const results = await backtestApiV2.getRunResults(finalRun.id);
setRunResults(results);
} catch (err) {
console.error('Failed to load new run results:', err);
}
} else {
// Start monitoring the run
startMonitoringRun(finalRun.id);
}
return newRun; // Return the created run
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create run');
throw err; // Re-throw so caller knows it failed
} finally {
setIsLoading(false);
}
}, [backtest]);
// Run control actions
const pauseRun = useCallback(async () => {
if (!currentRun || currentRun.status !== 'running') return;
try {
await backtestApiV2.pauseRun(currentRun.id);
setCurrentRun(prev => prev ? { ...prev, status: 'paused' } : null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to pause run');
}
}, [currentRun]);
const resumeRun = useCallback(async () => {
if (!currentRun || currentRun.status !== 'paused') return;
try {
await backtestApiV2.resumeRun(currentRun.id);
setCurrentRun(prev => prev ? { ...prev, status: 'running' } : null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to resume run');
}
}, [currentRun]);
const cancelRun = useCallback(async () => {
if (!currentRun || (currentRun.status !== 'running' && currentRun.status !== 'paused')) return;
try {
await backtestApiV2.cancelRun(currentRun.id);
setCurrentRun(prev => prev ? { ...prev, status: 'cancelled' } : null);
stopMonitoringRun();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to cancel run');
}
}, [currentRun]);
const updateRunSpeed = useCallback(async (speedMultiplier: number | null) => {
if (!currentRun) return;
try {
// Keep null as null for max speed (no limit)
const apiSpeed = speedMultiplier;
// Only call API if run is active
if (currentRun.status === 'running' || currentRun.status === 'paused') {
await backtestApiV2.updateRunSpeed(currentRun.id, apiSpeed);
}
// Always update local state so UI reflects the selection
setCurrentRun(prev => prev ? { ...prev, speedMultiplier: apiSpeed } : null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update run speed');
}
}, [currentRun]);
// Select a specific run
const selectRun = useCallback(async (runId: string | undefined) => {
if (!runId) {
setCurrentRun(null);
setRunResults(null);
stopMonitoringRun();
return;
}
let run = runs.find(r => r.id === runId);
// If run not found in list, try to fetch it directly
if (!run) {
let attempts = 0;
const maxAttempts = 3;
while (attempts < maxAttempts) {
try {
run = await backtestApiV2.getRun(runId);
// Add to runs list if not present
setRuns(prevRuns => {
const exists = prevRuns.some(r => r.id === run!.id);
if (!exists) {
return [run!, ...prevRuns];
}
return prevRuns;
});
break; // Success, exit loop
} catch (err) {
attempts++;
if (attempts >= maxAttempts) {
console.error('Failed to fetch run after all attempts:', runId, err);
setError(`Failed to load run ${runId}`);
return;
}
// Wait before retrying
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
setCurrentRun(run);
setRunResults(null);
if (run.status === 'completed') {
try {
const results = await backtestApiV2.getRunResults(run.id);
setRunResults(results);
} catch (err) {
console.error('Failed to load run results:', err);
setError(err instanceof Error ? err.message : 'Failed to load run results');
}
} else if (run.status === 'running' || run.status === 'paused' || run.status === 'pending') {
startMonitoringRun(run.id);
} else {
console.warn('Run has unexpected status:', run.status);
}
}, [runs]);
// Monitor run progress
const startMonitoringRun = useCallback((runId: string) => {
// Stop any existing monitoring
stopMonitoringRun();
// For pending runs, we need to poll until they start or complete
// We'll check the run status by fetching it
pollingIntervalRef.current = setInterval(async () => {
try {
const updatedRun = await backtestApiV2.getRun(runId);
// Update the run in state
setCurrentRun(updatedRun);
setRuns(prevRuns =>
prevRuns.map(r => r.id === updatedRun.id ? updatedRun : r)
);
// If run is no longer pending, handle the new status
if (updatedRun.status === 'completed') {
stopMonitoringRun();
try {
const results = await backtestApiV2.getRunResults(runId);
setRunResults(results);
} catch (err) {
console.error('Failed to load completed run results:', err);
}
} else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') {
stopMonitoringRun();
}
} catch (err) {
console.error('Failed to poll run status:', err);
}
}, 1000); // Poll every second
}, []);
const startPollingRun = (runId: string) => {
pollingIntervalRef.current = setInterval(async () => {
try {
const updatedRun = await backtestApiV2.getRun(runId);
handleRunUpdate(updatedRun);
if (updatedRun.status === 'completed') {
const results = await backtestApiV2.getRunResults(runId);
setRunResults(results);
stopMonitoringRun();
} else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') {
stopMonitoringRun();
}
} catch (err) {
console.error('Failed to poll run status:', err);
}
}, 1000); // Poll every second
};
const stopMonitoringRun = () => {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
};
const handleRunUpdate = (update: Run) => {
setCurrentRun(update);
setRuns(prevRuns =>
prevRuns.map(run => run.id === update.id ? update : run)
);
};
// Cleanup on unmount
useEffect(() => {
return () => {
stopMonitoringRun();
};
}, []);
return {
backtest,
runs,
currentRun,
runResults,
isLoading,
error,
loadBacktest,
createBacktest,
updateBacktest,
deleteBacktest,
createRun,
pauseRun,
resumeRun,
cancelRun,
updateRunSpeed,
selectRun,
};
}
import { useCallback, useEffect, useRef, useState } from 'react';
import { defined } from '@stock-bot/invariants';
import { browserLog } from '@/utils/browserLog';
import { backtestApiV2 } from '../services/backtestApiV2';
import type { Backtest, CreateBacktestRequest, Run, RunResult } from '../services/backtestApiV2';
interface UseBacktestV2Return {
// State
backtest: Backtest | null;
runs: Run[];
currentRun: Run | null;
runResults: RunResult | null;
isLoading: boolean;
error: string | null;
// Actions
loadBacktest: (id: string) => Promise<void>;
createBacktest: (request: CreateBacktestRequest) => Promise<Backtest>;
updateBacktest: (id: string, updates: Partial<CreateBacktestRequest>) => Promise<void>;
deleteBacktest: (id: string) => Promise<void>;
createRun: (speedMultiplier?: number | null) => Promise<Run | undefined>;
pauseRun: () => Promise<void>;
resumeRun: () => Promise<void>;
cancelRun: () => Promise<void>;
updateRunSpeed: (speedMultiplier: number | null) => Promise<void>;
selectRun: (runId: string | undefined) => Promise<void>;
}
export function useBacktestV2(): UseBacktestV2Return {
const [backtest, setBacktest] = useState<Backtest | null>(null);
const [runs, setRuns] = useState<Run[]>([]);
const [currentRun, setCurrentRun] = useState<Run | null>(null);
const [runResults, setRunResults] = useState<RunResult | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const pollingIntervalRef = useRef<NodeJS.Timeout | null>(null);
// Load a specific backtest and its runs
const loadBacktest = useCallback(async (id: string) => {
setIsLoading(true);
setError(null);
try {
const [loadedBacktest, loadedRuns] = await Promise.all([
backtestApiV2.getBacktest(id),
backtestApiV2.listRuns(id),
]);
setBacktest(loadedBacktest);
setRuns(loadedRuns);
// Don't auto-select runs here - let the URL parameter drive the selection
} catch (err) {
browserLog.error('Failed to load backtest:', err);
setError(err instanceof Error ? err.message : 'Failed to load backtest');
} finally {
setIsLoading(false);
}
}, []);
// Create a new backtest
const createBacktest = useCallback(async (request: CreateBacktestRequest): Promise<Backtest> => {
setIsLoading(true);
setError(null);
try {
const newBacktest = await backtestApiV2.createBacktest(request);
setBacktest(newBacktest);
setRuns([]);
setCurrentRun(null);
setRunResults(null);
return newBacktest;
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create backtest');
throw err;
} finally {
setIsLoading(false);
}
}, []);
// Update backtest configuration
const updateBacktest = useCallback(
async (id: string, updates: Partial<CreateBacktestRequest>) => {
setIsLoading(true);
setError(null);
try {
const updatedBacktest = await backtestApiV2.updateBacktest(id, updates);
setBacktest(updatedBacktest);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update backtest');
throw err;
} finally {
setIsLoading(false);
}
},
[]
);
// Delete backtest
const deleteBacktest = useCallback(async (id: string) => {
setIsLoading(true);
setError(null);
try {
await backtestApiV2.deleteBacktest(id);
setBacktest(null);
setRuns([]);
setCurrentRun(null);
setRunResults(null);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete backtest');
throw err;
} finally {
setIsLoading(false);
}
}, []);
// Create a new run
const createRun = useCallback(
async (speedMultiplier?: number | null) => {
if (!backtest) {
return;
}
setIsLoading(true);
setError(null);
setRunResults(null);
try {
// Pass speedMultiplier as-is, null means max speed
const newRun = await backtestApiV2.createRun(backtest.id, {
speedMultiplier: speedMultiplier === undefined ? null : speedMultiplier,
});
// Add to runs array first
setRuns(prevRuns => [newRun, ...prevRuns]);
// Clear previous results immediately
setRunResults(null);
// Set as current run
setCurrentRun(newRun);
// Small delay to ensure the run is properly created in the database
await new Promise(resolve => setTimeout(resolve, 100));
// Check if the run is completed (it might complete instantly)
let finalRun = newRun;
// If status is pending, check again after a short delay
if (newRun.status === 'pending') {
await new Promise(resolve => setTimeout(resolve, 500));
try {
finalRun = await backtestApiV2.getRun(newRun.id);
// Update the current run with the latest status
setCurrentRun(finalRun);
setRuns(prevRuns => prevRuns.map(r => (r.id === finalRun.id ? finalRun : r)));
} catch (err) {
browserLog.error('Failed to re-check run status:', err);
}
}
// If the run is completed, load results
if (finalRun.status === 'completed') {
try {
const results = await backtestApiV2.getRunResults(finalRun.id);
setRunResults(results);
} catch (err) {
browserLog.error('Failed to load new run results:', err);
}
} else {
// Start monitoring the run
startMonitoringRun(finalRun.id);
}
return newRun; // Return the created run
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create run');
throw err; // Re-throw so caller knows it failed
} finally {
setIsLoading(false);
}
},
[backtest]
);
// Run control actions
const pauseRun = useCallback(async () => {
if (!currentRun || currentRun.status !== 'running') {
return;
}
try {
await backtestApiV2.pauseRun(currentRun.id);
setCurrentRun(prev => (prev ? { ...prev, status: 'paused' } : null));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to pause run');
}
}, [currentRun]);
const resumeRun = useCallback(async () => {
if (!currentRun || currentRun.status !== 'paused') {
return;
}
try {
await backtestApiV2.resumeRun(currentRun.id);
setCurrentRun(prev => (prev ? { ...prev, status: 'running' } : null));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to resume run');
}
}, [currentRun]);
const cancelRun = useCallback(async () => {
if (!currentRun || (currentRun.status !== 'running' && currentRun.status !== 'paused')) {
return;
}
try {
await backtestApiV2.cancelRun(currentRun.id);
setCurrentRun(prev => (prev ? { ...prev, status: 'cancelled' } : null));
stopMonitoringRun();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to cancel run');
}
}, [currentRun]);
const updateRunSpeed = useCallback(
async (speedMultiplier: number | null) => {
if (!currentRun) {
return;
}
try {
// Keep null as null for max speed (no limit)
const apiSpeed = speedMultiplier;
// Only call API if run is active
if (currentRun.status === 'running' || currentRun.status === 'paused') {
await backtestApiV2.updateRunSpeed(currentRun.id, apiSpeed);
}
// Always update local state so UI reflects the selection
setCurrentRun(prev => (prev ? { ...prev, speedMultiplier: apiSpeed } : null));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update run speed');
}
},
[currentRun]
);
// Select a specific run
const selectRun = useCallback(
async (runId: string | undefined) => {
if (!runId) {
setCurrentRun(null);
setRunResults(null);
stopMonitoringRun();
return;
}
let run = runs.find(r => r.id === runId);
// If run not found in list, try to fetch it directly
if (!run) {
let attempts = 0;
const maxAttempts = 3;
while (attempts < maxAttempts) {
try {
run = await backtestApiV2.getRun(runId);
// Add to runs list if not present
setRuns(prevRuns => {
const exists = prevRuns.some(r => r.id === defined(run).id);
if (!exists) {
return [defined(run), ...prevRuns];
}
return prevRuns;
});
break; // Success, exit loop
} catch (err) {
attempts++;
if (attempts >= maxAttempts) {
browserLog.error('Failed to fetch run after all attempts:', runId, err);
setError(`Failed to load run ${runId}`);
return;
}
// Wait before retrying
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
if (!run) {
setError(`Run ${runId} not found`);
return;
}
setCurrentRun(run);
setRunResults(null);
if (run.status === 'completed') {
try {
const results = await backtestApiV2.getRunResults(run.id);
setRunResults(results);
} catch (err) {
browserLog.error('Failed to load run results:', err);
setError(err instanceof Error ? err.message : 'Failed to load run results');
}
} else if (run.status === 'running' || run.status === 'paused' || run.status === 'pending') {
startMonitoringRun(run.id);
} else {
browserLog.warn('Run has unexpected status:', run.status);
}
},
[runs]
);
// Monitor run progress
const startMonitoringRun = useCallback((runId: string) => {
// Stop any existing monitoring
stopMonitoringRun();
// For pending runs, we need to poll until they start or complete
// We'll check the run status by fetching it
pollingIntervalRef.current = setInterval(async () => {
try {
const updatedRun = await backtestApiV2.getRun(runId);
// Update the run in state
setCurrentRun(updatedRun);
setRuns(prevRuns => prevRuns.map(r => (r.id === updatedRun.id ? updatedRun : r)));
// If run is no longer pending, handle the new status
if (updatedRun.status === 'completed') {
stopMonitoringRun();
try {
const results = await backtestApiV2.getRunResults(runId);
setRunResults(results);
} catch (err) {
browserLog.error('Failed to load completed run results:', err);
}
} else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') {
stopMonitoringRun();
}
} catch (err) {
browserLog.error('Failed to poll run status:', err);
}
}, 1000); // Poll every second
}, []);
const _startPollingRun = (runId: string) => {
pollingIntervalRef.current = setInterval(async () => {
try {
const updatedRun = await backtestApiV2.getRun(runId);
handleRunUpdate(updatedRun);
if (updatedRun.status === 'completed') {
const results = await backtestApiV2.getRunResults(runId);
setRunResults(results);
stopMonitoringRun();
} else if (updatedRun.status === 'failed' || updatedRun.status === 'cancelled') {
stopMonitoringRun();
}
} catch (err) {
browserLog.error('Failed to poll run status:', err);
}
}, 1000); // Poll every second
};
const stopMonitoringRun = () => {
if (pollingIntervalRef.current) {
clearInterval(pollingIntervalRef.current);
pollingIntervalRef.current = null;
}
};
const handleRunUpdate = (update: Run) => {
setCurrentRun(update);
setRuns(prevRuns => prevRuns.map(run => (run.id === update.id ? update : run)));
};
// Cleanup on unmount
useEffect(() => {
return () => {
stopMonitoringRun();
};
}, []);
return {
backtest,
runs,
currentRun,
runResults,
isLoading,
error,
loadBacktest,
createBacktest,
updateBacktest,
deleteBacktest,
createRun,
pauseRun,
resumeRun,
cancelRun,
updateRunSpeed,
selectRun,
};
}

View file

@ -1,232 +1,244 @@
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';
export interface Backtest {
id: string;
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config: Record<string, any>;
createdAt: string;
updatedAt: string;
}
export interface Run {
id: string;
backtestId: string;
runNumber: number;
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
speedMultiplier: number;
error?: string;
startedAt?: string;
completedAt?: string;
pausedAt?: string;
progress: number;
currentSimulationDate?: string;
createdAt: string;
updatedAt: string;
}
export interface CreateBacktestRequest {
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config?: Record<string, any>;
}
export interface CreateRunRequest {
speedMultiplier?: number | null;
}
export interface RunResult {
runId: string;
backtestId: string;
status: 'completed';
completedAt: string;
config: {
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
commission: number;
slippage: number;
dataFrequency: string;
};
metrics: any;
equity: any[];
ohlcData: Record<string, any[]>;
trades: any[];
positions: any;
analytics: any;
executionTime: number;
}
export const backtestApiV2 = {
// Backtest operations
async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
});
if (!response.ok) {
throw new Error(`Failed to create backtest: ${response.statusText}`);
}
return response.json();
},
async getBacktest(id: string): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`);
if (!response.ok) {
throw new Error(`Failed to get backtest: ${response.statusText}`);
}
return response.json();
},
async listBacktests(limit = 50, offset = 0): Promise<Backtest[]> {
const response = await fetch(
`${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}`
);
if (!response.ok) {
throw new Error(`Failed to list backtests: ${response.statusText}`);
}
return response.json();
},
async updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updates),
});
if (!response.ok) {
throw new Error(`Failed to update backtest: ${response.statusText}`);
}
return response.json();
},
async deleteBacktest(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error(`Failed to delete backtest: ${response.statusText}`);
}
},
// Run operations
async createRun(backtestId: string, request?: CreateRunRequest): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request || {}),
});
if (!response.ok) {
const errorText = await response.text();
console.error(`Failed to create run:`, response.status, errorText);
throw new Error(`Failed to create run: ${response.statusText}`);
}
return response.json();
},
async listRuns(backtestId: string): Promise<Run[]> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`);
if (!response.ok) {
throw new Error(`Failed to list runs: ${response.statusText}`);
}
return response.json();
},
async getRun(id: string): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`);
if (!response.ok) {
throw new Error(`Failed to get run: ${response.statusText}`);
}
return response.json();
},
async getRunResults(runId: string): Promise<RunResult> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`);
if (!response.ok) {
throw new Error(`Failed to get run results: ${response.status} ${response.statusText}`);
}
return response.json();
},
async pauseRun(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/pause`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to pause run: ${response.statusText}`);
}
},
async resumeRun(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/resume`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to resume run: ${response.statusText}`);
}
},
async cancelRun(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to cancel run: ${response.statusText}`);
}
},
async updateRunSpeed(id: string, speedMultiplier: number): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/speed`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ speedMultiplier }),
});
if (!response.ok) {
throw new Error(`Failed to update run speed: ${response.statusText}`);
}
},
// Note: WebSocket connections are handled by the useWebSocket hook
// which connects to ws://localhost:2003/ws?runId={runId}
};
import { browserLog } from '@/utils/browserLog';
import type { BacktestMetrics, Position, Trade } from '../types/backtest.types';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';
export interface Backtest {
id: string;
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config: Record<string, unknown>;
createdAt: string;
updatedAt: string;
}
export interface Run {
id: string;
backtestId: string;
runNumber: number;
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
speedMultiplier: number | null;
error?: string;
startedAt?: string;
completedAt?: string;
pausedAt?: string;
progress: number;
currentSimulationDate?: string;
createdAt: string;
updatedAt: string;
}
export interface CreateBacktestRequest {
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config?: Record<string, unknown>;
}
export interface CreateRunRequest {
speedMultiplier?: number | null;
}
export interface RunResult {
runId: string;
backtestId: string;
status: 'completed';
completedAt: string;
config: {
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
commission: number;
slippage: number;
dataFrequency: string;
};
metrics: BacktestMetrics;
equity: { date: string; value: number }[];
ohlcData: Record<
string,
{ timestamp: number; open: number; high: number; low: number; close: number; volume?: number }[]
>;
trades: Trade[];
positions: Position[] | Record<string, Omit<Position, 'symbol'>>;
analytics: {
exposureTime?: number;
drawdownSeries?: { timestamp: number; value: number }[];
dailyReturns?: number[];
monthlyReturns?: Record<string, number>;
riskMetrics?: Record<string, number>;
};
executionTime: number;
}
export const backtestApiV2 = {
// Backtest operations
async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
});
if (!response.ok) {
throw new Error(`Failed to create backtest: ${response.statusText}`);
}
return response.json();
},
async getBacktest(id: string): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`);
if (!response.ok) {
throw new Error(`Failed to get backtest: ${response.statusText}`);
}
return response.json();
},
async listBacktests(limit = 50, offset = 0): Promise<Backtest[]> {
const response = await fetch(
`${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}`
);
if (!response.ok) {
throw new Error(`Failed to list backtests: ${response.statusText}`);
}
return response.json();
},
async updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updates),
});
if (!response.ok) {
throw new Error(`Failed to update backtest: ${response.statusText}`);
}
return response.json();
},
async deleteBacktest(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error(`Failed to delete backtest: ${response.statusText}`);
}
},
// Run operations
async createRun(backtestId: string, request?: CreateRunRequest): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request || {}),
});
if (!response.ok) {
const errorText = await response.text();
browserLog.error(`Failed to create run:`, response.status, errorText);
throw new Error(`Failed to create run: ${response.statusText}`);
}
return response.json();
},
async listRuns(backtestId: string): Promise<Run[]> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`);
if (!response.ok) {
throw new Error(`Failed to list runs: ${response.statusText}`);
}
return response.json();
},
async getRun(id: string): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`);
if (!response.ok) {
throw new Error(`Failed to get run: ${response.statusText}`);
}
return response.json();
},
async getRunResults(runId: string): Promise<RunResult> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`);
if (!response.ok) {
throw new Error(`Failed to get run results: ${response.status} ${response.statusText}`);
}
return response.json();
},
async pauseRun(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/pause`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to pause run: ${response.statusText}`);
}
},
async resumeRun(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/resume`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to resume run: ${response.statusText}`);
}
},
async cancelRun(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to cancel run: ${response.statusText}`);
}
},
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/speed`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ speedMultiplier }),
});
if (!response.ok) {
throw new Error(`Failed to update run speed: ${response.statusText}`);
}
},
// Note: WebSocket connections are handled by the useWebSocket hook
// which connects to ws://localhost:2003/ws?runId={runId}
};

View file

@ -1,89 +1,103 @@
export type BacktestStatus =
| 'idle'
| 'configured'
| 'running'
| 'paused'
| 'stopped'
| 'completed'
| 'error';
export interface BacktestConfig {
name: string;
startDate: Date;
endDate: Date;
initialCapital: number;
symbols: string[];
strategy: string;
speedMultiplier: number;
commission: number;
slippage: number;
}
export interface BacktestMetrics {
totalReturn: number;
sharpeRatio: number;
maxDrawdown: number;
winRate: number;
totalTrades: number;
profitableTrades: number;
}
export interface Position {
symbol: string;
quantity: number;
averagePrice: number;
currentPrice: number;
realizedPnl: number;
unrealizedPnl: number;
lastUpdate: string;
}
export interface Trade {
id: string;
timestamp: string;
symbol: string;
side: 'buy' | 'sell';
quantity: number;
price: number;
commission: number;
pnl?: number;
positionAfter: number; // Position size after this trade
}
export interface PerformanceDataPoint {
timestamp: string;
portfolioValue: number;
pnl: number;
drawdown: number;
}
export interface BacktestResult {
id: string;
config: BacktestConfig;
metrics: BacktestMetrics;
positions: Position[];
trades: Trade[];
performanceData: PerformanceDataPoint[];
}
export interface OrderBookLevel {
price: number;
size: number;
orderCount?: number;
}
export interface OrderBookSnapshot {
symbol: string;
timestamp: string;
bids: OrderBookLevel[];
asks: OrderBookLevel[];
}
export interface RiskMetrics {
currentExposure: number;
dailyPnl: number;
positionCount: number;
grossExposure: number;
maxPositionSize: number;
utilizationPct: number;
}
export type BacktestStatus =
| 'idle'
| 'configured'
| 'running'
| 'paused'
| 'stopped'
| 'completed'
| 'error';
export interface BacktestConfig {
name: string;
startDate: Date;
endDate: Date;
initialCapital: number;
symbols: string[];
strategy: string;
speedMultiplier: number;
commission: number;
slippage: number;
}
export interface BacktestMetrics {
totalReturn: number;
sharpeRatio: number;
maxDrawdown: number;
winRate: number;
totalTrades: number;
profitableTrades: number;
profitFactor?: number;
totalProfit?: number;
avgWin?: number;
avgLoss?: number;
expectancy?: number;
calmarRatio?: number;
sortinoRatio?: number;
}
export interface Position {
symbol: string;
quantity: number;
averagePrice: number;
currentPrice: number;
realizedPnl: number;
unrealizedPnl: number;
lastUpdate?: string;
avgPrice?: number;
lastPrice?: number;
}
export interface Trade {
id: string;
timestamp: string;
symbol: string;
side: 'buy' | 'sell';
quantity: number;
price: number;
commission: number;
pnl?: number;
entryDate?: string;
entryPrice?: number;
date?: string;
realizedPnl?: number;
positionAfter: number; // Position size after this trade
}
export interface PerformanceDataPoint {
timestamp: string;
portfolioValue: number;
pnl: number;
drawdown: number;
}
export interface BacktestResult {
id: string;
config: BacktestConfig;
metrics: BacktestMetrics;
positions: Position[];
trades: Trade[];
performanceData: PerformanceDataPoint[];
analytics?: { exposureTime?: number };
}
export interface OrderBookLevel {
price: number;
size: number;
orderCount?: number;
}
export interface OrderBookSnapshot {
symbol: string;
timestamp: string;
bids: OrderBookLevel[];
asks: OrderBookLevel[];
}
export interface RiskMetrics {
currentExposure: number;
dailyPnl: number;
positionCount: number;
grossExposure: number;
maxPositionSize: number;
utilizationPct: number;
}