continuation
This commit is contained in:
parent
32e43c9243
commit
879e9b4228
42 changed files with 2607 additions and 1306 deletions
|
|
@ -1,5 +1,6 @@
|
|||
import { readdirSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { existsSync, readdirSync, readFileSync } from 'fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'path';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
|
|
@ -27,11 +28,21 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
`);
|
||||
|
||||
// Get list of migration files from database/postgres/init
|
||||
const migrationsDir = join(process.cwd(), 'database', 'postgres', 'init');
|
||||
let directory = dirname(fileURLToPath(import.meta.url));
|
||||
while (!existsSync(join(directory, 'database', 'postgres', 'init'))) {
|
||||
const parent = dirname(directory);
|
||||
if (parent === directory) {
|
||||
throw new Error('Cannot locate PostgreSQL migrations');
|
||||
}
|
||||
directory = parent;
|
||||
}
|
||||
const migrationsDir = join(directory, 'database', 'postgres', 'init');
|
||||
logger.info('Looking for migrations', { directory: migrationsDir });
|
||||
|
||||
const files = readdirSync(migrationsDir)
|
||||
.filter(f => f.endsWith('.sql') && f.startsWith('001_')) // Only run our backtest migration for now
|
||||
.filter(
|
||||
f => f.endsWith('.sql') && (f.startsWith('001_') || f === '09-backtest-run-contract.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
logger.info('Found migration files:', files);
|
||||
|
|
@ -48,10 +59,13 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
|
||||
// Read and execute migration
|
||||
const sql = readFileSync(join(migrationsDir, file), 'utf8');
|
||||
await container.postgres.query(sql);
|
||||
|
||||
// Record migration as executed
|
||||
await container.postgres.query('INSERT INTO migrations (filename) VALUES ($1)', [file]);
|
||||
await container.postgres.transaction(async client => {
|
||||
await client.query(sql);
|
||||
await client.query(
|
||||
'INSERT INTO migrations (filename) VALUES ($1) ON CONFLICT (filename) DO NOTHING',
|
||||
[file]
|
||||
);
|
||||
});
|
||||
|
||||
logger.info(`Migration completed: ${file}`);
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -172,7 +172,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
const { progress, currentDate } = body;
|
||||
|
||||
// Update run progress in database
|
||||
await backtestService.updateRunStatus(runId, 'running', {
|
||||
await backtestService.updateRunProgress(runId, {
|
||||
progress,
|
||||
currentDate,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import type { QueryResultRow } from 'pg';
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||
|
||||
|
|
@ -11,6 +12,8 @@ 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;
|
||||
|
|
@ -39,7 +42,7 @@ export interface Run {
|
|||
backtestId: string;
|
||||
runNumber: number;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
|
||||
speedMultiplier: number;
|
||||
speedMultiplier: number | null;
|
||||
error?: string;
|
||||
startedAt?: Date;
|
||||
completedAt?: Date;
|
||||
|
|
@ -59,13 +62,19 @@ export class BacktestServiceV2 {
|
|||
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
|
||||
private wsHandler: WebSocketHandler | null = null;
|
||||
|
||||
constructor(container: IServiceContainer) {
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
private readonly request: BacktestTransport = fetch
|
||||
) {
|
||||
this.container = requireServices(container, 'postgres');
|
||||
logger.info('BacktestServiceV2 initialized');
|
||||
}
|
||||
|
||||
// Backtest CRUD operations
|
||||
async createBacktest(request: BacktestRequest): Promise<Backtest> {
|
||||
async createBacktest(
|
||||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
const backtestId = uuidv4();
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
|
|
@ -88,19 +97,20 @@ export class BacktestServiceV2 {
|
|||
const backtest = this.mapBacktest(at(result.rows, 0));
|
||||
|
||||
// Automatically create and start a run for the new backtest
|
||||
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
|
||||
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;
|
||||
}
|
||||
|
||||
|
|
@ -188,27 +198,29 @@ export class BacktestServiceV2 {
|
|||
// Run operations
|
||||
async createRun(request: RunRequest): Promise<Run> {
|
||||
const runId = uuidv4();
|
||||
|
||||
// Get the next run number for this backtest
|
||||
const runNumberResult = await this.container.postgres.query(
|
||||
'SELECT COALESCE(MAX(run_number), 0) + 1 as next_run_number FROM runs WHERE backtest_id = $1',
|
||||
[request.backtestId]
|
||||
);
|
||||
const runNumber = at(runNumberResult.rows, 0).next_run_number;
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status)
|
||||
VALUES ($1, $2, $3, $4, 'pending')
|
||||
RETURNING *`,
|
||||
[runId, request.backtestId, runNumber, request.speedMultiplier ?? 1.0]
|
||||
);
|
||||
|
||||
const run = this.mapRun(at(result.rows, 0));
|
||||
|
||||
// Start the run immediately
|
||||
this.startRun(run);
|
||||
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
request.backtestId,
|
||||
]);
|
||||
if (!parent.rows.length) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status
|
||||
FROM runs WHERE backtest_id = $2 RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
request.backtestId,
|
||||
request.speedMultiplier === undefined ? null : request.speedMultiplier,
|
||||
]
|
||||
);
|
||||
return at(result.rows, 0);
|
||||
});
|
||||
const run = this.mapRun(row);
|
||||
// startRun handles dispatch failures; the runner owns execution and terminal persistence.
|
||||
void this.startRun(run);
|
||||
return run;
|
||||
}
|
||||
|
||||
|
|
@ -233,137 +245,57 @@ export class BacktestServiceV2 {
|
|||
return result.rows.map(row => this.mapRun(row));
|
||||
}
|
||||
|
||||
async updateRunStatus(
|
||||
async updateRunProgress(
|
||||
id: string,
|
||||
status: Run['status'],
|
||||
updates?: {
|
||||
error?: string;
|
||||
progress?: number;
|
||||
currentDate?: Date;
|
||||
speedMultiplier?: number | null;
|
||||
}
|
||||
updates: { progress?: number; currentDate?: Date }
|
||||
): Promise<void> {
|
||||
const setClauses = ['status = $2', 'updated_at = NOW()'];
|
||||
const values: unknown[] = [id, status];
|
||||
let paramCount = 3;
|
||||
|
||||
if (status === 'running' && !updates?.currentDate) {
|
||||
setClauses.push(`started_at = NOW()`);
|
||||
}
|
||||
if (status === 'completed' || status === 'failed' || status === 'cancelled') {
|
||||
setClauses.push(`completed_at = NOW()`);
|
||||
}
|
||||
if (status === 'paused') {
|
||||
setClauses.push(`paused_at = NOW()`);
|
||||
}
|
||||
|
||||
if (updates?.error !== undefined) {
|
||||
setClauses.push(`error = $${paramCount++}`);
|
||||
values.push(updates.error);
|
||||
}
|
||||
if (updates?.progress !== undefined) {
|
||||
setClauses.push(`progress = $${paramCount++}`);
|
||||
values.push(updates.progress);
|
||||
}
|
||||
if (updates?.currentDate !== undefined) {
|
||||
setClauses.push(`current_simulation_date = $${paramCount++}`);
|
||||
values.push(updates.currentDate);
|
||||
}
|
||||
if (updates?.speedMultiplier !== undefined) {
|
||||
setClauses.push(`speed_multiplier = $${paramCount++}`);
|
||||
values.push(updates.speedMultiplier);
|
||||
}
|
||||
|
||||
await this.container.postgres.query(
|
||||
`UPDATE runs SET ${setClauses.join(', ')} WHERE id = $1`,
|
||||
values
|
||||
const result = await this.container.postgres.query(
|
||||
`UPDATE runs
|
||||
SET progress = COALESCE($2, progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') RETURNING status`,
|
||||
[id, updates.progress ?? null, updates.currentDate ?? null]
|
||||
);
|
||||
|
||||
// Send WebSocket update if handler is available
|
||||
if (this.getWebSocketHandler()) {
|
||||
const row = result.rows[0];
|
||||
if (row) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
type: 'run_update',
|
||||
runId: id,
|
||||
data: {
|
||||
status,
|
||||
...updates,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
data: { status: row.status, ...updates, timestamp: new Date().toISOString() },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async pauseRun(id: string): Promise<void> {
|
||||
await this.updateRunStatus(id, 'paused');
|
||||
|
||||
// Send pause command to orchestrator
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/pause`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn('Failed to pause backtest in orchestrator');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error pausing backtest in orchestrator', error);
|
||||
}
|
||||
await this.sendControl(id, 'pause');
|
||||
}
|
||||
|
||||
async resumeRun(id: string): Promise<void> {
|
||||
const run = await this.getRun(id);
|
||||
if (!run || run.status !== 'paused') {
|
||||
throw new Error('Run is not paused');
|
||||
}
|
||||
|
||||
await this.updateRunStatus(id, 'running');
|
||||
|
||||
// Send resume command to orchestrator
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/resume`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn('Failed to resume backtest in orchestrator');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error resuming backtest in orchestrator', error);
|
||||
}
|
||||
await this.sendControl(id, 'resume');
|
||||
}
|
||||
|
||||
async cancelRun(id: string): Promise<void> {
|
||||
await this.updateRunStatus(id, 'cancelled');
|
||||
// TODO: Send cancel command to orchestrator
|
||||
await this.sendControl(id, 'stop');
|
||||
}
|
||||
|
||||
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
|
||||
await this.updateRunStatus(id, 'running', { speedMultiplier });
|
||||
|
||||
// Send speed update to orchestrator
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/speed`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ speed: speedMultiplier }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn('Failed to update backtest speed in orchestrator');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error updating backtest speed in orchestrator', error);
|
||||
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) {
|
||||
async getRunResults(runId: string): Promise<BacktestRunResult | null> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT
|
||||
br.*,
|
||||
r.backtest_id,
|
||||
r.status as run_status,
|
||||
b.strategy,
|
||||
b.symbols,
|
||||
b.start_date,
|
||||
|
|
@ -382,13 +314,64 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
const legacy = !row.configuration;
|
||||
const metrics: BacktestRunResult['metrics'] = { ...row.metrics };
|
||||
const analytics: BacktestRunResult['analytics'] = {
|
||||
...row.analytics,
|
||||
exposureTime: row.analytics?.exposureTime ?? 0,
|
||||
};
|
||||
const storedTrades: BacktestRunResult['trades'] = row.trades;
|
||||
const trades = storedTrades.map(trade => {
|
||||
const timestamp = trade.timestamp ?? trade.entryDate;
|
||||
const price = trade.price ?? trade.entryPrice;
|
||||
if (!timestamp || price === undefined) {
|
||||
throw new Error('Malformed stored backtest trade');
|
||||
}
|
||||
return {
|
||||
...trade,
|
||||
kind: trade.kind ?? (trade.entryDate ? 'closed' : 'fill'),
|
||||
timestamp,
|
||||
price,
|
||||
};
|
||||
});
|
||||
if (legacy) {
|
||||
// Pre-contract backends both reported return/win rate in percentage points.
|
||||
metrics.totalReturn /= 100;
|
||||
metrics.winRate /= 100;
|
||||
for (const key of ['annualReturn', 'annualizedReturn']) {
|
||||
if (typeof metrics[key] === 'number') {
|
||||
metrics[key] /= 100;
|
||||
}
|
||||
}
|
||||
if (trades.some(trade => trade.kind === 'closed')) {
|
||||
metrics.totalTrades = trades.length;
|
||||
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
analytics.exposureTime /= 100;
|
||||
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||
...point,
|
||||
value: point.value / 100,
|
||||
}));
|
||||
// Older native results identify themselves by finalValue and already use daily fractions.
|
||||
if (typeof row.metrics.finalValue !== 'number') {
|
||||
analytics.dailyReturns = analytics.dailyReturns?.map(value => value / 100);
|
||||
}
|
||||
if (analytics.monthlyReturns) {
|
||||
analytics.monthlyReturns = Object.fromEntries(
|
||||
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
runId: row.run_id,
|
||||
backtestId: row.backtest_id,
|
||||
status: 'completed',
|
||||
status: row.run_status ?? 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
config: {
|
||||
engine: row.engine ?? 'legacy',
|
||||
...(legacy ? { legacy: true } : {}),
|
||||
config: row.configuration ?? {
|
||||
parameters: row.backtest_config ?? {},
|
||||
name: row.backtest_config?.name || 'Backtest',
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
|
|
@ -399,48 +382,41 @@ export class BacktestServiceV2 {
|
|||
slippage: row.backtest_config?.slippage ?? 0.0001,
|
||||
dataFrequency: row.backtest_config?.dataFrequency || '1d',
|
||||
},
|
||||
metrics: row.metrics,
|
||||
metrics,
|
||||
equity: row.equity_curve,
|
||||
ohlcData: row.ohlc_data,
|
||||
trades: row.trades,
|
||||
trades,
|
||||
positions: row.positions,
|
||||
analytics: row.analytics,
|
||||
analytics,
|
||||
executionTime: row.execution_time,
|
||||
};
|
||||
}
|
||||
|
||||
// Private methods
|
||||
private async startRun(run: Run): Promise<void> {
|
||||
const backtest = await this.getBacktest(run.backtestId);
|
||||
if (!backtest) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
|
||||
await this.updateRunStatus(run.id, 'running', { progress: 0 });
|
||||
|
||||
// Send initial WebSocket update
|
||||
if (this.getWebSocketHandler()) {
|
||||
this.getWebSocketHandler()?.sendProgressUpdate(run.id, 0);
|
||||
}
|
||||
|
||||
try {
|
||||
// Call orchestrator to run backtest
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
const backtest = await this.getBacktest(run.backtestId);
|
||||
if (!backtest) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
this.getWebSocketHandler()?.sendProgressUpdate(run.id, 0);
|
||||
const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
runId: run.id,
|
||||
backtestId: backtest.id,
|
||||
name: backtest.name,
|
||||
mode: 'backtest',
|
||||
startDate: new Date(backtest.startDate).toISOString(),
|
||||
endDate: new Date(backtest.endDate).toISOString(),
|
||||
startDate: backtest.startDate.toISOString(),
|
||||
endDate: backtest.endDate.toISOString(),
|
||||
symbols: backtest.symbols,
|
||||
strategy: backtest.strategy,
|
||||
initialCapital: backtest.initialCapital,
|
||||
dataFrequency: backtest.config?.dataFrequency || '1d',
|
||||
commission: backtest.config?.commission ?? 0.001,
|
||||
slippage: backtest.config?.slippage ?? 0.0001,
|
||||
config: backtest.config,
|
||||
dataFrequency: backtest.config.dataFrequency ?? '1d',
|
||||
commission: backtest.config.commission ?? 0.001,
|
||||
slippage: backtest.config.slippage ?? 0.0001,
|
||||
speed:
|
||||
run.speedMultiplier === null
|
||||
? 'max'
|
||||
|
|
@ -451,82 +427,57 @@ export class BacktestServiceV2 {
|
|||
: run.speedMultiplier >= 2
|
||||
? '2x'
|
||||
: 'realtime',
|
||||
fillModel: {
|
||||
slippage: 'realistic',
|
||||
marketImpact: true,
|
||||
partialFills: true,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
logger.error('Orchestrator request failed', {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: errorText,
|
||||
request: {
|
||||
runId: run.id,
|
||||
strategy: backtest.strategy,
|
||||
symbols: backtest.symbols,
|
||||
startDate: new Date(backtest.startDate).toISOString(),
|
||||
endDate: new Date(backtest.endDate).toISOString(),
|
||||
},
|
||||
});
|
||||
throw new Error(`Orchestrator returned ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.status === 'completed') {
|
||||
await this.updateRunStatus(run.id, 'completed', { progress: 100 });
|
||||
await this.saveRunResults(run.id, result);
|
||||
|
||||
// Send completion via WebSocket
|
||||
if (this.getWebSocketHandler()) {
|
||||
this.getWebSocketHandler()?.sendCompletion(run.id, result);
|
||||
if (response.status === 409) {
|
||||
const outcome: unknown = await response
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => null);
|
||||
if (
|
||||
outcome &&
|
||||
typeof outcome === 'object' &&
|
||||
'status' in outcome &&
|
||||
outcome.status === 'cancelled' &&
|
||||
(await this.getRun(run.id))?.status === 'cancelled'
|
||||
) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(run.id, {
|
||||
type: 'run_update',
|
||||
data: { status: 'cancelled', timestamp: new Date().toISOString() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error(`Orchestrator returned ${response.status}: ${await response.text()}`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to start run', { runId: run.id, error });
|
||||
const errorMessage =
|
||||
error instanceof Error
|
||||
? error instanceof Error
|
||||
? error.message
|
||||
: String(error)
|
||||
: 'Unknown error';
|
||||
await this.updateRunStatus(run.id, 'failed', {
|
||||
error: errorMessage,
|
||||
});
|
||||
|
||||
// Send error via WebSocket
|
||||
if (this.getWebSocketHandler()) {
|
||||
this.getWebSocketHandler()?.sendError(run.id, errorMessage);
|
||||
const result: BacktestRunResult = await response.json();
|
||||
if (
|
||||
result.runId !== run.id ||
|
||||
result.backtestId !== backtest.id ||
|
||||
!['completed', 'cancelled'].includes(result.status)
|
||||
) {
|
||||
throw new Error('Invalid orchestrator run response');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async saveRunResults(runId: string, result: Record<string, unknown>): Promise<void> {
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`INSERT INTO backtest_results
|
||||
(run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
||||
[
|
||||
runId,
|
||||
result.completedAt || new Date(),
|
||||
JSON.stringify(result.metrics || {}),
|
||||
JSON.stringify(result.equity || result.equityCurve || []),
|
||||
JSON.stringify(result.ohlcData || {}),
|
||||
JSON.stringify(result.trades || []),
|
||||
JSON.stringify(result.positions || result.finalPositions || {}),
|
||||
JSON.stringify(result.analytics || {}),
|
||||
result.executionTime || 0,
|
||||
]
|
||||
);
|
||||
// Results and terminal state are already committed by the orchestrator.
|
||||
this.getWebSocketHandler()?.sendCompletion(run.id, result);
|
||||
} catch (error) {
|
||||
logger.error('Failed to save run results', { runId, error });
|
||||
throw error;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logger.error('Backtest dispatch failed', { runId: run.id, error });
|
||||
// A broken HTTP connection must not overwrite a claimed or completed execution.
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`UPDATE runs SET status = 'failed', error = $2,
|
||||
completed_at = NOW(), updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
|
||||
[run.id, message]
|
||||
);
|
||||
} catch (persistenceError) {
|
||||
logger.error('Could not record backtest dispatch failure', {
|
||||
runId: run.id,
|
||||
persistenceError,
|
||||
});
|
||||
}
|
||||
this.getWebSocketHandler()?.sendError(run.id, message);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -557,7 +508,7 @@ export class BacktestServiceV2 {
|
|||
backtestId: row.backtest_id,
|
||||
runNumber: row.run_number,
|
||||
status: row.status,
|
||||
speedMultiplier: parseFloat(row.speed_multiplier),
|
||||
speedMultiplier: row.speed_multiplier === null ? null : parseFloat(row.speed_multiplier),
|
||||
error: row.error,
|
||||
startedAt: row.started_at,
|
||||
completedAt: row.completed_at,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
import { randomUUID as uuidv4 } from 'node:crypto';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
|
||||
const logger = getLogger('backtest-service');
|
||||
|
||||
// Use environment variable or default
|
||||
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
BacktestServiceV2,
|
||||
type Backtest,
|
||||
type BacktestTransport,
|
||||
type Run,
|
||||
} from './backtest-v2.service';
|
||||
|
||||
export interface BacktestRequest {
|
||||
strategy: string;
|
||||
|
|
@ -16,10 +14,10 @@ export interface BacktestRequest {
|
|||
initialCapital: number;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BacktestJob {
|
||||
id: string;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
|
||||
runId?: string;
|
||||
status: Run['status'];
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: Date;
|
||||
|
|
@ -31,271 +29,56 @@ export interface BacktestJob {
|
|||
error?: string;
|
||||
}
|
||||
|
||||
/** Compatibility facade: V1 uses the same definitions, runs, and result reader as V2. */
|
||||
export class BacktestService {
|
||||
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
|
||||
|
||||
constructor(container: IServiceContainer) {
|
||||
this.container = requireServices(container, 'postgres');
|
||||
logger.info('BacktestService initialized', {
|
||||
hasPostgres: !!container.postgres,
|
||||
containerKeys: Object.keys(container),
|
||||
});
|
||||
private readonly service: BacktestServiceV2;
|
||||
constructor(container: IServiceContainer, request?: BacktestTransport) {
|
||||
this.service = new BacktestServiceV2(container, request);
|
||||
}
|
||||
|
||||
async createBacktest(request: BacktestRequest): Promise<BacktestJob> {
|
||||
const backtestId = uuidv4();
|
||||
|
||||
// Insert into PostgreSQL
|
||||
const result = await this.container.postgres.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending')
|
||||
RETURNING *`,
|
||||
[
|
||||
backtestId,
|
||||
request.config?.name || `Backtest ${new Date().toISOString()}`,
|
||||
request.strategy,
|
||||
JSON.stringify(request.symbols),
|
||||
request.startDate,
|
||||
request.endDate,
|
||||
request.initialCapital,
|
||||
JSON.stringify(request.config || {}),
|
||||
]
|
||||
);
|
||||
|
||||
const backtest: BacktestJob = {
|
||||
id: at(result.rows, 0).id,
|
||||
status: at(result.rows, 0).status,
|
||||
strategy: at(result.rows, 0).strategy,
|
||||
symbols: at(result.rows, 0).symbols,
|
||||
startDate: at(result.rows, 0).start_date,
|
||||
endDate: at(result.rows, 0).end_date,
|
||||
initialCapital: parseFloat(at(result.rows, 0).initial_capital),
|
||||
config: at(result.rows, 0).config,
|
||||
createdAt: at(result.rows, 0).created_at,
|
||||
updatedAt: at(result.rows, 0).updated_at,
|
||||
};
|
||||
|
||||
// Call orchestrator to run backtest
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
mode: 'backtest',
|
||||
startDate: new Date(request.startDate).toISOString(),
|
||||
endDate: new Date(request.endDate).toISOString(),
|
||||
symbols: request.symbols,
|
||||
strategy: request.strategy,
|
||||
initialCapital: request.initialCapital,
|
||||
dataFrequency: '1d', // Default to daily
|
||||
commission: request.config?.commission,
|
||||
slippage: request.config?.slippage,
|
||||
speed: 'max', // Default speed
|
||||
fillModel: {
|
||||
slippage: 'realistic',
|
||||
marketImpact: true,
|
||||
partialFills: true,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Orchestrator returned ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
// Store result directly without transformation
|
||||
if (result.status === 'completed') {
|
||||
// Update backtest status
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
['completed', backtestId]
|
||||
);
|
||||
|
||||
// Store results in backtest_results table
|
||||
await this.saveBacktestResults(backtestId, result);
|
||||
|
||||
logger.info('Backtest completed', {
|
||||
backtestId,
|
||||
trades: result.metrics?.totalTrades,
|
||||
return: result.metrics?.totalReturn,
|
||||
});
|
||||
} else {
|
||||
// Update status to running if not completed
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
['running', backtestId]
|
||||
);
|
||||
}
|
||||
|
||||
logger.info('Backtest started in orchestrator', { backtestId, result });
|
||||
} catch (error) {
|
||||
logger.error('Failed to start backtest in orchestrator', { backtestId, error });
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
|
||||
['failed', error instanceof Error ? error.message : String(error), backtestId]
|
||||
);
|
||||
backtest.status = 'failed';
|
||||
backtest.error = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
return backtest;
|
||||
}
|
||||
|
||||
async getBacktest(id: string): Promise<BacktestJob | null> {
|
||||
const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [
|
||||
id,
|
||||
]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
return {
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
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,
|
||||
error: row.error,
|
||||
};
|
||||
}
|
||||
|
||||
async getBacktestResults(id: string) {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT
|
||||
br.*,
|
||||
b.strategy,
|
||||
b.symbols,
|
||||
b.start_date,
|
||||
b.end_date,
|
||||
b.initial_capital,
|
||||
b.config as backtest_config
|
||||
FROM backtest_results br
|
||||
JOIN backtests b ON b.id = br.backtest_id
|
||||
WHERE br.backtest_id = $1`,
|
||||
[id]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
|
||||
// Reconstruct the result format expected by frontend
|
||||
return {
|
||||
backtestId: row.backtest_id,
|
||||
status: 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
config: {
|
||||
name: row.backtest_config?.name || 'Backtest',
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date.toISOString(),
|
||||
endDate: row.end_date.toISOString(),
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
commission: row.backtest_config?.commission ?? 0.001,
|
||||
slippage: row.backtest_config?.slippage ?? 0.0001,
|
||||
dataFrequency: row.backtest_config?.dataFrequency || '1d',
|
||||
const backtest = await this.service.createBacktest(
|
||||
{
|
||||
...request,
|
||||
name: typeof request.config?.name === 'string' ? request.config.name : 'Backtest',
|
||||
},
|
||||
metrics: row.metrics,
|
||||
equity: row.equity_curve,
|
||||
ohlcData: row.ohlc_data,
|
||||
trades: row.trades,
|
||||
positions: row.positions,
|
||||
analytics: row.analytics,
|
||||
executionTime: row.execution_time,
|
||||
};
|
||||
}
|
||||
|
||||
async listBacktests(params: { limit: number; offset: number }): Promise<BacktestJob[]> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT * FROM backtests
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1 OFFSET $2`,
|
||||
[params.limit, params.offset]
|
||||
{ autoStart: false }
|
||||
);
|
||||
|
||||
return result.rows.map(row => ({
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
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,
|
||||
error: row.error,
|
||||
}));
|
||||
const run = await this.service.createRun({ backtestId: backtest.id, speedMultiplier: null });
|
||||
return this.toJob(backtest, run);
|
||||
}
|
||||
|
||||
async updateBacktestStatus(
|
||||
id: string,
|
||||
status: BacktestJob['status'],
|
||||
error?: string
|
||||
): Promise<void> {
|
||||
if (error) {
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
|
||||
[status, error, id]
|
||||
);
|
||||
} else {
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
[status, id]
|
||||
);
|
||||
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> {
|
||||
await this.updateBacktestStatus(id, 'cancelled');
|
||||
|
||||
// Call orchestrator to stop backtest
|
||||
try {
|
||||
await fetch(`${ORCHESTRATOR_URL}/api/backtest/stop`, {
|
||||
method: 'POST',
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to stop backtest in orchestrator', { backtestId: id, error });
|
||||
const run = (await this.service.listRuns(id))[0];
|
||||
if (!run) {
|
||||
throw new Error('Backtest run not found');
|
||||
}
|
||||
await this.service.cancelRun(run.id);
|
||||
}
|
||||
|
||||
private async saveBacktestResults(
|
||||
backtestId: string,
|
||||
result: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`INSERT INTO backtest_results
|
||||
(backtest_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
||||
[
|
||||
backtestId,
|
||||
result.completedAt || new Date(),
|
||||
JSON.stringify(result.metrics || {}),
|
||||
JSON.stringify(result.equity || result.equityCurve || []),
|
||||
JSON.stringify(result.ohlcData || {}),
|
||||
JSON.stringify(result.trades || []),
|
||||
JSON.stringify(result.positions || result.finalPositions || {}),
|
||||
JSON.stringify(result.analytics || {}),
|
||||
result.executionTime || 0,
|
||||
]
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('Failed to save backtest results', { backtestId, error });
|
||||
throw error;
|
||||
}
|
||||
private toJob(backtest: Backtest, run?: Run): BacktestJob {
|
||||
return {
|
||||
...backtest,
|
||||
runId: run?.id,
|
||||
status: run?.status ?? 'pending',
|
||||
updatedAt: run?.updatedAt ?? backtest.updatedAt,
|
||||
error: run?.error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue