import { BacktestCancelledError } from './execution-engine'; export interface PlaybackProgress { processed: number; total: number; remaining: number; currentTime: Date; currentDate: string; progress: number; } /** One run's cursor and interruptible controls; independent of trading, storage and reporting. */ export class BacktestPlayback { private readonly controller = new AbortController(); private wake?: () => void; private running = true; private paused = false; private processed = 0; private total = 0; private started = false; constructor( private currentTime: number, private speed: number | null ) { this.validateSpeed(speed); } private validateSpeed(speed: number | null): void { if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) { throw new Error('Backtest speed must be positive or null'); } } assertRunning(): void { if (!this.running) { throw new BacktestCancelledError(); } this.controller.signal.throwIfAborted(); } get signal(): AbortSignal { return this.controller.signal; } /** Only race side-effect-free reads; late reads must never resume execution. */ async read(load: () => Promise): Promise { this.assertRunning(); const { signal } = this.controller; signal.throwIfAborted(); let rejectAbort!: (reason: unknown) => void; const aborted = new Promise((_resolve, reject) => { rejectAbort = reject; }); const onAbort = () => rejectAbort(signal.reason); signal.addEventListener('abort', onAbort, { once: true }); try { const work = Promise.resolve().then(() => { this.assertRunning(); return load(); }); return await Promise.race([work, aborted]); } finally { signal.removeEventListener('abort', onAbort); } } private async wait(ms?: number): Promise { this.assertRunning(); await new Promise(resolve => { let timer: ReturnType | undefined; const done = () => { if (timer !== undefined) { clearTimeout(timer); } this.wake = undefined; resolve(); }; this.wake = done; if (ms !== undefined) { timer = setTimeout(done, ms); } }); this.assertRunning(); } private async ready(): Promise { this.assertRunning(); while (this.paused) { await this.wait(); } } async process( events: readonly T[], timestamp: (event: T) => number, consume: (event: T) => Promise, progress: (value: PlaybackProgress) => void ): Promise { this.assertRunning(); if (this.started) { throw new Error('Backtest playback has already started'); } this.started = true; this.total = events.length; // Frozen inputs are already validated and ordered. A cursor avoids copying and shifting history. for (const event of events) { await this.ready(); if (this.speed !== null) { await this.wait(1000 / this.speed); } await this.ready(); this.currentTime = timestamp(event); await consume(event); this.processed++; this.assertRunning(); const interval = this.speed === null ? 100 : Math.max(1, Math.floor(10 / this.speed)); if (this.processed < this.total && this.processed % interval === 0) { progress(this.progress()); } // Let cancellation, lease heartbeats and other accounts run even at unlimited speed. if (this.speed === null && this.processed % 100 === 0) { await this.wait(0); } } this.assertRunning(); progress(this.progress()); this.assertRunning(); } private progress(): PlaybackProgress { return { processed: this.processed, total: this.total, remaining: this.total - this.processed, currentTime: new Date(this.currentTime), currentDate: new Date(this.currentTime).toISOString(), progress: this.total > 0 ? this.processed === this.total ? 100 : Math.min(99, Math.round((this.processed / this.total) * 100)) : 0, }; } pause(): void { if (!this.running) { return; } this.paused = true; this.wake?.(); } resume(): void { this.paused = false; this.wake?.(); } stop(): void { this.controller.abort(new BacktestCancelledError()); this.paused = false; this.wake?.(); } finish(): void { this.running = false; this.paused = false; this.wake?.(); } setSpeed(speed: number | null): void { this.validateSpeed(speed); this.speed = speed; this.wake?.(); } getStatus() { return { isRunning: this.running, isPaused: this.paused, progress: this.progress().progress, currentTime: this.currentTime, }; } }