continuation
This commit is contained in:
parent
32e43c9243
commit
879e9b4228
42 changed files with 2607 additions and 1306 deletions
|
|
@ -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(
|
||||
|
|
|
|||
236
apps/stock/orchestrator/src/backtest/BacktestRunner.ts
Normal file
236
apps/stock/orchestrator/src/backtest/BacktestRunner.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
121
apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts
Normal file
121
apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts
Normal 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)));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -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');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -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');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
35
apps/stock/orchestrator/src/backtest/execution-engine.ts
Normal file
35
apps/stock/orchestrator/src/backtest/execution-engine.ts
Normal 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';
|
||||
}
|
||||
}
|
||||
36
apps/stock/orchestrator/src/backtest/native-strategies.ts
Normal file
36
apps/stock/orchestrator/src/backtest/native-strategies.ts
Normal 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 };
|
||||
});
|
||||
}
|
||||
|
|
@ -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>;
|
||||
47
apps/stock/orchestrator/src/backtest/native-worker.ts
Normal file
47
apps/stock/orchestrator/src/backtest/native-worker.ts
Normal 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));
|
||||
186
apps/stock/orchestrator/src/backtest/result.ts
Normal file
186
apps/stock/orchestrator/src/backtest/result.ts
Normal 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,
|
||||
});
|
||||
}
|
||||
43
apps/stock/orchestrator/src/backtest/run-repository.ts
Normal file
43
apps/stock/orchestrator/src/backtest/run-repository.ts
Normal 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');
|
||||
}
|
||||
}
|
||||
84
apps/stock/orchestrator/src/backtest/typescript-result.ts
Normal file
84
apps/stock/orchestrator/src/backtest/typescript-result.ts
Normal 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>;
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue