continuation

This commit is contained in:
Boki 2026-10-20 16:57:59 -04:00
parent 32e43c9243
commit 879e9b4228
42 changed files with 2607 additions and 1306 deletions

View file

@ -92,6 +92,7 @@ export const stockAppSchema = baseAppSchema.extend({
.object({
maxConcurrent: z.number().default(5),
useRustEngine: z.boolean().default(true),
executionTimeoutMs: z.number().int().positive().max(2_147_483_647).default(300_000),
allowSyntheticData: z.boolean().default(false),
syntheticSeed: z.number().int().default(42),
defaultSpeed: z.string().default('max'),

View file

@ -6,7 +6,7 @@
"main": "dist/index.js",
"scripts": {
"dev": "bun --watch src/index.ts",
"build": "bun build src/index.ts --outdir dist --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core",
"build": "bun build src/index.ts src/backtest/native-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core",
"start": "bun dist/index.js",
"test": "bun test",
"test:indicators": "bun test tests/indicators.test.ts",
@ -35,7 +35,9 @@
"@stock-bot/services": "workspace:*",
"@stock-bot/mongodb": "workspace:*",
"@stock-bot/postgres": "workspace:*",
"@stock-bot/invariants": "workspace:*"
"@stock-bot/invariants": "workspace:*",
"@stock-bot/types": "workspace:*",
"@stock-bot/handlers": "workspace:*"
},
"peerDependencies": {
"@tensorflow/tfjs-node": "^4.0.0"

View file

@ -1,9 +1,10 @@
import { Hono } from 'hono';
import { Hono, type Handler } from 'hono';
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { ModeManager } from '../../core/ModeManager';
import { parseBacktestRequest } from '../../backtest/BacktestRunner';
import { BacktestCancelledError } from '../../backtest/execution-engine';
import { BacktestConflictError } from '../../backtest/run-repository';
import type { OrchestratorServices as IServiceContainer } from '../../types';
import { BacktestConfigSchema } from '../../types';
const _BacktestIdSchema = z.object({
backtestId: z.string(),
@ -11,23 +12,28 @@ const _BacktestIdSchema = z.object({
export function createBacktestRoutes(container: IServiceContainer): Hono {
const app = new Hono();
const backtestEngine = defined(container.custom?.BacktestEngine);
const modeManager = container.custom?.ModeManager as ModeManager;
const backtestEngine = defined(
container.custom?.BacktestRunner,
'Backtest runner is unavailable'
);
// Default POST to / is the same as /run for backward compatibility
app.post('/', async c => {
const runBacktest: Handler = async c => {
try {
const body = await c.req.json();
const config = BacktestConfigSchema.parse(body);
// Initialize backtest mode
await modeManager.initializeMode(config);
const config = parseBacktestRequest(body);
// Run backtest
const result = await backtestEngine.runBacktest(config);
return c.json(result, 201);
} catch (error) {
if (error instanceof BacktestCancelledError) {
return c.json({ status: 'cancelled', error: error.message }, 409);
}
if (error instanceof BacktestConflictError) {
return c.json({ error: error.message }, 409);
}
if (error instanceof z.ZodError) {
return c.json(
{
@ -46,46 +52,15 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
500
);
}
});
// Run new backtest (same as above but at /run)
app.post('/run', async c => {
try {
const body = await c.req.json();
const config = BacktestConfigSchema.parse(body);
// Initialize backtest mode
await modeManager.initializeMode(config);
// Run backtest
const result = await backtestEngine.runBacktest(config);
return c.json(result, 201);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid backtest configuration',
details: error.errors,
},
400
);
}
container.logger.error('Error running backtest:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to run backtest',
},
500
);
}
});
};
app.post('/', runBacktest);
app.post('/run', runBacktest);
// Stop running backtest
app.post('/stop', async c => {
try {
await backtestEngine.stopBacktest();
const { runId } = await c.req.json().catch(() => ({}));
await backtestEngine.stopBacktest(runId);
return c.json({
message: 'Backtest stop requested',
@ -105,7 +80,8 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
// Pause running backtest
app.post('/pause', async c => {
try {
await backtestEngine.pauseBacktest();
const { runId } = await c.req.json().catch(() => ({}));
await backtestEngine.pauseBacktest(runId);
return c.json({
message: 'Backtest paused',
@ -125,7 +101,8 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
// Resume paused backtest
app.post('/resume', async c => {
try {
await backtestEngine.resumeBacktest();
const { runId } = await c.req.json().catch(() => ({}));
await backtestEngine.resumeBacktest(runId);
return c.json({
message: 'Backtest resumed',
@ -146,9 +123,14 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
app.post('/speed', async c => {
try {
const body = await c.req.json();
const speed = body.speed ?? 1;
const { speed, runId } = z
.object({
speed: z.number().finite().positive().nullable().default(1),
runId: z.string().uuid().optional(),
})
.parse(body);
backtestEngine.setSpeedMultiplier(speed);
await backtestEngine.setSpeedMultiplier(speed, runId);
return c.json({
message: 'Backtest speed updated',
@ -177,6 +159,7 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
currentTime: new Date(status.currentTime).toISOString(),
isRunning: status.isRunning,
isPaused: status.isPaused,
runId: status.runId,
});
} catch (error) {
container.logger.error('Error getting backtest progress:', error);
@ -195,27 +178,57 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
c.header('Cache-Control', 'no-cache');
c.header('Connection', 'keep-alive');
const stream = new ReadableStream({
let dispose = () => {};
const stream = new ReadableStream<Uint8Array>({
start(controller) {
// Listen for backtest events
const onProgress = (data: unknown) => {
controller.enqueue(`data: ${JSON.stringify(data)}\n\n`);
};
const onComplete = (data: unknown) => {
controller.enqueue(`data: ${JSON.stringify({ event: 'complete', data })}\n\n`);
const encoder = new TextEncoder();
let closed = false;
const finish = () => {
if (closed) {
return;
}
dispose();
controller.close();
};
backtestEngine.on('progress', onProgress);
backtestEngine.on('complete', onComplete);
// Cleanup on close
c.req.raw.signal.addEventListener('abort', () => {
const onProgress = (data: unknown) => {
if (!closed) {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
}
};
const onComplete = (data: unknown) => {
onProgress({ event: 'complete', data });
finish();
};
const onError = (error: unknown) => {
onProgress({
event: 'error',
error: error instanceof Error ? error.message : String(error),
});
finish();
};
const onCancelled = (data: unknown) => {
onProgress({ event: 'cancelled', data });
finish();
};
dispose = () => {
closed = true;
backtestEngine.off('progress', onProgress);
backtestEngine.off('complete', onComplete);
controller.close();
});
backtestEngine.off('error', onError);
backtestEngine.off('cancelled', onCancelled);
c.req.raw.signal.removeEventListener('abort', finish);
};
backtestEngine.on('progress', onProgress);
backtestEngine.on('complete', onComplete);
backtestEngine.on('error', onError);
backtestEngine.on('cancelled', onCancelled);
c.req.raw.signal.addEventListener('abort', finish, { once: true });
if (c.req.raw.signal.aborted) {
finish();
}
},
cancel() {
dispose();
},
});
@ -226,7 +239,7 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
app.post('/validate', async c => {
try {
const body = await c.req.json();
const config = BacktestConfigSchema.parse(body);
const config = parseBacktestRequest(body);
// Additional validation logic
const validation = {
@ -253,6 +266,9 @@ export function createBacktestRoutes(container: IServiceContainer): Hono {
return c.json(validation);
} catch (error) {
if (error instanceof BacktestConflictError) {
return c.json({ error: error.message }, 409);
}
if (error instanceof z.ZodError) {
return c.json(
{

View file

@ -7,14 +7,12 @@ import type { StrategyFill } from '../services/ExecutionService';
import { StorageService } from '../services/StorageService';
import type { Signal } from '../strategies/BaseStrategy';
import { StrategyManager } from '../strategies/StrategyManager';
import type {
BacktestConfig,
OrchestratorServices as IServiceContainer,
OrderRequest,
} from '../types';
import type { OrchestratorServices as IServiceContainer, OrderRequest } from '../types';
import { BacktestConfigSchema, type MarketData, type MarketMicrostructure } from '../types';
import type { BacktestExecutionEngine } from './execution-engine';
import { MarketSimulator } from './MarketSimulator';
import { closedTradesSchema, openPositionsSchema, type ClosedTrade } from './native-result';
import type { BacktestResult, OHLCBar } from './typescript-result';
type BacktestEvent = { timestamp: number } & (
| { type: 'market_data'; data: MarketData }
@ -27,96 +25,15 @@ interface PendingOrder {
order: OrderRequest;
timestamp: number;
}
interface OHLCBar {
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
}
interface ExportResult {
summary: PerformanceMetrics;
trades: ClosedTrade[];
performanceReport: string;
}
export interface BacktestResult {
// Identification
backtestId: string;
status: 'completed' | 'failed' | 'cancelled';
completedAt: string;
export type { BacktestResult } from './typescript-result';
// Configuration
config: {
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
commission: number;
slippage: number;
dataFrequency: string;
};
// Performance metrics
metrics: {
totalReturn: number;
sharpeRatio: number;
maxDrawdown: number;
winRate: number;
totalTrades: number;
profitFactor: number;
profitableTrades: number;
avgWin: number;
avgLoss: number;
expectancy: number;
calmarRatio: number;
sortinoRatio: number;
};
// Chart data
equity: Array<{ date: string; value: number }>;
ohlcData: Record<string, OHLCBar[]>;
// Trade history
trades: Array<{
id: string;
symbol: string;
entryDate: string;
exitDate: string | null;
entryPrice: number;
exitPrice: number;
quantity: number;
side: string;
pnl: number;
pnlPercent: number;
commission: number;
duration: number;
}>;
// Positions
positions: Array<{
symbol: string;
quantity: number;
averagePrice: number;
currentPrice: number;
unrealizedPnl: number;
realizedPnl: number;
}>;
// Analytics
analytics: {
drawdownSeries: { timestamp: number; value: number }[];
dailyReturns: number[];
monthlyReturns: Record<string, number>;
exposureTime: number;
riskMetrics: Record<string, number>;
};
}
export class BacktestEngine extends EventEmitter {
export class BacktestEngine extends EventEmitter implements BacktestExecutionEngine {
private eventQueue: BacktestEvent[] = [];
private currentTime: number = 0;
private equityCurve: { timestamp: number; value: number }[] = [];
@ -129,7 +46,6 @@ export class BacktestEngine extends EventEmitter {
private performanceAnalyzer!: PerformanceAnalyzer;
private microstructures: Map<string, MarketMicrostructure> = new Map();
private container: IServiceContainer;
private runId: string | null = null;
private progressUpdateInterval = 100; // Update progress every 100 events
private totalEvents = 0;
private initialCapital: number = 100000;
@ -193,9 +109,8 @@ export class BacktestEngine extends EventEmitter {
`[BacktestEngine] Initial capital set to ${this.initialCapital}, equity curve initialized with ${this.equityCurve.length} points`
);
// Generate backtest ID and store runId if provided
// Backend-local identifier; the application runner supplies the persisted identity.
const backtestId = `backtest_${Date.now()}`;
this.runId = validatedConfig.runId || null;
// Set speed multiplier from config
if (validatedConfig.speed) {
@ -399,8 +314,6 @@ export class BacktestEngine extends EventEmitter {
},
};
await this.storeResults(result);
this.container.logger.info(
`Backtest completed: ${performance.totalTrades} trades, ${performance.totalReturn}% return`
);
@ -415,141 +328,6 @@ export class BacktestEngine extends EventEmitter {
}
}
private async loadHistoricalData(config: BacktestConfig): Promise<MarketData[]> {
const data: MarketData[] = [];
const startDate = new Date(config.startDate);
const endDate = new Date(config.endDate);
try {
for (const symbol of config.symbols) {
const bars = await this.storageService.getHistoricalBars(
symbol,
startDate,
endDate,
config.dataFrequency
);
// If no data found, use mock data
if (!bars || bars.length === 0) {
this.container.logger.warn(`No historical data found for ${symbol}, using mock data`);
// Tell the Rust core to generate mock data
const tradingEngine = this.strategyManager.getTradingEngine();
if (tradingEngine && tradingEngine.generateMockData) {
await tradingEngine.generateMockData(
symbol,
startDate.getTime(),
endDate.getTime(),
42 // seed for reproducibility
);
// For now, we'll generate mock data on the TypeScript side
// as the Rust integration needs more work
const mockData = this.generateMockData(symbol, startDate, endDate);
data.push(...mockData);
} else {
// Fallback to TypeScript mock data generation
const mockData = this.generateMockData(symbol, startDate, endDate);
data.push(...mockData);
}
} else {
// Convert to MarketData format
bars.forEach(bar => {
data.push({
type: 'bar',
data: {
symbol,
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap,
timestamp: new Date(bar.timestamp).getTime(),
},
});
});
}
}
} catch (error) {
this.container.logger.warn('Error loading historical data, using mock data:', {
value: error,
});
// Generate mock data for all symbols
for (const symbol of config.symbols) {
const mockData = this.generateMockData(symbol, startDate, endDate);
data.push(...mockData);
}
}
// Sort by timestamp
data.sort((a, b) => {
const timeA = a.data.timestamp;
const timeB = b.data.timestamp;
return timeA - timeB;
});
return data;
}
private generateMockData(symbol: string, startDate: Date, endDate: Date): MarketData[] {
const data: MarketData[] = [];
const startTime = startDate.getTime();
const endTime = endDate.getTime();
const interval = 24 * 60 * 60 * 1000; // 1 day in milliseconds
let price = 100; // Base price
let currentTime = startTime;
let trend = 0; // Current trend direction
let trendStrength = 0;
let trendDuration = 0;
while (currentTime <= endTime) {
// Every 10-30 days, change trend (more frequent for testing)
if (trendDuration <= 0) {
trend = Math.random() > 0.5 ? 1 : -1;
trendStrength = 0.003 + Math.random() * 0.005; // 0.3% to 0.8% daily trend
trendDuration = Math.floor(10 + Math.random() * 20); // Shorter trends
}
// Generate price movement with trend and noise
const trendComponent = trend * trendStrength;
const noiseComponent = (Math.random() - 0.5) * 0.03; // +/- 1.5% noise
const changePercent = trendComponent + noiseComponent;
price = price * (1 + changePercent);
// Generate OHLC with realistic intraday movement
const open = price * (1 + (Math.random() - 0.5) * 0.005);
const dayRange = 0.01 + Math.random() * 0.02; // 1-3% daily range
const high = Math.max(open, price) * (1 + Math.random() * dayRange);
const low = Math.min(open, price) * (1 - Math.random() * dayRange);
const close = low + Math.random() * (high - low);
const volume = Math.random() * 1000000 + 500000;
trendDuration--;
data.push({
type: 'bar',
data: {
symbol,
open,
high,
low,
close,
volume,
vwap: (open + high + low + close) / 4,
timestamp: currentTime,
},
});
currentTime += interval;
price = close; // Next bar opens at previous close
}
return data;
}
private populateEventQueue(marketData: MarketData[]): void {
// Convert market data to events
marketData.forEach(data => {
@ -815,8 +593,7 @@ export class BacktestEngine extends EventEmitter {
});
}
// Store in database
await this.storageService.storeFill(fill);
// Simulated fills are persisted only inside the runner's backtest result, not the trading ledger.
}
private async updateEquityCurve(): Promise<void> {
@ -916,24 +693,7 @@ export class BacktestEngine extends EventEmitter {
}
private sendProgressUpdate(progress: number, currentDate: string): void {
if (!this.runId) {
return;
}
try {
// Try to send WebSocket update to web-api
const url = `http://localhost:2003/api/runs/${this.runId}/progress`;
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ progress, currentDate }),
}).catch(err => {
// Ignore errors - WebSocket updates are best-effort
this.container.logger.debug('Failed to send progress update:', err);
});
} catch (_error) {
// Ignore errors
}
this.emit('progress', { progress, currentDate });
}
private calculateDrawdown(): { timestamp: number; value: number }[] {
@ -1057,7 +817,7 @@ export class BacktestEngine extends EventEmitter {
// Group equity by day
for (const point of this.equityCurve) {
const date = new Date(point.timestamp).toDateString();
const date = new Date(point.timestamp).toISOString().slice(0, 10);
dailyEquity.set(date, point.value);
}
@ -1090,14 +850,6 @@ export class BacktestEngine extends EventEmitter {
}));
}
private async storeResults(result: BacktestResult): Promise<void> {
// Store performance metrics
await this.storageService.storeStrategyPerformance(result.backtestId, result.metrics);
// Could also store detailed results in a separate table or file
this.container.logger.debug(`Backtest results stored with ID: ${result.backtestId}`);
}
private reset(): void {
this.eventQueue = [];
this.currentTime = 0;
@ -1431,6 +1183,10 @@ export class BacktestEngine extends EventEmitter {
this.isPaused = false;
}
async shutdown(): Promise<void> {
await this.stopBacktest();
}
setSpeedMultiplier(speed: number | null): void {
this.speedMultiplier = speed;
this.container.logger.info(

View file

@ -0,0 +1,236 @@
import { EventEmitter } from 'node:events';
import { z } from 'zod';
import type { Logger } from '@stock-bot/services';
import type { BacktestRunResult } from '@stock-bot/types';
import { BacktestConfigSchema, type BacktestConfig } from '../types';
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
import { normalizeBacktestResult } from './result';
import {
BacktestConflictError,
type BacktestRunRepository,
type RunIdentity,
} from './run-repository';
export function parseBacktestRequest(input: unknown): BacktestConfig {
const config = BacktestConfigSchema.parse(input);
if (new Date(config.endDate) <= new Date(config.startDate)) {
throw new z.ZodError([
{ code: 'custom', path: ['endDate'], message: 'Backtest endDate must be after startDate' },
]);
}
return config;
}
/** One application workflow for HTTP, jobs, and both execution backends. */
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: RunIdentity | undefined;
private cancelled = false;
private progressWrites: Promise<void> = Promise.resolve();
private closing = false;
private phase: 'preparing' | 'executing' | 'persisting' = 'preparing';
private execution: Promise<BacktestRunResult> | undefined;
constructor(
private readonly dependencies: {
engine: BacktestExecutionEngine;
engineName: Exclude<BacktestRunResult['engine'], 'legacy'>;
repository: BacktestRunRepository;
logger: Pick<Logger, 'error'>;
prepare?: (config: BacktestConfig) => Promise<void>;
}
) {
super();
}
async runBacktest(input: unknown): Promise<BacktestRunResult> {
const config = parseBacktestRequest(input);
if (this.closing) {
throw new BacktestConflictError('Backtest runner is shutting down');
}
if (this.busy) {
throw new BacktestConflictError('A backtest is already running');
}
this.busy = true;
this.cancelled = false;
this.phase = 'preparing';
this.execution = this.execute(config);
return this.execution;
}
private async execute(config: BacktestConfig): Promise<BacktestRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
const onProgress = (data: unknown) => {
const active = this.active;
if (
!active ||
typeof data !== 'object' ||
data === null ||
!('progress' in data) ||
typeof data.progress !== 'number' ||
!Number.isFinite(data.progress)
) {
return;
}
const progress = Math.max(0, Math.min(100, data.progress));
const date =
'currentDate' in data &&
typeof data.currentDate === 'string' &&
Number.isFinite(Date.parse(data.currentDate))
? data.currentDate
: undefined;
this.progressWrites = this.progressWrites
.then(() => this.dependencies.repository.updateProgress(active.runId, progress, date))
.catch(error => {
this.dependencies.logger.error('Could not persist backtest progress', { error });
});
this.publish('progress', { ...data, progress, runId: active.runId });
};
this.dependencies.engine.on('progress', onProgress);
try {
this.active = await this.dependencies.repository.start(config);
const executionConfig = { ...config, ...this.active };
await this.dependencies.prepare?.(executionConfig);
if (this.cancelled) {
throw new BacktestCancelledError();
}
this.phase = 'executing';
const raw = await this.dependencies.engine.runBacktest(executionConfig);
this.phase = 'persisting';
let result: BacktestRunResult;
try {
result = normalizeBacktestResult(
raw,
this.dependencies.engineName,
executionConfig,
this.active,
performance.now() - started,
this.cancelled
);
} catch (error) {
throw new Error('Backtest engine returned an invalid result', { cause: error });
}
await this.progressWrites;
await this.dependencies.repository.complete(result);
// Observers cannot turn a committed success into a failed run.
this.publish('complete', result);
return result;
} catch (error) {
await this.progressWrites;
let failure = error;
if (this.active) {
try {
if (error instanceof BacktestCancelledError) {
await this.dependencies.repository.cancel(this.active.runId);
} else {
await this.dependencies.repository.fail(
this.active.runId,
error instanceof Error ? error.message : String(error)
);
}
} catch (persistenceError) {
this.dependencies.logger.error('Could not record backtest failure', { persistenceError });
// A cancellation acknowledgement must never conceal a failed status write.
if (error instanceof BacktestCancelledError) {
failure = persistenceError;
}
}
}
if (failure instanceof BacktestCancelledError) {
this.publish('cancelled', { ...this.active, status: 'cancelled' });
} else if (this.listenerCount('error')) {
this.publish('error', failure);
}
throw failure;
} finally {
this.dependencies.engine.off('progress', onProgress);
this.active = undefined;
this.busy = false;
}
}
private publish(event: string, value: unknown) {
try {
this.emit(event, value);
} catch (error) {
this.dependencies.logger.error('Backtest observer failed', { event, error });
}
}
private requireActive(runId?: string) {
if (!this.active || (runId && this.active.runId !== runId)) {
throw new BacktestConflictError('No matching active backtest');
}
return this.active;
}
async stopBacktest(runId?: string) {
this.requireActive(runId);
if (this.phase === 'persisting') {
throw new BacktestConflictError('Backtest execution has already finished');
}
const execution = this.execution;
this.cancelled = true;
if (this.phase === 'executing') {
try {
await this.dependencies.engine.stopBacktest();
} catch (error) {
this.cancelled = false;
throw error;
}
}
try {
await execution;
} catch (error) {
if (!(error instanceof BacktestCancelledError)) {
throw error;
}
}
}
async shutdown(): Promise<void> {
this.closing = true;
const execution = this.busy ? this.execution : undefined;
if (this.busy && this.phase !== 'persisting') {
this.cancelled = true;
if (this.phase === 'executing') {
await this.dependencies.engine.stopBacktest();
}
}
// Allow the owner to commit cancellation/failure before database shutdown.
try {
await execution?.catch(error => {
if (!(error instanceof BacktestCancelledError)) {
throw error;
}
});
} finally {
await this.dependencies.engine.shutdown();
}
}
async pauseBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.pauseBacktest();
await this.dependencies.repository.updateControl(active.runId, { status: 'paused' });
}
async resumeBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.resumeBacktest();
await this.dependencies.repository.updateControl(active.runId, { status: 'running' });
}
async setSpeedMultiplier(speed: number | null, runId?: string) {
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
throw new Error('Backtest speed must be positive or null');
}
const active = this.requireActive(runId);
this.dependencies.engine.setSpeedMultiplier(speed);
await this.dependencies.repository.updateControl(active.runId, { speedMultiplier: speed });
}
getStatus() {
return {
...this.dependencies.engine.getStatus(),
isRunning: this.busy,
runId: this.active?.runId,
};
}
}

View file

@ -0,0 +1,121 @@
import { fork, type ChildProcess } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol';
import { BacktestConflictError } from './run-repository';
/** Hard cancellation requires a process boundary: a thread cannot interrupt native Rust. */
export class NativeBacktestWorker {
private active: ChildProcess | undefined;
constructor(
private readonly workerUrl = new URL(
import.meta.url.endsWith('.ts') ? './native-worker.ts' : './native-worker.js',
import.meta.url
)
) {}
async execute(
request: NativeWorkerRequest,
signal: AbortSignal,
onProgress: (progress: { progress: number; message: string }) => void
): Promise<string> {
signal.throwIfAborted();
if (this.active) {
throw new BacktestConflictError('A native backtest worker is already running');
}
const child = fork(fileURLToPath(this.workerUrl), [], {
execPath: process.execPath,
execArgv: [],
serialization: 'json',
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
});
this.active = child;
return new Promise<string>((resolve, reject) => {
let result: string | undefined;
let failure: Error | undefined;
let stderr = '';
let settled = false;
const terminate = (error: Error) => {
failure ??= error;
// SIGKILL also interrupts an uncooperative synchronous native call.
child.kill('SIGKILL');
};
const onAbort = () =>
terminate(
signal.reason instanceof Error ? signal.reason : new Error('Native execution aborted')
);
const onStderr = (chunk: Buffer) => {
// Drain native diagnostics without unbounded buffering or blocking on a full pipe.
stderr = (stderr + chunk.toString()).slice(-4096);
};
const onMessage = (input: unknown) => {
if (failure) {
return;
}
const parsed = nativeWorkerMessageSchema.safeParse(input);
if (!parsed.success || result !== undefined) {
terminate(new Error('Invalid native backtest worker response'));
return;
}
const message = parsed.data;
if (message.type === 'error') {
terminate(new Error(message.message));
} else if (message.type === 'result') {
result = message.result;
} else {
try {
onProgress({ progress: message.progress, message: message.message });
} catch (error) {
terminate(error instanceof Error ? error : new Error(String(error)));
}
}
};
const finish = (code: number | null, exitSignal: NodeJS.Signals | null) => {
if (settled) {
return;
}
settled = true;
signal.removeEventListener('abort', onAbort);
child.off('message', onMessage);
child.stderr?.off('data', onStderr);
this.active = undefined;
if (failure) {
reject(failure);
} else if (code !== 0 || result === undefined) {
reject(
new Error(
`Native backtest worker exited without a result (code ${code}, signal ${exitSignal})${stderr ? `: ${stderr}` : ''}`
)
);
} else {
resolve(result);
}
};
child.on('message', onMessage);
child.stderr?.on('data', onStderr);
child.once('error', error => {
terminate(error);
// Spawn failures have no process to reap; normal errors wait for exit.
if (child.pid === undefined) {
finish(null, null);
}
});
// Wait for IPC/stdio to drain too; exit alone can precede the last message.
child.once('close', finish);
signal.addEventListener('abort', onAbort, { once: true });
if (signal.aborted) {
onAbort();
return;
}
try {
child.send(request, error => {
if (error) {
terminate(error);
}
});
} catch (error) {
terminate(error instanceof Error ? error : new Error(String(error)));
}
});
}
}

View file

@ -0,0 +1,170 @@
import { randomUUID } from 'node:crypto';
import type { PostgresClient } from '@stock-bot/services';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
import {
BacktestConflictError,
type BacktestRunRepository,
type RunIdentity,
} from './run-repository';
/** Uses the existing backtests/runs schema; never commits completion without the result. */
export class PostgresBacktestRunRepository implements BacktestRunRepository {
constructor(private readonly postgres: Pick<PostgresClient, 'transaction'>) {}
async start(config: BacktestConfig): Promise<RunIdentity> {
return this.postgres.transaction(async client => {
if (config.runId) {
const claimed = await client.query<{ id: string; backtest_id: string }>(
`UPDATE runs SET status = 'running', progress = 0, error = NULL,
started_at = NOW(), completed_at = NULL, updated_at = NOW()
WHERE id = $1 AND status IN ('pending', 'failed')
AND ($2::uuid IS NULL OR backtest_id = $2::uuid)
RETURNING id, backtest_id`,
[config.runId, config.backtestId ?? null]
);
const run = claimed.rows[0];
if (!run) {
throw new BacktestConflictError('Run is missing, already claimed, or terminal');
}
return { runId: run.id, backtestId: run.backtest_id };
}
const backtestId = config.backtestId ?? randomUUID();
if (!config.backtestId) {
await client.query(
`INSERT INTO backtests
(id, name, strategy, symbols, start_date, end_date, initial_capital, config)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
[
backtestId,
config.name ?? 'Backtest',
config.strategy,
JSON.stringify(config.symbols),
config.startDate,
config.endDate,
config.initialCapital,
JSON.stringify({
...config.config,
dataFrequency: config.dataFrequency,
commission: config.commission,
slippage: config.slippage,
}),
]
);
}
// Serialize run numbering on the parent rather than racing MAX(run_number).
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
backtestId,
]);
if (!parent.rows.length) {
throw new Error('Backtest definition not found');
}
const runId = randomUUID();
await client.query(
`INSERT INTO runs (id, backtest_id, run_number, status, started_at, speed_multiplier)
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, 'running'::run_status, NOW(), $3
FROM runs WHERE backtest_id = $2`,
[
runId,
backtestId,
config.speed === 'max'
? null
: config.speed === 'realtime'
? 1
: Number.parseFloat(config.speed),
]
);
return { runId, backtestId };
});
}
async complete(result: BacktestRunResult): Promise<void> {
await this.postgres.transaction(async client => {
const updated = await client.query(
`UPDATE runs SET status = $2, progress = CASE WHEN $2 = 'completed' THEN 100 ELSE progress END,
completed_at = $3, updated_at = NOW(), error = NULL
WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused') RETURNING id`,
[result.runId, result.status, result.completedAt, result.backtestId]
);
if (!updated.rows.length) {
throw new BacktestConflictError('Run no longer belongs to this execution');
}
await client.query(
`INSERT INTO backtest_results
(run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time, configuration, engine)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
[
result.runId,
result.completedAt,
JSON.stringify(result.metrics),
JSON.stringify(result.equity),
JSON.stringify(result.ohlcData),
JSON.stringify(result.trades),
JSON.stringify(result.positions),
JSON.stringify(result.analytics),
result.executionTime,
JSON.stringify(result.config),
result.engine,
]
);
});
}
async updateProgress(runId: string, progress: number, currentDate?: string): Promise<void> {
await this.postgres.transaction(async client => {
await client.query(
`UPDATE runs SET progress = GREATEST(progress, $2),
current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused')`,
[runId, progress, currentDate ?? null]
);
});
}
async updateControl(
runId: string,
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null }
): Promise<void> {
await this.postgres.transaction(async client => {
const result = await client.query(
`UPDATE runs SET status = COALESCE($2::run_status, status),
paused_at = CASE WHEN $2 = 'paused' THEN NOW() ELSE paused_at END,
speed_multiplier = CASE WHEN $3 THEN $4 ELSE speed_multiplier END, updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused') RETURNING id`,
[
runId,
update.status ?? null,
update.speedMultiplier !== undefined,
update.speedMultiplier ?? null,
]
);
if (!result.rows.length) {
throw new BacktestConflictError('No matching active run');
}
});
}
async fail(runId: string, error: string): Promise<void> {
await this.postgres.transaction(async client => {
await client.query(
`UPDATE runs SET status = 'failed', error = $2, completed_at = NOW(), updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused')`,
[runId, error]
);
});
}
async cancel(runId: string): Promise<void> {
await this.postgres.transaction(async client => {
const result = await client.query(
`UPDATE runs SET status = 'cancelled', error = NULL, completed_at = NOW(), updated_at = NOW()
WHERE id = $1 AND status IN ('running', 'paused') RETURNING id`,
[runId]
);
if (!result.rows.length) {
throw new BacktestConflictError('No matching active run to cancel');
}
});
}
}

View file

@ -1,18 +1,42 @@
import { EventEmitter } from 'node:events';
import { BacktestEngine as RustEngine } from '@stock-bot/engine';
import { StorageService } from '../services/StorageService';
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
import {
BacktestCancelledError,
BacktestTimeoutError,
type BacktestExecutionEngine,
} from './execution-engine';
import { nativeResultSchema, type NativeBacktestResult } from './native-result';
import { resolveNativeStrategies } from './native-strategies';
import type { NativeWorkerRequest } from './native-worker-protocol';
import { NativeBacktestWorker } from './NativeBacktestWorker';
export type BacktestResult = NativeBacktestResult;
/** Validates the native boundary; all historical data comes from the storage owner. */
export class RustBacktestAdapter extends EventEmitter {
/** Storage stays in the parent; all native backtest execution stays in a disposable worker. */
export class RustBacktestAdapter extends EventEmitter implements BacktestExecutionEngine {
private readonly storageService: StorageService;
private isRunning = false;
private readonly worker: NativeBacktestWorker;
private readonly timeoutMs: number;
private active: { controller: AbortController; finished: Promise<void> } | undefined;
private closing = false;
private progress = 0;
private currentTime = 0;
constructor(private readonly container: OrchestratorServices) {
constructor(
private readonly container: OrchestratorServices,
options: { timeoutMs?: number; workerUrl?: URL } = {}
) {
super();
this.timeoutMs = options.timeoutMs ?? 300_000;
if (
!Number.isInteger(this.timeoutMs) ||
this.timeoutMs <= 0 ||
this.timeoutMs > 2_147_483_647
) {
throw new Error('Native backtest timeout must be a positive 32-bit integer');
}
this.worker = new NativeBacktestWorker(options.workerUrl);
this.storageService =
container.custom?.StorageService ??
new StorageService(
@ -24,103 +48,136 @@ export class RustBacktestAdapter extends EventEmitter {
}
async runBacktest(input: BacktestConfig): Promise<NativeBacktestResult> {
if (this.isRunning) {
throw new Error('Backtest already running');
if (this.closing || this.active) {
throw new Error(
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
);
}
const config = BacktestConfigSchema.parse(input);
this.isRunning = true;
const controller = new AbortController();
let finished!: () => void;
this.active = {
controller,
finished: new Promise<void>(resolve => {
finished = resolve;
}),
};
this.progress = 0;
this.currentTime = Date.parse(config.startDate);
const timeout = setTimeout(
() => controller.abort(new BacktestTimeoutError(this.timeoutMs)),
this.timeoutMs
);
const { signal } = controller;
const onAbort = () => rejectAbort(signal.reason);
let rejectAbort!: (reason: unknown) => void;
const aborted = new Promise<never>((_resolve, reject) => {
rejectAbort = reject;
});
signal.addEventListener('abort', onAbort, { once: true });
try {
const engine = new RustEngine({
name: config.name ?? 'Backtest',
strategy: config.strategy,
symbols: config.symbols,
startDate: config.startDate,
endDate: config.endDate,
initialCapital: config.initialCapital,
commission: config.commission ?? 0.001,
slippage: config.slippage ?? 0.0001,
dataFrequency: config.dataFrequency,
resolveNativeStrategies(config);
// Race the read too: a slow database must not prevent cancellation. A late read
// cannot spawn a worker after the run has been stopped.
const data = await Promise.race([this.loadData(config, signal), aborted]);
signal.throwIfAborted();
const raw = await this.worker.execute({ type: 'run', config, data }, signal, progress => {
this.progress = progress.progress;
this.publish('progress', progress);
});
const parameters = config.config ?? {};
if (parameters.useTypeScriptImplementation) {
throw new Error('The native engine does not execute TypeScript strategy callbacks');
}
const name = config.strategy.toLowerCase();
const strategy =
name.includes('mean') || name.includes('reversion')
? 'mean_reversion'
: name.includes('momentum')
? 'momentum'
: name.includes('pairs')
? 'pairs_trading'
: name.includes('sma') || name.includes('crossover') || name === 'moving-average'
? 'sma_crossover'
: undefined;
if (!strategy) {
throw new Error(`Unknown native strategy: ${config.strategy}`);
}
engine.addNativeStrategy(strategy, config.strategy, 'backtest-strategy', parameters);
const data = [];
for (const symbol of config.symbols) {
const bars = await this.storageService.getHistoricalBars(
symbol,
new Date(config.startDate),
new Date(config.endDate),
config.dataFrequency
);
if (!bars.length) {
throw new Error(`No historical data for ${symbol}`);
}
data.push(
...bars.map(bar => ({
symbol,
timestamp: bar.timestamp.getTime(),
type: 'bar',
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap ?? (bar.high + bar.low + bar.close) / 3,
}))
);
}
data.sort((a, b) => a.timestamp - b.timestamp);
engine.loadMarketData(data);
this.emit('progress', { progress: 0, message: 'Historical data loaded' });
const result = nativeResultSchema.parse(JSON.parse(engine.run()));
this.currentTime = new Date(config.endDate).getTime();
this.emit('complete', result);
const result = nativeResultSchema.parse(JSON.parse(raw));
this.currentTime = Date.parse(config.endDate);
this.progress = 100;
this.publish('complete', result);
return result;
} catch (error) {
this.container.logger.error('Native backtest failed', { error });
if (!(error instanceof BacktestCancelledError)) {
this.container.logger.error('Native backtest failed', { error });
}
if (this.listenerCount('error') > 0) {
this.emit('error', error);
this.publish('error', error);
}
throw error;
} finally {
this.isRunning = false;
clearTimeout(timeout);
signal.removeEventListener('abort', onAbort);
this.active = undefined;
finished();
}
}
private async loadData(
config: BacktestConfig,
signal: AbortSignal
): Promise<NativeWorkerRequest['data']> {
const data: NativeWorkerRequest['data'] = [];
for (const symbol of config.symbols) {
signal.throwIfAborted();
const bars = await this.storageService.getHistoricalBars(
symbol,
new Date(config.startDate),
new Date(config.endDate),
config.dataFrequency
);
signal.throwIfAborted();
if (!bars.length) {
throw new Error(`No historical data for ${symbol}`);
}
for (const bar of bars) {
data.push({
symbol,
timestamp: bar.timestamp.getTime(),
type: 'bar',
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap ?? (bar.high + bar.low + bar.close) / 3,
});
}
}
return data;
}
private publish(event: string, data: unknown): void {
try {
this.emit(event, data);
} catch (error) {
this.container.logger.error('Native backtest observer failed', { event, error });
}
}
getStatus() {
return {
isRunning: this.isRunning,
isRunning: !!this.active,
isPaused: false,
progress: this.isRunning ? 0 : 100,
progress: this.progress,
currentTime: this.currentTime,
};
}
async stopBacktest(): Promise<void> {
throw new Error('Native synchronous backtests do not support cancellation');
const active = this.active;
if (!active) {
throw new Error('No native backtest is running');
}
active.controller.abort(new BacktestCancelledError());
// Acknowledgement means the worker has exited, not merely that a signal was sent.
await active.finished;
}
async shutdown(): Promise<void> {
this.closing = true;
if (this.active) {
await this.stopBacktest();
}
}
async pauseBacktest(): Promise<void> {
throw new Error('Native synchronous backtests do not support pause');
throw new Error('Native backtests do not support pause');
}
async resumeBacktest(): Promise<void> {
throw new Error('Native synchronous backtests do not support resume');
throw new Error('Native backtests do not support resume');
}
setSpeedMultiplier(_speed: number | null): void {
throw new Error('Native synchronous backtests run at maximum speed');
throw new Error('Native backtests run at maximum speed');
}
}

View file

@ -0,0 +1,35 @@
import type { EventEmitter } from 'node:events';
import type { BacktestConfig } from '../types';
import type { NativeBacktestResult } from './native-result';
import type { BacktestResult } from './typescript-result';
/** The runner depends on execution capabilities, not backend implementations. */
export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'> {
runBacktest(config: BacktestConfig): Promise<BacktestResult | NativeBacktestResult>;
stopBacktest(): Promise<void>;
pauseBacktest(): Promise<void>;
resumeBacktest(): Promise<void>;
setSpeedMultiplier(speed: number | null): void;
getStatus(): {
isRunning: boolean;
isPaused: boolean;
progress: number;
currentTime: number;
};
shutdown(): Promise<void>;
}
/** Cancellation has no result when a native worker is forcibly stopped. */
export class BacktestCancelledError extends Error {
constructor() {
super('Backtest cancelled');
this.name = 'BacktestCancelledError';
}
}
export class BacktestTimeoutError extends Error {
constructor(timeoutMs: number) {
super(`Native backtest exceeded its ${timeoutMs}ms execution deadline`);
this.name = 'BacktestTimeoutError';
}
}

View file

@ -0,0 +1,36 @@
import type { BacktestConfig } from '../types';
/** Resolve before fetching data, and validate again in the isolated worker. */
export function resolveNativeStrategies(config: BacktestConfig) {
const strategies = config.strategies
? config.strategies
.filter(strategy => strategy.enabled)
.map(strategy => ({
name: strategy.name,
parameters: { ...config.config, ...strategy.config },
}))
: [{ name: config.strategy, parameters: config.config ?? {} }];
if (!strategies.length) {
throw new Error('No enabled backtest strategies');
}
const aliases: Record<string, string> = {
sma: 'sma_crossover',
smacrossover: 'sma_crossover',
simplemovingaveragecrossover: 'sma_crossover',
movingaverage: 'sma_crossover',
meanreversion: 'mean_reversion',
momentum: 'momentum',
pairs: 'pairs_trading',
pairstrading: 'pairs_trading',
};
return strategies.map(({ name, parameters }, index) => {
if (parameters.useTypeScriptImplementation) {
throw new Error('The native engine does not execute TypeScript strategy callbacks');
}
const strategy = aliases[name.toLowerCase().replace(/[-_ ]/g, '')];
if (!strategy) {
throw new Error(`Unknown native strategy: ${name}`);
}
return { strategy, name, id: `backtest-strategy-${index}`, parameters };
});
}

View file

@ -0,0 +1,30 @@
import { z } from 'zod';
import { BacktestConfigSchema } from '../types';
const finite = z.number().finite();
export const nativeWorkerRequestSchema = z.object({
type: z.literal('run'),
config: BacktestConfigSchema,
data: z.array(
z.object({
symbol: z.string(),
timestamp: finite,
type: z.literal('bar'),
open: finite,
high: finite,
low: finite,
close: finite,
volume: finite,
vwap: finite,
})
),
});
export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('progress'), progress: finite.min(0).max(100), message: z.string() }),
z.object({ type: z.literal('result'), result: z.string() }),
z.object({ type: z.literal('error'), message: z.string() }),
]);
export type NativeWorkerRequest = z.infer<typeof nativeWorkerRequestSchema>;
export type NativeWorkerMessage = z.infer<typeof nativeWorkerMessageSchema>;

View file

@ -0,0 +1,47 @@
import { BacktestEngine } from '@stock-bot/engine';
import { resolveNativeStrategies } from './native-strategies';
import { nativeWorkerRequestSchema, type NativeWorkerMessage } from './native-worker-protocol';
/** One process, one native engine, one request. No database or service-container access. */
function send(message: NativeWorkerMessage): Promise<void> {
return new Promise((resolve, reject) => {
if (!process.send) {
reject(new Error('Native backtest worker requires an IPC channel'));
return;
}
process.send(message, (error: Error | null) => (error ? reject(error) : resolve()));
});
}
process.once('message', async (input: unknown) => {
try {
const { config, data } = nativeWorkerRequestSchema.parse(input);
const engine = new BacktestEngine({
name: config.name ?? 'Backtest',
strategy: config.strategy,
symbols: config.symbols,
startDate: config.startDate,
endDate: config.endDate,
initialCapital: config.initialCapital,
commission: config.commission ?? 0.001,
slippage: config.slippage ?? 0.0001,
dataFrequency: config.dataFrequency,
});
for (const { strategy, name, id, parameters } of resolveNativeStrategies(config)) {
engine.addNativeStrategy(strategy, name, id, parameters);
}
data.sort((a, b) => a.timestamp - b.timestamp);
engine.loadMarketData(data);
await send({ type: 'progress', progress: 0, message: 'Native execution started' });
// This synchronous call is deliberately confined to the child process.
await send({ type: 'result', result: engine.run() });
} catch (error) {
await send({ type: 'error', message: error instanceof Error ? error.message : String(error) });
process.exitCode = 1;
} finally {
process.disconnect?.();
}
});
// Exit on parent disconnection once control returns from native code.
process.once('disconnect', () => process.exit(process.exitCode ?? 0));

View file

@ -0,0 +1,186 @@
import { z } from 'zod';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
import type { NativeBacktestResult } from './native-result';
import type { RunIdentity } from './run-repository';
import type { BacktestResult as TypeScriptResult } from './typescript-result';
const finite = z.number().finite();
const analyticsSchema = z.object({
exposureTime: finite,
drawdownSeries: z.array(z.object({ timestamp: finite, value: finite })).optional(),
dailyReturns: z.array(finite).optional(),
monthlyReturns: z.record(finite).optional(),
riskMetrics: z.record(finite).optional(),
});
/** Validate once before persistence and before publishing a terminal result. */
export const backtestRunResultSchema: z.ZodType<BacktestRunResult> = z.object({
runId: z.string().uuid(),
backtestId: z.string().uuid(),
engine: z.enum(['native', 'typescript']),
status: z.enum(['completed', 'cancelled']),
completedAt: z.string().datetime(),
config: z.object({
name: z.string(),
strategy: z.string(),
symbols: z.array(z.string()),
startDate: z.string().datetime(),
endDate: z.string().datetime(),
initialCapital: finite,
commission: finite,
slippage: finite,
dataFrequency: z.string(),
parameters: z.record(z.unknown()),
strategies: z
.array(
z.object({
name: z.string(),
enabled: z.boolean(),
config: z.record(z.unknown()).optional(),
})
)
.optional(),
}),
metrics: z
.object({
totalReturn: finite,
sharpeRatio: finite,
maxDrawdown: finite,
winRate: finite,
totalTrades: finite,
profitFactor: finite.nullable(),
avgWin: finite,
avgLoss: finite,
})
.catchall(finite.nullable()),
equity: z.array(z.object({ date: z.string(), value: finite })),
ohlcData: z.record(
z.array(
z.object({
timestamp: finite,
open: finite,
high: finite,
low: finite,
close: finite,
volume: finite.optional(),
})
)
),
trades: z.array(
z.object({
kind: z.enum(['fill', 'closed']),
id: z.string(),
symbol: z.string(),
timestamp: z.string(),
side: z.enum(['buy', 'sell']),
price: finite,
quantity: finite,
commission: finite,
pnl: finite.optional(),
positionAfter: finite.optional(),
entryDate: z.string().optional(),
exitDate: z.string().nullable().optional(),
entryPrice: finite.optional(),
exitPrice: finite.optional(),
pnlPercent: finite.optional(),
duration: finite.optional(),
})
),
positions: z.array(
z.object({
symbol: z.string(),
quantity: finite,
averagePrice: finite,
currentPrice: finite,
unrealizedPnl: finite,
realizedPnl: finite,
})
),
analytics: analyticsSchema,
executionTime: finite.nonnegative(),
});
export function normalizeBacktestResult(
raw: NativeBacktestResult | TypeScriptResult,
engine: Exclude<BacktestRunResult['engine'], 'legacy'>,
config: BacktestConfig,
identity: RunIdentity,
executionTime: number,
cancelled: boolean
): BacktestRunResult {
if (raw.status !== 'completed' && raw.status !== 'cancelled') {
throw new Error(
'error' in raw && typeof raw.error === 'string'
? raw.error
: `Backtest engine returned ${raw.status}`
);
}
const trades = raw.trades.map(trade =>
'entryDate' in trade
? {
...trade,
kind: 'closed',
timestamp: trade.entryDate,
price: trade.entryPrice,
}
: { ...trade, kind: 'fill' }
);
// Native serialization uses null for undefined ratios; do the same for TS infinities.
const metrics = Object.fromEntries(
Object.entries(raw.metrics).map(([key, value]) => [
key,
typeof value === 'number' && !Number.isFinite(value) ? null : value,
])
);
// Public returns/win rates are fractions, not percentage points. Both backends
// already report maxDrawdown as a fraction.
metrics.totalReturn = raw.metrics.totalReturn / 100;
metrics.winRate = raw.metrics.winRate / 100;
if (engine === 'typescript') {
metrics.totalTrades = raw.trades.length; // Completed round trips, not individual fills.
metrics.profitableTrades = raw.trades.filter(trade => (trade.pnl ?? 0) > 0).length;
}
for (const key of ['annualReturn', 'annualizedReturn']) {
if (typeof metrics[key] === 'number') {
metrics[key] /= 100;
}
}
const analytics = analyticsSchema.parse(raw.analytics);
analytics.exposureTime /= 100;
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
...point,
value: point.value / 100,
}));
analytics.dailyReturns = analytics.dailyReturns?.map(value =>
engine === 'typescript' ? value / 100 : value
);
if (analytics.monthlyReturns) {
analytics.monthlyReturns = Object.fromEntries(
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
);
}
return backtestRunResultSchema.parse({
...raw,
...identity,
engine,
completedAt: new Date(raw.completedAt).toISOString(),
status: cancelled ? 'cancelled' : raw.status,
executionTime,
config: {
name: config.name ?? 'Backtest',
strategy: config.strategy,
symbols: config.symbols,
startDate: config.startDate,
endDate: config.endDate,
initialCapital: config.initialCapital,
commission: config.commission ?? 0.001,
slippage: config.slippage ?? 0.0001,
dataFrequency: config.dataFrequency,
parameters: config.config ?? {},
strategies: config.strategies,
},
metrics,
trades,
analytics,
});
}

View file

@ -0,0 +1,43 @@
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
export interface RunIdentity {
runId: string;
backtestId: string;
}
/** The runner owns this lifecycle. Results and terminal status must commit atomically. */
export interface BacktestRunRepository {
start(config: BacktestConfig): Promise<RunIdentity>;
complete(result: BacktestRunResult): Promise<void>;
updateProgress(runId: string, progress: number, currentDate?: string): Promise<void>;
fail(runId: string, error: string): Promise<void>;
cancel(runId: string): Promise<void>;
updateControl(
runId: string,
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null }
): Promise<void>;
}
export class BacktestConflictError extends Error {}
export class UnavailableBacktestRunRepository implements BacktestRunRepository {
async start(_config: BacktestConfig): Promise<RunIdentity> {
throw new Error('Backtest execution requires a PostgreSQL run repository');
}
async complete(_result: BacktestRunResult): Promise<void> {
throw new Error('Backtest run repository is unavailable');
}
async updateProgress(): Promise<void> {
throw new Error('Backtest run repository is unavailable');
}
async updateControl(): Promise<void> {
throw new Error('Backtest run repository is unavailable');
}
async fail(_runId: string, _error: string): Promise<void> {
throw new Error('Backtest run repository is unavailable');
}
async cancel(_runId: string): Promise<void> {
throw new Error('Backtest run repository is unavailable');
}
}

View file

@ -0,0 +1,84 @@
/** Internal TypeScript backend output; normalized to BacktestRunResult by the runner. */
export interface OHLCBar {
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
}
export interface BacktestResult {
// Identification
backtestId: string;
status: 'completed' | 'failed' | 'cancelled';
completedAt: string;
// Configuration
config: {
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
commission: number;
slippage: number;
dataFrequency: string;
};
// Performance metrics
metrics: {
totalReturn: number;
sharpeRatio: number;
maxDrawdown: number;
winRate: number;
totalTrades: number;
profitFactor: number;
profitableTrades: number;
avgWin: number;
avgLoss: number;
expectancy: number;
calmarRatio: number;
sortinoRatio: number;
};
// Chart data
equity: Array<{ date: string; value: number }>;
ohlcData: Record<string, OHLCBar[]>;
// Trade history
trades: Array<{
id: string;
symbol: string;
entryDate: string;
exitDate: string | null;
entryPrice: number;
exitPrice: number;
quantity: number;
side: string;
pnl: number;
pnlPercent: number;
commission: number;
duration: number;
}>;
// Positions
positions: Array<{
symbol: string;
quantity: number;
averagePrice: number;
currentPrice: number;
unrealizedPnl: number;
realizedPnl: number;
}>;
// Analytics
analytics: {
drawdownSeries: { timestamp: number; value: number }[];
dailyReturns: number[];
monthlyReturns: Record<string, number>;
exposureTime: number;
riskMetrics: Record<string, number>;
};
}

View file

@ -1,8 +1,13 @@
import { asValue, type AwilixContainer } from 'awilix';
import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di';
import { BacktestEngine } from './backtest/BacktestEngine';
import { BacktestRunner } from './backtest/BacktestRunner';
import type { BacktestExecutionEngine } from './backtest/execution-engine';
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
import { ModeManager } from './core/ModeManager';
import { BacktestHandler } from './handlers/backtest/backtest.handler';
import { PaperTradingManager } from './paper/PaperTradingManager';
import { AnalyticsService } from './services/AnalyticsService';
import { ExecutionService } from './services/ExecutionService';
@ -21,6 +26,7 @@ export async function registerOrchestratorServices(
useRustEngine?: boolean;
allowSyntheticData?: boolean;
syntheticSeed?: number;
nativeExecutionTimeoutMs?: number;
} = {}
): Promise<void> {
// Create a service adapter that provides the expected interface
@ -46,7 +52,7 @@ export async function registerOrchestratorServices(
const strategyManager = new StrategyManager(services);
Object.assign(custom, { StorageService: storageService });
const backtestEngine = options.useRustEngine
? new RustBacktestAdapter(services)
? new RustBacktestAdapter(services, { timeoutMs: options.nativeExecutionTimeoutMs })
: new BacktestEngine(services, storageService, strategyManager);
const paperTradingManager = new PaperTradingManager(
services,
@ -61,6 +67,16 @@ export async function registerOrchestratorServices(
storageService
);
const backtestRunner = new BacktestRunner({
engine: backtestEngine,
engineName: options.useRustEngine ? 'native' : 'typescript',
repository: services.postgres
? new PostgresBacktestRunRepository(services.postgres)
: new UnavailableBacktestRunRepository(),
logger: services.logger,
prepare: options.useRustEngine ? undefined : config => modeManager.initializeMode(config),
});
// Store custom services
Object.assign(services.custom ?? {}, {
StorageService: storageService,
@ -69,6 +85,7 @@ export async function registerOrchestratorServices(
AnalyticsService: analyticsService,
StrategyManager: strategyManager,
BacktestEngine: backtestEngine,
BacktestRunner: backtestRunner,
PaperTradingManager: paperTradingManager,
ModeManager: modeManager,
});
@ -81,7 +98,8 @@ export async function registerOrchestratorServices(
ExecutionService: ExecutionService;
AnalyticsService: AnalyticsService;
StrategyManager: StrategyManager;
BacktestEngine: BacktestEngine | RustBacktestAdapter;
BacktestEngine: BacktestExecutionEngine;
BacktestRunner: BacktestRunner;
PaperTradingManager: PaperTradingManager;
ModeManager: ModeManager;
orchestratorServices: IServiceContainer;
@ -94,6 +112,7 @@ export async function registerOrchestratorServices(
AnalyticsService: asValue(analyticsService),
StrategyManager: asValue(strategyManager),
BacktestEngine: asValue(backtestEngine),
BacktestRunner: asValue(backtestRunner),
PaperTradingManager: asValue(paperTradingManager),
ModeManager: asValue(modeManager),
orchestratorServices: asValue(services),
@ -105,6 +124,10 @@ export async function registerOrchestratorServices(
Object.assign(serviceContainer.custom, services.custom);
}
container
.resolve('handlerScanner')
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
// Setup event listeners after all services are registered
strategyManager.setupEventListeners();
@ -112,6 +135,8 @@ export async function registerOrchestratorServices(
if (options.initializeMode !== false) {
await modeManager.initializeMode({ mode: 'paper', startingCapital: 100000 });
}
// Start job consumption only after the shared graph and initial mode are ready.
services.queueManager?.getQueue('orchestrator');
}
// For backward compatibility, export a container getter

View file

@ -66,17 +66,15 @@ export class DataManager extends EventEmitter {
for (const symbol of symbols) {
try {
// Load raw data
let data = await this.storageService.getHistoricalBars(
const data = await this.storageService.getHistoricalBars(
symbol,
startDate,
endDate,
resolution
);
// If no data found, generate mock data
if (!data || data.length === 0) {
logger.warn(`No historical data found for ${symbol}, generating mock data`);
data = this.generateMockBars(symbol, startDate, endDate, resolution);
if (!data.length) {
throw new Error(`No historical data for ${symbol}`);
}
// Apply corporate actions
@ -84,6 +82,9 @@ export class DataManager extends EventEmitter {
// Quality checks
const cleanedData = this.performQualityChecks(symbol, adjustedData);
if (!cleanedData.length) {
throw new Error(`No valid historical data for ${symbol}`);
}
// Convert to MarketData format
const marketData = this.convertToMarketData(symbol, cleanedData);
@ -95,6 +96,8 @@ export class DataManager extends EventEmitter {
} catch (error) {
logger.error(`Failed to load data for ${symbol}:`, error);
this.emit('dataError', { symbol, error });
this.dataCache.clear();
throw error;
}
}
@ -437,68 +440,4 @@ export class DataManager extends EventEmitter {
this.aggregatedCache.clear();
this.dataQualityIssues = [];
}
private generateMockBars(
symbol: string,
startDate: Date,
endDate: Date,
resolution: string
): HistoricalBar[] {
const bars: HistoricalBar[] = [];
const resolutionMs = DataManager.RESOLUTIONS[resolution]?.milliseconds || 86400000; // Default to 1 day
let currentTime = startDate.getTime();
const endTime = endDate.getTime();
// Base price varies by symbol
let basePrice = 100;
if (symbol === 'AAPL') {
basePrice = 150;
} else if (symbol === 'GOOGL') {
basePrice = 140;
} else if (symbol === 'MSFT') {
basePrice = 380;
} else if (symbol === 'TSLA') {
basePrice = 250;
}
let price = basePrice;
while (currentTime <= endTime) {
// Generate realistic intraday movement
const volatility = 0.02; // 2% daily volatility
const trend = 0.0001; // Slight upward trend
// Random walk with trend
const changePercent = (Math.random() - 0.5) * volatility + trend;
price = price * (1 + changePercent);
// Generate OHLC
const open = price;
const intraDayVolatility = volatility / 4;
const high = price * (1 + Math.random() * intraDayVolatility);
const low = price * (1 - Math.random() * intraDayVolatility);
const close = low + Math.random() * (high - low);
// Volume with some randomness
const baseVolume = 10000000; // 10M shares
const volume = baseVolume * (0.5 + Math.random());
bars.push({
symbol,
timestamp: new Date(currentTime),
open: Number(open.toFixed(2)),
high: Number(high.toFixed(2)),
low: Number(low.toFixed(2)),
close: Number(close.toFixed(2)),
volume: Math.floor(volume),
vwap: Number(((high + low + close) / 3).toFixed(2)),
});
currentTime += resolutionMs;
price = close; // Next bar opens at previous close
}
return bars;
}
}

View file

@ -1,120 +1,32 @@
import { z } from 'zod';
import { BaseHandler, Handler, Operation } from '@stock-bot/handlers';
import { getLogger } from '@stock-bot/logger';
import { defined } from '@stock-bot/invariants';
import type { BacktestRunner } from '../../backtest/BacktestRunner';
import type { OrchestratorServices } from '../../types';
const logger = getLogger('backtest-handler');
interface BacktestPayload {
backtestId: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config?: Record<string, unknown>;
}
interface CancelBacktestPayload {
backtestId: string;
}
@Handler('orchestrator')
export class BacktestHandler extends BaseHandler<OrchestratorServices> {
private readonly runner: BacktestRunner;
constructor(services: OrchestratorServices) {
super(services);
this.runner = defined(services.custom?.BacktestRunner, 'Backtest runner is unavailable');
}
@Operation('run-backtest')
async runBacktest(payload: BacktestPayload) {
const { backtestId, strategy, symbols, startDate, endDate, initialCapital, config } = payload;
logger.info('Starting backtest', { backtestId, strategy, symbolCount: symbols.length });
try {
// Update status in web-api (via Redis or direct DB update)
await this.updateBacktestStatus(backtestId, 'running');
// TODO: Call Rust core via NAPI bindings
// For now, we'll simulate the backtest
const results = await this.simulateBacktest({
strategy,
symbols,
startDate,
endDate,
initialCapital,
config,
});
// Store results
await this.storeBacktestResults(backtestId, results);
// Update status to completed
await this.updateBacktestStatus(backtestId, 'completed');
logger.info('Backtest completed', { backtestId });
return { success: true, backtestId, results };
} catch (error) {
logger.error('Backtest failed', { backtestId, error });
await this.updateBacktestStatus(
backtestId,
'failed',
error instanceof Error ? error.message : String(error)
);
throw error;
async runBacktest(payload: unknown) {
if (typeof payload !== 'object' || payload === null) {
throw new Error('Invalid backtest job');
}
// Old jobs omitted these fields. Normalize the envelope, never the execution result.
const config = { mode: 'backtest', dataFrequency: '1d', ...payload };
const results = await this.runner.runBacktest(config);
return { success: true, backtestId: results.backtestId, runId: results.runId, results };
}
@Operation('cancel-backtest')
async cancelBacktest(payload: CancelBacktestPayload) {
const { backtestId } = payload;
logger.info('Cancelling backtest', { backtestId });
// TODO: Implement actual cancellation logic
// For now, just update the status
await this.updateBacktestStatus(backtestId, 'cancelled');
return { success: true, backtestId };
}
private async updateBacktestStatus(backtestId: string, status: string, error?: string) {
// TODO: Update in MongoDB or notify web-api
logger.info('Updating backtest status', { backtestId, status, error });
}
private async storeBacktestResults(backtestId: string, _results: unknown) {
// TODO: Store in MongoDB
logger.info('Storing backtest results', { backtestId });
}
private async simulateBacktest(params: Omit<BacktestPayload, 'backtestId'>) {
// Simulate some processing time
await new Promise(resolve => setTimeout(resolve, 2000));
// Return mock results
return {
metrics: {
totalReturn: 0.15,
sharpeRatio: 1.2,
maxDrawdown: -0.08,
winRate: 0.55,
totalTrades: 150,
profitFactor: 1.8,
},
equity: [
{ date: params.startDate, value: params.initialCapital },
{ date: params.endDate, value: params.initialCapital * 1.15 },
],
trades: [
{
symbol: params.symbols[0],
entryDate: params.startDate,
exitDate: params.endDate,
entryPrice: 100,
exitPrice: 115,
quantity: 100,
pnl: 1500,
},
],
};
async cancelBacktest(payload: unknown) {
const { runId } = z.object({ runId: z.string().uuid() }).parse(payload);
await this.runner.stopBacktest(runId);
return { success: true, runId, message: 'Cancellation requested' };
}
}

View file

@ -134,20 +134,34 @@ async function main() {
}
// Graceful shutdown
process.on('SIGINT', async () => {
services.logger.info('Orchestrator service shutting down...');
// Cleanup any active trading sessions
const modeManager = services.custom?.ModeManager;
if (modeManager) {
await modeManager.shutdown();
let shuttingDown = false;
const shutdown = async (signal: string) => {
if (shuttingDown) {
return;
}
if (server) {
server.stop();
shuttingDown = true;
services.logger.info('Orchestrator service shutting down...', { signal });
const deadline = setTimeout(() => process.exit(1), 10_000);
deadline.unref();
// Stop accepting connections, but let the active run persist its terminal state.
const stopped = server?.stop();
let exitCode = 0;
try {
await services.custom?.BacktestRunner?.shutdown();
await services.queueManager?.shutdown();
await services.custom?.ModeManager?.shutdown();
await stopped;
} catch (error) {
exitCode = 1;
services.logger.error('Orchestrator shutdown failed', { error });
} finally {
clearTimeout(deadline);
server?.stop(true);
process.exit(exitCode);
}
process.exit(0);
});
};
process.on('SIGINT', () => void shutdown('SIGINT'));
process.on('SIGTERM', () => void shutdown('SIGTERM'));
} catch (error) {
logger.error('Failed to start orchestrator service:', error);
process.exit(1);

View file

@ -1,14 +1,12 @@
import { EventEmitter } from 'events';
import { io, Socket } from 'socket.io-client';
import { defined } from '@stock-bot/invariants';
import { QuestDBClient } from '@stock-bot/questdb';
import type { OrchestratorServices as IServiceContainer } from '../types';
import { BarSchema, QuoteSchema, TradeSchema, type MarketData, type ModeConfig } from '../types';
export class MarketDataService extends EventEmitter {
private mode: 'backtest' | 'paper' | 'live' = 'paper';
private dataIngestionSocket: Socket | null = null;
private questdbClient: QuestDBClient | null = null;
private subscriptions = new Set<string>();
private batchBuffer: MarketData[] = [];
private batchTimer: NodeJS.Timeout | null = null;
@ -24,16 +22,7 @@ export class MarketDataService extends EventEmitter {
async initialize(config: ModeConfig): Promise<void> {
this.mode = config.mode;
if (config.mode === 'backtest') {
// Initialize QuestDB client for historical data
this.questdbClient = new QuestDBClient({
host: process.env.QUESTDB_HOST || 'localhost',
httpPort: parseInt(process.env.QUESTDB_HTTP_PORT || '9000'),
pgPort: parseInt(process.env.QUESTDB_PG_PORT || '8812'),
influxPort: parseInt(process.env.QUESTDB_INFLUX_PORT || '9009'),
database: process.env.QUESTDB_DATABASE || 'trading',
});
} else {
if (config.mode !== 'backtest') {
// Connect to data-ingestion service for real-time data
await this.connectToDataIngestion();
}
@ -177,97 +166,33 @@ export class MarketDataService extends EventEmitter {
symbols: string[],
startTime: Date,
endTime: Date,
interval: string = '1m'
interval = '1m'
): Promise<MarketData[]> {
if (!this.questdbClient) {
throw new Error('QuestDB client not initialized');
}
const data: MarketData[] = [];
for (const symbol of symbols) {
// Query for bars
const bars = await this.questdbClient.query(`
SELECT
timestamp,
open,
high,
low,
close,
volume,
vwap
FROM bars_${interval}
WHERE symbol = '${symbol}'
AND timestamp >= '${startTime.toISOString()}'
AND timestamp < '${endTime.toISOString()}'
ORDER BY timestamp
`);
// Convert to MarketData format
bars.rows.forEach(row => {
data.push({
type: 'bar',
data: {
symbol,
open: row.open,
high: row.high,
low: row.low,
close: row.close,
volume: row.volume,
vwap: row.vwap,
timestamp: new Date(row.timestamp).getTime(),
},
});
});
// Also query for trades if needed for more granular simulation
if (interval === '1m' || interval === 'tick') {
const trades = await this.questdbClient.query(`
SELECT
timestamp,
price,
size,
side
FROM trades
WHERE symbol = '${symbol}'
AND timestamp >= '${startTime.toISOString()}'
AND timestamp < '${endTime.toISOString()}'
ORDER BY timestamp
`);
trades.rows.forEach(row => {
data.push({
type: 'trade',
const storage = defined(
this.container.custom?.StorageService,
'Historical storage is unavailable'
);
const groups = await Promise.all(
symbols.map(async symbol => {
const bars = await storage.getHistoricalBars(symbol, startTime, endTime, interval);
return bars.map(
(bar): MarketData => ({
type: 'bar',
data: {
symbol,
price: row.price,
size: row.size,
side: row.side,
timestamp: new Date(row.timestamp).getTime(),
timestamp: bar.timestamp.getTime(),
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap,
},
});
});
}
}
// Sort all data by timestamp
data.sort((a, b) => {
const timeA =
a.type === 'bar'
? a.data.timestamp
: a.type === 'trade'
? a.data.timestamp
: a.data.timestamp;
const timeB =
b.type === 'bar'
? b.data.timestamp
: b.type === 'trade'
? b.data.timestamp
: b.data.timestamp;
return timeA - timeB;
});
return data;
})
);
})
);
return groups.flat().sort((a, b) => a.data.timestamp - b.data.timestamp);
}
async shutdown(): Promise<void> {
@ -288,12 +213,6 @@ export class MarketDataService extends EventEmitter {
this.dataIngestionSocket = null;
}
// Close QuestDB connection
if (this.questdbClient) {
await this.questdbClient.disconnect();
this.questdbClient = null;
}
this.subscriptions.clear();
this.removeAllListeners();
}

View file

@ -50,7 +50,9 @@ export class StorageService {
async initialize(config: ModeConfig): Promise<void> {
this.mode = config.mode;
// Clients are already injected via DI
await this.createTables();
if (config.mode !== 'backtest') {
await this.createTables();
}
}
private async createTables(): Promise<void> {
@ -337,7 +339,67 @@ export class StorageService {
);
}
/** One historical-data policy for native and TypeScript execution. */
async getHistoricalBars(
symbol: string,
startTime: Date,
endTime: Date,
interval = '1m'
): Promise<HistoricalBar[]> {
if (
!Number.isFinite(startTime.getTime()) ||
!Number.isFinite(endTime.getTime()) ||
endTime <= startTime
) {
throw new Error('Invalid historical date range');
}
if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) {
throw new Error('Unsupported historical interval');
}
const rows = await this.readHistoricalBars(symbol, startTime, endTime, interval);
const bars = rows
.map(row => {
const timestamp = new Date(row.timestamp);
const numeric = (value: unknown) =>
typeof value === 'number'
? value
: typeof value === 'string' && value.trim()
? Number(value)
: NaN;
const open = numeric(row.open),
high = numeric(row.high),
low = numeric(row.low),
close = numeric(row.close),
volume = numeric(row.volume);
if (
!Number.isFinite(timestamp.getTime()) ||
![open, high, low, close, volume].every(Number.isFinite) ||
low <= 0 ||
high < Math.max(open, close) ||
low > Math.min(open, close) ||
volume < 0
) {
throw new Error(`Invalid historical OHLCV data for ${symbol}`);
}
return { ...row, symbol, timestamp, open, high, low, close, volume };
})
.filter(bar => bar.timestamp >= startTime && bar.timestamp < endTime)
.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
if (!bars.length) {
throw new Error(`No historical data for ${symbol}`);
}
if (
bars.some(
(bar, index) =>
index > 0 && bars[index - 1]?.timestamp.getTime() === bar.timestamp.getTime()
)
) {
throw new Error(`Duplicate historical timestamps for ${symbol}`);
}
return bars;
}
private async readHistoricalBars(
symbol: string,
startTime: Date,
endTime: Date,
@ -484,14 +546,6 @@ export class StorageService {
}
async shutdown(): Promise<void> {
if (this.questdb) {
await this.questdb.disconnect();
this.questdb = null;
}
if (this.postgres) {
await this.postgres.disconnect();
this.postgres = null;
}
// All adapters are borrowed from DI. Only their lifecycle owner may close them.
}
}

View file

@ -21,6 +21,7 @@ export async function createContainer(config: StockAppConfig) {
useRustEngine: config.services?.orchestrator?.backtesting?.useRustEngine ?? true,
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
});
return container.resolve('serviceContainer') as OrchestratorServices;
}

View file

@ -8,11 +8,12 @@ export type TradingMode = z.infer<typeof TradingModeSchema>;
export const BacktestConfigSchema = z.object({
mode: z.literal('backtest'),
name: z.string().optional(),
runId: z.string().optional(),
runId: z.string().uuid().optional(),
backtestId: z.string().uuid().optional(),
config: z.record(z.unknown()).optional(),
startDate: z.string().datetime(),
endDate: z.string().datetime(),
symbols: z.array(z.string()),
symbols: z.array(z.string().min(1)).min(1),
initialCapital: z.number().positive(),
dataFrequency: z.enum(['1m', '5m', '15m', '1h', '1d']),
strategy: z.string(),
@ -72,14 +73,13 @@ export type BacktestConfig = z.infer<typeof BacktestConfigSchema>;
export type OrchestratorServices = import('@stock-bot/services').IServiceContainer & {
custom?: Partial<{
BacktestRunner: import('./backtest/BacktestRunner').BacktestRunner;
StorageService: import('./services/StorageService').StorageService;
MarketDataService: import('./services/MarketDataService').MarketDataService;
ExecutionService: import('./services/ExecutionService').ExecutionService;
AnalyticsService: import('./services/AnalyticsService').AnalyticsService;
StrategyManager: import('./strategies/StrategyManager').StrategyManager;
BacktestEngine:
| import('./backtest/BacktestEngine').BacktestEngine
| import('./backtest/RustBacktestAdapter').RustBacktestAdapter;
BacktestEngine: import('./backtest/execution-engine').BacktestExecutionEngine;
PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager;
ModeManager: import('./core/ModeManager').ModeManager;
}>;

View file

@ -23,7 +23,8 @@
"@stock-bot/handlers": "*",
"@stock-bot/di": "*",
"hono": "^4.0.0",
"@stock-bot/invariants": "workspace:*"
"@stock-bot/invariants": "workspace:*",
"@stock-bot/types": "workspace:*"
},
"devDependencies": {
"typescript": "^5.0.0"

View file

@ -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 {

View file

@ -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,
});

View file

@ -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,

View file

@ -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,
};
}
}

View file

@ -25,7 +25,8 @@
"recharts": "^2.10.4",
"tailwind-merge": "^3.3.1",
"zod": "^3.22.4",
"@stock-bot/invariants": "workspace:*"
"@stock-bot/invariants": "workspace:*",
"@stock-bot/types": "workspace:*"
},
"devDependencies": {
"@types/react": "^18.2.15",

View file

@ -20,7 +20,7 @@ interface ExtendedTrade {
price: number;
commission: number;
pnl?: number;
positionAfter: number;
positionAfter?: number;
entryPrice?: number;
entryDate?: string;
date?: string;

View file

@ -37,27 +37,13 @@ export const BacktestPlayback = memo(function BacktestPlayback({
const openPositions: Position[] = [];
const closedPositions: Position[] = [];
if (result.positions) {
if (Array.isArray(result.positions)) {
result.positions.forEach(p => {
if (p.quantity !== 0) {
openPositions.push(p);
} else if (p.realizedPnl !== 0) {
closedPositions.push(p);
}
});
} else if (typeof result.positions === 'object') {
// Convert positions object to array
Object.entries(result.positions).forEach(([symbol, position]) => {
const pos = { symbol, ...position };
if (position.quantity !== 0) {
openPositions.push(pos);
} else if (position.realizedPnl !== 0) {
closedPositions.push(pos);
}
});
result.positions.forEach(position => {
if (position.quantity !== 0) {
openPositions.push(position);
} else if (position.realizedPnl !== 0) {
closedPositions.push(position);
}
}
});
return (
<div className="h-full flex flex-col gap-4">

View file

@ -1,8 +1,8 @@
import type { ColumnDef } from '@tanstack/react-table';
import type { BacktestRunTrade as Trade } from '@stock-bot/types';
import { DataTable } from '@/components/ui/DataTable';
import { browserLog } from '@/utils/browserLog';
import type { RunResult } from '../services/backtestApiV2';
import type { Trade } from '../types/backtest.types';
interface BacktestTradesProps {
result: RunResult | null;
@ -66,7 +66,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
size: 180,
cell: ({ row }) => {
const trade = row.original;
const date = trade.timestamp || trade.entryDate || trade.date;
const date = trade.timestamp;
return (
<span className="text-sm text-text-secondary">
{date ? new Date(date).toLocaleString() : '-'}
@ -112,7 +112,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
size: 100,
cell: ({ row }) => {
const trade = row.original;
const pnl = trade.pnl || trade.realizedPnl || 0;
const pnl = trade.pnl ?? 0;
return (
<span className={`text-sm font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}>
${pnl.toFixed(2)}
@ -125,7 +125,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
// Calculate trade statistics
const tradeStats = result.trades.reduce(
(stats, trade) => {
const pnl = trade.pnl || trade.realizedPnl || 0;
const pnl = trade.pnl ?? 0;
if (pnl > 0) {
stats.wins++;
stats.totalWin += pnl;
@ -139,14 +139,14 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
{ wins: 0, losses: 0, totalWin: 0, totalLoss: 0, totalPnL: 0 }
);
const winRate = result.trades.length > 0 ? (tradeStats.wins / result.trades.length) * 100 : 0;
const winRate = result.metrics.winRate * 100;
return (
<div>
<div className="mb-4 grid grid-cols-1 md:grid-cols-5 gap-4">
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Total Trades</p>
<p className="text-lg font-medium text-text-primary">{result.trades.length}</p>
<p className="text-xs text-text-secondary">Closed Trades</p>
<p className="text-lg font-medium text-text-primary">{result.metrics.totalTrades}</p>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-3">
<p className="text-xs text-text-secondary">Win Rate</p>
@ -180,10 +180,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
{result.positions &&
Object.keys(result.positions).length > 0 &&
(() => {
const positionsArray = Object.entries(result.positions).map(([symbol, position]) => ({
symbol,
...position,
}));
const positionsArray = result.positions;
const positionColumns: ColumnDef<(typeof positionsArray)[0]>[] = [
{

View file

@ -82,21 +82,21 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return status.charAt(0).toUpperCase() + status.slice(1);
};
const formatPercentage = (value: number | undefined, decimals = 2) => {
const formatPercentage = (value: number | null | undefined, decimals = 2) => {
if (value === undefined || value === null) {
return '-';
}
return `${(value * 100).toFixed(decimals)}%`;
};
const formatNumber = (value: number | undefined, decimals = 2) => {
const formatNumber = (value: number | null | undefined, decimals = 2) => {
if (value === undefined || value === null) {
return '-';
}
return value.toFixed(decimals);
};
const formatCurrency = (value: number | undefined) => {
const formatCurrency = (value: number | null | undefined) => {
if (value === undefined || value === null) {
return '-';
}
@ -169,7 +169,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value >= 0
? 'text-success'
@ -191,7 +191,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value > 1
? 'text-success'
@ -215,7 +215,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value > -0.1
? 'text-success'
@ -239,7 +239,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value > 0.5
? 'text-success'
@ -261,7 +261,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value > 1.5
? 'text-success'
@ -285,7 +285,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
return (
<span
className={`text-sm font-medium ${
value === undefined
value === undefined || value === null
? 'text-text-secondary'
: value >= 0
? 'text-success'

View file

@ -1,5 +1,5 @@
import type { BacktestRunResult } from '@stock-bot/types';
import { browserLog } from '@/utils/browserLog';
import type { BacktestMetrics, Position, Trade } from '../types/backtest.types';
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';
@ -46,39 +46,7 @@ export interface CreateRunRequest {
speedMultiplier?: number | null;
}
export interface RunResult {
runId: string;
backtestId: string;
status: 'completed';
completedAt: string;
config: {
name: string;
strategy: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
commission: number;
slippage: number;
dataFrequency: string;
};
metrics: BacktestMetrics;
equity: { date: string; value: number }[];
ohlcData: Record<
string,
{ timestamp: number; open: number; high: number; low: number; close: number; volume?: number }[]
>;
trades: Trade[];
positions: Position[] | Record<string, Omit<Position, 'symbol'>>;
analytics: {
exposureTime?: number;
drawdownSeries?: { timestamp: number; value: number }[];
dailyReturns?: number[];
monthlyReturns?: Record<string, number>;
riskMetrics?: Record<string, number>;
};
executionTime: number;
}
export type RunResult = BacktestRunResult;
export const backtestApiV2 = {
// Backtest operations

View file

@ -60,7 +60,7 @@ export interface Trade {
entryPrice?: number;
date?: string;
realizedPnl?: number;
positionAfter: number; // Position size after this trade
positionAfter?: number; // Position size after this trade
}
export interface PerformanceDataPoint {