Separate backtest playback, market projection, and reporting

This commit is contained in:
Boki 2026-10-21 14:03:54 -04:00
parent 694c48bbdb
commit 366d39001b
12 changed files with 1642 additions and 1007 deletions

View file

@ -97,6 +97,34 @@ nothing. History is still retained in memory for the run; this is not a streamin
solution. Run `bun run scripts/benchmark-execution.ts` for a local journal-read microbenchmark,
not an end-to-end backtest performance estimate.
### TypeScript backtest composition
`BacktestEngine` coordinates fresh components for each run:
- `BacktestPlayback` owns the input cursor, pacing and interruptible pause/resume/stop.
Frozen bars are consumed in order without a second event array or queue shifting;
unlimited playback periodically yields so cancellation and lease heartbeats can run.
- `BacktestMarket` owns seeded market projection and per-symbol microstructure defaults.
It cannot submit orders; financial state still belongs to the execution ledger.
- `BacktestReport` records ledger equity and builds a detached completed snapshot.
`report-format.ts` formats that snapshot without re-reading the engine or adding trades.
Overlapping runs fail before state changes. Cancellation raises `BacktestCancelledError`;
the runner records cancellation without persisting a partial successful result. Pending
historical reads cannot resume a cancelled run, and stop wakes paused/paced playback.
Arbitrary custom strategy callbacks are still cooperative, not forcibly isolated.
Equity and final position valuations come from `ExecutionService`, not a best-effort native
P&L projection. Missing ledger state fails; zero/negative equity is never replaced with
starting capital. Drawdown duration uses simulated time. Month-end returns use UTC boundaries
and the preceding month-end balance (initial capital for the first month); percentage returns
with a nonpositive baseline are omitted. These corrections can change historical metrics.
`exportResults()` is available after successful completion until the next run begins.
Repeated JSON/CSV/HTML exports retain the finished equity and trade count; exports cannot
mutate analysis. Charts and quality observations group frozen bars in one pass, but datasets
and detailed equity history still reside in memory; this is not a streaming backtest engine.
## Backtest data integrity
Historical storage no longer invents prices when a database is unavailable. Configure a

View file

