209 lines
7.2 KiB
TypeScript
209 lines
7.2 KiB
TypeScript
import { EventEmitter } from 'node:events';
|
|
import type { Logger } from '@stock-bot/services';
|
|
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
|
import {
|
|
canonicalRunRequestSchema,
|
|
type CanonicalRunRequest,
|
|
type CanonicalRunResult,
|
|
} from '@stock-bot/stock-config/canonical-research';
|
|
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
|
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
|
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
|
import type { StorageService } from '../services/StorageService';
|
|
import type { BacktestConfig } from '../types';
|
|
import {
|
|
BacktestCancelledError,
|
|
BacktestTimeoutError,
|
|
type BacktestExecutionEngine,
|
|
} from './execution-engine';
|
|
import { nativeResultSchema, type NativeBacktestResult } from './native-result';
|
|
import { resolveNativeStrategies } from './native-strategies';
|
|
import { parseRetainedStrategyResult, 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 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 dependencies: {
|
|
logger: Pick<Logger, 'error'>;
|
|
storage: Pick<StorageService, 'getHistoricalBars'>;
|
|
},
|
|
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);
|
|
}
|
|
|
|
async runBacktest(
|
|
input: BacktestConfig,
|
|
dataset?: DatasetResolver
|
|
): Promise<NativeBacktestResult> {
|
|
const config = parseBacktestRequest(input);
|
|
return this.runOwned(Date.parse(config.startDate), async (signal, aborted) => {
|
|
resolveNativeStrategies(config);
|
|
const data = await Promise.race([this.loadData(config, signal, dataset), 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);
|
|
return result;
|
|
});
|
|
}
|
|
|
|
async runCanonical(
|
|
input: CanonicalRunRequest,
|
|
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
|
|
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>> {
|
|
const request = canonicalRunRequestSchema.parse(input);
|
|
return this.runOwned(
|
|
request.policy.matching.risk.ledger.riskSession.startsAt,
|
|
async (signal, aborted) => {
|
|
const dataset = await Promise.race([resolveDataset(signal), aborted]);
|
|
signal.throwIfAborted();
|
|
const raw = await this.worker.execute(
|
|
{ type: 'runRetainedStrategy', request, dataset },
|
|
signal,
|
|
progress => {
|
|
this.progress = progress.progress;
|
|
this.publish('progress', progress);
|
|
}
|
|
);
|
|
const result = parseRetainedStrategyResult(raw, request);
|
|
this.currentTime = dataset.manifest.bounds.tradeEnd;
|
|
return { financial: result.financial, analytics: result.analytics };
|
|
}
|
|
);
|
|
}
|
|
|
|
/** One ownership/deadline/cancellation lifecycle for legacy and canonical work. */
|
|
private async runOwned<Result>(
|
|
initialTime: number,
|
|
work: (signal: AbortSignal, aborted: Promise<never>) => Promise<Result>
|
|
): Promise<Result> {
|
|
if (this.closing || this.active) {
|
|
throw new Error(
|
|
this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running'
|
|
);
|
|
}
|
|
const controller = new AbortController();
|
|
let finished!: () => void;
|
|
this.active = {
|
|
controller,
|
|
finished: new Promise<void>(resolve => {
|
|
finished = resolve;
|
|
}),
|
|
};
|
|
this.progress = 0;
|
|
this.currentTime = initialTime;
|
|
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 result = await work(signal, aborted);
|
|
this.progress = 100;
|
|
this.publish('complete', result);
|
|
return result;
|
|
} catch (error) {
|
|
if (!(error instanceof BacktestCancelledError)) {
|
|
this.dependencies.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,
|
|
resolver?: DatasetResolver
|
|
): Promise<Extract<NativeWorkerRequest, { type: 'run' }>['data']> {
|
|
signal.throwIfAborted();
|
|
const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal);
|
|
signal.throwIfAborted();
|
|
const data: Extract<NativeWorkerRequest, { type: 'run' }>['data'] = [];
|
|
for (const bar of dataset.bars) {
|
|
data.push({ ...bar, type: 'bar' });
|
|
if (data.length % PREPARATION_BATCH_SIZE === 0) {
|
|
await preparationCheckpoint(signal);
|
|
}
|
|
}
|
|
signal.throwIfAborted();
|
|
return data;
|
|
}
|
|
|
|
private publish(event: string, data: unknown): void {
|
|
try {
|
|
this.emit(event, data);
|
|
} catch (error) {
|
|
this.dependencies.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');
|
|
}
|
|
}
|