266 lines
9.1 KiB
TypeScript
266 lines
9.1 KiB
TypeScript
import { XMarkIcon } from '@heroicons/react/24/solid';
|
|
import { useEffect, useRef, useState } from 'react';
|
|
import {
|
|
StrategySelection,
|
|
type CatalogSelection,
|
|
} from '@/features/strategies/components/StrategySelection';
|
|
import {
|
|
confirmDiscard,
|
|
useUnsavedWarning,
|
|
} from '@/features/strategies/components/useUnsavedWarning';
|
|
import { backtestApiV2, type Backtest } from '../services/backtestApiV2';
|
|
import type { HistoricalSelection } from '../services/historical-selection';
|
|
import { HistoricalDataSelection } from './HistoricalDataSelection';
|
|
|
|
interface CreateBacktestDialogProps {
|
|
initialSelection?: CatalogSelection;
|
|
onClose: () => void;
|
|
onCreated: (backtest: Backtest) => void;
|
|
}
|
|
|
|
export function CreateBacktestDialog({
|
|
onClose,
|
|
onCreated,
|
|
initialSelection,
|
|
}: CreateBacktestDialogProps) {
|
|
const [formData, setFormData] = useState<
|
|
HistoricalSelection & {
|
|
name: string;
|
|
initialCapital: number;
|
|
commission: number;
|
|
slippage: number;
|
|
}
|
|
>({
|
|
name: '',
|
|
symbols: ['AAPL.US'],
|
|
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,
|
|
priceAdjustment: 'raw',
|
|
dataFrequency: '1d',
|
|
dataSource: 'auto',
|
|
});
|
|
|
|
const [selection, setSelection] = useState<CatalogSelection>(initialSelection ?? {});
|
|
const [strategyValid, setStrategyValid] = useState(false);
|
|
const [edited, setEdited] = useState(false);
|
|
useUnsavedWarning(edited);
|
|
const [historicalValid, setHistoricalValid] = useState(true);
|
|
const [phase, setPhase] = useState<'idle' | 'saving'>('idle');
|
|
const isSubmitting = phase !== 'idle';
|
|
const [error, setError] = useState<string | null>(null);
|
|
const pending = useRef(false);
|
|
const active = useRef(true);
|
|
|
|
useEffect(() => {
|
|
active.current = true;
|
|
return () => {
|
|
active.current = false;
|
|
};
|
|
}, []);
|
|
|
|
const close = () => {
|
|
// A list refresh before this write settles could miss the newly saved row.
|
|
if (pending.current) {
|
|
return;
|
|
}
|
|
if (!confirmDiscard(edited)) {
|
|
return;
|
|
}
|
|
active.current = false;
|
|
onClose();
|
|
};
|
|
|
|
const handleSubmit = async () => {
|
|
if (pending.current || !active.current || !historicalValid || !strategyValid) {
|
|
return;
|
|
}
|
|
|
|
if (!formData.name.trim()) {
|
|
setError('Please enter a backtest name');
|
|
return;
|
|
}
|
|
|
|
pending.current = true;
|
|
setPhase('saving');
|
|
setError(null);
|
|
try {
|
|
const created = await backtestApiV2.createBacktest({
|
|
name: formData.name,
|
|
strategy: 'catalog',
|
|
...selection,
|
|
symbols: formData.symbols,
|
|
startDate: formData.startDate,
|
|
endDate: formData.endDate,
|
|
initialCapital: formData.initialCapital,
|
|
config: {
|
|
commission: formData.commission,
|
|
slippage: formData.slippage,
|
|
dataFrequency: formData.dataFrequency,
|
|
dataSource: formData.dataSource,
|
|
datasetHash: formData.datasetHash,
|
|
dataPolicy: {
|
|
adjustment: formData.priceAdjustment ?? 'raw',
|
|
timestamp: formData.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant',
|
|
},
|
|
},
|
|
});
|
|
if (active.current) {
|
|
onCreated(created);
|
|
}
|
|
} catch (err) {
|
|
if (active.current) {
|
|
const detail = err instanceof Error ? err.message : 'Please try again.';
|
|
setError(`Failed to save backtest. ${detail}`);
|
|
}
|
|
} finally {
|
|
pending.current = false;
|
|
if (active.current) {
|
|
setPhase('idle');
|
|
}
|
|
}
|
|
};
|
|
|
|
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={close}
|
|
disabled={phase === 'saving'}
|
|
aria-label="Close backtest dialog"
|
|
className="p-1 hover:bg-surface-tertiary rounded transition-colors"
|
|
>
|
|
<XMarkIcon className="w-5 h-5 text-text-secondary" />
|
|
</button>
|
|
</div>
|
|
|
|
{error && (
|
|
<p role="alert" className="mb-4 text-sm text-error">
|
|
{error}
|
|
</p>
|
|
)}
|
|
<form
|
|
onSubmit={e => {
|
|
e.preventDefault();
|
|
void handleSubmit();
|
|
}}
|
|
className="space-y-6"
|
|
onChange={() => setEdited(true)}
|
|
>
|
|
<fieldset disabled={isSubmitting} 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>
|
|
|
|
<p className="text-sm text-text-secondary">
|
|
Select an immutable strategy version. After saving, configure a retained dataset and
|
|
financial policies before running a canonical backtest.
|
|
</p>
|
|
<StrategySelection
|
|
value={selection}
|
|
onChange={setSelection}
|
|
onValidityChange={setStrategyValid}
|
|
disabled={isSubmitting}
|
|
/>
|
|
|
|
<HistoricalDataSelection
|
|
value={formData}
|
|
onChange={selection => setFormData(previous => ({ ...previous, ...selection }))}
|
|
onValidityChange={setHistoricalValid}
|
|
disabled={isSubmitting}
|
|
/>
|
|
|
|
<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>
|
|
</fieldset>
|
|
<div className="flex justify-end gap-3 pt-4">
|
|
<button
|
|
type="button"
|
|
onClick={close}
|
|
disabled={phase === 'saving'}
|
|
className="px-4 py-2 border border-border text-text-secondary rounded-md text-sm font-medium hover:bg-surface-tertiary transition-colors"
|
|
>
|
|
Close
|
|
</button>
|
|
<button
|
|
type="submit"
|
|
disabled={isSubmitting || !historicalValid || !strategyValid}
|
|
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
|
>
|
|
{isSubmitting ? 'Saving...' : 'Save'}
|
|
</button>
|
|
<button
|
|
type="button"
|
|
disabled
|
|
title="Save first, then configure the retained dataset and financial policies."
|
|
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium opacity-50"
|
|
>
|
|
Save and run
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|