@ -1,7 +1,6 @@
import * as stats from 'simple-statistics';
import { defined } from '@stock-bot/invariants';
import { at, defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { at } from '@stock-bot/utils';
const logger = getLogger('PerformanceAnalyzer');
@ -246,7 +245,12 @@ export class PerformanceAnalyzer {
// Calculate max drawdown duration
const maxDrawdownDuration = Math.max(
...drawdownPeriods.map(p => p.duration),
currentDrawdownStart ? this.daysBetween(currentDrawdownStart, new Date()) : 0
currentDrawdownStart
? this.daysBetween(
currentDrawdownStart,
at(this.equityCurve, this.equityCurve.length - 1).date
)
: 0
);
return {
@ -662,10 +666,7 @@ export class PerformanceAnalyzer {
};
}
exportReport(): string {
const metrics = this.analyze();
const _drawdowns = this.analyzeDrawdowns();
exportReport(metrics: PerformanceMetrics = this.analyze()): string {
return `
# Performance Report
@ -674,7 +675,7 @@ export class PerformanceAnalyzer {
- Annualized Return: ${metrics.annualizedReturn.toFixed(2)}%
- CAGR: ${metrics.cagr.toFixed(2)}%
- Volatility: ${metrics.volatility.toFixed(2)}%
- Max Drawdown: ${metrics.maxDrawdown.toFixed(2)}%
- Max Drawdown: ${(metrics.maxDrawdown * 100).toFixed(2)}%
- Sharpe Ratio: ${metrics.sharpeRatio.toFixed(2)}
- Sortino Ratio: ${metrics.sortinoRatio.toFixed(2)}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,128 @@
import type { TradingEngine } from '@stock-bot/engine';
import { at } from '@stock-bot/invariants';
import type { MarketData, MarketMicrostructure } from '../types';
import { MarketSimulator } from './MarketSimulator';
export type BacktestMarketPort = Pick<
TradingEngine,
'updateQuote' | 'updateTrade' | 'setMicrostructure'
>;
/** Market projection only: orders and financial accounting still go through ExecutionService. */
export class BacktestMarket {
private readonly simulator = new MarketSimulator();
private readonly microstructures = new Map<string, MarketMicrostructure>();
constructor(
private readonly engine: BacktestMarketPort,
symbols: string[],
datasetHash: string
) {
this.simulator.resetWithSeed(Number.parseInt(datasetHash.slice(0, 8), 16));
this.loadMarketMicrostructure(symbols);
}
process(data: MarketData): void {
// Process through market simulator for realistic orderbook
const orderbook = this.simulator.processMarketData(data);
if (orderbook) {
// Update trading engine with simulated orderbook
if (orderbook.bids.length > 0 && orderbook.asks.length > 0) {
this.engine.updateQuote(
orderbook.symbol,
at(orderbook.bids, 0).price,
at(orderbook.asks, 0).price,
at(orderbook.bids, 0).size,
at(orderbook.asks, 0).size
);
}
// Set microstructure in trading core for realistic fills
const microstructure = this.microstructures.get(orderbook.symbol);
if (microstructure && this.engine.setMicrostructure) {
this.engine.setMicrostructure(orderbook.symbol, microstructure);
}
} else {
// Fallback to simple processing
switch (data.type) {
case 'quote':
this.engine.updateQuote(
data.data.symbol,
data.data.bid,
data.data.ask,
data.data.bidSize,
data.data.askSize
);
break;
case 'trade':
this.engine.updateTrade(
data.data.symbol,
data.data.price,
data.data.size,
data.data.side
);
break;
case 'bar': {
const spread = data.data.high - data.data.low;
const spreadBps = (spread / data.data.close) * 10000;
const halfSpread = (data.data.close * Math.min(spreadBps, 10)) / 20000;
this.engine.updateQuote(
data.data.symbol,
data.data.close - halfSpread,
data.data.close + halfSpread,
data.data.volume / 100,
data.data.volume / 100
);
break;
}
}
}
}
private loadMarketMicrostructure(symbols: string[]): void {
// In real implementation, would load from database
// For now, create reasonable defaults based on symbol characteristics
for (const symbol of symbols) {
const microstructure: MarketMicrostructure = {
symbol,
avgSpreadBps: 3,
dailyVolume: 10_000_000,
avgTradeSize: 100,
volatility: 0.2,
tickSize: 0.01,
lotSize: 1,
intradayVolumeProfile: this.generateIntradayProfile(),
};
this.microstructures.set(symbol, microstructure);
this.simulator.setMicrostructure(symbol, microstructure);
}
}
private generateIntradayProfile(): number[] {
// U-shaped intraday volume pattern
const profile = new Array(24).fill(0);
const tradingHours = [9, 10, 11, 12, 13, 14, 15, 16]; // 9:30 AM to 4:00 PM
tradingHours.forEach((hour, idx) => {
if (idx === 0 || idx === tradingHours.length - 1) {
// High volume at open and close
profile[hour] = 0.2;
} else if (idx === 1 || idx === tradingHours.length - 2) {
// Moderate volume
profile[hour] = 0.15;
} else {
// Lower midday volume
profile[hour] = 0.1;
}
});
// Normalize
const sum = profile.reduce((a, b) => a + b, 0);
return profile.map(v => v / sum);
}
}

View file

@ -0,0 +1,177 @@
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();
}
/** Only race side-effect-free reads; late reads must never resume execution. */
async read<T>(load: () => Promise<T>): Promise<T> {
this.assertRunning();
const { signal } = this.controller;
signal.throwIfAborted();
let rejectAbort!: (reason: unknown) => void;
const aborted = new Promise<never>((_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<void> {
this.assertRunning();
await new Promise<void>(resolve => {
let timer: ReturnType<typeof setTimeout> | 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<void> {
this.assertRunning();
while (this.paused) {
await this.wait();
}
}
async process<T>(
events: readonly T[],
timestamp: (event: T) => number,
consume: (event: T) => Promise<void>,
progress: (value: PlaybackProgress) => void
): Promise<void> {
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,
};
}
}

View file

@ -0,0 +1,324 @@
import { at, defined } from '@stock-bot/invariants';
import type { HistoricalDataset } from '@stock-bot/types';
import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
import type { BacktestConfig } from '../types';
import type { ClosedTrade } from './native-result';
import { formatReport, type ReportExport } from './report-format';
import type { BacktestResult, OHLCBar } from './typescript-result';
/** Run-local observations and a detached completed report; never reads services or financial state. */
export class BacktestReport {
private readonly equityCurve: { timestamp: number; value: number }[];
private performanceAnalyzer?: PerformanceAnalyzer;
private snapshot?: ReportExport;
private readonly config: BacktestConfig;
constructor(
config: BacktestConfig,
private readonly backtestId: string
) {
this.config = structuredClone(config);
const start = Date.parse(config.startDate);
this.equityCurve = [{ timestamp: start, value: config.initialCapital }];
this.performanceAnalyzer = new PerformanceAnalyzer(config.initialCapital);
this.performanceAnalyzer.addEquityPoint(new Date(start), config.initialCapital);
}
record(timestamp: number, equity: number): void {
if (this.snapshot) {
throw new Error('Backtest report is already finalized');
}
if (!Number.isFinite(timestamp) || !Number.isFinite(equity)) {
throw new Error('Invalid backtest equity observation');
}
const last = defined(this.equityCurve[this.equityCurve.length - 1]);
if (timestamp < last.timestamp) {
throw new Error('Out-of-order backtest equity observation');
}
defined(this.performanceAnalyzer).addEquityPoint(new Date(timestamp), equity);
if (last.timestamp === timestamp) {
last.value = equity;
} else {
this.equityCurve.push({ timestamp, value: equity });
}
}
complete(
dataset: HistoricalDataset,
trades: ClosedTrade[],
finalPositions: BacktestResult['positions'],
dataQuality: unknown,
completedAt = new Date().toISOString()
): BacktestResult {
if (this.snapshot) {
throw new Error('Backtest report is already finalized');
}
const closedTrades = structuredClone(trades);
const performance = this.calculatePerformance(closedTrades);
const result: BacktestResult = {
// Identification
backtestId: this.backtestId,
status: 'completed' as const,
completedAt,
// Configuration used
config: {
name: this.config.name || 'Backtest',
strategy: this.config.strategy,
symbols: this.config.symbols,
startDate: this.config.startDate,
endDate: this.config.endDate,
initialCapital: this.config.initialCapital,
commission: this.config.commission ?? 0.001,
slippage: this.config.slippage ?? 0.0001,
dataFrequency: this.config.dataFrequency || '1d',
},
// Performance metrics (frontend-ready)
metrics: {
totalReturn: performance.totalReturn,
sharpeRatio: performance.sharpeRatio,
maxDrawdown: performance.maxDrawdown,
winRate: performance.winRate,
totalTrades: performance.totalTrades,
profitFactor: performance.profitFactor || 0,
profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100),
avgWin: performance.avgWin || 0,
avgLoss: performance.avgLoss || 0,
expectancy: performance.expectancy || 0,
calmarRatio: performance.calmarRatio || 0,
sortinoRatio: performance.sortinoRatio || 0,
},
// Chart data (frontend-ready format)
equity: this.equityCurve.map(point => ({
date: new Date(point.timestamp).toISOString(),
value: point.value,
})),
// OHLC data for charts
ohlcData: this.getOHLCData(dataset),
// Trade history (frontend-ready)
trades: closedTrades.map(trade => ({
id: trade.id,
symbol: trade.symbol,
entryDate: trade.entry_time,
exitDate: trade.exit_time,
entryPrice: trade.entry_price,
exitPrice: trade.exit_price,
quantity: trade.quantity,
side: trade.side === 'Buy' ? 'buy' : 'sell',
pnl: trade.pnl,
pnlPercent: trade.pnl_percent,
commission: trade.commission,
duration: trade.duration_ms,
})),
// Final positions
positions: finalPositions.map(pos => ({
symbol: pos.symbol,
quantity: pos.quantity,
averagePrice: pos.averagePrice,
currentPrice: pos.currentPrice || pos.averagePrice,
unrealizedPnl: pos.unrealizedPnl || 0,
realizedPnl: pos.realizedPnl || 0,
})),
// Additional analytics
analytics: {
drawdownSeries: this.calculateDrawdown(),
dailyReturns: this.calculateDailyReturns(),
monthlyReturns: this.calculateMonthlyReturns(),
exposureTime: this.calculateExposureTime(closedTrades),
riskMetrics: this.calculateRiskMetrics(closedTrades),
},
};
this.snapshot = structuredClone({
summary: performance,
trades: closedTrades,
equityCurve: this.equityCurve,
drawdowns: result.analytics.drawdownSeries,
dataQuality,
performanceReport: defined(this.performanceAnalyzer).exportReport(performance),
});
// The completed snapshot is sufficient for export; do not retain the analysis input twice.
this.equityCurve.length = 0;
this.performanceAnalyzer = undefined;
return structuredClone(result);
}
export(format: 'json' | 'csv' | 'html' = 'json'): string {
if (!this.snapshot) {
throw new Error('No completed backtest report is available');
}
return formatReport(this.snapshot, format);
}
private calculatePerformance(closedTrades: ClosedTrade[] = []): PerformanceMetrics {
const analyzer = defined(this.performanceAnalyzer);
// Import each closed trade once, when the completed snapshot is built.
closedTrades.forEach(trade => {
analyzer.addTrade({
entryTime: new Date(trade.entry_time),
exitTime: new Date(trade.exit_time),
symbol: trade.symbol,
side: trade.side === 'Buy' ? 'long' : 'short',
entryPrice: trade.entry_price,
exitPrice: trade.exit_price,
quantity: trade.quantity,
commission: trade.commission || 0,
pnl: trade.pnl || 0,
returnPct: trade.pnl_percent || 0,
holdingPeriod: trade.duration_ms / 60000, // Convert to minutes
mae: 0, // Not tracked yet
mfe: 0, // Not tracked yet
});
});
return analyzer.analyze();
}
private calculateDrawdown(): { timestamp: number; value: number }[] {
const drawdowns: { timestamp: number; value: number }[] = [];
let peak = this.config.initialCapital;
for (const point of this.equityCurve) {
if (point.value > peak) {
peak = point.value;
}
const drawdown = ((point.value - peak) / peak) * 100;
drawdowns.push({
timestamp: point.timestamp,
value: drawdown,
});
}
return drawdowns;
}
private calculateMonthlyReturns(): Record<string, number> {
const monthlyReturns: Record<string, number> = {};
const monthlyEquity = new Map<string, number>();
for (const point of this.equityCurve) {
monthlyEquity.set(new Date(point.timestamp).toISOString().slice(0, 7), point.value);
}
let previous = this.config.initialCapital;
for (const [month, value] of monthlyEquity) {
if (previous > 0) {
monthlyReturns[month] = ((value - previous) / previous) * 100;
}
previous = value;
}
return monthlyReturns;
}
private calculateExposureTime(closedTrades: ClosedTrade[] = []): number {
if (closedTrades.length === 0) {
return 0;
}
let totalExposureTime = 0;
for (const trade of closedTrades) {
totalExposureTime += trade.duration_ms || 0;
}
// Use equity curve to determine actual trading period
const startTime = this.equityCurve.length > 0 ? at(this.equityCurve, 0).timestamp : 0;
const endTime =
this.equityCurve.length > 0 ? at(this.equityCurve, this.equityCurve.length - 1).timestamp : 0;
const totalTime = endTime - startTime;
return totalTime > 0 ? (totalExposureTime / totalTime) * 100 : 0;
}
private calculateRiskMetrics(closedTrades: ClosedTrade[] = []): Record<string, number> {
const returns = this.calculateDailyReturns();
// Calculate various risk metrics
const avgReturn = returns.reduce((a, b) => a + b, 0) / Math.max(returns.length, 1);
const variance =
returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / Math.max(returns.length, 1);
const stdDev = Math.sqrt(variance);
// Downside deviation (for Sortino)
const downsideReturns = returns.filter(r => r < 0);
const downsideVariance =
downsideReturns.reduce((sum, r) => sum + Math.pow(r, 2), 0) /
Math.max(downsideReturns.length, 1);
const downsideDeviation = Math.sqrt(downsideVariance);
return {
volatility: stdDev * Math.sqrt(252), // Annualized
downsideDeviation: downsideDeviation * Math.sqrt(252),
var95: this.calculateVaR(returns, 0.95),
var99: this.calculateVaR(returns, 0.99),
cvar95: this.calculateCVaR(returns, 0.95),
maxConsecutiveLosses: this.calculateMaxConsecutiveLosses(closedTrades),
};
}
private calculateVaR(returns: number[], confidence: number): number {
const sorted = [...returns].sort((a, b) => a - b);
const index = Math.floor((1 - confidence) * sorted.length);
return sorted[index] || 0;
}
private calculateCVaR(returns: number[], confidence: number): number {
const sorted = [...returns].sort((a, b) => a - b);
const index = Math.floor((1 - confidence) * sorted.length);
const tail = sorted.slice(0, index + 1);
return tail.reduce((a, b) => a + b, 0) / Math.max(tail.length, 1);
}
private calculateMaxConsecutiveLosses(closedTrades: ClosedTrade[] = []): number {
let maxLosses = 0;
let currentLosses = 0;
for (const trade of closedTrades) {
if (trade.pnl && trade.pnl < 0) {
currentLosses++;
maxLosses = Math.max(maxLosses, currentLosses);
} else {
currentLosses = 0;
}
}
return maxLosses;
}
private calculateDailyReturns(): number[] {
const dailyReturns: number[] = [];
const dailyEquity = new Map<string, number>();
// Group equity by day
for (const point of this.equityCurve) {
const date = new Date(point.timestamp).toISOString().slice(0, 10);
dailyEquity.set(date, point.value);
}
// Calculate returns
const dates = Array.from(dailyEquity.keys()).sort();
for (let i = 1; i < dates.length; i++) {
const prevValue = defined(dailyEquity.get(at(dates, i - 1)));
const currValue = defined(dailyEquity.get(at(dates, i)));
if (prevValue > 0) {
dailyReturns.push(((currValue - prevValue) / prevValue) * 100);
}
}
return dailyReturns;
}
private getOHLCData(dataset: HistoricalDataset): Record<string, OHLCBar[]> {
const grouped: Record<string, OHLCBar[]> = Object.fromEntries(
this.config.symbols.map(symbol => [symbol, []])
);
for (const bar of dataset.bars) {
const { timestamp, open, high, low, close, volume } = bar;
defined(grouped[bar.symbol]).push({ timestamp, open, high, low, close, volume });
}
return grouped;
}
}

View file

@ -0,0 +1,120 @@
import type { PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
import type { ClosedTrade } from './native-result';
export interface ReportExport {
summary: PerformanceMetrics;
trades: ClosedTrade[];
equityCurve: { timestamp: number; value: number }[];
drawdowns: { timestamp: number; value: number }[];
dataQuality: unknown;
performanceReport: string;
}
export function formatReport(result: ReportExport, format: 'json' | 'csv' | 'html'): string {
switch (format) {
case 'json':
return JSON.stringify(result, null, 2);
case 'csv':
return convertToCSV(result);
case 'html':
return generateHTMLReport(result);
default:
throw new Error(`Unsupported backtest export format: ${format}`);
}
}
function csvCell(value: string | number): string {
let text = String(value);
// Text is not a spreadsheet formula; numeric losses remain ordinary numbers.
if (typeof value === 'string' && /^[=+\-@\t\r]/.test(text)) {
text = "'" + text;
}
return /[",\r\n]/.test(text) ? '"' + text.replaceAll('"', '""') + '"' : text;
}
function escapeHTML(value: string): string {
return value.replace(
/[&<>"']/g,
char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char] ?? char
);
}
export function convertToCSV(result: ReportExport): string {
// Simple CSV conversion for trades
const headers = ['Date', 'Symbol', 'Side', 'Entry', 'Exit', 'Quantity', 'PnL', 'Return%'];
const rows = result.trades.map(t => [
new Date(String(t.entry_time)).toISOString(),
t.symbol,
t.side === 'Buy' ? 'buy' : 'sell',
t.entry_price,
t.exit_price,
t.quantity,
t.pnl,
t.pnl_percent,
]);
return [headers, ...rows].map(row => row.map(csvCell).join(',')).join('\n');
}
export function generateHTMLReport(result: ReportExport): string {
return `
<!DOCTYPE html>
<html>
<head>
<title>Backtest Report</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
.metric { margin: 10px 0; }
.positive { color: green; }
.negative { color: red; }
</style>
</head>
<body>
<h1>Backtest Performance Report</h1>
<h2>Summary Statistics</h2>
<div class="metric">Total Return: <span class="${result.summary.totalReturn >= 0 ? 'positive' : 'negative'}">${result.summary.totalReturn.toFixed(2)}%</span></div>
<div class="metric">Sharpe Ratio: ${result.summary.sharpeRatio.toFixed(2)}</div>
<div class="metric">Max Drawdown: <span class="negative">${(result.summary.maxDrawdown * 100).toFixed(2)}%</span></div>
<div class="metric">Win Rate: ${result.summary.winRate.toFixed(1)}%</div>
<div class="metric">Total Trades: ${result.summary.totalTrades}</div>
<h2>Detailed Performance Metrics</h2>
<pre>${escapeHTML(result.performanceReport)}</pre>
<h2>Trade History</h2>
<table>
<tr>
<th>Date</th>
<th>Symbol</th>
<th>Side</th>
<th>Entry Price</th>
<th>Exit Price</th>
<th>Quantity</th>
<th>P&L</th>
<th>Return %</th>
</tr>
${result.trades
.map(
t => `
<tr>
<td>${new Date(t.entry_time).toISOString().slice(0, 10)}</td>
<td>${escapeHTML(t.symbol)}</td>
<td>${t.side}</td>
<td>$${t.entry_price.toFixed(2)}</td>
<td>$${t.exit_price.toFixed(2)}</td>
<td>${t.quantity}</td>
<td class="${t.pnl >= 0 ? 'positive' : 'negative'}">$${t.pnl.toFixed(2)}</td>
<td class="${t.pnl_percent >= 0 ? 'positive' : 'negative'}">${t.pnl_percent.toFixed(2)}%</td>
</tr>
`
)
.join('')}
</table>
</body>
</html>
`;
}

View file

@ -1,9 +1,8 @@
import { EventEmitter } from 'events';
import { defined } from '@stock-bot/invariants';
import { at, defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import type { HistoricalDataset } from '@stock-bot/types';
import { at } from '@stock-bot/utils';
import { StorageService, type HistoricalBar } from '../services/StorageService';
import type { HistoricalBar, StorageService } from '../services/StorageService';
import { type Bar, type MarketData } from '../types';
const logger = getLogger('DataManager');
@ -41,7 +40,7 @@ export class DataManager extends EventEmitter {
private aggregatedCache: Map<string, Map<string, Bar[]>> = new Map();
private dataQualityIssues: DataQualityIssue[] = [];
constructor(private storageService: StorageService) {
constructor(private storageService: Pick<StorageService, 'getHistoricalBars'>) {
super();
}
@ -90,17 +89,24 @@ export class DataManager extends EventEmitter {
/** Observations only: never repair, interpolate, drop, or re-adjust execution inputs. */
inspectDataset(dataset: HistoricalDataset): void {
this.clearCache();
const grouped = new Map<string, HistoricalDataset['bars']>();
for (const bar of dataset.bars) {
let bars = grouped.get(bar.symbol);
if (!bars) {
bars = [];
grouped.set(bar.symbol, bars);
}
bars.push(bar);
}
for (const instrument of dataset.manifest.instruments) {
this.recordQualityWarnings(
instrument.id,
dataset.bars
.filter(bar => bar.symbol === instrument.id)
.map(bar => ({ ...bar, timestamp: new Date(bar.timestamp) }))
);
this.recordQualityWarnings(instrument.id, grouped.get(instrument.id) ?? []);
}
}
private recordQualityWarnings(symbol: string, bars: HistoricalBar[]): void {
private recordQualityWarnings(
symbol: string,
bars: readonly { timestamp: Date | number; close: number }[]
): void {
bars.forEach((bar, index) => {
const previous = bars[index - 1];
if (previous && Math.abs((bar.close - previous.close) / previous.close) > 0.2) {

View file

@ -98,4 +98,21 @@ describe('orchestrator architecture boundaries', () => {
expect(readFileSync(file, 'utf8')).not.toMatch(/switch\s*\(\s*config\.name/);
expect(imports.get(join(root, 'strategies/StrategyRegistry.ts'))).toEqual([]);
});
it('backtest playback cannot depend on trading, data, reporting or service adapters', () => {
const dependencies = [...reachable(join(root, 'backtest/BacktestPlayback.ts'))].map(file => relative(root, file)).sort();
expect(dependencies).toEqual(['backtest/BacktestPlayback.ts', 'backtest/execution-engine.ts']);
});
it('backtest reports are independent of run control, native engines, data loading and financial mutation', () => {
for (const entry of ['backtest/BacktestReport.ts', 'backtest/report-format.ts']) {
for (const file of reachable(join(root, entry))) {
expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data|execution)\//);
expect(relative(root, file)).not.toMatch(/backtest\/(BacktestEngine|BacktestMarket|BacktestRunner|BacktestPlayback)/);
for (const specifier of imports.get(file) ?? []) {
expect(specifier.startsWith('.') || ['simple-statistics', 'zod', '@stock-bot/invariants', '@stock-bot/logger'].includes(specifier)).toBe(true);
}
}
}
});
});

View file

@ -0,0 +1,404 @@
import { describe, expect, spyOn, test } from 'bun:test';
import type { HistoricalDataset } from '@stock-bot/types';
import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer';
import {
BacktestPlayback,
type PlaybackProgress,
} from '../../apps/stock/orchestrator/src/backtest/BacktestPlayback';
import { BacktestReport } from '../../apps/stock/orchestrator/src/backtest/BacktestReport';
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import type { ClosedTrade } from '../../apps/stock/orchestrator/src/backtest/native-result';
import { formatReport } from '../../apps/stock/orchestrator/src/backtest/report-format';
import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager';
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
const day = 86400000;
const start = Date.parse('2024-01-01T00:00:00Z');
const config = BacktestConfigSchema.parse({
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['A.US', 'B.US'],
startDate: new Date(start).toISOString(),
endDate: '2024-03-01T00:00:00Z',
initialCapital: 1000,
dataFrequency: '1d',
});
const bars = [0, 1, 2].flatMap(index =>
config.symbols.map(symbol => ({
symbol,
timestamp: start + index * day,
open: 100,
high: 101,
low: 99,
close: 100,
volume: 1000,
vwap: 100,
}))
);
const dataset: HistoricalDataset = {
manifest: {
version: 1,
hash: '0'.repeat(64),
instruments: config.symbols.map(id => ({ id, symbol: id.split('.')[0]!, exchange: 'US' })),
startDate: config.startDate,
endDate: config.endDate,
interval: '1d',
policy: { adjustment: 'raw', timestamp: 'utc-session-date' },
volumePolicy: 'reported',
qualityPolicy: 'reject-invalid-no-interpolation',
sources: config.symbols.map(instrumentId => ({
instrumentId,
provider: 'synthetic',
revision: 'fixture',
})),
barCount: bars.length,
},
bars,
};
const trade: ClosedTrade = {
id: 'closed-1',
symbol: 'A.US',
side: 'Buy',
quantity: 1,
entry_price: 100,
exit_price: 90,
entry_time: new Date(start).toISOString(),
exit_time: new Date(start + day).toISOString(),
pnl: -10,
pnl_percent: -10,
commission: 0,
duration_ms: day,
};
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: unknown) => void;
const promise = new Promise<T>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
}
async function deadline<T>(work: Promise<T>): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
work,
new Promise<never>((_resolve, reject) => {
timer = setTimeout(() => reject(new Error('Control did not settle promptly')), 500);
}),
]);
} finally {
clearTimeout(timer);
}
}
const turn = () => new Promise<void>(resolve => setTimeout(resolve, 0));
describe('backtest playback isolation and controls', () => {
test('a cursor consumes frozen inputs in order, preserves timestamp ties and yields to timers', async () => {
const playback = new BacktestPlayback(start, null);
const events = Object.freeze(
Array.from({ length: 1001 }, (_, id) => ({ id, timestamp: start + Math.floor(id / 2) }))
);
const seen: number[] = [];
const updates: PlaybackProgress[] = [];
let timerRan = false;
setTimeout(() => {
timerRan = true;
}, 0);
await playback.process(
events,
event => event.timestamp,
async event => {
seen.push(event.id);
},
update => updates.push(update)
);
playback.finish();
expect(seen).toEqual(events.map(event => event.id));
expect(timerRan).toBe(true);
expect(events).toHaveLength(1001);
expect(updates.filter(update => update.progress === 100)).toHaveLength(1);
expect(updates.at(-1)).toMatchObject({
processed: 1001,
total: 1001,
remaining: 0,
progress: 100,
});
expect(playback.getStatus()).toMatchObject({
isRunning: false,
isPaused: false,
progress: 100,
});
});
test('pause blocks delivery and resume wakes it without a polling interval', async () => {
const playback = new BacktestPlayback(start, null);
playback.pause();
let processed = 0;
const work = playback.process(
[start],
time => time,
async () => {
processed++;
},
() => {}
);
await turn();
expect(processed).toBe(0);
playback.resume();
await deadline(work);
expect(processed).toBe(1);
playback.finish();
playback.pause();
expect(playback.getStatus().isPaused).toBe(false);
});
test('stop wakes a paused run and never emits completed progress', async () => {
const playback = new BacktestPlayback(start, null);
playback.pause();
const updates: number[] = [];
const work = playback.process(
[start],
time => time,
async () => {
throw new Error('Must not execute');
},
update => updates.push(update.progress)
);
const outcome = work.catch(error => error);
await turn();
playback.stop();
expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError);
expect(updates).toEqual([]);
playback.finish();
});
test.each(['stop', 'setSpeed'] as const)('%s interrupts a long pacing timer', async control => {
const playback = new BacktestPlayback(start, 0.001);
let processed = 0;
const work = playback.process(
[start],
time => time,
async () => {
processed++;
},
() => {}
);
const outcome = work.catch(error => error);
await turn();
if (control === 'stop') playback.stop();
else playback.setSpeed(null);
const settled = await deadline(outcome);
if (control === 'stop') expect(settled).toBeInstanceOf(BacktestCancelledError);
expect(processed).toBe(control === 'stop' ? 0 : 1);
playback.finish();
});
test('cancellation detaches a slow read and a late rejection cannot resume execution', async () => {
const playback = new BacktestPlayback(start, null);
const load = deferred<number>();
const entered = deferred<void>();
const work = playback.read(() => {
entered.resolve();
return load.promise;
});
const outcome = work.catch(error => error);
await entered.promise;
playback.stop();
expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError);
load.reject(new Error('Late read failure'));
await turn();
let calls = 0;
await expect(
playback.read(async () => {
calls++;
return 1;
})
).rejects.toBeInstanceOf(BacktestCancelledError);
expect(calls).toBe(0);
playback.finish();
});
test('failed delivery cannot advance its cursor or claim completion', async () => {
const playback = new BacktestPlayback(start, null);
const updates: number[] = [];
await expect(
playback.process(
[1, 2],
time => time,
async time => {
if (time === 2) throw new Error('delivery failure');
},
update => updates.push(update.progress)
)
).rejects.toThrow('delivery failure');
expect(playback.getStatus().progress).toBe(50);
expect(updates).not.toContain(100);
playback.finish();
});
test('speed validation rejects non-finite, zero and negative values', () => {
for (const speed of [NaN, Infinity, 0, -1]) {
expect(() => new BacktestPlayback(start, speed)).toThrow('positive or null');
expect(() => new BacktestPlayback(start, null).setSpeed(speed)).toThrow('positive or null');
}
});
test('one playback cannot run two cursors or continue after finalization', async () => {
const playback = new BacktestPlayback(start, null);
await playback.process(
[start],
time => time,
async () => {},
() => {}
);
await expect(
playback.process(
[start],
time => time,
async () => {},
() => {}
)
).rejects.toThrow('already started');
playback.finish();
await expect(playback.read(async () => 1)).rejects.toBeInstanceOf(BacktestCancelledError);
});
});
describe('detached, repeatable backtest reporting', () => {
test('analysis runs once per completion and formatting never re-analyzes retained inputs', () => {
const analyze = spyOn(PerformanceAnalyzer.prototype, 'analyze');
try {
const report = new BacktestReport(config, 'cached');
report.record(start + day, 990);
report.complete(dataset, [trade], [], {});
report.export('html');
report.export('csv');
report.export('json');
expect(analyze).toHaveBeenCalledTimes(1);
} finally {
analyze.mockRestore();
}
});
test('exports retain completed equity and do not append the same trades repeatedly', () => {
const report = new BacktestReport(config, 'report');
report.record(start, 1000);
report.record(start + day, 990);
const trades = structuredClone([trade]);
const result = report.complete(dataset, trades, [], { totalIssues: 0 });
expect(result.metrics.totalTrades).toBe(1);
expect(result.config).toMatchObject({ commission: 0.001, slippage: 0.0001 });
const first = report.export();
const parsed = JSON.parse(first);
expect(parsed.summary.totalTrades).toBe(1);
expect(parsed.equityCurve.at(-1).value).toBe(990);
trades[0]!.pnl = 10000;
result.equity[0]!.value = 1;
report.export('csv');
report.export('html');
expect(report.export()).toBe(first);
expect(() => report.complete(dataset, [], [], {})).toThrow('already finalized');
expect(() => report.record(start + day * 2, 0)).toThrow('already finalized');
});
test('zero and negative equity remain losses, never a fabricated starting balance', () => {
const report = new BacktestReport(config, 'loss');
report.record(start + day, 0);
report.record(start + day * 2, -100);
const result = report.complete(dataset, [], [], {});
expect(result.equity.map(point => point.value)).toEqual([1000, 0, -100]);
expect(result.metrics.totalReturn).toBeCloseTo(-110);
expect(result.metrics.maxDrawdown).toBe(1.1);
expect(result.analytics.drawdownSeries.at(-1)?.value).toBeCloseTo(-110);
expect(Object.values(result.analytics.riskMetrics).every(Number.isFinite)).toBe(true);
expect(result.analytics.dailyReturns.every(Number.isFinite)).toBe(true);
});
test('a one-timestamp run has finite analytics, stable timestamp ties and grouped OHLC', () => {
const report = new BacktestReport(config, 'single');
report.record(start, 999);
report.record(start, 998);
const result = report.complete(dataset, [], [], {});
expect(result.equity).toEqual([{ date: new Date(start).toISOString(), value: 998 }]);
expect(result.metrics.totalReturn).toBeCloseTo(-0.2);
expect(result.metrics.maxDrawdown).toBeCloseTo(0.002);
expect(result.analytics.dailyReturns).toEqual([]);
expect(Object.values(result.analytics.riskMetrics).every(Number.isFinite)).toBe(true);
expect(Object.keys(result.ohlcData)).toEqual(config.symbols);
expect(result.ohlcData['A.US']?.map(bar => bar.timestamp)).toEqual([
start,
start + day,
start + day * 2,
]);
expect(result.ohlcData['B.US']).toHaveLength(3);
});
test('ongoing drawdown duration uses the simulated horizon, not the wall clock', () => {
const report = new BacktestReport(config, 'drawdown');
report.record(start + day, 900);
report.record(start + day * 4, 800);
report.complete(dataset, [], [], {});
expect(JSON.parse(report.export()).summary.maxDrawdownDuration).toBe(3);
expect(report.export('html')).toContain('20.00%');
expect(JSON.parse(report.export()).performanceReport).toContain('Max Drawdown: 20.00%');
});
test('monthly grouping uses UTC, and invalid or unordered observations fail explicitly', () => {
const report = new BacktestReport(config, 'utc');
report.record(Date.parse('2024-01-31T23:30:00Z'), 1100);
report.record(Date.parse('2024-02-01T00:30:00Z'), 1200);
const result = report.complete(dataset, [], [], {});
expect(Object.keys(result.analytics.monthlyReturns)).toEqual(['2024-01', '2024-02']);
expect(result.analytics.monthlyReturns['2024-01']).toBeCloseTo(10);
expect(result.analytics.monthlyReturns['2024-02']).toBeCloseTo((100 / 1100) * 100);
const invalid = new BacktestReport(config, 'invalid');
expect(() => invalid.export()).toThrow('No completed');
expect(() => invalid.record(start - 1, 1000)).toThrow('Out-of-order');
expect(() => invalid.record(start, NaN)).toThrow('Invalid');
expect(() => invalid.record(Infinity, 1000)).toThrow('Invalid');
const insolvent = new BacktestReport(config, 'insolvent');
insolvent.record(start + day, 0);
insolvent.record(Date.parse('2024-02-01T00:30:00Z'), -10);
const losses = insolvent.complete(dataset, [], [], {});
expect(losses.analytics.monthlyReturns).toEqual({ '2024-01': -100 });
});
test('quality inspection groups symbols once without changing frozen inputs or retaining old warnings', () => {
const input = structuredClone(dataset);
for (const bar of input.bars.filter(bar => bar.timestamp === start + day)) {
bar.close = bar.symbol === 'A.US' ? 150 : 50;
bar.open = bar.close;
bar.high = bar.close + 1;
bar.low = bar.close - 1;
bar.vwap = bar.close;
}
const before = structuredClone(input);
const inspector = new DataManager({
async getHistoricalBars() {
return [];
},
});
inspector.inspectDataset(input);
const quality = inspector.getDataQualityReport();
expect(quality.totalIssues).toBe(4);
expect(quality.bySymbol).toEqual({ 'A.US': 2, 'B.US': 2 });
expect(quality.issues.map(issue => issue.symbol)).toEqual(['A.US', 'A.US', 'B.US', 'B.US']);
expect(input).toEqual(before);
inspector.inspectDataset(dataset);
expect(inspector.getDataQualityReport().totalIssues).toBe(0);
});
test('HTML escapes text and CSV quotes cells while preserving numeric losses', () => {
const report = new BacktestReport(config, 'escaping');
report.record(start + day, 990);
report.complete(dataset, [{ ...trade, symbol: '<script>"bad",\nvalue</script>' }], [], {});
expect(report.export('html')).not.toContain('<script>');
expect(report.export('html')).toContain('&lt;script&gt;');
expect(report.export('csv')).toContain('"<script>""bad"",\nvalue</script>"');
expect(report.export('csv')).toContain(',-10,-10');
const snapshot = JSON.parse(report.export());
snapshot.trades[0].symbol = '=HYPERLINK("hostile")';
expect(formatReport(snapshot, 'csv')).toContain('"\'=HYPERLINK(""hostile"")"');
});
});

View file

@ -142,6 +142,30 @@ async function fixture(
return { postgres, mongodb, storage, engine, repository, runner, services, routes };
}
async function typescriptRuntime(f: Awaited<ReturnType<typeof fixture>>) {
const di = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
enableQueue: false,
enableMongoDB: false,
enablePostgres: false,
enableQuestDB: false,
enableBrowser: false,
enableProxy: false,
})
.build();
const services: OrchestratorServices = {
logger,
postgres: f.postgres,
mongodb: f.mongodb,
custom: {},
};
di.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(di, { initializeMode: false, useRustEngine: false });
expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner);
return services;
}
describe('one backtest execution workflow', () => {
test('V2 rejects ambiguous listing IDs and incompatible timestamp policies before accepting work', async () => {
const f = await fixture();
@ -228,26 +252,7 @@ describe('one backtest execution workflow', () => {
test('the TypeScript backend uses the same runner, data policy, and persisted contract', async () => {
const f = await fixture();
const di = await new ServiceContainerBuilder()
.withOptions({
enableCache: false,
enableQueue: false,
enableMongoDB: false,
enablePostgres: false,
enableQuestDB: false,
enableBrowser: false,
enableProxy: false,
})
.build();
const services: OrchestratorServices = {
logger,
postgres: f.postgres,
mongodb: f.mongodb,
custom: {},
};
di.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(di, { initializeMode: false, useRustEngine: false });
expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner);
const services = await typescriptRuntime(f);
try {
const result = await services.custom!.BacktestRunner!.runBacktest(config);
expect(result.engine).toBe('typescript');
@ -271,6 +276,55 @@ describe('one backtest execution workflow', () => {
}
});
test('TypeScript cancellation is persisted without a partial success or completion event', async () => {
const f = await fixture();
const services = await typescriptRuntime(f);
const runner = services.custom!.BacktestRunner!;
cleanup.unshift(async () => {
await runner.shutdown();
await services.custom?.ModeManager?.shutdown();
});
let stopped: Promise<void> | undefined;
let controlError: unknown;
let completed = 0;
runner.on('complete', () => {
completed++;
});
const manager = services.custom!.StrategyManager!;
const deliver = manager.onMarketData.bind(manager);
manager.onMarketData = async data => {
await deliver(data);
stopped = runner.stopBacktest(runner.getStatus().runId).catch(error => {
controlError = error;
});
};
const outcome = await runner.runBacktest(config).catch(error => error);
expect(stopped).toBeDefined();
await stopped;
expect(controlError).toBeUndefined();
expect(outcome).toBeInstanceOf(BacktestCancelledError);
expect(completed).toBe(0);
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('cancelled');
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
expect(services.custom?.BacktestEngine?.getStatus().isRunning).toBe(false);
});
test('TypeScript ledger failures are persisted as failures, never fabricated equity or results', async () => {
const f = await fixture();
const services = await typescriptRuntime(f);
const runner = services.custom!.BacktestRunner!;
cleanup.unshift(async () => {
await runner.shutdown();
await services.custom?.ModeManager?.shutdown();
});
services.custom!.ExecutionService!.getAccount = async () => {
throw new Error('Ledger unavailable');
};
await expect(runner.runBacktest(config)).rejects.toThrow('Ledger unavailable');
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('failed');
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0);
});
test('V2 dispatch forwards strategy parameters and reads the runner-owned saved result', async () => {
const f = await fixture();
const api = new BacktestServiceV2(f.services, async () => {

View file

@ -0,0 +1,189 @@
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<void>)[] = [];
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<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');
});
});