stock-bot/test/integration/typescript-backtest.test.ts
2026-10-22 09:46:29 -04:00

205 lines
8.1 KiB
TypeScript

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 { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
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<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
});
async function fixture() {
const services: OrchestratorServices = { logger };
const storage = new StorageService(services, null, null, null, {
allowSyntheticData: true,
syntheticSeed: 42,
});
const market: MarketDataService = new MarketDataService({
logger,
storage,
drainStrategies: () => manager.drain(),
});
const execution = new ExecutionService(services, storage);
const registry = createBuiltinStrategyRegistry();
const manager: StrategyManager = new StrategyManager({
logger,
marketData: market,
execution,
createStrategy: config => registry.create(config, { execution, modeManager: mode }),
});
const mode: ModeManager = new ModeManager({
logger,
marketData: market,
execution,
storage,
strategies: manager,
});
const backend = new BacktestEngine({
logger,
storage,
strategies: manager,
execution,
getTradingEngine: () => mode.getTradingEngine(),
});
await mode.initializeMode(config);
cleanup.push(async () => {
await backend.shutdown();
await mode.shutdown();
});
return { services, storage, execution, manager, mode, backend };
}
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>(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<void>();
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<void>();
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');
});
});