continuation
This commit is contained in:
parent
32e43c9243
commit
879e9b4228
42 changed files with 2607 additions and 1306 deletions
|
|
@ -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(
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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>;
|
||||
};
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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' };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}>;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue