stock-bot/apps/stock/web-api/src/services/backtest.service.ts

89 lines
2.8 KiB
TypeScript

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<string, unknown>;
}
export interface BacktestJob {
id: string;
runId?: string;
status: Run['status'];
strategy: string;
symbols: string[];
startDate: Date;
endDate: Date;
initialCapital: number;
config: Record<string, unknown> | 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<BacktestJob> {
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<BacktestJob | null> {
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<BacktestJob[]> {
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<void> {
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,
};
}
}