refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
parent
ce9e2df67c
commit
4cd6038063
432 changed files with 1247 additions and 44469 deletions
|
|
@ -1,181 +0,0 @@
|
|||
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 { LegacyBacktestExecutionEngine } 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 LegacyBacktestExecutionEngine {
|
||||
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,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,128 +0,0 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,181 +0,0 @@
|
|||
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<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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,230 +0,0 @@
|
|||
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 analysis = defined(this.performanceAnalyzer).getAnalysis();
|
||||
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,
|
||||
profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100),
|
||||
avgWin: performance.avgWin || 0,
|
||||
avgLoss: performance.avgLoss || 0,
|
||||
expectancy: performance.expectancy || 0,
|
||||
calmarRatio: performance.calmarRatio,
|
||||
sortinoRatio: performance.sortinoRatio,
|
||||
annualizedReturn: performance.annualizedReturn,
|
||||
cagr: performance.cagr,
|
||||
},
|
||||
|
||||
// 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: analysis.equity.underwater.map(point => ({
|
||||
...point,
|
||||
value: point.value * 100,
|
||||
})),
|
||||
dailyReturns: analysis.equity.dailyReturns.map(value => value * 100),
|
||||
monthlyReturns: Object.fromEntries(
|
||||
Object.entries(analysis.equity.monthlyReturns).map(([month, value]) => [
|
||||
month,
|
||||
value * 100,
|
||||
])
|
||||
),
|
||||
exposureTime: this.calculateExposureTime(closedTrades),
|
||||
riskMetrics: {
|
||||
volatility: analysis.risk.volatility,
|
||||
downsideDeviation: analysis.risk.downsideDeviation,
|
||||
var95: analysis.risk.var95,
|
||||
var99: analysis.risk.var99,
|
||||
cvar95: analysis.risk.cvar95,
|
||||
maxConsecutiveLosses: analysis.trade.maxConsecutiveLosses,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
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 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 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,423 +0,0 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import {
|
||||
type Bar,
|
||||
type MarketData,
|
||||
type OrderBookSnapshot,
|
||||
type PriceLevel,
|
||||
type Quote,
|
||||
type Trade,
|
||||
} from '../types';
|
||||
import { type MarketMicrostructure } from '../types/MarketMicrostructure';
|
||||
|
||||
const _logger = getLogger('MarketSimulator');
|
||||
|
||||
export interface SimulationConfig {
|
||||
useHistoricalSpreads: boolean;
|
||||
modelHiddenLiquidity: boolean;
|
||||
includeDarkPools: boolean;
|
||||
latencyMs: number;
|
||||
rebateRate: number;
|
||||
takeFeeRate: number;
|
||||
}
|
||||
|
||||
export interface LiquidityProfile {
|
||||
visibleLiquidity: number;
|
||||
hiddenLiquidity: number;
|
||||
darkPoolLiquidity: number;
|
||||
totalLiquidity: number;
|
||||
}
|
||||
|
||||
export class MarketSimulator {
|
||||
private orderBooks: Map<string, OrderBookSnapshot> = new Map();
|
||||
private microstructures: Map<string, MarketMicrostructure> = new Map();
|
||||
private liquidityProfiles: Map<string, LiquidityProfile> = new Map();
|
||||
private lastTrades: Map<string, Trade> = new Map();
|
||||
private config: SimulationConfig;
|
||||
private randomState = 1;
|
||||
|
||||
resetWithSeed(seed: number): void {
|
||||
this.randomState = seed >>> 0;
|
||||
this.orderBooks.clear();
|
||||
this.microstructures.clear();
|
||||
this.liquidityProfiles.clear();
|
||||
this.lastTrades.clear();
|
||||
}
|
||||
|
||||
private random(): number {
|
||||
this.randomState = (Math.imul(this.randomState, 1664525) + 1013904223) >>> 0;
|
||||
return this.randomState / 4294967296;
|
||||
}
|
||||
|
||||
constructor(config: Partial<SimulationConfig> = {}) {
|
||||
this.config = {
|
||||
useHistoricalSpreads: true,
|
||||
modelHiddenLiquidity: true,
|
||||
includeDarkPools: true,
|
||||
latencyMs: 1,
|
||||
rebateRate: -0.0002, // 2 bps rebate for providing liquidity
|
||||
takeFeeRate: 0.0003, // 3 bps fee for taking liquidity
|
||||
...config,
|
||||
};
|
||||
}
|
||||
|
||||
setMicrostructure(symbol: string, microstructure: MarketMicrostructure): void {
|
||||
this.microstructures.set(symbol, microstructure);
|
||||
this.updateLiquidityProfile(symbol);
|
||||
}
|
||||
|
||||
processMarketData(data: MarketData): OrderBookSnapshot | null {
|
||||
const { symbol } = this.getSymbolFromData(data);
|
||||
|
||||
switch (data.type) {
|
||||
case 'quote':
|
||||
return this.updateFromQuote(symbol, data.data);
|
||||
case 'trade':
|
||||
return this.updateFromTrade(symbol, data.data);
|
||||
case 'bar':
|
||||
return this.reconstructFromBar(symbol, data.data);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private updateFromQuote(symbol: string, quote: Quote): OrderBookSnapshot {
|
||||
let orderbook = this.orderBooks.get(symbol);
|
||||
const microstructure = this.microstructures.get(symbol);
|
||||
|
||||
if (!orderbook || !microstructure) {
|
||||
// Create new orderbook
|
||||
orderbook = this.createOrderBook(symbol, quote, microstructure);
|
||||
} else {
|
||||
// Update existing orderbook
|
||||
orderbook = this.updateOrderBook(orderbook, quote, microstructure);
|
||||
}
|
||||
|
||||
this.orderBooks.set(symbol, orderbook);
|
||||
return orderbook;
|
||||
}
|
||||
|
||||
private updateFromTrade(symbol: string, trade: Trade): OrderBookSnapshot | null {
|
||||
const orderbook = this.orderBooks.get(symbol);
|
||||
if (!orderbook) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Update last trade
|
||||
this.lastTrades.set(symbol, trade);
|
||||
|
||||
// Adjust orderbook based on trade
|
||||
// Large trades likely consumed liquidity
|
||||
const impactFactor = Math.min(trade.size / 1000, 0.1); // Max 10% impact
|
||||
|
||||
if (trade.side === 'buy') {
|
||||
// Buy trade consumed ask liquidity
|
||||
orderbook.asks = orderbook.asks.map((level, i) => ({
|
||||
...level,
|
||||
size: level.size * (1 - impactFactor * Math.exp(-i * 0.5)),
|
||||
}));
|
||||
} else {
|
||||
// Sell trade consumed bid liquidity
|
||||
orderbook.bids = orderbook.bids.map((level, i) => ({
|
||||
...level,
|
||||
size: level.size * (1 - impactFactor * Math.exp(-i * 0.5)),
|
||||
}));
|
||||
}
|
||||
|
||||
return orderbook;
|
||||
}
|
||||
|
||||
private reconstructFromBar(symbol: string, bar: Bar): OrderBookSnapshot {
|
||||
const microstructure =
|
||||
this.microstructures.get(symbol) || this.createDefaultMicrostructure(symbol);
|
||||
|
||||
// Estimate spread from high-low range
|
||||
const hlSpread = (bar.high - bar.low) / bar.close;
|
||||
const estimatedSpreadBps = Math.max(
|
||||
microstructure.avgSpreadBps,
|
||||
hlSpread * 10000 * 0.1 // 10% of HL range as spread estimate
|
||||
);
|
||||
|
||||
// Create synthetic quote
|
||||
const midPrice = bar.vwap || (bar.high + bar.low + bar.close) / 3;
|
||||
const halfSpread = (midPrice * estimatedSpreadBps) / 20000;
|
||||
|
||||
const quote: Quote = {
|
||||
symbol,
|
||||
timestamp: bar.timestamp,
|
||||
bid: midPrice - halfSpread,
|
||||
ask: midPrice + halfSpread,
|
||||
bidSize: bar.volume / 100, // Rough estimate
|
||||
askSize: bar.volume / 100,
|
||||
};
|
||||
|
||||
return this.createOrderBook(symbol, quote, microstructure);
|
||||
}
|
||||
|
||||
private createOrderBook(
|
||||
symbol: string,
|
||||
topQuote: Quote,
|
||||
microstructure?: MarketMicrostructure
|
||||
): OrderBookSnapshot {
|
||||
const micro = microstructure || this.createDefaultMicrostructure(symbol);
|
||||
const levels = 10;
|
||||
|
||||
const bids: PriceLevel[] = [];
|
||||
const asks: PriceLevel[] = [];
|
||||
|
||||
// Model order book depth
|
||||
for (let i = 0; i < levels; i++) {
|
||||
const depthFactor = Math.exp(-i * 0.3); // Exponential decay
|
||||
const _spreadMultiplier = 1 + i * 0.1; // Wider spread at deeper levels
|
||||
|
||||
// Hidden liquidity modeling
|
||||
const hiddenRatio = this.config.modelHiddenLiquidity
|
||||
? 1 + this.random() * 2 // 1-3x visible size hidden
|
||||
: 1;
|
||||
|
||||
// Bid levels
|
||||
const bidPrice = topQuote.bid - i * micro.tickSize;
|
||||
const bidSize = topQuote.bidSize * depthFactor * (0.8 + this.random() * 0.4);
|
||||
bids.push({
|
||||
price: bidPrice,
|
||||
size: Math.round(bidSize / micro.lotSize) * micro.lotSize,
|
||||
orderCount: Math.max(1, Math.floor(bidSize / 100)),
|
||||
hiddenSize: this.config.modelHiddenLiquidity ? bidSize * (hiddenRatio - 1) : undefined,
|
||||
});
|
||||
|
||||
// Ask levels
|
||||
const askPrice = topQuote.ask + i * micro.tickSize;
|
||||
const askSize = topQuote.askSize * depthFactor * (0.8 + this.random() * 0.4);
|
||||
asks.push({
|
||||
price: askPrice,
|
||||
size: Math.round(askSize / micro.lotSize) * micro.lotSize,
|
||||
orderCount: Math.max(1, Math.floor(askSize / 100)),
|
||||
hiddenSize: this.config.modelHiddenLiquidity ? askSize * (hiddenRatio - 1) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
symbol,
|
||||
timestamp: new Date(),
|
||||
bids,
|
||||
asks,
|
||||
lastTrade: this.lastTrades.get(symbol),
|
||||
};
|
||||
}
|
||||
|
||||
private updateOrderBook(
|
||||
current: OrderBookSnapshot,
|
||||
quote: Quote,
|
||||
microstructure?: MarketMicrostructure
|
||||
): OrderBookSnapshot {
|
||||
const _micro = microstructure || this.createDefaultMicrostructure(current.symbol);
|
||||
|
||||
// Update top of book
|
||||
if (current.bids.length > 0) {
|
||||
at(current.bids, 0).price = quote.bid;
|
||||
at(current.bids, 0).size = quote.bidSize;
|
||||
}
|
||||
|
||||
if (current.asks.length > 0) {
|
||||
at(current.asks, 0).price = quote.ask;
|
||||
at(current.asks, 0).size = quote.askSize;
|
||||
}
|
||||
|
||||
// Adjust deeper levels based on spread changes
|
||||
const oldSpread = at(current.asks, 0).price - at(current.bids, 0).price;
|
||||
const newSpread = quote.ask - quote.bid;
|
||||
const spreadRatio = newSpread / oldSpread;
|
||||
|
||||
// Update deeper levels
|
||||
for (let i = 1; i < current.bids.length; i++) {
|
||||
// Adjust sizes based on top of book changes
|
||||
const sizeRatio = quote.bidSize / (at(current.bids, 0).size || quote.bidSize);
|
||||
at(current.bids, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
|
||||
|
||||
// Adjust prices to maintain relative spacing
|
||||
const spacing = (at(current.bids, i - 1).price - at(current.bids, i).price) * spreadRatio;
|
||||
at(current.bids, i).price = at(current.bids, i - 1).price - spacing;
|
||||
}
|
||||
|
||||
for (let i = 1; i < current.asks.length; i++) {
|
||||
const sizeRatio = quote.askSize / (at(current.asks, 0).size || quote.askSize);
|
||||
at(current.asks, i).size *= sizeRatio * (0.9 + this.random() * 0.2);
|
||||
|
||||
const spacing = (at(current.asks, i).price - at(current.asks, i - 1).price) * spreadRatio;
|
||||
at(current.asks, i).price = at(current.asks, i - 1).price + spacing;
|
||||
}
|
||||
|
||||
return current;
|
||||
}
|
||||
|
||||
simulateMarketImpact(
|
||||
symbol: string,
|
||||
side: 'buy' | 'sell',
|
||||
orderSize: number,
|
||||
orderType: 'market' | 'limit',
|
||||
limitPrice?: number
|
||||
): {
|
||||
fills: Array<{ price: number; size: number; venue: string }>;
|
||||
totalCost: number;
|
||||
avgPrice: number;
|
||||
marketImpact: number;
|
||||
fees: number;
|
||||
} {
|
||||
const orderbook = this.orderBooks.get(symbol);
|
||||
const microstructure = this.microstructures.get(symbol);
|
||||
const liquidityProfile = this.liquidityProfiles.get(symbol);
|
||||
|
||||
if (!orderbook) {
|
||||
throw new Error(`No orderbook available for ${symbol}`);
|
||||
}
|
||||
|
||||
const fills: Array<{ price: number; size: number; venue: string }> = [];
|
||||
let remainingSize = orderSize;
|
||||
let totalCost = 0;
|
||||
let fees = 0;
|
||||
|
||||
// Get relevant price levels
|
||||
const levels = side === 'buy' ? orderbook.asks : orderbook.bids;
|
||||
const multiplier = side === 'buy' ? 1 : -1;
|
||||
|
||||
// Simulate walking the book
|
||||
for (const level of levels) {
|
||||
if (remainingSize <= 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Check limit price constraint
|
||||
if (limitPrice !== undefined) {
|
||||
if (side === 'buy' && level.price > limitPrice) {
|
||||
break;
|
||||
}
|
||||
if (side === 'sell' && level.price < limitPrice) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate available liquidity including hidden
|
||||
let availableSize = level.size;
|
||||
if (level.hiddenSize && this.config.modelHiddenLiquidity) {
|
||||
availableSize += level.hiddenSize * this.random(); // Seeded hidden liquidity
|
||||
}
|
||||
|
||||
const fillSize = Math.min(remainingSize, availableSize);
|
||||
|
||||
// Simulate latency - price might move
|
||||
if (this.config.latencyMs > 0 && orderType === 'market') {
|
||||
const priceMovement = microstructure
|
||||
? (((this.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price
|
||||
: 0;
|
||||
level.price += priceMovement * multiplier;
|
||||
}
|
||||
|
||||
fills.push({
|
||||
price: level.price,
|
||||
size: fillSize,
|
||||
venue: 'primary',
|
||||
});
|
||||
|
||||
totalCost += fillSize * level.price;
|
||||
remainingSize -= fillSize;
|
||||
|
||||
// Calculate fees
|
||||
if (orderType === 'market') {
|
||||
fees += fillSize * level.price * this.config.takeFeeRate;
|
||||
} else {
|
||||
// Limit orders that provide liquidity get rebate
|
||||
fees += fillSize * level.price * this.config.rebateRate;
|
||||
}
|
||||
}
|
||||
|
||||
// Dark pool execution for remaining size
|
||||
if (remainingSize > 0 && this.config.includeDarkPools && liquidityProfile) {
|
||||
const darkPoolPct = liquidityProfile.darkPoolLiquidity / liquidityProfile.totalLiquidity;
|
||||
const darkPoolSize = remainingSize * darkPoolPct * this.random();
|
||||
|
||||
if (darkPoolSize > 0) {
|
||||
const midPrice = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2;
|
||||
fills.push({
|
||||
price: midPrice,
|
||||
size: darkPoolSize,
|
||||
venue: 'dark',
|
||||
});
|
||||
|
||||
totalCost += darkPoolSize * midPrice;
|
||||
remainingSize -= darkPoolSize;
|
||||
// Dark pools typically have lower fees
|
||||
fees += darkPoolSize * midPrice * 0.0001;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate results
|
||||
const filledSize = orderSize - remainingSize;
|
||||
const avgPrice = filledSize > 0 ? totalCost / filledSize : 0;
|
||||
|
||||
// Calculate market impact
|
||||
const initialMid = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2;
|
||||
const marketImpact =
|
||||
filledSize > 0
|
||||
? (Math.abs(avgPrice - initialMid) / initialMid) * 10000 // in bps
|
||||
: 0;
|
||||
|
||||
return {
|
||||
fills,
|
||||
totalCost,
|
||||
avgPrice,
|
||||
marketImpact,
|
||||
fees,
|
||||
};
|
||||
}
|
||||
|
||||
private updateLiquidityProfile(symbol: string): void {
|
||||
const microstructure = this.microstructures.get(symbol);
|
||||
if (!microstructure) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Estimate liquidity distribution
|
||||
const visiblePct = 0.3; // 30% visible
|
||||
const hiddenPct = 0.5; // 50% hidden
|
||||
const darkPct = 0.2; // 20% dark
|
||||
|
||||
const totalDailyLiquidity = microstructure.dailyVolume;
|
||||
|
||||
this.liquidityProfiles.set(symbol, {
|
||||
visibleLiquidity: totalDailyLiquidity * visiblePct,
|
||||
hiddenLiquidity: totalDailyLiquidity * hiddenPct,
|
||||
darkPoolLiquidity: totalDailyLiquidity * darkPct,
|
||||
totalLiquidity: totalDailyLiquidity,
|
||||
});
|
||||
}
|
||||
|
||||
private createDefaultMicrostructure(symbol: string): MarketMicrostructure {
|
||||
return {
|
||||
symbol,
|
||||
avgSpreadBps: 5,
|
||||
dailyVolume: 1000000,
|
||||
avgTradeSize: 100,
|
||||
volatility: 0.02,
|
||||
tickSize: 0.01,
|
||||
lotSize: 1,
|
||||
intradayVolumeProfile: new Array(24).fill(1 / 24),
|
||||
};
|
||||
}
|
||||
|
||||
private getSymbolFromData(data: MarketData): { symbol: string } {
|
||||
return { symbol: data.data.symbol };
|
||||
}
|
||||
|
||||
getOrderBook(symbol: string): OrderBookSnapshot | undefined {
|
||||
return this.orderBooks.get(symbol);
|
||||
}
|
||||
|
||||
getLiquidityProfile(symbol: string): LiquidityProfile | undefined {
|
||||
return this.liquidityProfiles.get(symbol);
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.orderBooks.clear();
|
||||
this.lastTrades.clear();
|
||||
}
|
||||
}
|
||||
|
|
@ -9,13 +9,13 @@ import {
|
|||
replayConfigSchema,
|
||||
replayIdentitySchema,
|
||||
replayResultFormatSchema,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import {
|
||||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
} from '../contracts/strategy-replay';
|
||||
import { removeCandidateContainer } from './candidate-sandbox';
|
||||
import { canonicalWorkerUrl } from './canonical-build';
|
||||
import { canonicalWorkerUrl } from '@stock-bot/trading-runtime/canonical-build';
|
||||
import {
|
||||
nativeWorkerMessageSchema,
|
||||
nativeWorkerRequestSchema,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/** This entrypoint runs ONLY inside the restricted image; never the API/native supervisor. */
|
||||
import { sameIdentity } from '../contracts/native-replay';
|
||||
import { sameIdentity } from '@stock-bot/stock-config/canonical-replay';
|
||||
import { importRetainedProgram } from '../strategies/retained-program';
|
||||
import { StrategyController } from '../strategies/strategy-controller';
|
||||
import { freeze } from '../strategies/strategy-decision';
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
retainedProgramSelectionSchema,
|
||||
} from '@stock-bot/stock-config/candidate-execution';
|
||||
import { parseFinancialStrategyDecision } from '@stock-bot/types';
|
||||
import { replayIdentitySchema, stepSchema, submissionSchema } from '../contracts/native-replay';
|
||||
import { replayIdentitySchema, stepSchema, submissionSchema } from '@stock-bot/stock-config/canonical-replay';
|
||||
|
||||
const base = {
|
||||
version: z.literal(1),
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import {
|
|||
verifyCandidateExecution,
|
||||
} from '@stock-bot/trading-runtime/candidate-environment';
|
||||
import { parseFinancialStrategyDecision } from '@stock-bot/types';
|
||||
import type { ReplaySubmissionOutcome } from '../contracts/native-replay';
|
||||
import type { ReplaySubmissionOutcome } from '@stock-bot/stock-config/canonical-replay';
|
||||
import {
|
||||
candidateResponseSchema,
|
||||
readCandidateFrames,
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
/** Shared read-only artifact inspection. */
|
||||
export * from '@stock-bot/trading-runtime/canonical-build';
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
/** Compatibility entrypoint for the shared, purely statistical report builder. */
|
||||
export * from '@stock-bot/research/results';
|
||||
|
|
@ -4,10 +4,6 @@ import type {
|
|||
CanonicalRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { HistoricalDatasetV2 } from '@stock-bot/types';
|
||||
import type { DatasetResolver } from '../data/historical-dataset';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import type { NativeBacktestResult } from './native-result';
|
||||
import type { BacktestResult } from './typescript-result';
|
||||
|
||||
/** Capabilities required by the canonical durable runner. No provider loading or playback. */
|
||||
export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'> {
|
||||
|
|
@ -26,18 +22,6 @@ export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'
|
|||
shutdown(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Retained algorithm/playback examples only; cannot satisfy the durable runner contract. */
|
||||
export interface LegacyBacktestExecutionEngine
|
||||
extends Pick<BacktestExecutionEngine, 'on' | 'off' | 'stopBacktest' | 'getStatus' | 'shutdown'> {
|
||||
runBacktest(
|
||||
config: BacktestConfig,
|
||||
dataset?: DatasetResolver
|
||||
): Promise<BacktestResult | NativeBacktestResult>;
|
||||
pauseBacktest(): Promise<void>;
|
||||
resumeBacktest(): Promise<void>;
|
||||
setSpeedMultiplier(speed: number | null): void;
|
||||
}
|
||||
|
||||
/** Cancellation has no result when a native worker is forcibly stopped. */
|
||||
export class BacktestCancelledError extends Error {
|
||||
constructor() {
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ import {
|
|||
type ReplayStep,
|
||||
type ReplaySubmissionOutcome,
|
||||
type ReplayTraceRequest,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import { validateDatasetV2 } from '../data/historical-dataset-v2';
|
||||
|
||||
export type {
|
||||
|
|
@ -47,7 +47,7 @@ export type {
|
|||
DecisionContext,
|
||||
PublishedObservation,
|
||||
ReplayTraceRequest,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
|
||||
/** Expand Number's exact shortest lexical representation, never round toFixed.
|
||||
* D01 already owns numeric data precision; >8 decimals cannot enter the ledger. */
|
||||
|
|
|
|||
|
|
@ -1,12 +0,0 @@
|
|||
import type { BacktestConfig } from '../types';
|
||||
import { backtestStrategies } from './strategy-plan';
|
||||
|
||||
/** Resolve and validate before fetching data, and validate again in the isolated worker. */
|
||||
export function resolveNativeStrategies(config: BacktestConfig) {
|
||||
return backtestStrategies(config, 'native').map(({ name, kind, parameters, index }) => {
|
||||
if (!kind) {
|
||||
throw new Error('Unknown native strategy: ' + name);
|
||||
}
|
||||
return { strategy: kind, name, id: 'backtest-strategy-' + index, parameters };
|
||||
});
|
||||
}
|
||||
|
|
@ -12,10 +12,10 @@ import {
|
|||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import type { CanonicalBacktestAnalytics } from '@stock-bot/types';
|
||||
import { replayTraceSchema } from '../contracts/native-replay';
|
||||
import type { ReplayReportResult } from '../contracts/native-replay';
|
||||
import { replayTraceSchema } from '@stock-bot/stock-config/canonical-replay';
|
||||
import type { ReplayReportResult } from '@stock-bot/stock-config/canonical-replay';
|
||||
import { strategyReplayRequestSchema } from '../contracts/strategy-replay';
|
||||
import { buildCanonicalBacktestReport } from './canonical-result';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
|
||||
const finite = z.number().finite();
|
||||
export const retainedStrategyRequestSchema = z
|
||||
|
|
|
|||
|
|
@ -8,8 +8,8 @@ import {
|
|||
verifyRetainedProgramPackage,
|
||||
} from '../strategies/retained-program';
|
||||
import { IsolatedCandidateController } from './candidate-sandbox';
|
||||
import { verifyCanonicalWorkerBuild } from './canonical-build';
|
||||
import { buildCanonicalBacktestReport } from './canonical-result';
|
||||
import { verifyCanonicalWorkerBuild } from '@stock-bot/trading-runtime/canonical-build';
|
||||
import { buildCanonicalBacktestReport } from '@stock-bot/research/results';
|
||||
import {
|
||||
executeReplayTrace,
|
||||
NativeReplaySession,
|
||||
|
|
|
|||
|
|
@ -1,121 +0,0 @@
|
|||
import { formatStatistic } from '@stock-bot/calculations/analytics';
|
||||
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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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: ${formatStatistic(result.summary.sharpeRatio)}</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>
|
||||
`;
|
||||
}
|
||||
|
|
@ -1,200 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
|
||||
import { datasetManifestSchema } from '../contracts/historical';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import type { NativeBacktestResult } from './native-result';
|
||||
import type { RunIdentity } from './run-repository';
|
||||
import type { BacktestResult as TypeScriptResult } from './typescript-result';
|
||||
|
||||
const finite = z.number().finite();
|
||||
const analyticsSchema = z.object({
|
||||
exposureTime: finite,
|
||||
drawdownSeries: z.array(z.object({ timestamp: finite, value: finite })).optional(),
|
||||
dailyReturns: z.array(finite).optional(),
|
||||
monthlyReturns: z.record(finite).optional(),
|
||||
riskMetrics: z.record(finite.nullable()).optional(),
|
||||
});
|
||||
/** Validate once before persistence and before publishing a terminal result. */
|
||||
export const backtestRunResultSchema: z.ZodType<BacktestRunResult> = z.object({
|
||||
runId: z.string().uuid(),
|
||||
backtestId: z.string().uuid(),
|
||||
engine: z.enum(['native', 'typescript']),
|
||||
status: z.enum(['completed', 'cancelled']),
|
||||
completedAt: z.string().datetime(),
|
||||
config: z.object({
|
||||
name: z.string(),
|
||||
strategy: z.string(),
|
||||
symbols: z.array(z.string()),
|
||||
startDate: z.string().datetime(),
|
||||
endDate: z.string().datetime(),
|
||||
initialCapital: finite,
|
||||
commission: finite,
|
||||
slippage: finite,
|
||||
dataFrequency: z.string(),
|
||||
parameters: z.record(z.unknown()),
|
||||
dataset: datasetManifestSchema.optional(),
|
||||
riskLimits: z
|
||||
.object({
|
||||
maxPositionSize: finite,
|
||||
maxOrderSize: finite,
|
||||
maxDailyLoss: finite,
|
||||
maxGrossExposure: finite,
|
||||
maxSymbolExposure: finite,
|
||||
})
|
||||
.optional(),
|
||||
strategies: z
|
||||
.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
enabled: z.boolean(),
|
||||
config: z.record(z.unknown()).optional(),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
}),
|
||||
metrics: z
|
||||
.object({
|
||||
totalReturn: finite,
|
||||
sharpeRatio: finite.nullable(),
|
||||
maxDrawdown: finite,
|
||||
winRate: finite,
|
||||
totalTrades: finite,
|
||||
profitFactor: finite.nullable(),
|
||||
avgWin: finite,
|
||||
avgLoss: finite,
|
||||
})
|
||||
.catchall(finite.nullable()),
|
||||
equity: z.array(z.object({ date: z.string(), value: finite })),
|
||||
ohlcData: z.record(
|
||||
z.array(
|
||||
z.object({
|
||||
timestamp: finite,
|
||||
open: finite,
|
||||
high: finite,
|
||||
low: finite,
|
||||
close: finite,
|
||||
volume: finite.optional(),
|
||||
})
|
||||
)
|
||||
),
|
||||
trades: z.array(
|
||||
z.object({
|
||||
kind: z.enum(['fill', 'closed']),
|
||||
id: z.string(),
|
||||
symbol: z.string(),
|
||||
timestamp: z.string(),
|
||||
side: z.enum(['buy', 'sell']),
|
||||
price: finite,
|
||||
quantity: finite,
|
||||
commission: finite,
|
||||
pnl: finite.optional(),
|
||||
positionAfter: finite.optional(),
|
||||
entryDate: z.string().optional(),
|
||||
exitDate: z.string().nullable().optional(),
|
||||
entryPrice: finite.optional(),
|
||||
exitPrice: finite.optional(),
|
||||
pnlPercent: finite.optional(),
|
||||
duration: finite.optional(),
|
||||
})
|
||||
),
|
||||
positions: z.array(
|
||||
z.object({
|
||||
symbol: z.string(),
|
||||
quantity: finite,
|
||||
averagePrice: finite,
|
||||
currentPrice: finite,
|
||||
unrealizedPnl: finite,
|
||||
realizedPnl: finite,
|
||||
})
|
||||
),
|
||||
analytics: analyticsSchema,
|
||||
executionTime: finite.nonnegative(),
|
||||
});
|
||||
|
||||
export function normalizeBacktestResult(
|
||||
raw: NativeBacktestResult | TypeScriptResult,
|
||||
engine: Exclude<BacktestRunResult['engine'], 'legacy'>,
|
||||
config: BacktestConfig,
|
||||
identity: RunIdentity,
|
||||
executionTime: number,
|
||||
cancelled: boolean,
|
||||
dataset?: HistoricalDatasetManifest
|
||||
): BacktestRunResult {
|
||||
if (raw.status !== 'completed' && raw.status !== 'cancelled') {
|
||||
throw new Error(
|
||||
'error' in raw && typeof raw.error === 'string'
|
||||
? raw.error
|
||||
: `Backtest engine returned ${raw.status}`
|
||||
);
|
||||
}
|
||||
const trades = raw.trades.map(trade =>
|
||||
'entryDate' in trade
|
||||
? {
|
||||
...trade,
|
||||
kind: 'closed',
|
||||
timestamp: trade.entryDate,
|
||||
price: trade.entryPrice,
|
||||
}
|
||||
: { ...trade, kind: 'fill' }
|
||||
);
|
||||
// Native serialization uses null for undefined ratios; do the same for TS infinities.
|
||||
const metrics = Object.fromEntries(
|
||||
Object.entries(raw.metrics).map(([key, value]) => [
|
||||
key,
|
||||
typeof value === 'number' && !Number.isFinite(value) ? null : value,
|
||||
])
|
||||
);
|
||||
// Public returns/win rates are fractions, not percentage points. Both backends
|
||||
// already report maxDrawdown as a fraction.
|
||||
metrics.totalReturn = raw.metrics.totalReturn / 100;
|
||||
metrics.winRate = raw.metrics.winRate / 100;
|
||||
if (engine === 'typescript') {
|
||||
metrics.totalTrades = raw.trades.length; // Completed round trips, not individual fills.
|
||||
metrics.profitableTrades = raw.trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
for (const key of ['annualReturn', 'annualizedReturn', 'cagr']) {
|
||||
if (typeof metrics[key] === 'number') {
|
||||
metrics[key] /= 100;
|
||||
}
|
||||
}
|
||||
const analytics = analyticsSchema.parse(raw.analytics);
|
||||
analytics.exposureTime /= 100;
|
||||
analytics.drawdownSeries = analytics.drawdownSeries?.map(point => ({
|
||||
...point,
|
||||
value: point.value / 100,
|
||||
}));
|
||||
analytics.dailyReturns = analytics.dailyReturns?.map(value =>
|
||||
engine === 'typescript' ? value / 100 : value
|
||||
);
|
||||
if (analytics.monthlyReturns) {
|
||||
analytics.monthlyReturns = Object.fromEntries(
|
||||
Object.entries(analytics.monthlyReturns).map(([month, value]) => [month, value / 100])
|
||||
);
|
||||
}
|
||||
return backtestRunResultSchema.parse({
|
||||
...raw,
|
||||
...identity,
|
||||
engine,
|
||||
completedAt: new Date(raw.completedAt).toISOString(),
|
||||
status: cancelled ? 'cancelled' : raw.status,
|
||||
executionTime,
|
||||
config: {
|
||||
name: config.name ?? 'Backtest',
|
||||
strategy: config.strategy,
|
||||
symbols: config.symbols,
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: config.initialCapital,
|
||||
commission: config.commission ?? 0.001,
|
||||
slippage: config.slippage ?? 0.0001,
|
||||
dataFrequency: config.dataFrequency,
|
||||
parameters: config.config ?? {},
|
||||
dataset,
|
||||
riskLimits: config.riskLimits,
|
||||
strategies: config.strategies,
|
||||
},
|
||||
metrics,
|
||||
trades,
|
||||
analytics,
|
||||
});
|
||||
}
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
import { normalizeBacktestStrategyConfig } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
nativeParameters,
|
||||
typescriptMeanReversionParameters,
|
||||
typescriptSmaParameters,
|
||||
} from '../contracts/strategies';
|
||||
import { builtinStrategy } from '../contracts/strategy-names';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
||||
/** One precedence rule for both backends: shared defaults, then per-strategy overrides. */
|
||||
export function backtestStrategies(config: BacktestConfig, backend: 'native' | 'typescript') {
|
||||
const entries = config.strategies ?? [{ name: config.strategy, enabled: true, config: {} }];
|
||||
if (!entries.some(entry => entry.enabled)) {
|
||||
throw new Error('No enabled backtest strategies');
|
||||
}
|
||||
return entries
|
||||
.filter(entry => entry.enabled)
|
||||
.map((entry, index) => {
|
||||
const kind = builtinStrategy(entry.name);
|
||||
const merged = { ...config.config, ...entry.config };
|
||||
// Built-ins cross the shared execution/parameter boundary once, after merging defaults.
|
||||
// Custom TypeScript factories retain their historical, factory-owned extension contract.
|
||||
const input = kind
|
||||
? normalizeBacktestStrategyConfig(merged)
|
||||
: { parameters: structuredClone(merged) };
|
||||
const { parameters } = input;
|
||||
if (backend === 'native') {
|
||||
if (!kind) {
|
||||
throw new Error(`Unknown native strategy: ${entry.name}`);
|
||||
}
|
||||
if (input.useTypeScriptImplementation) {
|
||||
throw new Error('The native engine does not execute TypeScript strategy callbacks');
|
||||
}
|
||||
const parsed = nativeParameters(kind, parameters);
|
||||
if (
|
||||
kind === 'pairs_trading' &&
|
||||
(typeof parsed.pairA !== 'string' ||
|
||||
typeof parsed.pairB !== 'string' ||
|
||||
!config.symbols.includes(parsed.pairA) ||
|
||||
!config.symbols.includes(parsed.pairB))
|
||||
) {
|
||||
throw new Error('Both pair instruments must be included in backtest symbols');
|
||||
}
|
||||
return { name: entry.name, kind, index, parameters: parsed };
|
||||
}
|
||||
const context = { ...parameters, initialCapital: config.initialCapital };
|
||||
const parsed =
|
||||
kind === 'sma_crossover'
|
||||
? typescriptSmaParameters.parse(context)
|
||||
: kind === 'mean_reversion'
|
||||
? typescriptMeanReversionParameters.parse(context)
|
||||
: context;
|
||||
return { name: entry.name, kind, index, parameters: parsed };
|
||||
});
|
||||
}
|
||||
|
|
@ -4,7 +4,7 @@ import type {
|
|||
DeepReadonly,
|
||||
StrategyDiagnosticSnapshot,
|
||||
StrategyProgram,
|
||||
} from '../contracts/canonical-strategy';
|
||||
} from '@stock-bot/research/strategy-api';
|
||||
import {
|
||||
replayConfigSchema,
|
||||
replayIdentitySchema,
|
||||
|
|
@ -12,7 +12,7 @@ import {
|
|||
type ReplayProjectionResult,
|
||||
type ReplayReportResult,
|
||||
type ReplayResult,
|
||||
} from '../contracts/native-replay';
|
||||
} from '@stock-bot/stock-config/canonical-replay';
|
||||
import { StrategyController } from '../strategies/strategy-controller';
|
||||
import { freeze } from '../strategies/strategy-decision';
|
||||
import {
|
||||
|
|
@ -23,7 +23,7 @@ import {
|
|||
type ReplayOptions,
|
||||
} from './native-replay';
|
||||
|
||||
export type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
export type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
export type StrategyReplayOptions = Omit<ReplayOptions, 'reverseCallbacks'>;
|
||||
type StrategyRun<Result extends ReplayOutput> = {
|
||||
result: Result;
|
||||
|
|
|
|||
|
|
@ -1,86 +0,0 @@
|
|||
/** Internal TypeScript backend output; normalized to BacktestRunResult by the runner. */
|
||||
export interface OHLCBar {
|
||||
timestamp: number;
|
||||
open: number;
|
||||
high: number;
|
||||
low: number;
|
||||
close: number;
|
||||
volume: number;
|
||||
}
|
||||
|
||||
export interface BacktestResult {
|
||||
// Identification
|
||||
backtestId: string;
|
||||
status: 'completed' | 'failed' | 'cancelled';
|
||||
completedAt: string;
|
||||
|
||||
// Configuration
|
||||
config: {
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
initialCapital: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
dataFrequency: string;
|
||||
};
|
||||
|
||||
// Performance metrics
|
||||
metrics: {
|
||||
totalReturn: number;
|
||||
sharpeRatio: number | null;
|
||||
maxDrawdown: number;
|
||||
winRate: number;
|
||||
totalTrades: number;
|
||||
profitFactor: number | null;
|
||||
profitableTrades: number;
|
||||
avgWin: number;
|
||||
avgLoss: number;
|
||||
expectancy: number;
|
||||
calmarRatio: number | null;
|
||||
sortinoRatio: number | null;
|
||||
annualizedReturn: number | null;
|
||||
cagr: number | null;
|
||||
};
|
||||
|
||||
// Chart data
|
||||
equity: Array<{ date: string; value: number }>;
|
||||
ohlcData: Record<string, OHLCBar[]>;
|
||||
|
||||
// Trade history
|
||||
trades: Array<{
|
||||
id: string;
|
||||
symbol: string;
|
||||
entryDate: string;
|
||||
exitDate: string | null;
|
||||
entryPrice: number;
|
||||
exitPrice: number;
|
||||
quantity: number;
|
||||
side: string;
|
||||
pnl: number;
|
||||
pnlPercent: number;
|
||||
commission: number;
|
||||
duration: number;
|
||||
}>;
|
||||
|
||||
// Positions
|
||||
positions: Array<{
|
||||
symbol: string;
|
||||
quantity: number;
|
||||
averagePrice: number;
|
||||
currentPrice: number;
|
||||
unrealizedPnl: number;
|
||||
realizedPnl: number;
|
||||
}>;
|
||||
|
||||
// Analytics
|
||||
analytics: {
|
||||
drawdownSeries: { timestamp: number; value: number }[];
|
||||
dailyReturns: number[];
|
||||
monthlyReturns: Record<string, number>;
|
||||
exposureTime: number;
|
||||
riskMetrics: Record<string, number | null>;
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue