feat(backtests): separate saving from retry-safe run submission
This commit is contained in:
parent
5eb0985057
commit
9b9403e36b
18 changed files with 1200 additions and 226 deletions
|
|
@ -53,7 +53,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '10-durable-backtest-dispatch.sql' ||
|
||||
f === '11-simulation-execution-ledger.sql' ||
|
||||
f === '12-historical-datasets.sql' ||
|
||||
f === '13-strategy-recovery.sql')
|
||||
f === '13-strategy-recovery.sql' ||
|
||||
f === '14-backtest-submission.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import { Hono } from 'hono';
|
||||
import { getVerifiedHttpPrincipal } from '@stock-bot/di';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { isBacktestRequestError } from '@stock-bot/stock-config/backtest';
|
||||
import { BacktestServiceV2 } from '../services/backtest-v2.service';
|
||||
import { BacktestServiceV2, RunSubmissionConflictError } from '../services/backtest-v2.service';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
||||
|
|
@ -40,7 +41,11 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
app.post('/api/v2/backtests', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const backtest = await backtestService.createBacktest(body);
|
||||
if (body.autoStart !== undefined && typeof body.autoStart !== 'boolean') {
|
||||
return c.json({ error: 'autoStart must be a boolean' }, 400);
|
||||
}
|
||||
// Omitted autoStart preserves legacy clients. New web clients explicitly save only.
|
||||
const backtest = await backtestService.createBacktest(body, { autoStart: body.autoStart });
|
||||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', error);
|
||||
|
|
@ -91,15 +96,29 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
|
||||
app.post('/api/v2/backtests/:backtestId/runs', async c => {
|
||||
try {
|
||||
const key = c.req.header('Idempotency-Key');
|
||||
const principal = getVerifiedHttpPrincipal(c.req.raw);
|
||||
if (key !== undefined && !principal) {
|
||||
return c.json({ error: 'Verified submission principal required' }, 401);
|
||||
}
|
||||
if (key !== undefined && !/^[\x21-\x7e]{1,200}$/.test(key)) {
|
||||
return c.json(
|
||||
{ error: 'Idempotency-Key must contain 1–200 visible ASCII characters' },
|
||||
400
|
||||
);
|
||||
}
|
||||
const body = await c.req.json();
|
||||
const run = await backtestService.createRun({
|
||||
backtestId: c.req.param('backtestId'),
|
||||
speedMultiplier: body.speedMultiplier,
|
||||
});
|
||||
const run = await backtestService.createRun(
|
||||
{ backtestId: c.req.param('backtestId'), speedMultiplier: body.speedMultiplier },
|
||||
key !== undefined && principal ? { principal, key } : undefined
|
||||
);
|
||||
c.header('Location', `/api/v2/runs/${run.id}`);
|
||||
return c.json(run, 202);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
if (error instanceof RunSubmissionConflictError) {
|
||||
return c.json({ error: error.message }, 409);
|
||||
}
|
||||
if (isBacktestRequestError(error)) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ export function createRoutes(
|
|||
cors({
|
||||
origin: security.allowedOrigins,
|
||||
allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
allowHeaders: ['Content-Type', 'Authorization'],
|
||||
allowHeaders: ['Content-Type', 'Authorization', 'Idempotency-Key'],
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { randomUUID as uuidv4 } from 'node:crypto';
|
||||
import { createHash, randomUUID as uuidv4 } from 'node:crypto';
|
||||
import type { QueryResultRow } from 'pg';
|
||||
import { authenticatedServiceFetch } from '@stock-bot/di';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
|
|
@ -6,6 +6,7 @@ import { getLogger } from '@stock-bot/logger';
|
|||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import { backtestRequestFromDefinition } from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||
|
|
@ -63,6 +64,18 @@ export interface RunRequest {
|
|||
speedMultiplier?: number | null;
|
||||
}
|
||||
|
||||
export interface RunSubmission {
|
||||
principal: 'operator' | 'service';
|
||||
key: string;
|
||||
}
|
||||
|
||||
export class RunSubmissionConflictError extends Error {
|
||||
constructor() {
|
||||
super('This submission key was already used for a different run request');
|
||||
this.name = 'RunSubmissionConflictError';
|
||||
}
|
||||
}
|
||||
|
||||
export class BacktestServiceV2 {
|
||||
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
|
||||
private wsHandler: WebSocketHandler | null = null;
|
||||
|
|
@ -208,17 +221,55 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
// Run operations
|
||||
async createRun(request: RunRequest): Promise<Run> {
|
||||
async createRun(request: RunRequest, submission?: RunSubmission): Promise<Run> {
|
||||
const runId = uuidv4();
|
||||
const multiplier = request.speedMultiplier ?? null;
|
||||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||
throw new HistoricalDataRequestError('Speed multiplier must be positive or null');
|
||||
}
|
||||
// Hash submission intent, not the mutable definition or newly generated run ID.
|
||||
// A retry after an edit must still return the original run and its frozen snapshot.
|
||||
const submissionHash = submission
|
||||
? createHash('sha256')
|
||||
.update(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
backtestId: request.backtestId,
|
||||
speedMultiplier: multiplier,
|
||||
})
|
||||
)
|
||||
.digest('hex')
|
||||
: null;
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const replay = async () => {
|
||||
if (!submission) {
|
||||
return undefined;
|
||||
}
|
||||
const existing = await client.query(
|
||||
'SELECT * FROM runs WHERE submission_principal = $1 AND submission_key = $2',
|
||||
[submission.principal, submission.key]
|
||||
);
|
||||
const saved = existing.rows[0];
|
||||
if (saved && saved.submission_hash !== submissionHash) {
|
||||
throw new RunSubmissionConflictError();
|
||||
}
|
||||
return saved;
|
||||
};
|
||||
const previous = await replay();
|
||||
if (previous) {
|
||||
return previous;
|
||||
}
|
||||
const parent = await client.query('SELECT * FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
request.backtestId,
|
||||
]);
|
||||
if (!parent.rows.length) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
const concurrent = await replay();
|
||||
if (concurrent) {
|
||||
return concurrent;
|
||||
}
|
||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||
const multiplier = request.speedMultiplier ?? null;
|
||||
const snapshot = backtestRequestFromDefinition(definition, {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
|
|
@ -226,11 +277,31 @@ export class BacktestServiceV2 {
|
|||
});
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb
|
||||
FROM runs WHERE backtest_id = $2 RETURNING *`,
|
||||
[runId, request.backtestId, multiplier, JSON.stringify(snapshot)]
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot,
|
||||
submission_principal, submission_key, submission_hash)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb, $5, $6, $7
|
||||
FROM runs WHERE backtest_id = $2
|
||||
${submission ? 'ON CONFLICT (submission_principal, submission_key) DO NOTHING' : ''}
|
||||
RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
request.backtestId,
|
||||
multiplier,
|
||||
JSON.stringify(snapshot),
|
||||
submission?.principal ?? null,
|
||||
submission?.key ?? null,
|
||||
submissionHash,
|
||||
]
|
||||
);
|
||||
// Different parent locks can race for one principal/key. The unique index waits for
|
||||
// the winner's transaction; this next READ COMMITTED query sees its committed row.
|
||||
if (!result.rows.length) {
|
||||
const winner = await replay();
|
||||
if (!winner) {
|
||||
throw new Error('Concurrent submission disappeared; retry with the same key');
|
||||
}
|
||||
return winner;
|
||||
}
|
||||
await client.query('INSERT INTO backtest_dispatch (run_id) VALUES ($1)', [runId]);
|
||||
return at(result.rows, 0);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useWebSocket } from '@/hooks/useWebSocket';
|
||||
import { BacktestConfiguration } from './components/BacktestConfiguration';
|
||||
|
|
@ -25,6 +25,7 @@ export function BacktestDetailPageV2() {
|
|||
const navigate = useNavigate();
|
||||
const [activeTab, setActiveTab] = useState('details');
|
||||
const [showNewRun, setShowNewRun] = useState(false);
|
||||
const navigationGeneration = useRef(0);
|
||||
|
||||
const {
|
||||
backtest,
|
||||
|
|
@ -33,6 +34,9 @@ export function BacktestDetailPageV2() {
|
|||
runResults,
|
||||
isLoading,
|
||||
error,
|
||||
submissionError,
|
||||
isSubmitting,
|
||||
hasPendingSubmission,
|
||||
loadBacktest,
|
||||
updateBacktest,
|
||||
createRun,
|
||||
|
|
@ -55,6 +59,14 @@ export function BacktestDetailPageV2() {
|
|||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
navigationGeneration.current++;
|
||||
setShowNewRun(false);
|
||||
return () => {
|
||||
navigationGeneration.current++;
|
||||
};
|
||||
}, [id, runId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (id) {
|
||||
void loadBacktest(id);
|
||||
|
|
@ -101,10 +113,10 @@ export function BacktestDetailPageV2() {
|
|||
|
||||
// Handle new run creation
|
||||
const handleCreateRun = useCallback(async () => {
|
||||
const generation = navigationGeneration.current;
|
||||
const newRun = await createRun(null);
|
||||
setShowNewRun(false);
|
||||
// Navigate to the new run
|
||||
if (newRun && id) {
|
||||
if (newRun && id && generation === navigationGeneration.current) {
|
||||
setShowNewRun(false);
|
||||
navigate(`/backtests/${id}/run/${newRun.id}`);
|
||||
}
|
||||
}, [createRun, navigate, id]);
|
||||
|
|
@ -112,11 +124,9 @@ export function BacktestDetailPageV2() {
|
|||
// Handle rerun
|
||||
const handleRerun = useCallback(
|
||||
async (speedMultiplier: number | null) => {
|
||||
// Pass null for max speed (no limit)
|
||||
const generation = navigationGeneration.current;
|
||||
const newRun = await createRun(speedMultiplier);
|
||||
|
||||
// Navigate to the new run's URL
|
||||
if (newRun && id) {
|
||||
if (newRun && id && generation === navigationGeneration.current) {
|
||||
navigate(`/backtests/${id}/run/${newRun.id}`);
|
||||
}
|
||||
},
|
||||
|
|
@ -217,21 +227,30 @@ export function BacktestDetailPageV2() {
|
|||
|
||||
{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>
|
||||
<h4 className="text-base font-medium text-text-primary">Run current settings</h4>
|
||||
<p className="text-sm text-text-secondary">
|
||||
This will start a new backtest run with the current configuration.
|
||||
Submit the current configuration, not a reproduction of a previous run. A retry
|
||||
recovers the original submission if it was already accepted.
|
||||
</p>
|
||||
<div className="flex space-x-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
void handleCreateRun();
|
||||
}}
|
||||
disabled={isSubmitting}
|
||||
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
Start Run
|
||||
{isSubmitting
|
||||
? 'Submitting...'
|
||||
: hasPendingSubmission
|
||||
? 'Retry submission'
|
||||
: 'Run current settings'}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowNewRun(false)}
|
||||
onClick={() => {
|
||||
navigationGeneration.current++;
|
||||
setShowNewRun(false);
|
||||
}}
|
||||
className="px-4 py-2 bg-surface-tertiary text-text-primary rounded-md text-sm font-medium hover:bg-surface-secondary transition-colors"
|
||||
>
|
||||
Cancel
|
||||
|
|
@ -365,6 +384,8 @@ export function BacktestDetailPageV2() {
|
|||
onCancel={cancelRun}
|
||||
cancelRequested={cancelRequested}
|
||||
onRerun={handleRerun}
|
||||
isSubmitting={isSubmitting}
|
||||
hasPendingSubmission={hasPendingSubmission}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -373,6 +394,22 @@ export function BacktestDetailPageV2() {
|
|||
|
||||
{/* Tab Content */}
|
||||
<div className="flex-1 overflow-hidden py-4">
|
||||
{submissionError && (
|
||||
<div className="mb-4 p-4 bg-error/10 border border-error/20 rounded-lg">
|
||||
<p role="alert" className="text-sm text-error">
|
||||
Run submission failed: {submissionError}. Retry to recover the same submission.
|
||||
</p>
|
||||
{!showNewRun && (
|
||||
<button
|
||||
disabled={isSubmitting}
|
||||
className="mt-2 text-primary-500"
|
||||
onClick={() => void handleCreateRun()}
|
||||
>
|
||||
Retry submission
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<div className="mb-4 p-4 bg-error/10 border border-error/20 rounded-lg">
|
||||
<p role="alert" className="text-sm text-error">
|
||||
|
|
|
|||
|
|
@ -32,18 +32,6 @@ export function BacktestListPageV2() {
|
|||
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',
|
||||
|
|
@ -134,8 +122,14 @@ export function BacktestListPageV2() {
|
|||
|
||||
{showCreateDialog && (
|
||||
<CreateBacktestDialog
|
||||
onClose={() => setShowCreateDialog(false)}
|
||||
onCreate={handleCreateBacktest}
|
||||
onClose={() => {
|
||||
setShowCreateDialog(false);
|
||||
void loadBacktests();
|
||||
}}
|
||||
onCreated={(created, run) => {
|
||||
setShowCreateDialog(false);
|
||||
navigate(`/backtests/${created.id}${run ? `/run/${run.id}` : ''}`);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
import { XMarkIcon } from '@heroicons/react/24/solid';
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { parseInstrumentId } from '@stock-bot/types';
|
||||
import type { Backtest } from '../services/backtestApiV2';
|
||||
import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2';
|
||||
|
||||
interface CreateBacktestDialogProps {
|
||||
onClose: () => void;
|
||||
onCreate: (config: Omit<Backtest, 'id' | 'createdAt' | 'updatedAt'>) => void;
|
||||
onCreated: (backtest: Backtest, run?: Run) => void;
|
||||
}
|
||||
|
||||
export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialogProps) {
|
||||
export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialogProps) {
|
||||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
strategy: 'moving-average',
|
||||
|
|
@ -22,23 +22,91 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog
|
|||
});
|
||||
|
||||
const [symbolInput, setSymbolInput] = useState('');
|
||||
const [phase, setPhase] = useState<'idle' | 'saving' | 'submitting'>('idle');
|
||||
const isSubmitting = phase !== 'idle';
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const saved = useRef<Backtest | null>(null);
|
||||
const submission = useRef<{ key: string; body: { speedMultiplier: null } } | null>(null);
|
||||
const pending = useRef(false);
|
||||
const active = useRef(true);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
useEffect(() => {
|
||||
active.current = true;
|
||||
return () => {
|
||||
active.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!formData.name.trim()) {
|
||||
alert('Please enter a backtest name');
|
||||
const close = () => {
|
||||
// A list refresh before this write settles could miss the newly saved row.
|
||||
if (pending.current && !saved.current) {
|
||||
return;
|
||||
}
|
||||
active.current = false;
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleSubmit = async (runAfterSave: boolean) => {
|
||||
if (pending.current || !active.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
onCreate({
|
||||
...formData,
|
||||
config: {
|
||||
commission: formData.commission,
|
||||
slippage: formData.slippage,
|
||||
dataPolicy: { adjustment: formData.priceAdjustment, timestamp: 'utc-session-date' },
|
||||
},
|
||||
});
|
||||
if (!formData.name.trim()) {
|
||||
setError('Please enter a backtest name');
|
||||
return;
|
||||
}
|
||||
|
||||
pending.current = true;
|
||||
setPhase(saved.current ? 'submitting' : 'saving');
|
||||
setError(null);
|
||||
try {
|
||||
if (!saved.current) {
|
||||
const created = await backtestApiV2.createBacktest({
|
||||
name: formData.name,
|
||||
strategy: formData.strategy,
|
||||
symbols: formData.symbols,
|
||||
startDate: formData.startDate,
|
||||
endDate: formData.endDate,
|
||||
initialCapital: formData.initialCapital,
|
||||
config: {
|
||||
commission: formData.commission,
|
||||
slippage: formData.slippage,
|
||||
dataPolicy: { adjustment: formData.priceAdjustment, timestamp: 'utc-session-date' },
|
||||
},
|
||||
});
|
||||
if (!active.current) {
|
||||
return;
|
||||
}
|
||||
saved.current = created;
|
||||
}
|
||||
let run: Run | undefined;
|
||||
if (runAfterSave) {
|
||||
setPhase('submitting');
|
||||
submission.current ??= { key: crypto.randomUUID(), body: { speedMultiplier: null } };
|
||||
run = await backtestApiV2.createRun(
|
||||
saved.current.id,
|
||||
submission.current.body,
|
||||
submission.current.key
|
||||
);
|
||||
}
|
||||
if (active.current) {
|
||||
onCreated(saved.current, run);
|
||||
}
|
||||
} catch (err) {
|
||||
if (active.current) {
|
||||
const detail = err instanceof Error ? err.message : 'Please try again.';
|
||||
setError(
|
||||
saved.current
|
||||
? `Backtest saved, but run submission failed. Retry submission to recover the same run. ${detail}`
|
||||
: `Failed to save backtest. ${detail}`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
pending.current = false;
|
||||
if (active.current) {
|
||||
setPhase('idle');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const addSymbol = () => {
|
||||
|
|
@ -68,192 +136,228 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog
|
|||
<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}
|
||||
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>
|
||||
|
||||
<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">
|
||||
{error && (
|
||||
<p role="alert" className="mb-4 text-sm text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<form
|
||||
onSubmit={e => {
|
||||
e.preventDefault();
|
||||
void handleSubmit(saved.current !== null);
|
||||
}}
|
||||
className="space-y-6"
|
||||
>
|
||||
<fieldset disabled={isSubmitting || saved.current !== null} className="space-y-6">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Backtest Name
|
||||
</label>
|
||||
<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="Instrument ID (e.g., AAPL.US)"
|
||||
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
|
||||
/>
|
||||
<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"
|
||||
</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"
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
<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 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"
|
||||
|
||||
<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="Instrument ID (e.g., AAPL.US)"
|
||||
/>
|
||||
<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"
|
||||
>
|
||||
{symbol}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeSymbol(symbol)}
|
||||
className="hover:text-error 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"
|
||||
>
|
||||
<XMarkIcon className="w-4 h-4" />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
{symbol}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeSymbol(symbol)}
|
||||
className="hover:text-error transition-colors"
|
||||
>
|
||||
<XMarkIcon className="w-4 h-4" />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Historical prices
|
||||
</label>
|
||||
<select
|
||||
value={formData.priceAdjustment}
|
||||
onChange={e =>
|
||||
setFormData({
|
||||
...formData,
|
||||
priceAdjustment:
|
||||
e.target.value === 'provider-adjusted' ? 'provider-adjusted' : 'raw',
|
||||
})
|
||||
}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary"
|
||||
>
|
||||
<option value="raw">Raw prices (no corporate-action adjustment)</option>
|
||||
<option value="provider-adjusted">
|
||||
Provider adjusted (splits/dividends; reported volume)
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Start Date
|
||||
Historical prices
|
||||
</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
|
||||
/>
|
||||
<select
|
||||
value={formData.priceAdjustment}
|
||||
onChange={e =>
|
||||
setFormData({
|
||||
...formData,
|
||||
priceAdjustment:
|
||||
e.target.value === 'provider-adjusted' ? 'provider-adjusted' : 'raw',
|
||||
})
|
||||
}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary"
|
||||
>
|
||||
<option value="raw">Raw prices (no corporate-action adjustment)</option>
|
||||
<option value="provider-adjusted">
|
||||
Provider adjusted (splits/dividends; reported volume)
|
||||
</option>
|
||||
</select>
|
||||
</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 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>
|
||||
|
||||
<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)
|
||||
Initial Capital
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.commission}
|
||||
value={formData.initialCapital}
|
||||
onChange={e =>
|
||||
setFormData({ ...formData, commission: parseFloat(e.target.value) || 0 })
|
||||
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="0.01"
|
||||
step="1000"
|
||||
required
|
||||
/>
|
||||
</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="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={onClose}
|
||||
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"
|
||||
>
|
||||
Cancel
|
||||
Close
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
Create Backtest
|
||||
{isSubmitting
|
||||
? 'Saving / submitting...'
|
||||
: saved.current
|
||||
? 'Retry submission'
|
||||
: 'Save'}
|
||||
</button>
|
||||
{!saved.current && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isSubmitting}
|
||||
onClick={e => {
|
||||
if (e.currentTarget.form?.reportValidity()) {
|
||||
void handleSubmit(true);
|
||||
}
|
||||
}}
|
||||
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors disabled:opacity-50"
|
||||
>
|
||||
Save and run
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ interface RunControlsCompactProps {
|
|||
cancelRequested: boolean;
|
||||
onCancel: () => void;
|
||||
onRerun: (speed: number | null) => void;
|
||||
isSubmitting?: boolean;
|
||||
hasPendingSubmission?: boolean;
|
||||
}
|
||||
|
||||
export function RunControlsCompact({
|
||||
|
|
@ -13,6 +15,8 @@ export function RunControlsCompact({
|
|||
cancelRequested,
|
||||
onCancel,
|
||||
onRerun,
|
||||
isSubmitting = false,
|
||||
hasPendingSubmission = false,
|
||||
}: RunControlsCompactProps) {
|
||||
const active = ['pending', 'running', 'paused'].includes(run.status);
|
||||
const requested = active && (cancelRequested || run.cancelRequested);
|
||||
|
|
@ -38,9 +42,10 @@ export function RunControlsCompact({
|
|||
)}
|
||||
<button
|
||||
onClick={() => onRerun(null)}
|
||||
className="p-1 rounded hover:bg-surface-tertiary transition-colors"
|
||||
title="Rerun"
|
||||
aria-label="Rerun"
|
||||
disabled={isSubmitting}
|
||||
className="p-1 rounded hover:bg-surface-tertiary transition-colors disabled:opacity-50"
|
||||
title={hasPendingSubmission ? 'Retry submission' : 'Run current settings'}
|
||||
aria-label={hasPendingSubmission ? 'Retry submission' : 'Run current settings'}
|
||||
>
|
||||
<ArrowPathIcon className="w-4 h-4 text-text-primary" />
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -24,9 +24,21 @@ export function useBacktestV2() {
|
|||
const [isRunLoading, setIsRunLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [runError, setRunError] = useState<string | null>(null);
|
||||
const [submissionError, setSubmissionError] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [cancelRequested, setCancelRequested] = useState(false);
|
||||
const mounted = useRef(true);
|
||||
const backtestGeneration = useRef(0);
|
||||
const loadedBacktestId = useRef<string | null>(null);
|
||||
const selectionGeneration = useRef(0);
|
||||
// The intent survives an ambiguous response and configuration edits. Only an
|
||||
// acknowledged submission (or leaving this definition) releases its key.
|
||||
const submission = useRef<{
|
||||
backtestId: string;
|
||||
key: string;
|
||||
body: { speedMultiplier: number | null };
|
||||
pending: boolean;
|
||||
} | null>(null);
|
||||
const selection = useRef<RunSelection | null>(null);
|
||||
const cancellation = useRef<RunSelection | null>(null);
|
||||
|
||||
|
|
@ -36,6 +48,7 @@ export function useBacktestV2() {
|
|||
);
|
||||
|
||||
const stopMonitoring = useCallback(() => {
|
||||
selectionGeneration.current++;
|
||||
const selected = selection.current;
|
||||
selection.current = null;
|
||||
cancellation.current = null;
|
||||
|
|
@ -165,6 +178,12 @@ export function useBacktestV2() {
|
|||
|
||||
const loadBacktest = useCallback(async (id: string) => {
|
||||
const generation = ++backtestGeneration.current;
|
||||
if (loadedBacktestId.current !== id) {
|
||||
submission.current = null;
|
||||
setSubmissionError(null);
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
loadedBacktestId.current = id;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
setBacktest(null);
|
||||
|
|
@ -205,6 +224,10 @@ export function useBacktestV2() {
|
|||
try {
|
||||
const created = await backtestApiV2.createBacktest(request);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
loadedBacktestId.current = created.id;
|
||||
submission.current = null;
|
||||
setSubmissionError(null);
|
||||
setIsSubmitting(false);
|
||||
setBacktest(created);
|
||||
setRuns([]);
|
||||
await selectRun(undefined);
|
||||
|
|
@ -256,6 +279,10 @@ export function useBacktestV2() {
|
|||
try {
|
||||
await backtestApiV2.deleteBacktest(id);
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
loadedBacktestId.current = null;
|
||||
submission.current = null;
|
||||
setSubmissionError(null);
|
||||
setIsSubmitting(false);
|
||||
setBacktest(null);
|
||||
setRuns([]);
|
||||
await selectRun(undefined);
|
||||
|
|
@ -276,29 +303,44 @@ export function useBacktestV2() {
|
|||
|
||||
const createRun = useCallback(
|
||||
async (speedMultiplier: number | null = null) => {
|
||||
if (!backtest) {
|
||||
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
|
||||
return undefined;
|
||||
}
|
||||
const generation = backtestGeneration.current;
|
||||
const selected = selection.current;
|
||||
setIsBacktestLoading(true);
|
||||
setError(null);
|
||||
const intent = (submission.current ??= {
|
||||
backtestId: backtest.id,
|
||||
key: crypto.randomUUID(),
|
||||
body: { speedMultiplier },
|
||||
pending: false,
|
||||
});
|
||||
intent.pending = true;
|
||||
const selectedGeneration = selectionGeneration.current;
|
||||
const ownsSubmission = () => mounted.current && submission.current === intent;
|
||||
const ownsSelection = () =>
|
||||
ownsSubmission() && selectionGeneration.current === selectedGeneration;
|
||||
setIsSubmitting(true);
|
||||
setSubmissionError(null);
|
||||
try {
|
||||
const created = await backtestApiV2.createRun(backtest.id, { speedMultiplier });
|
||||
if (!mounted.current || generation !== backtestGeneration.current) {
|
||||
const created = await backtestApiV2.createRun(intent.backtestId, intent.body, intent.key);
|
||||
if (!ownsSubmission()) {
|
||||
return undefined;
|
||||
}
|
||||
setRuns(previous => [created, ...previous]);
|
||||
// The route owns selection. Never navigate away from a newer user selection.
|
||||
return selection.current === selected ? created : undefined;
|
||||
const selected = ownsSelection();
|
||||
submission.current = null;
|
||||
setIsSubmitting(false);
|
||||
if (!selected) {
|
||||
return undefined;
|
||||
}
|
||||
setRuns(previous => [created, ...previous.filter(run => run.id !== created.id)]);
|
||||
return created;
|
||||
} catch (err) {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setError(messageOf(err, 'Failed to create run'));
|
||||
if (ownsSubmission()) {
|
||||
setSubmissionError(messageOf(err, 'Failed to submit run'));
|
||||
}
|
||||
return undefined;
|
||||
} finally {
|
||||
if (mounted.current && generation === backtestGeneration.current) {
|
||||
setIsBacktestLoading(false);
|
||||
intent.pending = false;
|
||||
if (ownsSubmission()) {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -349,6 +391,9 @@ export function useBacktestV2() {
|
|||
runResults,
|
||||
isLoading: isBacktestLoading || isRunLoading,
|
||||
error: runError ?? error,
|
||||
submissionError,
|
||||
isSubmitting,
|
||||
hasPendingSubmission: submission.current !== null,
|
||||
cancelRequested,
|
||||
loadBacktest,
|
||||
createBacktest,
|
||||
|
|
|
|||
|
|
@ -64,7 +64,8 @@ export const backtestApiV2 = {
|
|||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(request),
|
||||
// Web saves are deliberately separate from durable run submission.
|
||||
body: JSON.stringify({ ...request, autoStart: false }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
|
|
@ -123,11 +124,16 @@ export const backtestApiV2 = {
|
|||
},
|
||||
|
||||
// Run operations
|
||||
async createRun(backtestId: string, request?: CreateRunRequest): Promise<Run> {
|
||||
async createRun(
|
||||
backtestId: string,
|
||||
request?: CreateRunRequest,
|
||||
submissionKey?: string
|
||||
): Promise<Run> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}),
|
||||
},
|
||||
body: JSON.stringify(request || {}),
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue