commit 2 refactor

This commit is contained in:
Boki 2026-10-20 14:35:45 -04:00
parent 588f666943
commit 32e43c9243
310 changed files with 33318 additions and 31189 deletions

File diff suppressed because it is too large Load diff

View file

@ -1,387 +1,409 @@
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('MarketSimulator');
import { MarketData, Quote, Trade, Bar, OrderBookSnapshot, PriceLevel } from '../types';
import { MarketMicrostructure } from '../types/MarketMicrostructure';
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;
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 = {
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 + Math.random() * 2 : // 1-3x visible size hidden
1;
// Bid levels
const bidPrice = topQuote.bid - (i * micro.tickSize);
const bidSize = topQuote.bidSize * depthFactor * (0.8 + Math.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 + Math.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) {
current.bids[0].price = quote.bid;
current.bids[0].size = quote.bidSize;
}
if (current.asks.length > 0) {
current.asks[0].price = quote.ask;
current.asks[0].size = quote.askSize;
}
// Adjust deeper levels based on spread changes
const oldSpread = current.asks[0].price - 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 / (current.bids[0].size || quote.bidSize);
current.bids[i].size *= sizeRatio * (0.9 + Math.random() * 0.2);
// Adjust prices to maintain relative spacing
const spacing = (current.bids[i-1].price - current.bids[i].price) * spreadRatio;
current.bids[i].price = current.bids[i-1].price - spacing;
}
for (let i = 1; i < current.asks.length; i++) {
const sizeRatio = quote.askSize / (current.asks[0].size || quote.askSize);
current.asks[i].size *= sizeRatio * (0.9 + Math.random() * 0.2);
const spacing = (current.asks[i].price - current.asks[i-1].price) * spreadRatio;
current.asks[i].price = 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 * Math.random(); // Hidden liquidity probabilistic
}
const fillSize = Math.min(remainingSize, availableSize);
// Simulate latency - price might move
if (this.config.latencyMs > 0 && orderType === 'market') {
const priceMovement = microstructure ?
(Math.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 * Math.random();
if (darkPoolSize > 0) {
const midPrice = (orderbook.bids[0].price + 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 = (orderbook.bids[0].price + 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();
}
}
import { getLogger } from '@stock-bot/logger';
import { at } from '@stock-bot/utils';
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;
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 + Math.random() * 2 // 1-3x visible size hidden
: 1;
// Bid levels
const bidPrice = topQuote.bid - i * micro.tickSize;
const bidSize = topQuote.bidSize * depthFactor * (0.8 + Math.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 + Math.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 + Math.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 + Math.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 * Math.random(); // Hidden liquidity probabilistic
}
const fillSize = Math.min(remainingSize, availableSize);
// Simulate latency - price might move
if (this.config.latencyMs > 0 && orderType === 'market') {
const priceMovement = microstructure
? (((Math.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 * Math.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();
}
}

View file

@ -1,266 +1,126 @@
import { IServiceContainer } from '@stock-bot/di';
import { BacktestEngine as RustEngine } from '@stock-bot/engine';
import { EventEmitter } from 'events';
import { StorageService } from '../services/StorageService';
import { SMACrossoverStrategy, StrategyExecutor } from '../strategies/StrategyExecutor';
import { BacktestConfig, BacktestResult } from '../types';
/**
* Adapter that bridges the orchestrator with the Rust backtest engine
*/
export class RustBacktestAdapter extends EventEmitter {
private container: IServiceContainer;
private storageService: StorageService;
private currentEngine?: RustEngine;
private isRunning = false;
private strategyExecutor: StrategyExecutor;
constructor(container: IServiceContainer) {
super();
this.container = container;
this.storageService = container.custom?.StorageService || new StorageService(
container,
container.mongodb,
container.postgres,
null
);
this.strategyExecutor = new StrategyExecutor();
}
async runBacktest(config: BacktestConfig): Promise<BacktestResult> {
if (this.isRunning) {
throw new Error('Backtest already running');
}
this.isRunning = true;
const startTime = Date.now();
try {
this.container.logger.info('Starting Rust backtest engine', {
symbols: config.symbols,
startDate: config.startDate,
endDate: config.endDate,
});
// Create Rust engine configuration
const rustConfig = {
name: config.name || 'Backtest',
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 || '1d',
};
// Create new Rust engine instance
this.currentEngine = new RustEngine(rustConfig);
// For now, use a simple strategy mapping
// In the future, strategies should be written in Rust or use a common interface
this.container.logger.info('About to register strategy', {
strategy: config.strategy,
config: config.config
});
this.registerStrategy(config.strategy, config.config || {});
// Load historical data
await this.loadHistoricalData(config);
// Emit progress events
this.emit('progress', {
progress: 0.1,
message: 'Data loaded, starting backtest...',
});
// Run the backtest in Rust
this.container.logger.info('Starting Rust engine execution');
const resultJson = this.currentEngine.run();
this.container.logger.info('Rust engine execution completed');
const rustResult = JSON.parse(resultJson);
this.container.logger.info('Rust backtest result summary', {
totalTrades: rustResult.metrics?.total_trades,
equityCurveLength: rustResult.equity_curve?.length,
tradesLength: rustResult.trades?.length,
finalPositions: rustResult.final_positions
});
// Log first trade structure to understand format
if (rustResult.trades?.length > 0) {
this.container.logger.info('First trade structure:', rustResult.trades[0]);
}
// Rust result already contains OHLC data from the engine
const result: BacktestResult = rustResult;
this.emit('complete', result);
return result;
} catch (error) {
this.container.logger.error('Rust backtest failed', error);
const errorResult: BacktestResult = {
backtestId: `rust-${Date.now()}`,
status: 'failed',
completedAt: new Date().toISOString(),
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 || '1d',
},
metrics: this.getEmptyMetrics(),
equityCurve: [],
trades: [],
dailyReturns: [],
finalPositions: {},
executionTime: Date.now() - startTime,
error: error instanceof Error ? error.message : 'Unknown error',
};
this.emit('error', error);
return errorResult;
} finally {
this.isRunning = false;
this.currentEngine = undefined;
}
}
async stopBacktest(): Promise<void> {
if (!this.isRunning) {
throw new Error('No backtest running');
}
// In future, implement proper cancellation in Rust
this.isRunning = false;
this.emit('cancelled');
}
private async loadHistoricalData(config: BacktestConfig): Promise<void> {
const startDate = new Date(config.startDate);
const endDate = new Date(config.endDate);
const allMarketData = [];
// Collect all data for all symbols
for (const symbol of config.symbols) {
const bars = await this.storageService.getHistoricalBars(
symbol,
startDate,
endDate,
config.dataFrequency || '1d'
);
// Convert to Rust format
const marketData = bars.map(bar => ({
symbol,
timestamp: bar.timestamp.getTime(),
type: 'bar',
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap || (bar.high + bar.low + bar.close) / 3,
}));
allMarketData.push(...marketData);
this.container.logger.info(`Collected ${marketData.length} bars for ${symbol}`);
}
// Sort all data by timestamp to ensure chronological order
allMarketData.sort((a, b) => a.timestamp - b.timestamp);
// Load all data at once into Rust engine
if (this.currentEngine) {
this.container.logger.info(`Loading ${allMarketData.length} total bars into Rust engine`);
this.currentEngine.loadMarketData(allMarketData);
}
}
private registerStrategy(strategyName: string, parameters: any): void {
if (!this.currentEngine) {return;}
this.container.logger.info('Registering strategy', {
strategyName,
parameters
});
// Check if we should use TypeScript or native Rust implementation
const useTypeScript = parameters.useTypeScriptImplementation || false;
if (useTypeScript) {
// Register TypeScript strategy
this.container.logger.info('Using TypeScript strategy implementation');
// For now, we'll use the SMACrossoverStrategy
if (strategyName.toLowerCase().includes('sma') || strategyName.toLowerCase().includes('crossover')) {
const strategyId = `strategy-${Date.now()}`;
this.strategyExecutor.registerStrategy(strategyId, SMACrossoverStrategy);
// Create a callback that uses the strategy executor
const callback = (callJson: string) => {
try {
const call = JSON.parse(callJson);
if (call.method === 'on_market_data') {
const signals = this.strategyExecutor.onMarketData(call.data);
return JSON.stringify({ signals });
} else if (call.method === 'on_fill') {
const { symbol, quantity, price, side } = call.data;
this.strategyExecutor.onFill(symbol, quantity, price, side);
return JSON.stringify({ signals: [] });
}
return JSON.stringify({ signals: [] });
} catch (error) {
this.container.logger.error('Strategy execution error:', error);
return JSON.stringify({ signals: [] });
}
};
// Register with Rust engine
this.currentEngine.addTypescriptStrategy(
strategyName,
strategyId,
parameters,
callback
);
}
} else {
// Use native Rust strategy for maximum performance
this.container.logger.info('Using native Rust strategy implementation');
// Map strategy names to their Rust strategy types
let strategyType = 'sma_crossover'; // default
if (strategyName.toLowerCase().includes('mean') || strategyName.toLowerCase().includes('reversion')) {
strategyType = 'mean_reversion';
} else if (strategyName.toLowerCase().includes('momentum')) {
strategyType = 'momentum';
} else if (strategyName.toLowerCase().includes('pairs')) {
strategyType = 'pairs_trading';
} else if (strategyName.toLowerCase().includes('sma') || strategyName.toLowerCase().includes('crossover')) {
strategyType = 'sma_crossover';
}
this.container.logger.info(`Mapped strategy '${strategyName}' to type '${strategyType}'`);
// Use the addNativeStrategy method instead
this.currentEngine.addNativeStrategy(
strategyType,
strategyName,
`strategy-${Date.now()}`,
parameters
);
}
}
}
import { EventEmitter } from 'node:events';
import { BacktestEngine as RustEngine } from '@stock-bot/engine';
import { StorageService } from '../services/StorageService';
import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types';
import { nativeResultSchema, type NativeBacktestResult } from './native-result';
export type BacktestResult = NativeBacktestResult;
/** Validates the native boundary; all historical data comes from the storage owner. */
export class RustBacktestAdapter extends EventEmitter {
private readonly storageService: StorageService;
private isRunning = false;
private currentTime = 0;
constructor(private readonly container: OrchestratorServices) {
super();
this.storageService =
container.custom?.StorageService ??
new StorageService(
container,
container.mongodb,
container.postgres,
container.questdb ?? null
);
}
async runBacktest(input: BacktestConfig): Promise<NativeBacktestResult> {
if (this.isRunning) {
throw new Error('Backtest already running');
}
const config = BacktestConfigSchema.parse(input);
this.isRunning = true;
try {
const engine = new RustEngine({
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,
});
const parameters = config.config ?? {};
if (parameters.useTypeScriptImplementation) {
throw new Error('The native engine does not execute TypeScript strategy callbacks');
}
const name = config.strategy.toLowerCase();
const strategy =
name.includes('mean') || name.includes('reversion')
? 'mean_reversion'
: name.includes('momentum')
? 'momentum'
: name.includes('pairs')
? 'pairs_trading'
: name.includes('sma') || name.includes('crossover') || name === 'moving-average'
? 'sma_crossover'
: undefined;
if (!strategy) {
throw new Error(`Unknown native strategy: ${config.strategy}`);
}
engine.addNativeStrategy(strategy, config.strategy, 'backtest-strategy', parameters);
const data = [];
for (const symbol of config.symbols) {
const bars = await this.storageService.getHistoricalBars(
symbol,
new Date(config.startDate),
new Date(config.endDate),
config.dataFrequency
);
if (!bars.length) {
throw new Error(`No historical data for ${symbol}`);
}
data.push(
...bars.map(bar => ({
symbol,
timestamp: bar.timestamp.getTime(),
type: 'bar',
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap ?? (bar.high + bar.low + bar.close) / 3,
}))
);
}
data.sort((a, b) => a.timestamp - b.timestamp);
engine.loadMarketData(data);
this.emit('progress', { progress: 0, message: 'Historical data loaded' });
const result = nativeResultSchema.parse(JSON.parse(engine.run()));
this.currentTime = new Date(config.endDate).getTime();
this.emit('complete', result);
return result;
} catch (error) {
this.container.logger.error('Native backtest failed', { error });
if (this.listenerCount('error') > 0) {
this.emit('error', error);
}
throw error;
} finally {
this.isRunning = false;
}
}
getStatus() {
return {
isRunning: this.isRunning,
isPaused: false,
progress: this.isRunning ? 0 : 100,
currentTime: this.currentTime,
};
}
async stopBacktest(): Promise<void> {
throw new Error('Native synchronous backtests do not support cancellation');
}
async pauseBacktest(): Promise<void> {
throw new Error('Native synchronous backtests do not support pause');
}
async resumeBacktest(): Promise<void> {
throw new Error('Native synchronous backtests do not support resume');
}
setSpeedMultiplier(_speed: number | null): void {
throw new Error('Native synchronous backtests run at maximum speed');
}
}

View file

@ -1,187 +1,188 @@
import { IServiceContainer } from '@stock-bot/di';
import { BacktestEngine as RustEngine } from '@stock-bot/engine';
import { StorageService } from '../services/StorageService';
import { RustStrategy } from '../strategies/RustStrategy';
import { BacktestConfig } from '../types';
export interface RustBacktestConfig {
name: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
commission: number;
slippage: number;
dataFrequency: string;
}
export interface RustBacktestResult {
config: RustBacktestConfig;
metrics: {
totalReturn: number;
totalTrades: number;
profitableTrades: number;
winRate: number;
profitFactor: number;
sharpeRatio: number;
maxDrawdown: number;
totalPnl: number;
avgWin: number;
avgLoss: number;
};
equityCurve: Array<{ date: string; value: number }>;
trades: any[];
finalPositions: Record<string, any>;
}
export class RustBacktestEngine {
private engine: RustEngine;
private container: IServiceContainer;
private storageService: StorageService;
private config: RustBacktestConfig;
constructor(
container: IServiceContainer,
storageService: StorageService,
config: BacktestConfig
) {
this.container = container;
this.storageService = storageService;
// Convert config for Rust
const rustConfig: RustBacktestConfig = {
name: config.name || 'Backtest',
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 || '1d',
};
this.config = rustConfig;
this.engine = new RustEngine(rustConfig as any);
}
/**
* Add a TypeScript strategy to the backtest
*/
addStrategy(strategy: RustStrategy): void {
strategy.register(this.engine);
}
/**
* Load historical data for the backtest
*/
async loadData(): Promise<void> {
// Get config from engine
const config = this.getConfig();
const startDate = new Date(config.startDate);
const endDate = new Date(config.endDate);
// Load data for each symbol
for (const symbol of config.symbols) {
const bars = await this.storageService.getHistoricalBars(
symbol,
startDate,
endDate,
config.dataFrequency
);
// Convert to Rust format
const marketData = bars.map(bar => ({
symbol,
timestamp: bar.timestamp.getTime(), // Convert to milliseconds
type: 'bar',
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap || (bar.high + bar.low + bar.close) / 3,
}));
// Load into Rust engine
console.log(`Loading ${marketData.length} bars for ${symbol}`);
this.engine.loadMarketData(marketData as any);
}
}
/**
* Run the backtest
*/
async run(): Promise<RustBacktestResult> {
console.log('Starting backtest run...');
// Load data first
await this.loadData();
// Run backtest in Rust
const resultJson = await this.engine.run();
// Parse result and convert snake_case to camelCase
const rustResult = JSON.parse(resultJson);
const result: RustBacktestResult = {
config: rustResult.config,
metrics: {
totalReturn: rustResult.metrics.total_return,
totalTrades: rustResult.metrics.total_trades,
profitableTrades: rustResult.metrics.profitable_trades,
winRate: rustResult.metrics.win_rate,
profitFactor: rustResult.metrics.profit_factor,
sharpeRatio: rustResult.metrics.sharpe_ratio,
maxDrawdown: rustResult.metrics.max_drawdown,
totalPnl: rustResult.metrics.total_pnl,
avgWin: rustResult.metrics.avg_win,
avgLoss: rustResult.metrics.avg_loss,
},
equityCurve: rustResult.equity_curve.map((point: any) => ({
date: point[0],
value: point[1],
})),
trades: rustResult.trades,
finalPositions: rustResult.final_positions,
};
// Log results
this.container.logger.info('Rust backtest completed', {
totalReturn: result.metrics.totalReturn,
totalTrades: result.metrics.totalTrades,
sharpeRatio: result.metrics.sharpeRatio,
});
return result;
}
/**
* Get the backtest configuration
*/
private getConfig(): RustBacktestConfig {
return this.config;
}
}
/**
* Factory function to create a Rust-powered backtest
*/
export async function createRustBacktest(
container: IServiceContainer,
config: BacktestConfig,
strategies: RustStrategy[]
): Promise<RustBacktestResult> {
const storageService = container.custom?.StorageService || new StorageService();
// Create engine
const engine = new RustBacktestEngine(container, storageService, config);
// Add strategies
for (const strategy of strategies) {
engine.addStrategy(strategy);
}
// Run backtest
return await engine.run();
}
import { BacktestEngine as RustEngine } from '@stock-bot/engine';
import { StorageService } from '../services/StorageService';
import { RustStrategy } from '../strategies/RustStrategy';
import type { BacktestConfig, OrchestratorServices as IServiceContainer } from '../types';
import { nativeResultSchema } from './native-result';
export interface RustBacktestConfig {
name: string;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
commission: number;
slippage: number;
dataFrequency: string;
}
export interface RustBacktestResult {
config: RustBacktestConfig;
metrics: {
totalReturn: number;
totalTrades: number;
profitableTrades: number;
winRate: number;
profitFactor: number | null;
sharpeRatio: number;
maxDrawdown: number;
totalPnl: number;
avgWin: number;
avgLoss: number;
};
equityCurve: Array<{ date: string; value: number }>;
trades: import('./native-result').NativeBacktestResult['trades'];
finalPositions: Record<string, unknown>;
}
export class RustBacktestEngine {
private engine: RustEngine;
private container: IServiceContainer;
private storageService: StorageService;
private config: RustBacktestConfig;
constructor(
container: IServiceContainer,
storageService: StorageService,
config: BacktestConfig
) {
this.container = container;
this.storageService = storageService;
// Convert config for Rust
const rustConfig: RustBacktestConfig = {
name: config.name || 'Backtest',
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 || '1d',
};
this.config = rustConfig;
this.engine = new RustEngine(rustConfig);
}
/**
* Add a TypeScript strategy to the backtest
*/
addStrategy(strategy: RustStrategy): void {
strategy.register(this.engine);
}
/**
* Load historical data for the backtest
*/
async loadData(): Promise<void> {
// Get config from engine
const config = this.getConfig();
const startDate = new Date(config.startDate);
const endDate = new Date(config.endDate);
// Load data for each symbol
for (const symbol of config.symbols) {
const bars = await this.storageService.getHistoricalBars(
symbol,
startDate,
endDate,
config.dataFrequency
);
// Convert to Rust format
const marketData = bars.map(bar => ({
symbol,
timestamp: bar.timestamp.getTime(), // Convert to milliseconds
type: 'bar',
open: bar.open,
high: bar.high,
low: bar.low,
close: bar.close,
volume: bar.volume,
vwap: bar.vwap || (bar.high + bar.low + bar.close) / 3,
}));
// Load into Rust engine
this.container.logger.info(`Loading ${marketData.length} bars for ${symbol}`);
this.engine.loadMarketData(marketData);
}
}
/**
* Run the backtest
*/
async run(): Promise<RustBacktestResult> {
this.container.logger.info('Starting backtest run...');
// Load data first
await this.loadData();
// Run backtest in Rust
const resultJson = await this.engine.run();
// Parse result and convert snake_case to camelCase
const rustResult = nativeResultSchema.parse(JSON.parse(resultJson));
const result: RustBacktestResult = {
config: this.config,
metrics: {
totalReturn: rustResult.metrics.totalReturn,
totalTrades: rustResult.metrics.totalTrades,
profitableTrades: rustResult.trades.filter(trade => (trade.pnl ?? 0) > 0).length,
winRate: rustResult.metrics.winRate,
profitFactor: rustResult.metrics.profitFactor,
sharpeRatio: rustResult.metrics.sharpeRatio,
maxDrawdown: rustResult.metrics.maxDrawdown,
totalPnl: rustResult.trades.reduce((sum, trade) => sum + (trade.pnl ?? 0), 0),
avgWin: rustResult.metrics.avgWin,
avgLoss: rustResult.metrics.avgLoss,
},
equityCurve: rustResult.equity,
trades: rustResult.trades,
finalPositions: Object.fromEntries(
rustResult.positions.map(position => [position.symbol, position])
),
};
// Log results
this.container.logger.info('Rust backtest completed', {
totalReturn: result.metrics.totalReturn,
totalTrades: result.metrics.totalTrades,
sharpeRatio: result.metrics.sharpeRatio,
});
return result;
}
/**
* Get the backtest configuration
*/
private getConfig(): RustBacktestConfig {
return this.config;
}
}
/**
* Factory function to create a Rust-powered backtest
*/
export async function createRustBacktest(
container: IServiceContainer,
config: BacktestConfig,
strategies: RustStrategy[]
): Promise<RustBacktestResult> {
const storageService =
container.custom?.StorageService ||
new StorageService(container, container.mongodb, container.postgres, container.questdb ?? null);
// Create engine
const engine = new RustBacktestEngine(container, storageService, config);
// Add strategies
for (const strategy of strategies) {
engine.addStrategy(strategy);
}
// Run backtest
return await engine.run();
}

View file

@ -0,0 +1,89 @@
import { z } from 'zod';
/** Serialized contract of engine/src/backtest/simple_results.rs. */
export const nativeResultSchema = z
.object({
backtestId: z.string(),
status: z.enum(['completed', 'failed', 'cancelled']),
completedAt: z.string(),
config: z
.object({
name: z.string(),
symbols: z.array(z.string()),
startDate: z.string(),
endDate: z.string(),
initialCapital: z.number(),
})
.passthrough(),
metrics: z
.object({
totalReturn: z.number(),
sharpeRatio: z.number(),
maxDrawdown: z.number(),
winRate: z.number(),
totalTrades: z.number(),
profitFactor: z.number().nullable(),
avgWin: z.number(),
avgLoss: z.number(),
})
.passthrough(),
equity: z.array(z.object({ date: z.string(), value: z.number() })),
trades: z.array(
z.object({
id: z.string(),
symbol: z.string(),
timestamp: z.string(),
side: z.enum(['buy', 'sell']),
price: z.number(),
quantity: z.number(),
commission: z.number(),
positionAfter: z.number(),
pnl: z.number().optional(),
})
),
positions: z.array(
z.object({
symbol: z.string(),
quantity: z.number(),
averagePrice: z.number(),
currentPrice: z.number(),
unrealizedPnl: z.number(),
realizedPnl: z.number(),
})
),
analytics: z.object({ exposureTime: z.number() }).passthrough(),
ohlcData: z.record(z.array(z.record(z.unknown()))),
executionTime: z.number(),
error: z.string().optional(),
})
.passthrough();
export type NativeBacktestResult = z.infer<typeof nativeResultSchema>;
/** Serialized contracts of engine/src/positions/mod.rs. */
export const closedTradesSchema = z.array(
z.object({
id: z.string(),
symbol: z.string(),
entry_time: z.string(),
exit_time: z.string(),
entry_price: z.number(),
exit_price: z.number(),
quantity: z.number(),
side: z.enum(['Buy', 'Sell']),
pnl: z.number(),
pnl_percent: z.number(),
commission: z.number(),
duration_ms: z.number(),
})
);
export type ClosedTrade = z.infer<typeof closedTradesSchema>[number];
export const openPositionsSchema = z.array(
z.object({
symbol: z.string(),
quantity: z.number(),
average_price: z.number(),
realized_pnl: z.number(),
unrealized_pnl: z.number(),
})
);