import type { CanonicalDatasetCatalogEntry, CanonicalRunCapability, ResearchRunResult, } from '@stock-bot/stock-config/canonical-research'; import type { BacktestRunDatasetSelection, BacktestRunResult, HistoricalDatasetCatalogEntry, StrategyParameterValue, } from '@stock-bot/types'; import { API_BASE_URL, apiFetch as fetch } from '@/lib/api'; export interface Backtest { id: string; name: string; strategy: string; strategyVersionId?: string | null; strategyParameters?: Record | null; symbols: string[]; startDate: string; endDate: string; initialCapital: number; config: Record; createdAt: string; updatedAt: string; archivedAt: string | null; } 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; cancelRequested?: boolean; attemptNumber?: number; currentSimulationDate?: string; createdAt: string; updatedAt: string; dataset?: BacktestRunDatasetSelection; } export interface CreateBacktestRequest { name: string; strategy: string; strategyVersionId?: string | null; strategyParameters?: Record | null; symbols: string[]; startDate: string; endDate: string; initialCapital: number; config?: Record; } export interface CreateRunRequest { speedMultiplier?: number | null; } export type RunResult = BacktestRunResult; export type { ResearchRunResult }; export class RunResultsUnavailableError extends Error { constructor() { super('Completed run results are not available'); this.name = 'RunResultsUnavailableError'; } } async function requestError(response: Response, fallback: string): Promise { const payload: unknown = await response.json().catch(() => null); const message = payload && typeof payload === 'object' && 'error' in payload && typeof payload.error === 'string' ? payload.error : `${fallback}: ${response.status} ${response.statusText}`; return new Error(message); } export const backtestApiV2 = { async canonicalCapability(id: string, signal?: AbortSignal): Promise { const response = await fetch( `${API_BASE_URL}/api/v2/backtests/${encodeURIComponent(id)}/canonical-capability`, { signal } ); if (!response.ok) { throw await requestError(response, 'Could not check canonical execution eligibility'); } return response.json(); }, async listCanonicalDatasets(signal?: AbortSignal): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical?limit=50&offset=0`, { signal, }); if (!response.ok) { throw await requestError(response, 'Could not load canonical datasets'); } return (await response.json()).datasets; }, async canonicalDataset( hash: string, signal?: AbortSignal ): Promise { const response = await fetch( `${API_BASE_URL}/api/v2/datasets/canonical/${encodeURIComponent(hash)}`, { signal } ); if (!response.ok) { throw await requestError(response, 'Could not load canonical dataset'); } return (await response.json()).dataset; }, async listDatasets( limit = 50, offset = 0, signal?: AbortSignal ): Promise { const response = await fetch( `${API_BASE_URL}/api/v2/datasets?limit=${limit}&offset=${offset}`, { signal } ); if (!response.ok) { throw await requestError(response, 'Failed to load frozen datasets'); } return (await response.json()).datasets; }, async getDataset(hash: string, signal?: AbortSignal): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/datasets/${encodeURIComponent(hash)}`, { signal, }); if (!response.ok) { throw await requestError(response, 'Failed to load frozen dataset'); } return (await response.json()).dataset; }, // Backtest operations async createBacktest(request: CreateBacktestRequest): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, // Web saves are deliberately separate from durable run submission. body: JSON.stringify({ ...request, autoStart: false }), }); if (!response.ok) { throw await requestError(response, 'Failed to create backtest'); } return response.json(); }, async getBacktest(id: string): Promise { 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, includeArchived = false, signal?: AbortSignal ): Promise { const response = await fetch( `${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`, { signal } ); if (!response.ok) { throw await requestError(response, 'Failed to list backtests'); } return response.json(); }, async updateBacktest(id: string, updates: Partial): Promise { 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 await requestError(response, 'Failed to update backtest'); } return response.json(); }, async deleteBacktest(id: string): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, { method: 'DELETE', }); if (!response.ok) { throw await requestError(response, 'Failed to delete backtest'); } }, async setBacktestArchived(id: string, archived: boolean): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}/archive`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ archived }), }); if (!response.ok) { throw await requestError(response, 'Failed to change archive status'); } return response.json(); }, // Run operations async createRun( backtestId: string, request?: CreateRunRequest, submissionKey?: string ): Promise { 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 || {}), }); if (!response.ok) { throw await requestError(response, 'Failed to create run'); } return response.json(); }, async listRuns(backtestId: string): Promise { 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, signal?: AbortSignal): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`, { signal }); if (!response.ok) { throw new Error(`Failed to get run: ${response.statusText}`); } return response.json(); }, async getRunResults(runId: string, signal?: AbortSignal): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`, { signal }); if (response.status === 404) { throw new RunResultsUnavailableError(); } if (!response.ok) { throw await requestError(response, 'Failed to get run results'); } return response.json(); }, async pauseRun(id: string): Promise { 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 { 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, signal?: AbortSignal): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, { method: 'POST', signal, }); if (!response.ok) { throw new Error(`Failed to cancel run: ${response.statusText}`); } }, async updateRunSpeed(id: string, speedMultiplier: number | null): Promise { 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} };