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

461 lines
15 KiB
TypeScript

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';
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';
const logger = getLogger('backtest-v2-service');
// Use environment variable or default
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
export type BacktestTransport = (url: string, init?: RequestInit) => Promise<Response>;
export interface BacktestRequest {
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config?: Record<string, unknown>;
}
export interface Backtest {
id: string;
name: string;
strategy: string;
symbols: string[];
startDate: Date;
endDate: Date;
initialCapital: number;
config: Record<string, unknown>;
createdAt: Date;
updatedAt: Date;
}
export interface Run {
id: string;
backtestId: string;
runNumber: number;
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
speedMultiplier: number | null;
error?: string;
startedAt?: Date;
completedAt?: Date;
pausedAt?: Date;
progress: number;
cancelRequested: boolean;
attemptNumber: number;
currentDate?: Date;
createdAt: Date;
updatedAt: Date;
}
export interface RunRequest {
backtestId: string;
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;
constructor(
container: IServiceContainer,
private readonly request: BacktestTransport = authenticatedServiceFetch
) {
this.container = requireServices(container, 'postgres');
logger.info('BacktestServiceV2 initialized');
}
// Backtest CRUD operations
async createBacktest(
request: BacktestRequest,
options: { autoStart?: boolean } = {}
): Promise<Backtest> {
backtestRequestFromDefinition(request);
const backtestId = uuidv4();
const result = await this.container.postgres.query(
`INSERT INTO backtests
(id, name, strategy, symbols, start_date, end_date, initial_capital, config)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *`,
[
backtestId,
request.name,
request.strategy,
JSON.stringify(request.symbols),
request.startDate,
request.endDate,
request.initialCapital,
JSON.stringify(request.config || {}),
]
);
const backtest = this.mapBacktest(at(result.rows, 0));
// Automatically create and start a run for the new backtest
if (options.autoStart !== false) {
try {
await this.createRun({
backtestId: backtest.id,
speedMultiplier: null, // Max speed (instant)
});
} catch (error) {
logger.error('Failed to auto-create run for new backtest', {
backtestId: backtest.id,
error,
});
// Don't fail the backtest creation if run creation fails
}
}
return backtest;
}
async getBacktest(id: string): Promise<Backtest | null> {
const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [
id,
]);
if (result.rows.length === 0) {
return null;
}
return this.mapBacktest(at(result.rows, 0));
}
async updateBacktest(id: string, request: Partial<BacktestRequest>): Promise<Backtest | null> {
const existing = await this.getBacktest(id);
if (!existing) {
return null;
}
const next = { ...existing, ...request };
backtestRequestFromDefinition(next);
const updates: string[] = [];
const values: unknown[] = [];
let paramCount = 1;
if (request.name !== undefined) {
updates.push(`name = $${paramCount++}`);
values.push(request.name);
}
if (request.strategy !== undefined) {
updates.push(`strategy = $${paramCount++}`);
values.push(request.strategy);
}
if (request.symbols !== undefined) {
updates.push(`symbols = $${paramCount++}`);
values.push(JSON.stringify(request.symbols));
}
if (request.startDate !== undefined) {
updates.push(`start_date = $${paramCount++}`);
values.push(request.startDate);
}
if (request.endDate !== undefined) {
updates.push(`end_date = $${paramCount++}`);
values.push(request.endDate);
}
if (request.initialCapital !== undefined) {
updates.push(`initial_capital = $${paramCount++}`);
values.push(request.initialCapital);
}
if (request.config !== undefined) {
updates.push(`config = $${paramCount++}`);
values.push(JSON.stringify(request.config));
}
if (updates.length === 0) {
return this.getBacktest(id);
}
values.push(id);
const result = await this.container.postgres.query(
`UPDATE backtests
SET ${updates.join(', ')}, updated_at = NOW()
WHERE id = $${paramCount}
RETURNING *`,
values
);
if (result.rows.length === 0) {
return null;
}
return this.mapBacktest(at(result.rows, 0));
}
async listBacktests(params: { limit: number; offset: number }): Promise<Backtest[]> {
const result = await this.container.postgres.query(
`SELECT * FROM backtests
ORDER BY created_at DESC
LIMIT $1 OFFSET $2`,
[params.limit, params.offset]
);
return result.rows.map(row => this.mapBacktest(row));
}
async deleteBacktest(id: string): Promise<void> {
await this.container.postgres.query('DELETE FROM backtests WHERE id = $1', [id]);
}
// Run operations
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 snapshot = backtestRequestFromDefinition(definition, {
runId,
backtestId: definition.id,
speedMultiplier: multiplier,
});
const result = await client.query(
`INSERT INTO runs
(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);
});
return this.mapRun(row);
}
async getRun(id: string): Promise<Run | null> {
const result = await this.container.postgres.query('SELECT * FROM runs WHERE id = $1', [id]);
if (result.rows.length === 0) {
return null;
}
return this.mapRun(at(result.rows, 0));
}
async listRuns(backtestId: string): Promise<Run[]> {
const result = await this.container.postgres.query(
`SELECT * FROM runs
WHERE backtest_id = $1
ORDER BY run_number DESC`,
[backtestId]
);
return result.rows.map(row => this.mapRun(row));
}
async updateRunProgress(
id: string,
updates: { progress?: number; currentDate?: Date; attemptId: string }
): Promise<void> {
const result = await this.container.postgres.transaction(async client => {
await client.query('SELECT id FROM runs WHERE id = $1 FOR UPDATE', [id]);
return client.query(
`UPDATE runs
SET progress = GREATEST(COALESCE($2::numeric, progress), progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused') AND attempt_id = $4 AND lease_expires_at > clock_timestamp() RETURNING status`,
[id, updates.progress ?? null, updates.currentDate ?? null, updates.attemptId]
);
});
const row = result.rows[0];
if (row) {
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
type: 'run_update',
runId: id,
data: { status: row.status, ...updates, timestamp: new Date().toISOString() },
});
}
}
async pauseRun(id: string): Promise<void> {
await this.sendControl(id, 'pause');
}
async resumeRun(id: string): Promise<void> {
await this.sendControl(id, 'resume');
}
async cancelRun(id: string): Promise<void> {
const result = await this.container.postgres.query(
`UPDATE runs SET cancel_requested = TRUE,
status = CASE WHEN status = 'pending' THEN 'cancelled'::run_status ELSE status END,
completed_at = CASE WHEN status = 'pending' THEN NOW() ELSE completed_at END, updated_at = NOW()
WHERE id = $1 AND status IN ('pending', 'running', 'paused', 'cancelled') RETURNING status`,
[id]
);
const row = result.rows[0];
if (!row) {
throw new Error('No cancellable run found');
}
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
type: 'run_update',
data: { status: row.status, cancelRequested: true, timestamp: new Date().toISOString() },
});
}
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
await this.sendControl(id, 'speed', { speed: speedMultiplier });
}
private async sendControl(runId: string, command: string, payload: object = {}): Promise<void> {
const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/${command}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...payload, runId }),
});
if (!response.ok) {
throw new Error(`Backtest ${command} was not acknowledged: ${await response.text()}`);
}
// The runner, not the API client, commits acknowledged state changes.
}
// Get run results
async getRunResults(runId: string): Promise<BacktestRunResult | null> {
const result = await this.container.postgres.query<StoredBacktestResult>(
`SELECT
br.*,
r.backtest_id,
r.status as run_status,
b.strategy,
b.symbols,
b.start_date,
b.end_date,
b.initial_capital,
b.config as backtest_config
FROM backtest_results br
JOIN runs r ON r.id = br.run_id
JOIN backtests b ON b.id = r.backtest_id
WHERE br.run_id = $1`,
[runId]
);
if (result.rows.length === 0) {
return null;
}
return mapStoredBacktestResult(at(result.rows, 0));
}
// Private methods
private mapBacktest(row: QueryResultRow): Backtest {
return {
id: row.id,
name: row.name,
strategy: row.strategy,
symbols: row.symbols,
startDate: row.start_date,
endDate: row.end_date,
initialCapital: parseFloat(row.initial_capital),
config: row.config,
createdAt: row.created_at,
updatedAt: row.updated_at,
};
}
private getWebSocketHandler(): WebSocketHandler | null {
// Try to get from global if not already set
this.wsHandler ??= getWebSocketHandler();
return this.wsHandler;
}
private mapRun(row: QueryResultRow): Run {
return {
id: row.id,
backtestId: row.backtest_id,
runNumber: row.run_number,
status: row.status,
speedMultiplier: row.speed_multiplier === null ? null : parseFloat(row.speed_multiplier),
error: row.error,
startedAt: row.started_at,
completedAt: row.completed_at,
pausedAt: row.paused_at,
progress: parseFloat(row.progress),
cancelRequested: row.cancel_requested === true,
attemptNumber: Number(row.attempt_number ?? 0),
currentDate: row.current_simulation_date,
createdAt: row.created_at,
updatedAt: row.updated_at,
};
}
}