continuation

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

View file

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