183 lines
6 KiB
TypeScript
183 lines
6 KiB
TypeScript
import { EventEmitter } from 'node:events';
|
|
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;
|
|
|
|
/** 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 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,
|
|
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(
|
|
container,
|
|
container.mongodb,
|
|
container.postgres,
|
|
container.questdb ?? null
|
|
);
|
|
}
|
|
|
|
async runBacktest(input: BacktestConfig): Promise<NativeBacktestResult> {
|
|
if (this.closing || this.active) {
|
|
throw new Error(
|
|
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
|
|
);
|
|
}
|
|
const config = BacktestConfigSchema.parse(input);
|
|
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 {
|
|
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 result = nativeResultSchema.parse(JSON.parse(raw));
|
|
this.currentTime = Date.parse(config.endDate);
|
|
this.progress = 100;
|
|
this.publish('complete', result);
|
|
return result;
|
|
} catch (error) {
|
|
if (!(error instanceof BacktestCancelledError)) {
|
|
this.container.logger.error('Native backtest failed', { error });
|
|
}
|
|
if (this.listenerCount('error') > 0) {
|
|
this.publish('error', error);
|
|
}
|
|
throw error;
|
|
} finally {
|
|
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.active,
|
|
isPaused: false,
|
|
progress: this.progress,
|
|
currentTime: this.currentTime,
|
|
};
|
|
}
|
|
async stopBacktest(): Promise<void> {
|
|
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 backtests do not support pause');
|
|
}
|
|
async resumeBacktest(): Promise<void> {
|
|
throw new Error('Native backtests do not support resume');
|
|
}
|
|
setSpeedMultiplier(_speed: number | null): void {
|
|
throw new Error('Native backtests run at maximum speed');
|
|
}
|
|
}
|