import type { IServiceContainer } from '@stock-bot/services'; import { rejectCatalogVersionReferences } from '@stock-bot/stock-config/backtest'; import { BacktestServiceV2, type Backtest, type BacktestTransport, type Run, } from './backtest-v2.service'; export interface BacktestRequest { strategy: string; symbols: string[]; startDate: string; endDate: string; initialCapital: number; config?: Record; } export interface BacktestJob { id: string; runId?: string; status: Run['status']; strategy: string; symbols: string[]; startDate: Date; endDate: Date; initialCapital: number; config: Record | null; createdAt: Date; updatedAt: Date; error?: string; } export class LegacyBacktestCreationRetiredError extends Error { readonly code = 'legacy_backtest_creation_retired'; constructor() { super( 'Legacy backtest creation is retired. Create a catalog template with POST /api/v2/backtests, then submit a run through its /runs endpoint.' ); } } /** Historical V1 reads and cancellation use the same saved records as V2. */ export class BacktestService { private readonly service: BacktestServiceV2; constructor(container: IServiceContainer, request?: BacktestTransport) { this.service = new BacktestServiceV2(container, request); } async createBacktest(request: BacktestRequest): Promise { rejectCatalogVersionReferences(request); // Reject before saving a template: no legacy definition can execute, and a // failure after its commit would leave an orphan on every client retry. throw new LegacyBacktestCreationRetiredError(); } async getBacktest(id: string): Promise { const backtest = await this.service.getBacktest(id); if (!backtest) { return null; } return this.toJob(backtest, (await this.service.listRuns(id))[0]); } async listBacktests(params: { limit: number; offset: number }): Promise { return Promise.all( (await this.service.listBacktests(params)).map(async backtest => this.toJob(backtest, (await this.service.listRuns(backtest.id))[0]) ) ); } async getBacktestResults(id: string) { const run = (await this.service.listRuns(id))[0]; return run ? this.service.getRunResults(run.id) : null; } async cancelBacktest(id: string): Promise { const run = (await this.service.listRuns(id))[0]; if (!run) { throw new Error('Backtest run not found'); } await this.service.cancelRun(run.id); } private toJob(backtest: Backtest, run?: Run): BacktestJob { return { ...backtest, runId: run?.id, status: run?.status ?? 'pending', updatedAt: run?.updatedAt ?? backtest.updatedAt, error: run?.error ?? undefined, }; } }