continuation
This commit is contained in:
parent
32e43c9243
commit
879e9b4228
42 changed files with 2607 additions and 1306 deletions
56
README.md
56
README.md
|
|
@ -80,3 +80,59 @@ is contacted. Native SMA and MACD regressions are covered by the repository chec
|
|||
|
||||
Coverage reports contain measured LCOV data only. Missing coverage or an empty package
|
||||
selection fails the coverage command instead of producing an estimated score.
|
||||
|
||||
## Backtest execution workflow
|
||||
|
||||
The orchestrator's `BacktestRunner` is the application boundary for both HTTP and decorated
|
||||
jobs. It validates the request, claims a run, executes the configured native or TypeScript
|
||||
backend, normalizes the result, and commits the result and terminal status in one transaction.
|
||||
Completion events are published only after that commit. Progress cannot revive a terminal
|
||||
run, duplicate claims are rejected, and unsupported controls do not change persisted state.
|
||||
|
||||
`@stock-bot/types` exports the shared `BacktestRunResult` used by the runner, API, and UI.
|
||||
Return, win-rate, drawdown, and chart-analytics percentages use fractions (`0.10` means 10%).
|
||||
Trade records identify their granularity with `kind: 'fill' | 'closed'`; `totalTrades` counts
|
||||
completed round trips. Undefined ratios remain `null`. Engine-specific supplemental metrics
|
||||
retain their documented backend meaning.
|
||||
|
||||
The web API owns backtest definitions and pending-run creation; the orchestrator owns
|
||||
execution state and result writes. V1 is a compatibility facade over V2, not a second SQL
|
||||
schema or execution path. Strategy parameters and exact run configuration are preserved.
|
||||
All historical readers delegate to the same storage policy; simulated fills do not enter
|
||||
the trading ledger. Shared adapters are closed by DI, not by a backtest mode transition.
|
||||
|
||||
Deployment requires the additive migration
|
||||
`database/postgres/init/09-backtest-run-contract.sql`, after the existing runs migration.
|
||||
The web API's migration allowlist includes it. It adds configuration/provenance columns and
|
||||
a unique result-per-run index without deleting history. Existing duplicate result rows must
|
||||
be reconciled before applying that index. Historical rows without snapshots remain readable
|
||||
and are explicitly marked `legacy`; their configuration is reconstructed from the definition.
|
||||
New executions require PostgreSQL; there is no implicit in-memory production repository.
|
||||
|
||||
Native execution uses a disposable **worker process**, not the HTTP thread. A small
|
||||
`BacktestExecutionEngine` port separates the runner from both implementations. The parent
|
||||
owns storage reads and persistence; only serializable configuration, bars, progress, and
|
||||
results cross IPC. One native worker runs at a time per orchestrator instance; additional
|
||||
requests receive a conflict rather than spawning unbounded workers. The existing
|
||||
`maxConcurrent` setting does not enable parallel runs through this serialized runner.
|
||||
|
||||
`services.orchestrator.backtesting.executionTimeoutMs` defaults to 300000 (five minutes)
|
||||
and covers historical reads, worker startup, and native execution, not result persistence.
|
||||
Cancellation and deadlines kill and reap the worker even during a synchronous Rust call.
|
||||
A forced cancellation commits `cancelled` without a result row or fabricated partial metrics;
|
||||
the original execution request returns HTTP 409 with `status: 'cancelled'`, and `/stop`
|
||||
acknowledges only after that status is persisted. SSE publishes a terminal `cancelled` event.
|
||||
Native pause/resume and speed controls remain explicitly unsupported. Native progress is
|
||||
stage-level, not an invented percentage inside Rust's synchronous loop. Shutdown handles
|
||||
SIGINT and SIGTERM, stops the worker, and settles its run before service cleanup.
|
||||
|
||||
The orchestrator build emits **both** `dist/index.js` and `dist/native-worker.js`; deploy
|
||||
them together with the external `@stock-bot/engine` package/native binary. The worker does
|
||||
not require source TypeScript in production. Process isolation is intentional: terminating
|
||||
a thread cannot guarantee interruption or contain a native process crash.
|
||||
|
||||
The integration suite covers both real engines, REST/job parity, V1/V2 dispatch and result
|
||||
reads, missing data, duplicate/concurrent requests, failed persistence/rollback, controls,
|
||||
responsive requests/streams, worker crashes, deadlines, cancellation, and cleanup. SQL tests
|
||||
use an in-process PostgreSQL emulator and the real transaction manager, not a live database.
|
||||
Durable queued dispatch and recovery after an orchestrator crash remain follow-up work.
|
||||
|
|
|
|||
|
|
@ -92,6 +92,7 @@ export const stockAppSchema = baseAppSchema.extend({
|
|||
.object({
|
||||
maxConcurrent: z.number().default(5),
|
||||
useRustEngine: z.boolean().default(true),
|
||||
executionTimeoutMs: z.number().int().positive().max(2_147_483_647).default(300_000),
|
||||
allowSyntheticData: z.boolean().default(false),
|
||||
syntheticSeed: z.number().int().default(42),
|
||||
defaultSpeed: z.string().default('max'),
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"dev": "bun --watch src/index.ts",
|
||||
"build": "bun build src/index.ts --outdir dist --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core",
|
||||
"build": "bun build src/index.ts src/backtest/native-worker.ts --outdir dist --entry-naming '[name].[ext]' --target node --external @stock-bot/engine --external @tensorflow/tfjs-node --external chromium-bidi --external electron --external playwright --external playwright-core",
|
||||
"start": "bun dist/index.js",
|
||||
"test": "bun test",
|
||||
"test:indicators": "bun test tests/indicators.test.ts",
|
||||
|
|
@ -35,7 +35,9 @@
|
|||
"@stock-bot/services": "workspace:*",
|
||||
"@stock-bot/mongodb": "workspace:*",
|
||||
"@stock-bot/postgres": "workspace:*",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
"@stock-bot/invariants": "workspace:*",
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"@stock-bot/handlers": "workspace:*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tensorflow/tfjs-node": "^4.0.0"
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}>;
|
||||
|
|
|
|||
|
|
@ -23,7 +23,8 @@
|
|||
"@stock-bot/handlers": "*",
|
||||
"@stock-bot/di": "*",
|
||||
"hono": "^4.0.0",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
"@stock-bot/invariants": "workspace:*",
|
||||
"@stock-bot/types": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.0.0"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { readdirSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { existsSync, readdirSync, readFileSync } from 'fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'path';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
|
||||
|
|
@ -27,11 +28,21 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
`);
|
||||
|
||||
// Get list of migration files from database/postgres/init
|
||||
const migrationsDir = join(process.cwd(), 'database', 'postgres', 'init');
|
||||
let directory = dirname(fileURLToPath(import.meta.url));
|
||||
while (!existsSync(join(directory, 'database', 'postgres', 'init'))) {
|
||||
const parent = dirname(directory);
|
||||
if (parent === directory) {
|
||||
throw new Error('Cannot locate PostgreSQL migrations');
|
||||
}
|
||||
directory = parent;
|
||||
}
|
||||
const migrationsDir = join(directory, 'database', 'postgres', 'init');
|
||||
logger.info('Looking for migrations', { directory: migrationsDir });
|
||||
|
||||
const files = readdirSync(migrationsDir)
|
||||
.filter(f => f.endsWith('.sql') && f.startsWith('001_')) // Only run our backtest migration for now
|
||||
.filter(
|
||||
f => f.endsWith('.sql') && (f.startsWith('001_') || f === '09-backtest-run-contract.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
logger.info('Found migration files:', files);
|
||||
|
|
@ -48,10 +59,13 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
|
||||
// Read and execute migration
|
||||
const sql = readFileSync(join(migrationsDir, file), 'utf8');
|
||||
await container.postgres.query(sql);
|
||||
|
||||
// Record migration as executed
|
||||
await container.postgres.query('INSERT INTO migrations (filename) VALUES ($1)', [file]);
|
||||
await container.postgres.transaction(async client => {
|
||||
await client.query(sql);
|
||||
await client.query(
|
||||
'INSERT INTO migrations (filename) VALUES ($1) ON CONFLICT (filename) DO NOTHING',
|
||||
[file]
|
||||
);
|
||||
});
|
||||
|
||||
logger.info(`Migration completed: ${file}`);
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -172,7 +172,7 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
const { progress, currentDate } = body;
|
||||
|
||||
// Update run progress in database
|
||||
await backtestService.updateRunStatus(runId, 'running', {
|
||||
await backtestService.updateRunProgress(runId, {
|
||||
progress,
|
||||
currentDate,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import type { QueryResultRow } from 'pg';
|
|||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||
|
||||
|
|
@ -11,6 +12,8 @@ const logger = getLogger('backtest-v2-service');
|
|||
// Use environment variable or default
|
||||
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
|
||||
|
||||
export type BacktestTransport = (url: string, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
export interface BacktestRequest {
|
||||
name: string;
|
||||
strategy: string;
|
||||
|
|
@ -39,7 +42,7 @@ export interface Run {
|
|||
backtestId: string;
|
||||
runNumber: number;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
|
||||
speedMultiplier: number;
|
||||
speedMultiplier: number | null;
|
||||
error?: string;
|
||||
startedAt?: Date;
|
||||
completedAt?: Date;
|
||||
|
|
@ -59,13 +62,19 @@ export class BacktestServiceV2 {
|
|||
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
|
||||
private wsHandler: WebSocketHandler | null = null;
|
||||
|
||||
constructor(container: IServiceContainer) {
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
private readonly request: BacktestTransport = fetch
|
||||
) {
|
||||
this.container = requireServices(container, 'postgres');
|
||||
logger.info('BacktestServiceV2 initialized');
|
||||
}
|
||||
|
||||
// Backtest CRUD operations
|
||||
async createBacktest(request: BacktestRequest): Promise<Backtest> {
|
||||
async createBacktest(
|
||||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
const backtestId = uuidv4();
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
|
|
@ -88,19 +97,20 @@ export class BacktestServiceV2 {
|
|||
const backtest = this.mapBacktest(at(result.rows, 0));
|
||||
|
||||
// Automatically create and start a run for the new backtest
|
||||
try {
|
||||
await this.createRun({
|
||||
backtestId: backtest.id,
|
||||
speedMultiplier: null, // Max speed (instant)
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to auto-create run for new backtest', {
|
||||
backtestId: backtest.id,
|
||||
error,
|
||||
});
|
||||
// Don't fail the backtest creation if run creation fails
|
||||
if (options.autoStart !== false) {
|
||||
try {
|
||||
await this.createRun({
|
||||
backtestId: backtest.id,
|
||||
speedMultiplier: null, // Max speed (instant)
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to auto-create run for new backtest', {
|
||||
backtestId: backtest.id,
|
||||
error,
|
||||
});
|
||||
// Don't fail the backtest creation if run creation fails
|
||||
}
|
||||
}
|
||||
|
||||
return backtest;
|
||||
}
|
||||
|
||||
|
|
@ -188,27 +198,29 @@ export class BacktestServiceV2 {
|
|||
// Run operations
|
||||
async createRun(request: RunRequest): Promise<Run> {
|
||||
const runId = uuidv4();
|
||||
|
||||
// Get the next run number for this backtest
|
||||
const runNumberResult = await this.container.postgres.query(
|
||||
'SELECT COALESCE(MAX(run_number), 0) + 1 as next_run_number FROM runs WHERE backtest_id = $1',
|
||||
[request.backtestId]
|
||||
);
|
||||
const runNumber = at(runNumberResult.rows, 0).next_run_number;
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status)
|
||||
VALUES ($1, $2, $3, $4, 'pending')
|
||||
RETURNING *`,
|
||||
[runId, request.backtestId, runNumber, request.speedMultiplier ?? 1.0]
|
||||
);
|
||||
|
||||
const run = this.mapRun(at(result.rows, 0));
|
||||
|
||||
// Start the run immediately
|
||||
this.startRun(run);
|
||||
|
||||
const row = await this.container.postgres.transaction(async client => {
|
||||
const parent = await client.query('SELECT id FROM backtests WHERE id = $1 FOR UPDATE', [
|
||||
request.backtestId,
|
||||
]);
|
||||
if (!parent.rows.length) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status
|
||||
FROM runs WHERE backtest_id = $2 RETURNING *`,
|
||||
[
|
||||
runId,
|
||||
request.backtestId,
|
||||
request.speedMultiplier === undefined ? null : request.speedMultiplier,
|
||||
]
|
||||
);
|
||||
return at(result.rows, 0);
|
||||
});
|
||||
const run = this.mapRun(row);
|
||||
// startRun handles dispatch failures; the runner owns execution and terminal persistence.
|
||||
void this.startRun(run);
|
||||
return run;
|
||||
}
|
||||
|
||||
|
|
@ -233,137 +245,57 @@ export class BacktestServiceV2 {
|
|||
return result.rows.map(row => this.mapRun(row));
|
||||
}
|
||||
|
||||
async updateRunStatus(
|
||||
async updateRunProgress(
|
||||
id: string,
|
||||
status: Run['status'],
|
||||
updates?: {
|
||||
error?: string;
|
||||
progress?: number;
|
||||
currentDate?: Date;
|
||||
speedMultiplier?: number | null;
|
||||
}
|
||||
updates: { progress?: number; currentDate?: Date }
|
||||
): Promise<void> {
|
||||
const setClauses = ['status = $2', 'updated_at = NOW()'];
|
||||
const values: unknown[] = [id, status];
|
||||
let paramCount = 3;
|
||||
|
||||
if (status === 'running' && !updates?.currentDate) {
|
||||
setClauses.push(`started_at = NOW()`);
|
||||
}
|
||||
if (status === 'completed' || status === 'failed' || status === 'cancelled') {
|
||||
setClauses.push(`completed_at = NOW()`);
|
||||
}
|
||||
if (status === 'paused') {
|
||||
setClauses.push(`paused_at = NOW()`);
|
||||
}
|
||||
|
||||
if (updates?.error !== undefined) {
|
||||
setClauses.push(`error = $${paramCount++}`);
|
||||
values.push(updates.error);
|
||||
}
|
||||
if (updates?.progress !== undefined) {
|
||||
setClauses.push(`progress = $${paramCount++}`);
|
||||
values.push(updates.progress);
|
||||
}
|
||||
if (updates?.currentDate !== undefined) {
|
||||
setClauses.push(`current_simulation_date = $${paramCount++}`);
|
||||
values.push(updates.currentDate);
|
||||
}
|
||||
if (updates?.speedMultiplier !== undefined) {
|
||||
setClauses.push(`speed_multiplier = $${paramCount++}`);
|
||||
values.push(updates.speedMultiplier);
|
||||
}
|
||||
|
||||
await this.container.postgres.query(
|
||||
`UPDATE runs SET ${setClauses.join(', ')} WHERE id = $1`,
|
||||
values
|
||||
const result = await this.container.postgres.query(
|
||||
`UPDATE runs
|
||||
SET progress = COALESCE($2, progress), current_simulation_date = COALESCE($3, current_simulation_date), updated_at = NOW()
|
||||
WHERE id = $1 AND status IN ('running', 'paused') RETURNING status`,
|
||||
[id, updates.progress ?? null, updates.currentDate ?? null]
|
||||
);
|
||||
|
||||
// Send WebSocket update if handler is available
|
||||
if (this.getWebSocketHandler()) {
|
||||
const row = result.rows[0];
|
||||
if (row) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(id, {
|
||||
type: 'run_update',
|
||||
runId: id,
|
||||
data: {
|
||||
status,
|
||||
...updates,
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
data: { status: row.status, ...updates, timestamp: new Date().toISOString() },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async pauseRun(id: string): Promise<void> {
|
||||
await this.updateRunStatus(id, 'paused');
|
||||
|
||||
// Send pause command to orchestrator
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/pause`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn('Failed to pause backtest in orchestrator');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error pausing backtest in orchestrator', error);
|
||||
}
|
||||
await this.sendControl(id, 'pause');
|
||||
}
|
||||
|
||||
async resumeRun(id: string): Promise<void> {
|
||||
const run = await this.getRun(id);
|
||||
if (!run || run.status !== 'paused') {
|
||||
throw new Error('Run is not paused');
|
||||
}
|
||||
|
||||
await this.updateRunStatus(id, 'running');
|
||||
|
||||
// Send resume command to orchestrator
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/resume`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn('Failed to resume backtest in orchestrator');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error resuming backtest in orchestrator', error);
|
||||
}
|
||||
await this.sendControl(id, 'resume');
|
||||
}
|
||||
|
||||
async cancelRun(id: string): Promise<void> {
|
||||
await this.updateRunStatus(id, 'cancelled');
|
||||
// TODO: Send cancel command to orchestrator
|
||||
await this.sendControl(id, 'stop');
|
||||
}
|
||||
|
||||
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
|
||||
await this.updateRunStatus(id, 'running', { speedMultiplier });
|
||||
|
||||
// Send speed update to orchestrator
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/speed`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ speed: speedMultiplier }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn('Failed to update backtest speed in orchestrator');
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error updating backtest speed in orchestrator', error);
|
||||
await this.sendControl(id, 'speed', { speed: speedMultiplier });
|
||||
}
|
||||
private async sendControl(runId: string, command: string, payload: object = {}): Promise<void> {
|
||||
const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/${command}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...payload, runId }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Backtest ${command} was not acknowledged: ${await response.text()}`);
|
||||
}
|
||||
// The runner, not the API client, commits acknowledged state changes.
|
||||
}
|
||||
|
||||
// Get run results
|
||||
async getRunResults(runId: string) {
|
||||
async getRunResults(runId: string): Promise<BacktestRunResult | null> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT
|
||||
br.*,
|
||||
r.backtest_id,
|
||||
r.status as run_status,
|
||||
b.strategy,
|
||||
b.symbols,
|
||||
b.start_date,
|
||||
|
|
@ -382,13 +314,64 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
const legacy = !row.configuration;
|
||||
const metrics: BacktestRunResult['metrics'] = { ...row.metrics };
|
||||
const analytics: BacktestRunResult['analytics'] = {
|
||||
...row.analytics,
|
||||
exposureTime: row.analytics?.exposureTime ?? 0,
|
||||
};
|
||||
const storedTrades: BacktestRunResult['trades'] = row.trades;
|
||||
const trades = storedTrades.map(trade => {
|
||||
const timestamp = trade.timestamp ?? trade.entryDate;
|
||||
const price = trade.price ?? trade.entryPrice;
|
||||
if (!timestamp || price === undefined) {
|
||||
throw new Error('Malformed stored backtest trade');
|
||||
}
|
||||
return {
|
||||
...trade,
|
||||
kind: trade.kind ?? (trade.entryDate ? 'closed' : 'fill'),
|
||||
timestamp,
|
||||
price,
|
||||
};
|
||||
});
|
||||
if (legacy) {
|
||||
// Pre-contract backends both reported return/win rate in percentage points.
|
||||
metrics.totalReturn /= 100;
|
||||
metrics.winRate /= 100;
|
||||
for (const key of ['annualReturn', 'annualizedReturn']) {
|
||||
if (typeof metrics[key] === 'number') {
|
||||
metrics[key] /= 100;
|
||||
}
|
||||
}
|
||||
if (trades.some(trade => trade.kind === 'closed')) {
|
||||
metrics.totalTrades = trades.length;
|
||||
metrics.profitableTrades = trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
analytics.exposureTime /= 100;
|
||||
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||
...point,
|
||||
value: point.value / 100,
|
||||
}));
|
||||
// Older native results identify themselves by finalValue and already use daily fractions.
|
||||
if (typeof row.metrics.finalValue !== 'number') {
|
||||
analytics.dailyReturns = analytics.dailyReturns?.map(value => value / 100);
|
||||
}
|
||||
if (analytics.monthlyReturns) {
|
||||
analytics.monthlyReturns = Object.fromEntries(
|
||||
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
runId: row.run_id,
|
||||
backtestId: row.backtest_id,
|
||||
status: 'completed',
|
||||
status: row.run_status ?? 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
config: {
|
||||
engine: row.engine ?? 'legacy',
|
||||
...(legacy ? { legacy: true } : {}),
|
||||
config: row.configuration ?? {
|
||||
parameters: row.backtest_config ?? {},
|
||||
name: row.backtest_config?.name || 'Backtest',
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
|
|
@ -399,48 +382,41 @@ export class BacktestServiceV2 {
|
|||
slippage: row.backtest_config?.slippage ?? 0.0001,
|
||||
dataFrequency: row.backtest_config?.dataFrequency || '1d',
|
||||
},
|
||||
metrics: row.metrics,
|
||||
metrics,
|
||||
equity: row.equity_curve,
|
||||
ohlcData: row.ohlc_data,
|
||||
trades: row.trades,
|
||||
trades,
|
||||
positions: row.positions,
|
||||
analytics: row.analytics,
|
||||
analytics,
|
||||
executionTime: row.execution_time,
|
||||
};
|
||||
}
|
||||
|
||||
// Private methods
|
||||
private async startRun(run: Run): Promise<void> {
|
||||
const backtest = await this.getBacktest(run.backtestId);
|
||||
if (!backtest) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
|
||||
await this.updateRunStatus(run.id, 'running', { progress: 0 });
|
||||
|
||||
// Send initial WebSocket update
|
||||
if (this.getWebSocketHandler()) {
|
||||
this.getWebSocketHandler()?.sendProgressUpdate(run.id, 0);
|
||||
}
|
||||
|
||||
try {
|
||||
// Call orchestrator to run backtest
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
const backtest = await this.getBacktest(run.backtestId);
|
||||
if (!backtest) {
|
||||
throw new Error('Backtest not found');
|
||||
}
|
||||
this.getWebSocketHandler()?.sendProgressUpdate(run.id, 0);
|
||||
const response = await this.request(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
runId: run.id,
|
||||
backtestId: backtest.id,
|
||||
name: backtest.name,
|
||||
mode: 'backtest',
|
||||
startDate: new Date(backtest.startDate).toISOString(),
|
||||
endDate: new Date(backtest.endDate).toISOString(),
|
||||
startDate: backtest.startDate.toISOString(),
|
||||
endDate: backtest.endDate.toISOString(),
|
||||
symbols: backtest.symbols,
|
||||
strategy: backtest.strategy,
|
||||
initialCapital: backtest.initialCapital,
|
||||
dataFrequency: backtest.config?.dataFrequency || '1d',
|
||||
commission: backtest.config?.commission ?? 0.001,
|
||||
slippage: backtest.config?.slippage ?? 0.0001,
|
||||
config: backtest.config,
|
||||
dataFrequency: backtest.config.dataFrequency ?? '1d',
|
||||
commission: backtest.config.commission ?? 0.001,
|
||||
slippage: backtest.config.slippage ?? 0.0001,
|
||||
speed:
|
||||
run.speedMultiplier === null
|
||||
? 'max'
|
||||
|
|
@ -451,82 +427,57 @@ export class BacktestServiceV2 {
|
|||
: run.speedMultiplier >= 2
|
||||
? '2x'
|
||||
: 'realtime',
|
||||
fillModel: {
|
||||
slippage: 'realistic',
|
||||
marketImpact: true,
|
||||
partialFills: true,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
logger.error('Orchestrator request failed', {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: errorText,
|
||||
request: {
|
||||
runId: run.id,
|
||||
strategy: backtest.strategy,
|
||||
symbols: backtest.symbols,
|
||||
startDate: new Date(backtest.startDate).toISOString(),
|
||||
endDate: new Date(backtest.endDate).toISOString(),
|
||||
},
|
||||
});
|
||||
throw new Error(`Orchestrator returned ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.status === 'completed') {
|
||||
await this.updateRunStatus(run.id, 'completed', { progress: 100 });
|
||||
await this.saveRunResults(run.id, result);
|
||||
|
||||
// Send completion via WebSocket
|
||||
if (this.getWebSocketHandler()) {
|
||||
this.getWebSocketHandler()?.sendCompletion(run.id, result);
|
||||
if (response.status === 409) {
|
||||
const outcome: unknown = await response
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => null);
|
||||
if (
|
||||
outcome &&
|
||||
typeof outcome === 'object' &&
|
||||
'status' in outcome &&
|
||||
outcome.status === 'cancelled' &&
|
||||
(await this.getRun(run.id))?.status === 'cancelled'
|
||||
) {
|
||||
this.getWebSocketHandler()?.broadcastRunUpdate(run.id, {
|
||||
type: 'run_update',
|
||||
data: { status: 'cancelled', timestamp: new Date().toISOString() },
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
throw new Error(`Orchestrator returned ${response.status}: ${await response.text()}`);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Failed to start run', { runId: run.id, error });
|
||||
const errorMessage =
|
||||
error instanceof Error
|
||||
? error instanceof Error
|
||||
? error.message
|
||||
: String(error)
|
||||
: 'Unknown error';
|
||||
await this.updateRunStatus(run.id, 'failed', {
|
||||
error: errorMessage,
|
||||
});
|
||||
|
||||
// Send error via WebSocket
|
||||
if (this.getWebSocketHandler()) {
|
||||
this.getWebSocketHandler()?.sendError(run.id, errorMessage);
|
||||
const result: BacktestRunResult = await response.json();
|
||||
if (
|
||||
result.runId !== run.id ||
|
||||
result.backtestId !== backtest.id ||
|
||||
!['completed', 'cancelled'].includes(result.status)
|
||||
) {
|
||||
throw new Error('Invalid orchestrator run response');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async saveRunResults(runId: string, result: Record<string, unknown>): Promise<void> {
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`INSERT INTO backtest_results
|
||||
(run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
||||
[
|
||||
runId,
|
||||
result.completedAt || new Date(),
|
||||
JSON.stringify(result.metrics || {}),
|
||||
JSON.stringify(result.equity || result.equityCurve || []),
|
||||
JSON.stringify(result.ohlcData || {}),
|
||||
JSON.stringify(result.trades || []),
|
||||
JSON.stringify(result.positions || result.finalPositions || {}),
|
||||
JSON.stringify(result.analytics || {}),
|
||||
result.executionTime || 0,
|
||||
]
|
||||
);
|
||||
// Results and terminal state are already committed by the orchestrator.
|
||||
this.getWebSocketHandler()?.sendCompletion(run.id, result);
|
||||
} catch (error) {
|
||||
logger.error('Failed to save run results', { runId, error });
|
||||
throw error;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logger.error('Backtest dispatch failed', { runId: run.id, error });
|
||||
// A broken HTTP connection must not overwrite a claimed or completed execution.
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`UPDATE runs SET status = 'failed', error = $2,
|
||||
completed_at = NOW(), updated_at = NOW() WHERE id = $1 AND status = 'pending'`,
|
||||
[run.id, message]
|
||||
);
|
||||
} catch (persistenceError) {
|
||||
logger.error('Could not record backtest dispatch failure', {
|
||||
runId: run.id,
|
||||
persistenceError,
|
||||
});
|
||||
}
|
||||
this.getWebSocketHandler()?.sendError(run.id, message);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -557,7 +508,7 @@ export class BacktestServiceV2 {
|
|||
backtestId: row.backtest_id,
|
||||
runNumber: row.run_number,
|
||||
status: row.status,
|
||||
speedMultiplier: parseFloat(row.speed_multiplier),
|
||||
speedMultiplier: row.speed_multiplier === null ? null : parseFloat(row.speed_multiplier),
|
||||
error: row.error,
|
||||
startedAt: row.started_at,
|
||||
completedAt: row.completed_at,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
import { randomUUID as uuidv4 } from 'node:crypto';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
|
||||
const logger = getLogger('backtest-service');
|
||||
|
||||
// Use environment variable or default
|
||||
const ORCHESTRATOR_URL = process.env.ORCHESTRATOR_URL || 'http://localhost:2004';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
BacktestServiceV2,
|
||||
type Backtest,
|
||||
type BacktestTransport,
|
||||
type Run,
|
||||
} from './backtest-v2.service';
|
||||
|
||||
export interface BacktestRequest {
|
||||
strategy: string;
|
||||
|
|
@ -16,10 +14,10 @@ export interface BacktestRequest {
|
|||
initialCapital: number;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface BacktestJob {
|
||||
id: string;
|
||||
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
|
||||
runId?: string;
|
||||
status: Run['status'];
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: Date;
|
||||
|
|
@ -31,271 +29,56 @@ export interface BacktestJob {
|
|||
error?: string;
|
||||
}
|
||||
|
||||
/** Compatibility facade: V1 uses the same definitions, runs, and result reader as V2. */
|
||||
export class BacktestService {
|
||||
private container: IServiceContainer & { postgres: NonNullable<IServiceContainer['postgres']> };
|
||||
|
||||
constructor(container: IServiceContainer) {
|
||||
this.container = requireServices(container, 'postgres');
|
||||
logger.info('BacktestService initialized', {
|
||||
hasPostgres: !!container.postgres,
|
||||
containerKeys: Object.keys(container),
|
||||
});
|
||||
private readonly service: BacktestServiceV2;
|
||||
constructor(container: IServiceContainer, request?: BacktestTransport) {
|
||||
this.service = new BacktestServiceV2(container, request);
|
||||
}
|
||||
|
||||
async createBacktest(request: BacktestRequest): Promise<BacktestJob> {
|
||||
const backtestId = uuidv4();
|
||||
|
||||
// Insert into PostgreSQL
|
||||
const result = await this.container.postgres.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending')
|
||||
RETURNING *`,
|
||||
[
|
||||
backtestId,
|
||||
request.config?.name || `Backtest ${new Date().toISOString()}`,
|
||||
request.strategy,
|
||||
JSON.stringify(request.symbols),
|
||||
request.startDate,
|
||||
request.endDate,
|
||||
request.initialCapital,
|
||||
JSON.stringify(request.config || {}),
|
||||
]
|
||||
);
|
||||
|
||||
const backtest: BacktestJob = {
|
||||
id: at(result.rows, 0).id,
|
||||
status: at(result.rows, 0).status,
|
||||
strategy: at(result.rows, 0).strategy,
|
||||
symbols: at(result.rows, 0).symbols,
|
||||
startDate: at(result.rows, 0).start_date,
|
||||
endDate: at(result.rows, 0).end_date,
|
||||
initialCapital: parseFloat(at(result.rows, 0).initial_capital),
|
||||
config: at(result.rows, 0).config,
|
||||
createdAt: at(result.rows, 0).created_at,
|
||||
updatedAt: at(result.rows, 0).updated_at,
|
||||
};
|
||||
|
||||
// Call orchestrator to run backtest
|
||||
try {
|
||||
const response = await fetch(`${ORCHESTRATOR_URL}/api/backtest/run`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
mode: 'backtest',
|
||||
startDate: new Date(request.startDate).toISOString(),
|
||||
endDate: new Date(request.endDate).toISOString(),
|
||||
symbols: request.symbols,
|
||||
strategy: request.strategy,
|
||||
initialCapital: request.initialCapital,
|
||||
dataFrequency: '1d', // Default to daily
|
||||
commission: request.config?.commission,
|
||||
slippage: request.config?.slippage,
|
||||
speed: 'max', // Default speed
|
||||
fillModel: {
|
||||
slippage: 'realistic',
|
||||
marketImpact: true,
|
||||
partialFills: true,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Orchestrator returned ${response.status}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
// Store result directly without transformation
|
||||
if (result.status === 'completed') {
|
||||
// Update backtest status
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
['completed', backtestId]
|
||||
);
|
||||
|
||||
// Store results in backtest_results table
|
||||
await this.saveBacktestResults(backtestId, result);
|
||||
|
||||
logger.info('Backtest completed', {
|
||||
backtestId,
|
||||
trades: result.metrics?.totalTrades,
|
||||
return: result.metrics?.totalReturn,
|
||||
});
|
||||
} else {
|
||||
// Update status to running if not completed
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
['running', backtestId]
|
||||
);
|
||||
}
|
||||
|
||||
logger.info('Backtest started in orchestrator', { backtestId, result });
|
||||
} catch (error) {
|
||||
logger.error('Failed to start backtest in orchestrator', { backtestId, error });
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
|
||||
['failed', error instanceof Error ? error.message : String(error), backtestId]
|
||||
);
|
||||
backtest.status = 'failed';
|
||||
backtest.error = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
return backtest;
|
||||
}
|
||||
|
||||
async getBacktest(id: string): Promise<BacktestJob | null> {
|
||||
const result = await this.container.postgres.query('SELECT * FROM backtests WHERE id = $1', [
|
||||
id,
|
||||
]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
return {
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date,
|
||||
endDate: row.end_date,
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
config: row.config,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
error: row.error,
|
||||
};
|
||||
}
|
||||
|
||||
async getBacktestResults(id: string) {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT
|
||||
br.*,
|
||||
b.strategy,
|
||||
b.symbols,
|
||||
b.start_date,
|
||||
b.end_date,
|
||||
b.initial_capital,
|
||||
b.config as backtest_config
|
||||
FROM backtest_results br
|
||||
JOIN backtests b ON b.id = br.backtest_id
|
||||
WHERE br.backtest_id = $1`,
|
||||
[id]
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = at(result.rows, 0);
|
||||
|
||||
// Reconstruct the result format expected by frontend
|
||||
return {
|
||||
backtestId: row.backtest_id,
|
||||
status: 'completed',
|
||||
completedAt: row.completed_at.toISOString(),
|
||||
config: {
|
||||
name: row.backtest_config?.name || 'Backtest',
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date.toISOString(),
|
||||
endDate: row.end_date.toISOString(),
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
commission: row.backtest_config?.commission ?? 0.001,
|
||||
slippage: row.backtest_config?.slippage ?? 0.0001,
|
||||
dataFrequency: row.backtest_config?.dataFrequency || '1d',
|
||||
const backtest = await this.service.createBacktest(
|
||||
{
|
||||
...request,
|
||||
name: typeof request.config?.name === 'string' ? request.config.name : 'Backtest',
|
||||
},
|
||||
metrics: row.metrics,
|
||||
equity: row.equity_curve,
|
||||
ohlcData: row.ohlc_data,
|
||||
trades: row.trades,
|
||||
positions: row.positions,
|
||||
analytics: row.analytics,
|
||||
executionTime: row.execution_time,
|
||||
};
|
||||
}
|
||||
|
||||
async listBacktests(params: { limit: number; offset: number }): Promise<BacktestJob[]> {
|
||||
const result = await this.container.postgres.query(
|
||||
`SELECT * FROM backtests
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1 OFFSET $2`,
|
||||
[params.limit, params.offset]
|
||||
{ autoStart: false }
|
||||
);
|
||||
|
||||
return result.rows.map(row => ({
|
||||
id: row.id,
|
||||
status: row.status,
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
startDate: row.start_date,
|
||||
endDate: row.end_date,
|
||||
initialCapital: parseFloat(row.initial_capital),
|
||||
config: row.config,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
error: row.error,
|
||||
}));
|
||||
const run = await this.service.createRun({ backtestId: backtest.id, speedMultiplier: null });
|
||||
return this.toJob(backtest, run);
|
||||
}
|
||||
|
||||
async updateBacktestStatus(
|
||||
id: string,
|
||||
status: BacktestJob['status'],
|
||||
error?: string
|
||||
): Promise<void> {
|
||||
if (error) {
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, error = $2, updated_at = NOW() WHERE id = $3',
|
||||
[status, error, id]
|
||||
);
|
||||
} else {
|
||||
await this.container.postgres.query(
|
||||
'UPDATE backtests SET status = $1, updated_at = NOW() WHERE id = $2',
|
||||
[status, id]
|
||||
);
|
||||
async getBacktest(id: string): Promise<BacktestJob | null> {
|
||||
const backtest = await this.service.getBacktest(id);
|
||||
if (!backtest) {
|
||||
return null;
|
||||
}
|
||||
return this.toJob(backtest, (await this.service.listRuns(id))[0]);
|
||||
}
|
||||
async listBacktests(params: { limit: number; offset: number }): Promise<BacktestJob[]> {
|
||||
return Promise.all(
|
||||
(await this.service.listBacktests(params)).map(async backtest =>
|
||||
this.toJob(backtest, (await this.service.listRuns(backtest.id))[0])
|
||||
)
|
||||
);
|
||||
}
|
||||
async getBacktestResults(id: string) {
|
||||
const run = (await this.service.listRuns(id))[0];
|
||||
return run ? this.service.getRunResults(run.id) : null;
|
||||
}
|
||||
|
||||
async cancelBacktest(id: string): Promise<void> {
|
||||
await this.updateBacktestStatus(id, 'cancelled');
|
||||
|
||||
// Call orchestrator to stop backtest
|
||||
try {
|
||||
await fetch(`${ORCHESTRATOR_URL}/api/backtest/stop`, {
|
||||
method: 'POST',
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to stop backtest in orchestrator', { backtestId: id, error });
|
||||
const run = (await this.service.listRuns(id))[0];
|
||||
if (!run) {
|
||||
throw new Error('Backtest run not found');
|
||||
}
|
||||
await this.service.cancelRun(run.id);
|
||||
}
|
||||
|
||||
private async saveBacktestResults(
|
||||
backtestId: string,
|
||||
result: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.container.postgres.query(
|
||||
`INSERT INTO backtest_results
|
||||
(backtest_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
|
||||
[
|
||||
backtestId,
|
||||
result.completedAt || new Date(),
|
||||
JSON.stringify(result.metrics || {}),
|
||||
JSON.stringify(result.equity || result.equityCurve || []),
|
||||
JSON.stringify(result.ohlcData || {}),
|
||||
JSON.stringify(result.trades || []),
|
||||
JSON.stringify(result.positions || result.finalPositions || {}),
|
||||
JSON.stringify(result.analytics || {}),
|
||||
result.executionTime || 0,
|
||||
]
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error('Failed to save backtest results', { backtestId, error });
|
||||
throw error;
|
||||
}
|
||||
private toJob(backtest: Backtest, run?: Run): BacktestJob {
|
||||
return {
|
||||
...backtest,
|
||||
runId: run?.id,
|
||||
status: run?.status ?? 'pending',
|
||||
updatedAt: run?.updatedAt ?? backtest.updatedAt,
|
||||
error: run?.error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@
|
|||
"recharts": "^2.10.4",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"zod": "^3.22.4",
|
||||
"@stock-bot/invariants": "workspace:*"
|
||||
"@stock-bot/invariants": "workspace:*",
|
||||
"@stock-bot/types": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.15",
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ interface ExtendedTrade {
|
|||
price: number;
|
||||
commission: number;
|
||||
pnl?: number;
|
||||
positionAfter: number;
|
||||
positionAfter?: number;
|
||||
entryPrice?: number;
|
||||
entryDate?: string;
|
||||
date?: string;
|
||||
|
|
|
|||
|
|
@ -37,27 +37,13 @@ export const BacktestPlayback = memo(function BacktestPlayback({
|
|||
const openPositions: Position[] = [];
|
||||
const closedPositions: Position[] = [];
|
||||
|
||||
if (result.positions) {
|
||||
if (Array.isArray(result.positions)) {
|
||||
result.positions.forEach(p => {
|
||||
if (p.quantity !== 0) {
|
||||
openPositions.push(p);
|
||||
} else if (p.realizedPnl !== 0) {
|
||||
closedPositions.push(p);
|
||||
}
|
||||
});
|
||||
} else if (typeof result.positions === 'object') {
|
||||
// Convert positions object to array
|
||||
Object.entries(result.positions).forEach(([symbol, position]) => {
|
||||
const pos = { symbol, ...position };
|
||||
if (position.quantity !== 0) {
|
||||
openPositions.push(pos);
|
||||
} else if (position.realizedPnl !== 0) {
|
||||
closedPositions.push(pos);
|
||||
}
|
||||
});
|
||||
result.positions.forEach(position => {
|
||||
if (position.quantity !== 0) {
|
||||
openPositions.push(position);
|
||||
} else if (position.realizedPnl !== 0) {
|
||||
closedPositions.push(position);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col gap-4">
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import type { ColumnDef } from '@tanstack/react-table';
|
||||
import type { BacktestRunTrade as Trade } from '@stock-bot/types';
|
||||
import { DataTable } from '@/components/ui/DataTable';
|
||||
import { browserLog } from '@/utils/browserLog';
|
||||
import type { RunResult } from '../services/backtestApiV2';
|
||||
import type { Trade } from '../types/backtest.types';
|
||||
|
||||
interface BacktestTradesProps {
|
||||
result: RunResult | null;
|
||||
|
|
@ -66,7 +66,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
size: 180,
|
||||
cell: ({ row }) => {
|
||||
const trade = row.original;
|
||||
const date = trade.timestamp || trade.entryDate || trade.date;
|
||||
const date = trade.timestamp;
|
||||
return (
|
||||
<span className="text-sm text-text-secondary">
|
||||
{date ? new Date(date).toLocaleString() : '-'}
|
||||
|
|
@ -112,7 +112,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
size: 100,
|
||||
cell: ({ row }) => {
|
||||
const trade = row.original;
|
||||
const pnl = trade.pnl || trade.realizedPnl || 0;
|
||||
const pnl = trade.pnl ?? 0;
|
||||
return (
|
||||
<span className={`text-sm font-medium ${pnl >= 0 ? 'text-success' : 'text-error'}`}>
|
||||
${pnl.toFixed(2)}
|
||||
|
|
@ -125,7 +125,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
// Calculate trade statistics
|
||||
const tradeStats = result.trades.reduce(
|
||||
(stats, trade) => {
|
||||
const pnl = trade.pnl || trade.realizedPnl || 0;
|
||||
const pnl = trade.pnl ?? 0;
|
||||
if (pnl > 0) {
|
||||
stats.wins++;
|
||||
stats.totalWin += pnl;
|
||||
|
|
@ -139,14 +139,14 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
{ wins: 0, losses: 0, totalWin: 0, totalLoss: 0, totalPnL: 0 }
|
||||
);
|
||||
|
||||
const winRate = result.trades.length > 0 ? (tradeStats.wins / result.trades.length) * 100 : 0;
|
||||
const winRate = result.metrics.winRate * 100;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-4 grid grid-cols-1 md:grid-cols-5 gap-4">
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-3">
|
||||
<p className="text-xs text-text-secondary">Total Trades</p>
|
||||
<p className="text-lg font-medium text-text-primary">{result.trades.length}</p>
|
||||
<p className="text-xs text-text-secondary">Closed Trades</p>
|
||||
<p className="text-lg font-medium text-text-primary">{result.metrics.totalTrades}</p>
|
||||
</div>
|
||||
<div className="bg-surface-secondary rounded-lg border border-border p-3">
|
||||
<p className="text-xs text-text-secondary">Win Rate</p>
|
||||
|
|
@ -180,10 +180,7 @@ export function BacktestTrades({ result, isLoading }: BacktestTradesProps) {
|
|||
{result.positions &&
|
||||
Object.keys(result.positions).length > 0 &&
|
||||
(() => {
|
||||
const positionsArray = Object.entries(result.positions).map(([symbol, position]) => ({
|
||||
symbol,
|
||||
...position,
|
||||
}));
|
||||
const positionsArray = result.positions;
|
||||
|
||||
const positionColumns: ColumnDef<(typeof positionsArray)[0]>[] = [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -82,21 +82,21 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
return status.charAt(0).toUpperCase() + status.slice(1);
|
||||
};
|
||||
|
||||
const formatPercentage = (value: number | undefined, decimals = 2) => {
|
||||
const formatPercentage = (value: number | null | undefined, decimals = 2) => {
|
||||
if (value === undefined || value === null) {
|
||||
return '-';
|
||||
}
|
||||
return `${(value * 100).toFixed(decimals)}%`;
|
||||
};
|
||||
|
||||
const formatNumber = (value: number | undefined, decimals = 2) => {
|
||||
const formatNumber = (value: number | null | undefined, decimals = 2) => {
|
||||
if (value === undefined || value === null) {
|
||||
return '-';
|
||||
}
|
||||
return value.toFixed(decimals);
|
||||
};
|
||||
|
||||
const formatCurrency = (value: number | undefined) => {
|
||||
const formatCurrency = (value: number | null | undefined) => {
|
||||
if (value === undefined || value === null) {
|
||||
return '-';
|
||||
}
|
||||
|
|
@ -169,7 +169,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
return (
|
||||
<span
|
||||
className={`text-sm font-medium ${
|
||||
value === undefined
|
||||
value === undefined || value === null
|
||||
? 'text-text-secondary'
|
||||
: value >= 0
|
||||
? 'text-success'
|
||||
|
|
@ -191,7 +191,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
return (
|
||||
<span
|
||||
className={`text-sm font-medium ${
|
||||
value === undefined
|
||||
value === undefined || value === null
|
||||
? 'text-text-secondary'
|
||||
: value > 1
|
||||
? 'text-success'
|
||||
|
|
@ -215,7 +215,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
return (
|
||||
<span
|
||||
className={`text-sm font-medium ${
|
||||
value === undefined
|
||||
value === undefined || value === null
|
||||
? 'text-text-secondary'
|
||||
: value > -0.1
|
||||
? 'text-success'
|
||||
|
|
@ -239,7 +239,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
return (
|
||||
<span
|
||||
className={`text-sm font-medium ${
|
||||
value === undefined
|
||||
value === undefined || value === null
|
||||
? 'text-text-secondary'
|
||||
: value > 0.5
|
||||
? 'text-success'
|
||||
|
|
@ -261,7 +261,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
return (
|
||||
<span
|
||||
className={`text-sm font-medium ${
|
||||
value === undefined
|
||||
value === undefined || value === null
|
||||
? 'text-text-secondary'
|
||||
: value > 1.5
|
||||
? 'text-success'
|
||||
|
|
@ -285,7 +285,7 @@ export function RunsListWithMetrics({ runs, currentRunId, onSelectRun }: RunsLis
|
|||
return (
|
||||
<span
|
||||
className={`text-sm font-medium ${
|
||||
value === undefined
|
||||
value === undefined || value === null
|
||||
? 'text-text-secondary'
|
||||
: value >= 0
|
||||
? 'text-success'
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { browserLog } from '@/utils/browserLog';
|
||||
import type { BacktestMetrics, Position, Trade } from '../types/backtest.types';
|
||||
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:2003';
|
||||
|
||||
|
|
@ -46,39 +46,7 @@ export interface CreateRunRequest {
|
|||
speedMultiplier?: number | null;
|
||||
}
|
||||
|
||||
export interface RunResult {
|
||||
runId: string;
|
||||
backtestId: string;
|
||||
status: 'completed';
|
||||
completedAt: string;
|
||||
config: {
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
dataFrequency: string;
|
||||
};
|
||||
metrics: BacktestMetrics;
|
||||
equity: { date: string; value: number }[];
|
||||
ohlcData: Record<
|
||||
string,
|
||||
{ timestamp: number; open: number; high: number; low: number; close: number; volume?: number }[]
|
||||
>;
|
||||
trades: Trade[];
|
||||
positions: Position[] | Record<string, Omit<Position, 'symbol'>>;
|
||||
analytics: {
|
||||
exposureTime?: number;
|
||||
drawdownSeries?: { timestamp: number; value: number }[];
|
||||
dailyReturns?: number[];
|
||||
monthlyReturns?: Record<string, number>;
|
||||
riskMetrics?: Record<string, number>;
|
||||
};
|
||||
executionTime: number;
|
||||
}
|
||||
export type RunResult = BacktestRunResult;
|
||||
|
||||
export const backtestApiV2 = {
|
||||
// Backtest operations
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ export interface Trade {
|
|||
entryPrice?: number;
|
||||
date?: string;
|
||||
realizedPnl?: number;
|
||||
positionAfter: number; // Position size after this trade
|
||||
positionAfter?: number; // Position size after this trade
|
||||
}
|
||||
|
||||
export interface PerformanceDataPoint {
|
||||
|
|
|
|||
4
bun.lock
4
bun.lock
|
|
@ -128,6 +128,7 @@
|
|||
"@stock-bot/config": "*",
|
||||
"@stock-bot/di": "*",
|
||||
"@stock-bot/engine": "*",
|
||||
"@stock-bot/handlers": "workspace:*",
|
||||
"@stock-bot/invariants": "workspace:*",
|
||||
"@stock-bot/logger": "*",
|
||||
"@stock-bot/mongodb": "workspace:*",
|
||||
|
|
@ -137,6 +138,7 @@
|
|||
"@stock-bot/services": "workspace:*",
|
||||
"@stock-bot/shutdown": "*",
|
||||
"@stock-bot/stock-config": "*",
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"@stock-bot/utils": "*",
|
||||
"axios": "^1.6.0",
|
||||
"hono": "^4.0.0",
|
||||
|
|
@ -173,6 +175,7 @@
|
|||
"@stock-bot/services": "workspace:*",
|
||||
"@stock-bot/shutdown": "*",
|
||||
"@stock-bot/stock-config": "*",
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"hono": "^4.0.0",
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
@ -187,6 +190,7 @@
|
|||
"@heroicons/react": "^2.0.18",
|
||||
"@hookform/resolvers": "^3.3.4",
|
||||
"@stock-bot/invariants": "workspace:*",
|
||||
"@stock-bot/types": "workspace:*",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^3.3.1",
|
||||
|
|
|
|||
4
database/postgres/init/09-backtest-run-contract.sql
Normal file
4
database/postgres/init/09-backtest-run-contract.sql
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
-- Additive migration. Preserve existing history while new runs store their exact configuration.
|
||||
ALTER TABLE backtest_results ADD COLUMN IF NOT EXISTS configuration JSONB;
|
||||
ALTER TABLE backtest_results ADD COLUMN IF NOT EXISTS engine TEXT;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_backtest_results_one_per_run ON backtest_results(run_id);
|
||||
82
libs/core/types/src/backtest-run.ts
Normal file
82
libs/core/types/src/backtest-run.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
/** Transport-neutral contract shared by backtest entry points and result readers. */
|
||||
export interface BacktestRunConfiguration {
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
dataFrequency: string;
|
||||
parameters: Record<string, unknown>;
|
||||
strategies?: { name: string; enabled: boolean; config?: Record<string, unknown> }[];
|
||||
}
|
||||
|
||||
/** Return, drawdown, and win-rate metrics are fractions (0.10 = 10%). */
|
||||
export interface BacktestRunMetrics {
|
||||
totalReturn: number;
|
||||
sharpeRatio: number;
|
||||
maxDrawdown: number;
|
||||
winRate: number;
|
||||
/** Completed round trips; trades[] can contain fills or closed trades, identified by kind. */
|
||||
totalTrades: number;
|
||||
profitFactor: number | null;
|
||||
avgWin: number;
|
||||
avgLoss: number;
|
||||
[name: string]: number | null;
|
||||
}
|
||||
|
||||
export interface BacktestRunTrade {
|
||||
kind: 'fill' | 'closed';
|
||||
id: string;
|
||||
symbol: string;
|
||||
timestamp: string;
|
||||
side: 'buy' | 'sell';
|
||||
price: number;
|
||||
quantity: number;
|
||||
commission: number;
|
||||
pnl?: number;
|
||||
positionAfter?: number;
|
||||
entryDate?: string;
|
||||
exitDate?: string | null;
|
||||
entryPrice?: number;
|
||||
exitPrice?: number;
|
||||
pnlPercent?: number;
|
||||
duration?: number;
|
||||
}
|
||||
|
||||
export interface BacktestRunResult {
|
||||
runId: string;
|
||||
backtestId: string;
|
||||
/** legacy marks historical rows whose execution provenance was not stored. */
|
||||
engine: 'native' | 'typescript' | 'legacy';
|
||||
legacy?: boolean;
|
||||
status: 'completed' | 'cancelled';
|
||||
completedAt: string;
|
||||
config: BacktestRunConfiguration;
|
||||
metrics: BacktestRunMetrics;
|
||||
equity: { date: string; value: number }[];
|
||||
ohlcData: Record<
|
||||
string,
|
||||
{ timestamp: number; open: number; high: number; low: number; close: number; volume?: number }[]
|
||||
>;
|
||||
trades: BacktestRunTrade[];
|
||||
positions: {
|
||||
symbol: string;
|
||||
quantity: number;
|
||||
averagePrice: number;
|
||||
currentPrice: number;
|
||||
unrealizedPnl: number;
|
||||
realizedPnl: number;
|
||||
}[];
|
||||
/** Returns, drawdowns, and exposure use fractions here as well. */
|
||||
analytics: {
|
||||
exposureTime: number;
|
||||
drawdownSeries?: { timestamp: number; value: number }[];
|
||||
dailyReturns?: number[];
|
||||
monthlyReturns?: Record<string, number>;
|
||||
riskMetrics?: Record<string, number>;
|
||||
};
|
||||
executionTime: number;
|
||||
}
|
||||
|
|
@ -44,6 +44,12 @@ export type {
|
|||
|
||||
// Export backtesting types
|
||||
export type { BacktestResults } from './backtesting';
|
||||
export type {
|
||||
BacktestRunConfiguration,
|
||||
BacktestRunMetrics,
|
||||
BacktestRunTrade,
|
||||
BacktestRunResult,
|
||||
} from './backtest-run';
|
||||
|
||||
// Export helper types
|
||||
export type { HasClose, HasOHLC, HasTimestamp, HasVolume } from './helpers';
|
||||
|
|
|
|||
49
test/fixtures/native-backtest-worker.ts
vendored
Normal file
49
test/fixtures/native-backtest-worker.ts
vendored
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import {
|
||||
nativeWorkerRequestSchema,
|
||||
type NativeWorkerMessage,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/native-worker-protocol';
|
||||
|
||||
function send(message: NativeWorkerMessage | { invalid: boolean }): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
process.send!(message, (error: Error | null) => (error ? reject(error) : resolve()));
|
||||
});
|
||||
}
|
||||
|
||||
process.once('message', async (input: unknown) => {
|
||||
const { config } = nativeWorkerRequestSchema.parse(input);
|
||||
const behavior = config.config?.fixtureBehavior;
|
||||
if (!behavior) {
|
||||
// The same adapter can recover and run the actual Rust engine after a failed worker.
|
||||
await import('../../apps/stock/orchestrator/src/backtest/native-worker');
|
||||
process.emit('message', input);
|
||||
return;
|
||||
}
|
||||
await send({ type: 'progress', progress: 0, message: `Fixture worker ready:${process.pid}` });
|
||||
switch (behavior) {
|
||||
case 'block':
|
||||
// Intentionally block this process. Messages, timers, and cooperative stop cannot run.
|
||||
while (true) {
|
||||
Math.sqrt(Math.random());
|
||||
}
|
||||
case 'crash':
|
||||
process.kill(process.pid, 'SIGKILL');
|
||||
break;
|
||||
case 'malformed':
|
||||
await send({ invalid: true });
|
||||
break;
|
||||
case 'invalid-result':
|
||||
await send({ type: 'result', result: '{"not":"a backtest result"}' });
|
||||
process.disconnect?.();
|
||||
break;
|
||||
case 'reported-error':
|
||||
await send({ type: 'error', message: 'Fixture native failure' });
|
||||
break;
|
||||
case 'no-result':
|
||||
process.exit(0);
|
||||
case 'result-then-block':
|
||||
await send({ type: 'result', result: '{}' });
|
||||
while (true) {
|
||||
Math.sqrt(Math.random());
|
||||
}
|
||||
}
|
||||
});
|
||||
715
test/integration/backtest-workflow.test.ts
Normal file
715
test/integration/backtest-workflow.test.ts
Normal file
|
|
@ -0,0 +1,715 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { asValue } from 'awilix';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import { newDb } from 'pg-mem';
|
||||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import type { MongoDBClient } from '@stock-bot/services';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { persistEodPrices } from '../../apps/stock/data-ingestion/src/handlers/eod/shared/price-storage';
|
||||
import { createBacktestRoutes } from '../../apps/stock/orchestrator/src/api/rest/backtest';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import {
|
||||
BacktestCancelledError,
|
||||
BacktestTimeoutError,
|
||||
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { normalizeBacktestResult } from '../../apps/stock/orchestrator/src/backtest/result';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
||||
import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager';
|
||||
import { BacktestHandler } from '../../apps/stock/orchestrator/src/handlers/backtest/backtest.handler';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
|
||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||
import {
|
||||
createWebSocketHandler,
|
||||
type RunUpdateMessage,
|
||||
} from '../../apps/stock/web-api/src/websocket/run-updates';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('workflow-test');
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0)) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
name: 'Workflow fixture',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['FIXTURE'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-15T00:00:00.000Z',
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
});
|
||||
|
||||
async function fixture(
|
||||
empty = false,
|
||||
engineOptions: ConstructorParameters<typeof RustBacktestAdapter>[1] = {}
|
||||
) {
|
||||
// PostgreSQL protocol is replaced with an in-process database; SQL and transaction manager are real.
|
||||
const db = newDb();
|
||||
db.public
|
||||
.none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb,
|
||||
start_date timestamptz, end_date timestamptz, initial_capital numeric, config jsonb,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
|
||||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
|
||||
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
|
||||
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_results (run_id uuid PRIMARY KEY REFERENCES runs(id), completed_at timestamptz,
|
||||
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
|
||||
execution_time numeric, configuration jsonb, engine text);`);
|
||||
const { Pool } = db.adapters.createPg();
|
||||
const pool = new Pool();
|
||||
cleanup.push(() => pool.end());
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'fixture', user: 'fixture', password: 'fixture' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const documents: Record<string, unknown>[] = [];
|
||||
const mongodb = {
|
||||
async batchUpsert(_collection: string, rows: typeof documents) {
|
||||
documents.push(...rows);
|
||||
},
|
||||
async find() {
|
||||
return documents;
|
||||
},
|
||||
} as unknown as MongoDBClient;
|
||||
if (!empty) {
|
||||
await persistEodPrices(
|
||||
mongodb,
|
||||
{ symbol: 'FIXTURE', exchange: 'TEST', eodSearchCode: 'FIXTURE.TEST' },
|
||||
Array.from({ length: 70 }, (_, index) => {
|
||||
const close = 100 + Math.sin((index * Math.PI) / 6) * 8 + index * 0.02;
|
||||
return {
|
||||
date: new Date(Date.parse(config.startDate) + index * 86400000)
|
||||
.toISOString()
|
||||
.slice(0, 10),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
})
|
||||
);
|
||||
}
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const engine = new RustBacktestAdapter(
|
||||
{ logger, custom: { StorageService: storage } },
|
||||
engineOptions
|
||||
);
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const runner = new BacktestRunner({ engine, engineName: 'native', repository, logger });
|
||||
cleanup.unshift(() => runner.shutdown());
|
||||
const services = { logger, postgres, custom: { BacktestRunner: runner } };
|
||||
const routes = new Hono().route('/api/backtest', createBacktestRoutes(services));
|
||||
return { postgres, mongodb, storage, engine, repository, runner, services, routes };
|
||||
}
|
||||
|
||||
describe('one backtest execution workflow', () => {
|
||||
test('REST and decorated jobs execute real data and commit the same canonical result', async () => {
|
||||
const f = await fixture();
|
||||
const response = await f.routes.request('/api/backtest/run', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(config),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
expect(response.status).toBe(201);
|
||||
const rest: BacktestRunResult = await response.json();
|
||||
const handler = new BacktestHandler(f.services);
|
||||
const job = (await handler.execute('run-backtest', config, {
|
||||
type: 'queue',
|
||||
metadata: {},
|
||||
})) as { results: BacktestRunResult };
|
||||
expect(rest.trades.length).toBeGreaterThan(0);
|
||||
expect(job.results.metrics).toEqual(rest.metrics);
|
||||
expect(job.results.trades).toEqual(rest.trades);
|
||||
expect(job.results.trades.every(trade => trade.kind === 'fill')).toBe(true);
|
||||
for (const result of [rest, job.results]) {
|
||||
const saved = await f.postgres.query(
|
||||
'SELECT r.status, br.* FROM runs r JOIN backtest_results br ON br.run_id = r.id WHERE r.id = $1',
|
||||
[result.runId]
|
||||
);
|
||||
expect(saved.rows[0]?.status).toBe('completed');
|
||||
expect(saved.rows[0]?.metrics).toEqual(result.metrics);
|
||||
expect(saved.rows[0]?.configuration).toEqual(result.config);
|
||||
expect(saved.rows[0]?.engine).toBe('native');
|
||||
}
|
||||
const duplicate = await f.routes.request('/api/backtest/run', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ ...config, runId: rest.runId }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
expect(duplicate.status).toBe(409);
|
||||
expect(
|
||||
(await f.postgres.query('SELECT * FROM backtest_results WHERE run_id = $1', [rest.runId]))
|
||||
.rows
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('the TypeScript backend uses the same runner, data policy, and persisted contract', async () => {
|
||||
const f = await fixture();
|
||||
const di = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableMongoDB: false,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.build();
|
||||
const services: OrchestratorServices = {
|
||||
logger,
|
||||
postgres: f.postgres,
|
||||
mongodb: f.mongodb,
|
||||
custom: {},
|
||||
};
|
||||
di.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(di, { initializeMode: false, useRustEngine: false });
|
||||
expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner);
|
||||
try {
|
||||
const result = await services.custom!.BacktestRunner!.runBacktest(config);
|
||||
expect(result.engine).toBe('typescript');
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect(result.status).toBe('completed');
|
||||
const repeated = await services.custom!.BacktestRunner!.runBacktest(config);
|
||||
expect(repeated.trades).toEqual(result.trades);
|
||||
expect(repeated.metrics).toEqual(result.metrics);
|
||||
expect(result.ohlcData.FIXTURE).toHaveLength(70);
|
||||
expect(result.trades.every(trade => trade.kind === 'closed')).toBe(true);
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed');
|
||||
} finally {
|
||||
await services.custom?.ModeManager?.shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test('V2 dispatch forwards strategy parameters and reads the runner-owned saved result', async () => {
|
||||
const f = await fixture();
|
||||
let finish!: () => void;
|
||||
const finished = new Promise<void>(resolve => {
|
||||
finish = resolve;
|
||||
});
|
||||
let forwarded: Record<string, unknown> = {};
|
||||
const api = new BacktestServiceV2(f.services, async (url, init) => {
|
||||
forwarded = JSON.parse(String(init?.body));
|
||||
const response = await f.routes.request(new URL(url).pathname, init);
|
||||
finish();
|
||||
return response;
|
||||
});
|
||||
const definition = await api.createBacktest(
|
||||
{ ...config, name: config.name!, config: { ...config.config, commission: 0, slippage: 0 } },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const run = await api.createRun({ backtestId: definition.id, speedMultiplier: null });
|
||||
await finished;
|
||||
expect(forwarded.config).toMatchObject({ fastPeriod: 3, slowPeriod: 7 });
|
||||
expect(forwarded.speed).toBe('max');
|
||||
expect((await api.getRun(run.id))?.status).toBe('completed');
|
||||
const saved = await api.getRunResults(run.id);
|
||||
expect(saved?.config.parameters).toMatchObject({ fastPeriod: 3, slowPeriod: 7 });
|
||||
expect(saved?.engine).toBe('native');
|
||||
expect(saved?.trades.length).toBeGreaterThan(0);
|
||||
await api.updateRunProgress(run.id, { progress: 2 });
|
||||
expect((await api.getRun(run.id))?.status).toBe('completed');
|
||||
expect((await api.getRun(run.id))?.progress).toBe(100);
|
||||
});
|
||||
|
||||
test('the V1 facade creates runs instead of writing removed backtest status columns', async () => {
|
||||
const f = await fixture();
|
||||
let finish!: () => void;
|
||||
const finished = new Promise<void>(resolve => {
|
||||
finish = resolve;
|
||||
});
|
||||
const api = new BacktestService(f.services, async (url, init) => {
|
||||
const response = await f.routes.request(new URL(url).pathname, init);
|
||||
finish();
|
||||
return response;
|
||||
});
|
||||
const created = await api.createBacktest({
|
||||
...config,
|
||||
config: { ...config.config, commission: 0, slippage: 0 },
|
||||
});
|
||||
await finished;
|
||||
expect((await api.getBacktest(created.id))?.status).toBe('completed');
|
||||
expect((await api.getBacktestResults(created.id))?.runId).toBe(created.runId);
|
||||
});
|
||||
|
||||
test('empty data fails both data paths instead of producing synthetic prices or success', async () => {
|
||||
const f = await fixture(true);
|
||||
await expect(
|
||||
new DataManager(f.storage).loadHistoricalData(
|
||||
['FIXTURE'],
|
||||
new Date(config.startDate),
|
||||
new Date(config.endDate),
|
||||
'1d'
|
||||
)
|
||||
).rejects.toThrow('No historical data');
|
||||
await expect(f.runner.runBacktest(config)).rejects.toThrow('No historical data');
|
||||
const runs = await f.postgres.query('SELECT status, error FROM runs');
|
||||
expect(runs.rows[0]?.status).toBe('failed');
|
||||
expect(runs.rows[0]?.error).toContain('No historical data');
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toEqual([]);
|
||||
});
|
||||
|
||||
test('a result write failure never publishes completion and releases the runner', async () => {
|
||||
const f = await fixture();
|
||||
let completions = 0;
|
||||
f.runner.on('complete', () => {
|
||||
completions++;
|
||||
});
|
||||
const complete = f.repository.complete.bind(f.repository);
|
||||
f.repository.complete = async () => {
|
||||
throw new Error('Result store unavailable');
|
||||
};
|
||||
await expect(f.runner.runBacktest(config)).rejects.toThrow('Result store unavailable');
|
||||
expect(completions).toBe(0);
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('failed');
|
||||
f.repository.complete = complete;
|
||||
expect((await f.runner.runBacktest(config)).status).toBe('completed');
|
||||
});
|
||||
|
||||
test('concurrent requests cannot prepare or claim a second run', async () => {
|
||||
const f = await fixture();
|
||||
const first = f.runner.runBacktest(config);
|
||||
await expect(f.runner.runBacktest(config)).rejects.toThrow('already running');
|
||||
await first;
|
||||
expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('the real transaction manager rolls back when terminal result insertion fails', async () => {
|
||||
const f = await fixture();
|
||||
const result = await f.runner.runBacktest(config);
|
||||
const statements: string[] = [];
|
||||
let released = false;
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', database: 'fixture', user: 'fixture', password: 'fixture', port: 5432 },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', {
|
||||
get: () => ({
|
||||
async connect() {
|
||||
return {
|
||||
async query(sql: string) {
|
||||
statements.push(sql.trim());
|
||||
if (sql.includes('INSERT INTO backtest_results')) {
|
||||
throw new Error('Insert failed');
|
||||
}
|
||||
return { rows: [{ id: result.runId }], rowCount: 1 };
|
||||
},
|
||||
release() {
|
||||
released = true;
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
});
|
||||
await expect(new PostgresBacktestRunRepository(postgres).complete(result)).rejects.toThrow(
|
||||
'Insert failed'
|
||||
);
|
||||
expect(statements[0]).toBe('BEGIN');
|
||||
expect(statements.at(-1)).toBe('ROLLBACK');
|
||||
expect(statements).not.toContain('COMMIT');
|
||||
expect(released).toBe(true);
|
||||
});
|
||||
|
||||
test('observer errors cannot change committed success into failure', async () => {
|
||||
const f = await fixture();
|
||||
f.runner.on('complete', () => {
|
||||
throw new Error('Disconnected observer');
|
||||
});
|
||||
const result = await f.runner.runBacktest(config);
|
||||
expect(result.status).toBe('completed');
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed');
|
||||
});
|
||||
|
||||
test('unsupported controls are rejected without changing persisted state', async () => {
|
||||
const f = await fixture();
|
||||
let controlError: unknown;
|
||||
let control: Promise<void> | undefined;
|
||||
f.runner.on('progress', (data: { runId: string }) => {
|
||||
control = f.runner.pauseBacktest(data.runId).catch(error => {
|
||||
controlError = error;
|
||||
});
|
||||
});
|
||||
const result = await f.runner.runBacktest(config);
|
||||
await control;
|
||||
expect(String(controlError)).toContain('do not support pause');
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed');
|
||||
const api = new BacktestServiceV2(f.services, async (_url, init) => {
|
||||
expect(JSON.parse(String(init?.body)).runId).toBe(result.runId);
|
||||
return new Response('Unsupported', { status: 501 });
|
||||
});
|
||||
await expect(api.cancelRun(result.runId)).rejects.toThrow('was not acknowledged');
|
||||
expect((await api.getRun(result.runId))?.status).toBe('completed');
|
||||
});
|
||||
|
||||
test('invalid input and controls cannot claim or falsify a run', async () => {
|
||||
const f = await fixture();
|
||||
await expect(f.runner.runBacktest({ ...config, symbols: [] })).rejects.toThrow();
|
||||
await expect(f.runner.runBacktest({ ...config, endDate: config.startDate })).rejects.toThrow();
|
||||
await expect(f.runner.stopBacktest(randomUUID())).rejects.toThrow('No matching active');
|
||||
expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('the shared result contract fixes percentage units and preserves undefined ratios', async () => {
|
||||
const f = await fixture();
|
||||
const raw = await f.engine.runBacktest(config);
|
||||
const result = normalizeBacktestResult(
|
||||
{
|
||||
...raw,
|
||||
metrics: {
|
||||
...raw.metrics,
|
||||
totalReturn: 25,
|
||||
winRate: 80,
|
||||
maxDrawdown: 0.1,
|
||||
profitFactor: null,
|
||||
},
|
||||
},
|
||||
'native',
|
||||
config,
|
||||
{ runId: randomUUID(), backtestId: randomUUID() },
|
||||
10,
|
||||
false
|
||||
);
|
||||
expect(result.metrics.totalReturn).toBe(0.25);
|
||||
expect(result.metrics.winRate).toBe(0.8);
|
||||
expect(result.metrics.maxDrawdown).toBe(0.1);
|
||||
expect(result.metrics.profitFactor).toBeNull();
|
||||
});
|
||||
|
||||
test('pre-contract history is readable with explicit legacy provenance and normalized units', async () => {
|
||||
const f = await fixture();
|
||||
const result = await f.runner.runBacktest(config);
|
||||
await f.postgres.query(
|
||||
'UPDATE backtest_results SET configuration = NULL, engine = NULL, metrics = $2 WHERE run_id = $1',
|
||||
[result.runId, JSON.stringify({ ...result.metrics, totalReturn: 25, winRate: 80 })]
|
||||
);
|
||||
const restored = await new BacktestServiceV2(f.services).getRunResults(result.runId);
|
||||
expect(restored?.legacy).toBe(true);
|
||||
expect(restored?.engine).toBe('legacy');
|
||||
expect(restored?.metrics.totalReturn).toBe(0.25);
|
||||
expect(restored?.metrics.winRate).toBe(0.8);
|
||||
});
|
||||
|
||||
test('SSE completion detaches listeners so later runs do not target a closed stream', async () => {
|
||||
const f = await fixture();
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const response = await f.routes.request('/api/backtest/stream');
|
||||
const body = response.text();
|
||||
await f.runner.runBacktest(config);
|
||||
expect(await body).toContain('"event":"complete"');
|
||||
expect(f.runner.listenerCount('complete')).toBe(0);
|
||||
expect(f.runner.listenerCount('error')).toBe(0);
|
||||
expect(f.runner.listenerCount('progress')).toBe(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const workerUrl = new URL('../fixtures/native-backtest-worker.ts', import.meta.url);
|
||||
const blockingConfig = { ...config, config: { ...config.config, fixtureBehavior: 'block' } };
|
||||
|
||||
function workerReady(runner: BacktestRunner) {
|
||||
return new Promise<{ pid: number; runId: string }>(resolve => {
|
||||
runner.once('progress', (progress: { message: string; runId: string }) => {
|
||||
resolve({ pid: Number(progress.message.split(':')[1]), runId: progress.runId });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function expectWorkerExited(pid: number) {
|
||||
expect(pid).toBeGreaterThan(0);
|
||||
expect(() => process.kill(pid, 0)).toThrow();
|
||||
}
|
||||
|
||||
describe('isolated native backtest workers', () => {
|
||||
test('HTTP, status, and SSE stay responsive while a worker blocks; stop reaps it before acknowledgement', async () => {
|
||||
const f = await fixture(false, { workerUrl });
|
||||
f.routes.get('/health', c => c.json({ status: 'ok' }));
|
||||
const stream = await f.routes.request('/api/backtest/stream');
|
||||
const reader = stream.body!.getReader();
|
||||
const ready = workerReady(f.runner);
|
||||
const request = f.routes.request('/api/backtest/run', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(blockingConfig),
|
||||
});
|
||||
const { pid, runId } = await ready;
|
||||
expect((await f.routes.request('/health')).status).toBe(200);
|
||||
const status = await (await f.routes.request('/api/backtest/progress')).json();
|
||||
expect(status).toMatchObject({ status: 'running', isRunning: true, runId });
|
||||
const chunk = await reader.read();
|
||||
expect(new TextDecoder().decode(chunk.value)).toContain('Fixture worker ready');
|
||||
expect(
|
||||
(
|
||||
await f.routes.request('/api/backtest/run', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(config),
|
||||
})
|
||||
).status
|
||||
).toBe(409);
|
||||
await expect(f.runner.stopBacktest(randomUUID())).rejects.toThrow('No matching active');
|
||||
expect(f.runner.getStatus().isRunning).toBe(true);
|
||||
const stop = await f.routes.request('/api/backtest/stop', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ runId }),
|
||||
});
|
||||
expect(stop.status).toBe(200);
|
||||
expectWorkerExited(pid);
|
||||
expect((await request).status).toBe(409);
|
||||
expect(
|
||||
(await f.postgres.query('SELECT status FROM runs WHERE id = $1', [runId])).rows[0]?.status
|
||||
).toBe('cancelled');
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
|
||||
expect(f.runner.getStatus().isRunning).toBe(false);
|
||||
const terminal = await reader.read();
|
||||
expect(new TextDecoder().decode(terminal.value)).toContain('"event":"cancelled"');
|
||||
expect((await reader.read()).done).toBe(true);
|
||||
for (const event of ['complete', 'error', 'progress', 'cancelled']) {
|
||||
expect(f.runner.listenerCount(event)).toBe(0);
|
||||
}
|
||||
expect((await f.runner.runBacktest(config)).status).toBe('completed');
|
||||
});
|
||||
|
||||
test('the execution deadline kills a stuck worker, records failure, and releases capacity', async () => {
|
||||
const f = await fixture(false, { workerUrl, timeoutMs: 750 });
|
||||
const ready = workerReady(f.runner);
|
||||
const started = performance.now();
|
||||
const failed = f.runner.runBacktest(blockingConfig).catch(error => error);
|
||||
const { pid } = await ready;
|
||||
expect(await failed).toBeInstanceOf(BacktestTimeoutError);
|
||||
expect(performance.now() - started).toBeLessThan(3000);
|
||||
expectWorkerExited(pid);
|
||||
expect((await f.postgres.query('SELECT status, error FROM runs')).rows[0]).toMatchObject({
|
||||
status: 'failed',
|
||||
error: expect.stringContaining('execution deadline'),
|
||||
});
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
|
||||
expect((await f.runner.runBacktest(config)).status).toBe('completed');
|
||||
});
|
||||
|
||||
test.each([
|
||||
['crash', 'exited without a result'],
|
||||
['no-result', 'exited without a result'],
|
||||
['malformed', 'Invalid native backtest worker response'],
|
||||
['invalid-result', 'Required'],
|
||||
['reported-error', 'Fixture native failure'],
|
||||
])('%s does not crash the parent or publish a result', async (behavior, message) => {
|
||||
const f = await fixture(false, { workerUrl });
|
||||
let completions = 0;
|
||||
f.runner.on('complete', () => {
|
||||
completions++;
|
||||
});
|
||||
const ready = workerReady(f.runner);
|
||||
const failed = f.runner
|
||||
.runBacktest({ ...config, config: { fixtureBehavior: behavior } })
|
||||
.catch(error => error);
|
||||
const { pid } = await ready;
|
||||
expect(String(await failed)).toContain(message);
|
||||
expectWorkerExited(pid);
|
||||
expect(completions).toBe(0);
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('failed');
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
|
||||
expect((await f.runner.runBacktest(config)).status).toBe('completed');
|
||||
});
|
||||
|
||||
test('shutdown kills the worker and persists cancellation before rejecting new runs', async () => {
|
||||
const f = await fixture(false, { workerUrl });
|
||||
const ready = workerReady(f.runner);
|
||||
const cancelled = f.runner.runBacktest(blockingConfig).catch(error => error);
|
||||
const { pid } = await ready;
|
||||
await f.runner.shutdown();
|
||||
expect(await cancelled).toBeInstanceOf(BacktestCancelledError);
|
||||
expectWorkerExited(pid);
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('cancelled');
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
|
||||
await expect(f.runner.runBacktest(config)).rejects.toThrow('shutting down');
|
||||
});
|
||||
|
||||
test('cancellation during a slow historical read cannot start a late worker', async () => {
|
||||
const f = await fixture();
|
||||
const read = f.storage.getHistoricalBars.bind(f.storage);
|
||||
let release!: () => void;
|
||||
let reading!: () => void;
|
||||
const gate = new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
const entered = new Promise<void>(resolve => {
|
||||
reading = resolve;
|
||||
});
|
||||
f.storage.getHistoricalBars = async (...args) => {
|
||||
reading();
|
||||
await gate;
|
||||
return read(...args);
|
||||
};
|
||||
let progress = 0;
|
||||
f.runner.on('progress', () => {
|
||||
progress++;
|
||||
});
|
||||
const cancelled = f.runner.runBacktest(config).catch(error => error);
|
||||
await entered;
|
||||
await f.runner.stopBacktest(f.runner.getStatus().runId);
|
||||
expect(await cancelled).toBeInstanceOf(BacktestCancelledError);
|
||||
release();
|
||||
await gate;
|
||||
f.storage.getHistoricalBars = read;
|
||||
expect((await f.runner.runBacktest(config)).status).toBe('completed');
|
||||
expect(progress).toBe(1);
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('a worker result is not accepted before the worker has exited', async () => {
|
||||
const f = await fixture(false, { workerUrl });
|
||||
const ready = workerReady(f.runner);
|
||||
const cancelled = f.runner
|
||||
.runBacktest({ ...config, config: { fixtureBehavior: 'result-then-block' } })
|
||||
.catch(error => error);
|
||||
const { pid, runId } = await ready;
|
||||
await f.runner.stopBacktest(runId);
|
||||
expect(await cancelled).toBeInstanceOf(BacktestCancelledError);
|
||||
expectWorkerExited(pid);
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('cancelled');
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('a failed cancellation write is not acknowledged or published as successful', async () => {
|
||||
const f = await fixture(false, { workerUrl });
|
||||
const ready = workerReady(f.runner);
|
||||
let cancellations = 0;
|
||||
f.runner.on('cancelled', () => {
|
||||
cancellations++;
|
||||
});
|
||||
f.repository.cancel = async () => {
|
||||
throw new Error('Cancellation store unavailable');
|
||||
};
|
||||
const failed = f.runner.runBacktest(blockingConfig).catch(error => error);
|
||||
const { pid, runId } = await ready;
|
||||
await expect(f.runner.stopBacktest(runId)).rejects.toThrow('Cancellation store unavailable');
|
||||
expect(String(await failed)).toContain('Cancellation store unavailable');
|
||||
expectWorkerExited(pid);
|
||||
expect(cancellations).toBe(0);
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('running');
|
||||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('late cancellation cannot relabel a completed execution while its result commits', async () => {
|
||||
const f = await fixture();
|
||||
const complete = f.repository.complete.bind(f.repository);
|
||||
let entered!: () => void;
|
||||
let release!: () => void;
|
||||
const committing = new Promise<void>(resolve => {
|
||||
entered = resolve;
|
||||
});
|
||||
const gate = new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
f.repository.complete = async result => {
|
||||
entered();
|
||||
await gate;
|
||||
await complete(result);
|
||||
};
|
||||
const running = f.runner.runBacktest(config);
|
||||
await committing;
|
||||
await expect(f.runner.stopBacktest()).rejects.toThrow('already finished');
|
||||
const stopped = f.runner.shutdown();
|
||||
release();
|
||||
expect((await running).status).toBe('completed');
|
||||
await stopped;
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed');
|
||||
});
|
||||
|
||||
test('shutdown while a run claim is pending never starts native execution', async () => {
|
||||
const f = await fixture();
|
||||
const start = f.repository.start.bind(f.repository);
|
||||
let entered!: () => void;
|
||||
let release!: () => void;
|
||||
const claiming = new Promise<void>(resolve => {
|
||||
entered = resolve;
|
||||
});
|
||||
const gate = new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
f.repository.start = async input => {
|
||||
const identity = await start(input);
|
||||
entered();
|
||||
await gate;
|
||||
return identity;
|
||||
};
|
||||
let progress = 0;
|
||||
f.runner.on('progress', () => {
|
||||
progress++;
|
||||
});
|
||||
const cancelled = f.runner.runBacktest(config).catch(error => error);
|
||||
await claiming;
|
||||
const stopped = f.runner.shutdown();
|
||||
release();
|
||||
await stopped;
|
||||
expect(await cancelled).toBeInstanceOf(BacktestCancelledError);
|
||||
expect(progress).toBe(0);
|
||||
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('cancelled');
|
||||
});
|
||||
|
||||
test('the built worker executes the real engine without TypeScript source imports', async () => {
|
||||
const f = await fixture(false, {
|
||||
workerUrl: new URL('../../apps/stock/orchestrator/dist/native-worker.js', import.meta.url),
|
||||
});
|
||||
const result = await f.runner.runBacktest(config);
|
||||
expect(result.status).toBe('completed');
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect(result.engine).toBe('native');
|
||||
});
|
||||
|
||||
test('V2 cancellation publishes cancelled state, not a dispatch error or fabricated result', async () => {
|
||||
const f = await fixture(false, { workerUrl });
|
||||
const api = new BacktestServiceV2(f.services, (url, init) =>
|
||||
f.routes.request(new URL(url).pathname, init)
|
||||
);
|
||||
const notifications: Partial<RunUpdateMessage>[] = [];
|
||||
let notify!: () => void;
|
||||
const cancelled = new Promise<void>(resolve => {
|
||||
notify = resolve;
|
||||
});
|
||||
const handler = createWebSocketHandler(f.services);
|
||||
handler.broadcastRunUpdate = (_runId, update) => {
|
||||
notifications.push(update);
|
||||
if (update.type === 'run_update') {
|
||||
notify();
|
||||
}
|
||||
};
|
||||
Object.defineProperty(api, 'wsHandler', { value: handler });
|
||||
const definition = await api.createBacktest(
|
||||
{ ...blockingConfig, name: config.name! },
|
||||
{ autoStart: false }
|
||||
);
|
||||
const ready = workerReady(f.runner);
|
||||
const run = await api.createRun({ backtestId: definition.id, speedMultiplier: null });
|
||||
const { pid, runId } = await ready;
|
||||
expect(runId).toBe(run.id);
|
||||
await api.cancelRun(run.id);
|
||||
await cancelled;
|
||||
expectWorkerExited(pid);
|
||||
expect(notifications).toContainEqual({
|
||||
type: 'run_update',
|
||||
data: { status: 'cancelled', timestamp: expect.any(String) },
|
||||
});
|
||||
expect(notifications.some(update => update.type === 'error')).toBe(false);
|
||||
expect((await api.getRun(run.id))?.status).toBe('cancelled');
|
||||
expect(await api.getRunResults(run.id)).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue