import { afterEach, describe, expect, test } from 'bun:test'; import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine'; import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService'; import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; import { BacktestConfigSchema, type OrchestratorServices, } from '../../apps/stock/orchestrator/src/types'; import { logger } from '../fixtures/execution'; const config = BacktestConfigSchema.parse({ mode: 'backtest', strategy: 'sma-crossover', symbols: ['A.US', 'B.US'], startDate: '2024-01-01T00:00:00Z', endDate: '2024-03-15T00:00:00Z', initialCapital: 10000, dataFrequency: '1d', speed: 'max', commission: 0.001, slippage: 0, }); const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); }); async function fixture() { const services: OrchestratorServices = { logger, custom: {} }; const storage = new StorageService(services, null, null, null, { allowSyntheticData: true, syntheticSeed: 42, }); const market = new MarketDataService(services); const execution = new ExecutionService(services, storage); const manager = new StrategyManager(services); const mode = new ModeManager(services, market, execution, storage); const backend = new BacktestEngine(services, storage, manager); Object.assign(services.custom!, { StorageService: storage, ExecutionService: execution, StrategyManager: manager, ModeManager: mode, MarketDataService: market, }); await mode.initializeMode(config); cleanup.push(async () => { await backend.shutdown(); await mode.shutdown(); }); return { services, storage, execution, manager, mode, backend }; } function deferred() { let resolve!: (value: T) => void; const promise = new Promise(done => { resolve = done; }); return { promise, resolve }; } describe('composed TypeScript backtests', () => { test('completed results and repeatable exports agree with the authoritative ledger', async () => { const f = await fixture(); const result = await f.backend.runBacktest(config); const account = await f.execution.getAccount(); expect(result.status).toBe('completed'); expect(result.trades.length).toBeGreaterThan(0); expect(result.equity.at(-1)?.value).toBe(account.equity); expect(result.metrics.totalReturn).toBeCloseTo( ((account.equity - config.initialCapital) / config.initialCapital) * 100 ); expect(result.positions.every(position => position.quantity !== 0)).toBe(true); for (const position of result.positions) { const quote = account.quotes[position.symbol]!; expect(position.currentPrice).toBe((quote.bid + quote.ask) / 2); } const first = await f.backend.exportResults(); expect(JSON.parse(first).summary.totalTrades).toBe(result.trades.length); expect(JSON.parse(first).equityCurve.map((point: { value: number }) => point.value)).toEqual( result.equity.map(point => point.value) ); result.equity[0]!.value = -1; await f.backend.exportResults('csv'); await f.backend.exportResults('html'); expect(await f.backend.exportResults()).toBe(first); expect(f.backend.getStatus()).toMatchObject({ isRunning: false, isPaused: false, progress: 100, }); }); test('service reuse does not leak symbols, indicators, equity or exports across runs', async () => { const f = await fixture(); const first = await f.backend.runBacktest(config); const secondConfig = { ...config, symbols: ['C.US'] }; await f.mode.initializeMode(secondConfig); const second = await f.backend.runBacktest(secondConfig); expect(Object.keys(second.ohlcData)).toEqual(['C.US']); expect(second.trades.every(trade => trade.symbol === 'C.US')).toBe(true); await f.mode.initializeMode(config); const repeated = await f.backend.runBacktest(config); expect(repeated.trades).toEqual(first.trades); expect(repeated.metrics).toEqual(first.metrics); expect(repeated.equity).toEqual(first.equity); }); test('overlapping runs fail before they can reset the active read or its controls', async () => { const f = await fixture(); const gate = deferred(); let loads = 0; const run = f.backend.runBacktest(config, async load => { loads++; await gate.promise; return load(); }); const settled = run.catch(error => error); await expect(f.backend.runBacktest(config)).rejects.toThrow('already running'); await expect(f.backend.exportResults()).rejects.toThrow('unfinished'); expect(loads).toBe(1); await f.backend.stopBacktest(); expect(await settled).toBeInstanceOf(BacktestCancelledError); gate.resolve(); await new Promise(resolve => setTimeout(resolve, 0)); expect(f.manager.getAllStrategies()).toEqual([]); await expect(f.backend.exportResults()).rejects.toThrow('No completed'); expect(f.backend.getStatus()).toMatchObject({ isRunning: false, progress: 0 }); }); test('cancellation at progress never returns a partial completed result or a reusable export', async () => { const f = await fixture(); const updates: number[] = []; f.backend.on('progress', update => { updates.push(update.progress); void f.backend.stopBacktest(); }); const outcome = await f.backend.runBacktest(config).catch(error => error); expect(outcome).toBeInstanceOf(BacktestCancelledError); expect(updates).not.toContain(100); expect(f.backend.getStatus()).toMatchObject({ isRunning: false, isPaused: false }); await expect(f.backend.exportResults()).rejects.toThrow('No completed'); }); test('pause gates the next input, and resume produces the same ledger result', async () => { const f = await fixture(); const paused = deferred(); const original = f.manager.onMarketData.bind(f.manager); let received = 0; f.manager.onMarketData = async data => { await original(data); if (++received === 1) { await f.backend.pauseBacktest(); paused.resolve(); } }; const run = f.backend.runBacktest(config); await paused.promise; await new Promise(resolve => setTimeout(resolve, 0)); expect(received).toBe(1); expect(f.backend.getStatus().isPaused).toBe(true); await f.backend.resumeBacktest(); const result = await run; expect(result.status).toBe('completed'); expect(result.equity.at(-1)?.value).toBe((await f.execution.getAccount()).equity); }); test('unavailable financial state fails instead of fabricating initial-capital performance', async () => { const f = await fixture(); f.execution.getAccount = async () => { throw new Error('Ledger unavailable'); }; await expect(f.backend.runBacktest(config)).rejects.toThrow('Ledger unavailable'); expect(f.backend.getStatus().isRunning).toBe(false); await expect(f.backend.exportResults()).rejects.toThrow('No completed'); }); test('observer failures cannot change the result, and shutdown closes future admission', async () => { const f = await fixture(); f.backend.on('progress', () => { throw new Error('observer failed'); }); expect((await f.backend.runBacktest(config)).status).toBe('completed'); await f.backend.shutdown(); await expect(f.backend.runBacktest(config)).rejects.toThrow('shutting down'); }); });