181 lines
6.5 KiB
TypeScript
181 lines
6.5 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { EventEmitter } from 'node:events';
|
|
import type { TradingEngine } from '@stock-bot/engine';
|
|
import { defined } from '@stock-bot/invariants';
|
|
import type { Logger } from '@stock-bot/services';
|
|
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
|
import { DataManager } from '../data/DataManager';
|
|
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
|
import { amount, decimal } from '../execution/model';
|
|
import type { ExecutionService } from '../services/ExecutionService';
|
|
import type { StorageService } from '../services/StorageService';
|
|
import type { StrategyManager } from '../strategies/StrategyManager';
|
|
import type { BacktestConfig } from '../types';
|
|
import { BacktestMarket } from './BacktestMarket';
|
|
import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
|
|
import { BacktestReport } from './BacktestReport';
|
|
import type { BacktestExecutionEngine } from './execution-engine';
|
|
import { closedTradesSchema } from './native-result';
|
|
import { backtestStrategies } from './strategy-plan';
|
|
import type { BacktestResult } from './typescript-result';
|
|
|
|
export type { BacktestResult } from './typescript-result';
|
|
const speeds = { max: null, realtime: 1, '2x': 2, '5x': 5, '10x': 10 } as const;
|
|
|
|
/** Composes one run's playback, market projection and report. The runner owns durable lifecycle. */
|
|
export class BacktestEngine extends EventEmitter implements BacktestExecutionEngine {
|
|
private playback?: BacktestPlayback;
|
|
private active?: Promise<BacktestResult>;
|
|
private completedReport?: BacktestReport;
|
|
private closing = false;
|
|
|
|
constructor(
|
|
private readonly dependencies: {
|
|
logger: Pick<Logger, 'info' | 'error'>;
|
|
storage: Pick<StorageService, 'getHistoricalBars'>;
|
|
strategies: Pick<StrategyManager, 'initializeStrategies' | 'onMarketData'>;
|
|
execution: Pick<ExecutionService, 'getAccount'>;
|
|
getTradingEngine: () => TradingEngine;
|
|
}
|
|
) {
|
|
super();
|
|
}
|
|
|
|
async runBacktest(input: unknown, resolver?: DatasetResolver): Promise<BacktestResult> {
|
|
if (this.closing || this.active) {
|
|
throw new Error(
|
|
this.closing ? 'Backtest engine is shutting down' : 'Backtest already running'
|
|
);
|
|
}
|
|
const config = parseBacktestRequest(input);
|
|
const playback = new BacktestPlayback(Date.parse(config.startDate), speeds[config.speed]);
|
|
this.playback = playback;
|
|
this.completedReport = undefined;
|
|
const work = this.execute(config, playback, resolver);
|
|
this.active = work;
|
|
try {
|
|
return await work;
|
|
} finally {
|
|
playback.finish();
|
|
this.active = undefined;
|
|
}
|
|
}
|
|
|
|
private async execute(
|
|
config: BacktestConfig,
|
|
playback: BacktestPlayback,
|
|
resolver?: DatasetResolver
|
|
): Promise<BacktestResult> {
|
|
const plan = backtestStrategies(config, 'typescript');
|
|
const { logger, storage, strategies: strategyManager, execution } = this.dependencies;
|
|
logger.info('Starting TypeScript backtest', { symbols: config.symbols });
|
|
const dataset = await playback.read(() =>
|
|
resolveDataset(storage, config, resolver, playback.signal)
|
|
);
|
|
playback.assertRunning();
|
|
const dataManager = new DataManager(storage);
|
|
dataManager.inspectDataset(dataset);
|
|
const strategies = plan.map(({ name, parameters, index }) => ({
|
|
id: name + '-' + index,
|
|
name,
|
|
enabled: true,
|
|
parameters,
|
|
symbols: config.symbols,
|
|
allocation: 1 / plan.length,
|
|
}));
|
|
await strategyManager.initializeStrategies(strategies);
|
|
playback.assertRunning();
|
|
const trading = this.dependencies.getTradingEngine();
|
|
const market = new BacktestMarket(trading, config.symbols, dataset.manifest.hash);
|
|
const report = new BacktestReport(config, config.runId ?? randomUUID());
|
|
await playback.process(
|
|
dataset.bars,
|
|
bar => bar.timestamp,
|
|
async bar => {
|
|
trading.advanceTime(bar.timestamp);
|
|
const data = {
|
|
type: 'bar' as const,
|
|
data: bar,
|
|
eventId: [dataset.manifest.hash, bar.symbol, bar.timestamp].join(':'),
|
|
};
|
|
market.process(data);
|
|
await strategyManager.onMarketData(data);
|
|
report.record(bar.timestamp, (await execution.getAccount()).equity);
|
|
},
|
|
progress => this.publishProgress(progress)
|
|
);
|
|
playback.assertRunning();
|
|
const closedTrades = closedTradesSchema.parse(JSON.parse(trading.getClosedTrades()));
|
|
const account = await execution.getAccount();
|
|
playback.assertRunning();
|
|
const positions = Object.values(account.positions)
|
|
.filter(position => position.quantity !== 0)
|
|
.map(position => {
|
|
const quote = account.quotes[position.symbol];
|
|
const currentPrice = quote ? (quote.bid + quote.ask) / 2 : position.averagePrice;
|
|
return {
|
|
...position,
|
|
currentPrice,
|
|
unrealizedPnl: amount(
|
|
decimal(currentPrice).minus(position.averagePrice).times(position.quantity)
|
|
),
|
|
};
|
|
});
|
|
const result = report.complete(
|
|
dataset,
|
|
closedTrades,
|
|
positions,
|
|
dataManager.getDataQualityReport()
|
|
);
|
|
this.completedReport = report;
|
|
logger.info('TypeScript backtest completed', { trades: result.trades.length });
|
|
return result;
|
|
}
|
|
|
|
private publishProgress(progress: PlaybackProgress): void {
|
|
try {
|
|
this.emit('progress', progress);
|
|
} catch (error) {
|
|
this.dependencies.logger.error('Backtest progress observer failed', { error });
|
|
}
|
|
}
|
|
|
|
async exportResults(format: 'json' | 'csv' | 'html' = 'json'): Promise<string> {
|
|
if (this.active) {
|
|
throw new Error('Cannot export an unfinished backtest');
|
|
}
|
|
return defined(this.completedReport, 'No completed backtest report is available').export(
|
|
format
|
|
);
|
|
}
|
|
async pauseBacktest(): Promise<void> {
|
|
this.playback?.pause();
|
|
}
|
|
async resumeBacktest(): Promise<void> {
|
|
this.playback?.resume();
|
|
}
|
|
async stopBacktest(): Promise<void> {
|
|
this.playback?.stop();
|
|
}
|
|
async shutdown(): Promise<void> {
|
|
this.closing = true;
|
|
await this.stopBacktest();
|
|
await this.active?.catch(() => {});
|
|
}
|
|
setSpeedMultiplier(speed: number | null): void {
|
|
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
|
|
throw new Error('Backtest speed must be positive or null');
|
|
}
|
|
this.playback?.setSpeed(speed);
|
|
}
|
|
getStatus() {
|
|
return (
|
|
this.playback?.getStatus() ?? {
|
|
isRunning: false,
|
|
isPaused: false,
|
|
progress: 0,
|
|
currentTime: 0,
|
|
}
|
|
);
|
|
}
|
|
}
|