stock-bot/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts

231 lines
6.2 KiB
TypeScript

import type { BacktestRunResult } from '@stock-bot/types';
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
import { browserLog } from '@/utils/browserLog';
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;
cancelRequested?: boolean;
attemptNumber?: 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 type RunResult = BacktestRunResult;
export class RunResultsUnavailableError extends Error {
constructor() {
super('Completed run results are not available');
this.name = 'RunResultsUnavailableError';
}
}
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',
},
// Web saves are deliberately separate from durable run submission.
body: JSON.stringify({ ...request, autoStart: false }),
});
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,
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 || {}),
});
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, signal?: AbortSignal): Promise<Run> {
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<RunResult> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`, { signal });
if (response.status === 404) {
throw new RunResultsUnavailableError();
}
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, signal?: AbortSignal): Promise<void> {
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<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}
};