diff --git a/README.md b/README.md index 9d43febf..fc527148 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,53 @@ is contacted. Native SMA and MACD regressions are covered by the repository chec Coverage reports contain measured LCOV data only. Missing coverage or an empty package selection fails the coverage command instead of producing an estimated score. +## Historical input identity and reproducibility + +Backtest `symbols` are exchange-qualified IDs such as `AAPL.US` or `BRK.B.US`, using +the existing EOD provider exchange namespace (not a guessed venue MIC). Ticker-only +definitions remain readable but must be explicitly updated before a new run. MongoDB +history reads match the qualified `eodSearchCode` and verify each returned identity; +QuestDB `bars_.symbol` must contain the same qualified ID. No ticker fallback, +automatic legacy-history rewrite, or cross-provider fallback is performed. +Provider namespace (`providerExchange`, also encoded in the ID) is distinct from the +source's `exchange` venue metadata. Older rows with a valid qualified key remain readable +without rewriting that metadata. + +`dataPolicy` explicitly describes prices and timestamps: + +- `adjustment: 'raw'` is the default; no corporate-action accounting is implied. +- `adjustment: 'provider-adjusted'` scales **all OHLC/VWAP prices** by + `adjustedClose / close`. Missing/nonpositive provider factors fail the run. This is + the provider's combined split/dividend adjustment, not a split-only or point-in-time + total-return model. Reported volume is unchanged; no extra dividend cash is credited. +- Daily bars use `timestamp: 'utc-session-date'`: UTC-midnight session labels, not + exchange close instants. Daily range boundaries must be UTC midnight. Intraday bars + use `timestamp: 'utc-instant'` with an explicit timezone. Ranges are `[start, end)`. +- Invalid prices, duplicate timestamps, mixed identities, or missing requested listings + fail; prices are never interpolated or silently repaired. Market holidays are not + synthesized, and exchange-calendar/session completeness is not yet verified. + +Apply additive migration `database/postgres/init/12-historical-datasets.sql` via the +web API migration runner before starting a new backtest. The first execution attempt +validates and content-hashes the actual input bars and provenance, then atomically stores +them in `backtest_datasets` and pins `runs.dataset_hash` **before executing any bar**. +Recovered attempts reuse that snapshot, never revised provider data. Both execution +backends consume the same normalized, deterministically ordered bars with no second +corporate-action transformation. The TypeScript simulator's pseudo-random sequence is +seeded from the dataset hash; native same-timestamp seeks retain every listing. + +The canonical result records the manifest in `config.dataset`: SHA-256 hash, listing +identities, range, interval, adjustment/timestamp/volume policies, source normalization +revision, and bar count. Replay through the runner by supplying `datasetHash` (or put it +in a V2 definition's `config`); the range, listings, interval and policy must match. +Missing, corrupted or incompatible snapshots fail instead of falling back to provider +history. Runs capture data at execution preparation, **not HTTP acceptance time**. +Reproducibility assumes the same engine/strategy code and configuration; the snapshot +is not an engine binary archive or a point-in-time constituent universe. Direct backend +calls can load data for diagnostics, but durable replay/persistence requires the runner. +Snapshots are currently JSONB and load in memory; large tick datasets need chunked storage +and an explicit retention policy before scaling. + ## Simulation order execution `ExecutionService` is the runtime order gateway for REST, Socket.IO (when enabled), and diff --git a/apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts b/apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts index b3366a1a..eb8dd724 100644 --- a/apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts +++ b/apps/stock/data-ingestion/src/handlers/eod/shared/price-storage.ts @@ -1,4 +1,5 @@ import type { MongoDBClient } from '@stock-bot/services'; +import { parseInstrumentId } from '@stock-bot/types'; export interface EodPrice { date: string; @@ -16,6 +17,10 @@ export async function persistEodPrices( identity: { symbol: string; exchange: string; eodSearchCode: string }, prices: readonly EodPrice[] ) { + const parsed = parseInstrumentId(identity.eodSearchCode); + if (parsed.symbol !== identity.symbol) { + throw new Error('EOD instrument identity mismatch'); + } const documents = prices.map(price => { if ( typeof price.date !== 'string' || @@ -23,7 +28,8 @@ export async function persistEodPrices( !Number.isFinite(Date.parse(price.date)) || new Date(price.date).toISOString().slice(0, 10) !== price.date || ![price.open, price.high, price.low, price.close, price.volume].every(Number.isFinite) || - (price.adjusted_close !== undefined && !Number.isFinite(price.adjusted_close)) || + (price.adjusted_close !== undefined && + (!Number.isFinite(price.adjusted_close) || price.adjusted_close <= 0)) || price.low <= 0 || price.high < Math.max(price.open, price.close) || price.low > Math.min(price.open, price.close) || @@ -33,13 +39,16 @@ export async function persistEodPrices( } return { ...identity, + // Exchange can name the venue; the provider routing namespace is distinct. + providerExchange: parsed.exchange, source: 'eod', date: price.date, open: price.open, high: price.high, low: price.low, close: price.close, - adjustedClose: price.adjusted_close ?? price.close, + // Missing adjustment data must not masquerade as an unadjusted factor of one. + ...(price.adjusted_close === undefined ? {} : { adjustedClose: price.adjusted_close }), volume: price.volume, }; }); diff --git a/apps/stock/engine/src/backtest/price_tracking_test.rs b/apps/stock/engine/src/backtest/price_tracking_test.rs index ab36555f..a246bf66 100644 --- a/apps/stock/engine/src/backtest/price_tracking_test.rs +++ b/apps/stock/engine/src/backtest/price_tracking_test.rs @@ -1,370 +1,400 @@ -#[cfg(test)] -mod tests { - use super::super::*; - use crate::{ - Bar, MarketDataType, MarketUpdate, TradingMode, - core::{ - time_providers::SimulatedTime, - market_data_sources::HistoricalDataSource, - execution_handlers::{SimulatedExecution, BacktestFillSimulator}, - }, - }; - use chrono::{DateTime, Utc, TimeZone}; - use std::collections::HashMap; - - // Test strategy that tracks prices and places orders - struct PriceTrackingStrategy { - name: String, - price_history: Vec<(DateTime, String, f64)>, - should_buy_at: Vec<(String, usize)>, // (symbol, bar_index) - should_sell_at: Vec<(String, usize)>, - bar_count: HashMap, - } - - impl PriceTrackingStrategy { - fn new(name: &str) -> Self { - Self { - name: name.to_string(), - price_history: Vec::new(), - should_buy_at: Vec::new(), - should_sell_at: Vec::new(), - bar_count: HashMap::new(), - } - } - - fn with_trades(mut self, buys: Vec<(String, usize)>, sells: Vec<(String, usize)>) -> Self { - self.should_buy_at = buys; - self.should_sell_at = sells; - self - } - } - - impl Strategy for PriceTrackingStrategy { - fn get_name(&self) -> &str { - &self.name - } - - fn get_parameters(&self) -> serde_json::Value { - serde_json::json!({}) - } - - fn on_market_data(&mut self, data: &MarketUpdate) -> Vec { - let mut signals = Vec::new(); - - // Track the price - if let MarketDataType::Bar(bar) = &data.data { - self.price_history.push((data.timestamp, data.symbol.clone(), bar.close)); - - let count = self.bar_count.entry(data.symbol.clone()).or_insert(0); - *count += 1; - - // Check if we should trade at this bar - for (symbol, bar_index) in &self.should_buy_at { - if &data.symbol == symbol && *count == *bar_index { - signals.push(Signal { - symbol: symbol.clone(), - signal_type: SignalType::Buy, - strength: 1.0, - quantity: Some(100.0), - reason: Some("Test buy signal".to_string()), - metadata: None, - }); - } - } - - for (symbol, bar_index) in &self.should_sell_at { - if &data.symbol == symbol && *count == *bar_index { - signals.push(Signal { - symbol: symbol.clone(), - signal_type: SignalType::Sell, - strength: 1.0, - quantity: Some(100.0), - reason: Some("Test sell signal".to_string()), - metadata: None, - }); - } - } - } - - signals - } - - fn on_fill(&mut self, _symbol: &str, _quantity: f64, _price: f64, _side: &str) { - // Track fills if needed - } - } - - fn create_test_bars(symbol: &str, start_time: DateTime, prices: Vec) -> Vec { - prices.into_iter().enumerate().map(|(i, close)| { - let timestamp = start_time + chrono::Duration::days(i as i64); - let high = close * 1.01; - let low = close * 0.99; - let open = if i == 0 { close } else { close * 0.995 }; - - MarketUpdate { - symbol: symbol.to_string(), - timestamp, - data: MarketDataType::Bar(Bar { - open, - high, - low, - close, - volume: 1000000.0, - vwap: Some(close), - }), - } - }).collect() - } - - #[tokio::test] - async fn test_price_tracking_single_symbol() { - // Create test data with known prices - let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(); - let end_time = Utc.with_ymd_and_hms(2024, 1, 10, 0, 0, 0).unwrap(); - - // Prices: index 0=100, 1=101, 2=102, 3=103, 4=104, 5=105, 6=104, 7=103, 8=102, 9=101 - let prices = vec![100.0, 101.0, 102.0, 103.0, 104.0, 105.0, 104.0, 103.0, 102.0, 101.0]; - let bars = create_test_bars("AAPL", start_time, prices.clone()); - - // Setup backtest engine - let config = BacktestConfig { - name: "PriceTrackingTest".to_string(), - strategy: None, - start_time, - end_time, - initial_capital: 100000.0, - commission: 0.001, - slippage: 0.0001, - symbols: vec!["AAPL".to_string()], - data_frequency: "1d".to_string(), - }; - - let time_provider = Box::new(SimulatedTime::new(start_time)); - let mut data_source = Box::new(HistoricalDataSource::new()); - data_source.load_data(bars.clone()); - - let fill_simulator = Box::new(BacktestFillSimulator::new()); - let execution_handler = Box::new(SimulatedExecution::new(fill_simulator)); - - let mode = TradingMode::Backtest { - start_time, - end_time, - speed_multiplier: 1.0, - }; - - let mut engine = BacktestEngine::new( - config, - mode, - time_provider, - data_source, - execution_handler, - ); - - // Add strategy that tracks prices and trades at specific bars - // Note: bar_count starts at 1, so bar 3 is the 3rd bar (index 2, price 102.0) - let strategy = PriceTrackingStrategy::new("PriceTracker") - .with_trades( - vec![("AAPL".to_string(), 3)], // Buy at bar 3 (3rd bar, price 102) - vec![("AAPL".to_string(), 7)], // Sell at bar 7 (7th bar, price 103) - ); - - let strategy_ref = Box::new(strategy); - engine.add_strategy(strategy_ref); - - // Run backtest - let result = engine.run().await.unwrap(); - - // Verify trades executed at correct prices - assert_eq!(result.trades.len(), 2, "Should have exactly 2 trades"); - - let buy_trade = &result.trades[0]; - assert_eq!(buy_trade.side, "buy"); - assert_eq!(buy_trade.symbol, "AAPL"); - // Buy signal at bar 3 (index 2, price 102) executes at that bar's close price - // In backtesting, we execute at the close price of the bar that generated the signal - let expected_buy_price = 102.0 * (1.0 + 0.0001); - assert!( - (buy_trade.price - expected_buy_price).abs() < 0.01, - "Buy price {} should be close to {}", buy_trade.price, expected_buy_price - ); - - let sell_trade = &result.trades[1]; - assert_eq!(sell_trade.side, "sell"); - assert_eq!(sell_trade.symbol, "AAPL"); - // Sell signal at bar 7 (7th bar, index 6, price 104) executes at that bar's close price - let expected_sell_price = 104.0 * (1.0 - 0.0001); - assert!( - (sell_trade.price - expected_sell_price).abs() < 0.01, - "Sell price {} should be close to {}", sell_trade.price, expected_sell_price - ); - } - - #[tokio::test] - async fn test_price_tracking_multiple_symbols() { - let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(); - let end_time = Utc.with_ymd_and_hms(2024, 1, 5, 0, 0, 0).unwrap(); - - // Create different price series for each symbol - // AAPL: index 0=100, 1=101, 2=102, 3=103, 4=104 - let aapl_prices = vec![100.0, 101.0, 102.0, 103.0, 104.0]; - // GOOGL: index 0=150, 1=149, 2=148, 3=147, 4=146 - let googl_prices = vec![150.0, 149.0, 148.0, 147.0, 146.0]; - // MSFT: index 0=200, 1=202, 2=204, 3=206, 4=208 - let msft_prices = vec![200.0, 202.0, 204.0, 206.0, 208.0]; - - let mut all_bars = Vec::new(); - all_bars.extend(create_test_bars("AAPL", start_time, aapl_prices)); - all_bars.extend(create_test_bars("GOOGL", start_time, googl_prices)); - all_bars.extend(create_test_bars("MSFT", start_time, msft_prices)); - - // Sort by timestamp to simulate realistic data flow - all_bars.sort_by_key(|bar| bar.timestamp); - - // Setup backtest - let config = BacktestConfig { - name: "MultiSymbolTest".to_string(), - strategy: None, - start_time, - end_time, - initial_capital: 100000.0, - commission: 0.001, - slippage: 0.0, - symbols: vec!["AAPL".to_string(), "GOOGL".to_string(), "MSFT".to_string()], - data_frequency: "1d".to_string(), - }; - - let time_provider = Box::new(SimulatedTime::new(start_time)); - let mut data_source = Box::new(HistoricalDataSource::new()); - data_source.load_data(all_bars); - - let fill_simulator = Box::new(BacktestFillSimulator::new()); - let execution_handler = Box::new(SimulatedExecution::new(fill_simulator)); - - let mode = TradingMode::Backtest { - start_time, - end_time, - speed_multiplier: 1.0, - }; - - let mut engine = BacktestEngine::new( - config, - mode, - time_provider, - data_source, - execution_handler, - ); - - // Strategy that trades each symbol at different times - let strategy = PriceTrackingStrategy::new("MultiSymbolTracker") - .with_trades( - vec![ - ("AAPL".to_string(), 2), // Buy AAPL at bar 2 (price 102) - ("GOOGL".to_string(), 3), // Buy GOOGL at bar 3 (price 147) - ("MSFT".to_string(), 4), // Buy MSFT at bar 4 (price 208) - ], - vec![ - ("AAPL".to_string(), 4), // Sell AAPL at bar 4 (price 104) - ("GOOGL".to_string(), 5), // Sell GOOGL at bar 5 (price 146) - ("MSFT".to_string(), 5), // Sell MSFT at bar 5 (price 208) - ], - ); - - engine.add_strategy(Box::new(strategy)); - - // Run backtest - let result = engine.run().await.unwrap(); - - // Verify each symbol traded at its own correct price - // Note: Trades execute at the close price of the bar when the signal is generated - let aapl_trades: Vec<_> = result.trades.iter().filter(|t| t.symbol == "AAPL").collect(); - assert_eq!(aapl_trades.len(), 2); - // Buy at bar 2 (when bar_count=2) = Jan 3 = index 2 = price 102 - assert!((aapl_trades[0].price - 102.0).abs() < 0.1, "AAPL buy price should be ~102 (bar 2)"); - // Sell at bar 4 (when bar_count=4) = Jan 5 = index 4 = price 104 - assert!((aapl_trades[1].price - 104.0).abs() < 0.1, "AAPL sell price should be ~104 (bar 4)"); - - let googl_trades: Vec<_> = result.trades.iter().filter(|t| t.symbol == "GOOGL").collect(); - assert_eq!(googl_trades.len(), 2); - // Buy at bar 3 = Jan 4 = index 3 = price 147 - assert!((googl_trades[0].price - 147.0).abs() < 0.1, "GOOGL buy price should be ~147 (bar 3)"); - // Sell at bar 5 or closing = price 146 - assert!((googl_trades[1].price - 146.0).abs() < 0.1, "GOOGL sell price should be ~146 (closing)"); - - let msft_trades: Vec<_> = result.trades.iter().filter(|t| t.symbol == "MSFT").collect(); - assert_eq!(msft_trades.len(), 2); - // Buy at bar 4 = Jan 5 = index 4 = price 208 (but on Jan 4 it's 206) - assert!((msft_trades[0].price - 206.0).abs() < 0.1, "MSFT buy price should be ~206 (bar 4)"); - // Sell at bar 5 = end of data = price 208 - assert!((msft_trades[1].price - 208.0).abs() < 0.1, "MSFT sell price should be ~208 (bar 5)"); - } - - #[tokio::test] - async fn test_closing_position_prices() { - let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(); - let end_time = Utc.with_ymd_and_hms(2024, 1, 5, 0, 0, 0).unwrap(); - - // Prices that change significantly - let prices = vec![100.0, 110.0, 120.0, 130.0, 140.0]; - let bars = create_test_bars("TEST", start_time, prices); - - let config = BacktestConfig { - name: "ClosePositionTest".to_string(), - strategy: None, - start_time, - end_time, - initial_capital: 100000.0, - commission: 0.0, - slippage: 0.0, - symbols: vec!["TEST".to_string()], - data_frequency: "1d".to_string(), - }; - - let time_provider = Box::new(SimulatedTime::new(start_time)); - let mut data_source = Box::new(HistoricalDataSource::new()); - data_source.load_data(bars); - - let fill_simulator = Box::new(BacktestFillSimulator::new()); - let execution_handler = Box::new(SimulatedExecution::new(fill_simulator)); - - let mode = TradingMode::Backtest { - start_time, - end_time, - speed_multiplier: 1.0, - }; - - let mut engine = BacktestEngine::new( - config, - mode, - time_provider, - data_source, - execution_handler, - ); - - // Buy early, never sell (position will be closed at end) - let strategy = PriceTrackingStrategy::new("ClosePositionTest") - .with_trades( - vec![("TEST".to_string(), 1)], // Buy at bar 1 (price 110) - vec![], // Never sell - ); - - engine.add_strategy(Box::new(strategy)); - - let result = engine.run().await.unwrap(); - - // Should have 2 trades: the buy and the closing trade - assert_eq!(result.trades.len(), 2, "Should have buy and closing trade"); - - let buy_trade = &result.trades[0]; - assert_eq!(buy_trade.side, "buy"); - // Buy at bar 1 executes at the first bar's price (100.0) - assert!((buy_trade.price - 100.0).abs() < 0.1, "Buy price should be ~100 (bar 1)"); - - let close_trade = &result.trades[1]; - assert_eq!(close_trade.side, "sell"); - // Position should be closed at the last available price (140) - assert!( - (close_trade.price - 140.0).abs() < 0.1, - "Close price {} should be ~140 (last bar price)", close_trade.price - ); - } -} \ No newline at end of file +#[cfg(test)] +mod tests { + use super::super::*; + use crate::{ + core::{ + execution_handlers::{BacktestFillSimulator, SimulatedExecution}, + market_data_sources::HistoricalDataSource, + time_providers::SimulatedTime, + }, + Bar, MarketDataType, MarketUpdate, TradingMode, + }; + use chrono::{DateTime, TimeZone, Utc}; + use std::collections::HashMap; + + // Test strategy that tracks prices and places orders + struct PriceTrackingStrategy { + name: String, + price_history: Vec<(DateTime, String, f64)>, + should_buy_at: Vec<(String, usize)>, // (symbol, bar_index) + should_sell_at: Vec<(String, usize)>, + bar_count: HashMap, + } + + impl PriceTrackingStrategy { + fn new(name: &str) -> Self { + Self { + name: name.to_string(), + price_history: Vec::new(), + should_buy_at: Vec::new(), + should_sell_at: Vec::new(), + bar_count: HashMap::new(), + } + } + + fn with_trades(mut self, buys: Vec<(String, usize)>, sells: Vec<(String, usize)>) -> Self { + self.should_buy_at = buys; + self.should_sell_at = sells; + self + } + } + + impl Strategy for PriceTrackingStrategy { + fn get_name(&self) -> &str { + &self.name + } + + fn get_parameters(&self) -> serde_json::Value { + serde_json::json!({}) + } + + fn on_market_data(&mut self, data: &MarketUpdate) -> Vec { + let mut signals = Vec::new(); + + // Track the price + if let MarketDataType::Bar(bar) = &data.data { + self.price_history + .push((data.timestamp, data.symbol.clone(), bar.close)); + + let count = self.bar_count.entry(data.symbol.clone()).or_insert(0); + *count += 1; + + // Check if we should trade at this bar + for (symbol, bar_index) in &self.should_buy_at { + if &data.symbol == symbol && *count == *bar_index { + signals.push(Signal { + symbol: symbol.clone(), + signal_type: SignalType::Buy, + strength: 1.0, + quantity: Some(100.0), + reason: Some("Test buy signal".to_string()), + metadata: None, + }); + } + } + + for (symbol, bar_index) in &self.should_sell_at { + if &data.symbol == symbol && *count == *bar_index { + signals.push(Signal { + symbol: symbol.clone(), + signal_type: SignalType::Sell, + strength: 1.0, + quantity: Some(100.0), + reason: Some("Test sell signal".to_string()), + metadata: None, + }); + } + } + } + + signals + } + + fn on_fill(&mut self, _symbol: &str, _quantity: f64, _price: f64, _side: &str) { + // Track fills if needed + } + } + + fn create_test_bars( + symbol: &str, + start_time: DateTime, + prices: Vec, + ) -> Vec { + prices + .into_iter() + .enumerate() + .map(|(i, close)| { + let timestamp = start_time + chrono::Duration::days(i as i64); + let high = close * 1.01; + let low = close * 0.99; + let open = if i == 0 { close } else { close * 0.995 }; + + MarketUpdate { + symbol: symbol.to_string(), + timestamp, + data: MarketDataType::Bar(Bar { + open, + high, + low, + close, + volume: 1000000.0, + vwap: Some(close), + }), + } + }) + .collect() + } + + #[tokio::test] + async fn test_price_tracking_single_symbol() { + // Create test data with known prices + let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(); + let end_time = Utc.with_ymd_and_hms(2024, 1, 10, 0, 0, 0).unwrap(); + + // Prices: index 0=100, 1=101, 2=102, 3=103, 4=104, 5=105, 6=104, 7=103, 8=102, 9=101 + let prices = vec![ + 100.0, 101.0, 102.0, 103.0, 104.0, 105.0, 104.0, 103.0, 102.0, 101.0, + ]; + let bars = create_test_bars("AAPL", start_time, prices.clone()); + + // Setup backtest engine + let config = BacktestConfig { + name: "PriceTrackingTest".to_string(), + strategy: None, + start_time, + end_time, + initial_capital: 100000.0, + commission: 0.001, + slippage: 0.0001, + symbols: vec!["AAPL".to_string()], + data_frequency: "1d".to_string(), + }; + + let time_provider = Box::new(SimulatedTime::new(start_time)); + let mut data_source = Box::new(HistoricalDataSource::new()); + data_source.load_data(bars.clone()); + + let fill_simulator = Box::new(BacktestFillSimulator::new()); + let execution_handler = Box::new(SimulatedExecution::new(fill_simulator)); + + let mode = TradingMode::Backtest { + start_time, + end_time, + speed_multiplier: 1.0, + }; + + let mut engine = + BacktestEngine::new(config, mode, time_provider, data_source, execution_handler); + + // Add strategy that tracks prices and trades at specific bars + // Note: bar_count starts at 1, so bar 3 is the 3rd bar (index 2, price 102.0) + let strategy = PriceTrackingStrategy::new("PriceTracker").with_trades( + vec![("AAPL".to_string(), 3)], // Buy at bar 3 (3rd bar, price 102) + vec![("AAPL".to_string(), 7)], // Sell at bar 7 (7th bar, price 103) + ); + + let strategy_ref = Box::new(strategy); + engine.add_strategy(strategy_ref); + + // Run backtest + let result = engine.run().await.unwrap(); + + // Verify trades executed at correct prices + assert_eq!(result.trades.len(), 2, "Should have exactly 2 trades"); + + let buy_trade = &result.trades[0]; + assert_eq!(buy_trade.side, "buy"); + assert_eq!(buy_trade.symbol, "AAPL"); + // Buy signal at bar 3 (index 2, price 102) executes at that bar's close price + // In backtesting, we execute at the close price of the bar that generated the signal + let expected_buy_price = 102.0 * (1.0 + 0.0001); + assert!( + (buy_trade.price - expected_buy_price).abs() < 0.01, + "Buy price {} should be close to {}", + buy_trade.price, + expected_buy_price + ); + + let sell_trade = &result.trades[1]; + assert_eq!(sell_trade.side, "sell"); + assert_eq!(sell_trade.symbol, "AAPL"); + // Sell signal at bar 7 (7th bar, index 6, price 104) executes at that bar's close price + let expected_sell_price = 104.0 * (1.0 - 0.0001); + assert!( + (sell_trade.price - expected_sell_price).abs() < 0.01, + "Sell price {} should be close to {}", + sell_trade.price, + expected_sell_price + ); + } + + #[tokio::test] + async fn test_price_tracking_multiple_symbols() { + let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(); + let end_time = Utc.with_ymd_and_hms(2024, 1, 5, 0, 0, 0).unwrap(); + + // Create different price series for each symbol + // AAPL: index 0=100, 1=101, 2=102, 3=103, 4=104 + let aapl_prices = vec![100.0, 101.0, 102.0, 103.0, 104.0]; + // GOOGL: index 0=150, 1=149, 2=148, 3=147, 4=146 + let googl_prices = vec![150.0, 149.0, 148.0, 147.0, 146.0]; + // MSFT: index 0=200, 1=202, 2=204, 3=206, 4=208 + let msft_prices = vec![200.0, 202.0, 204.0, 206.0, 208.0]; + + let mut all_bars = Vec::new(); + all_bars.extend(create_test_bars("AAPL", start_time, aapl_prices)); + all_bars.extend(create_test_bars("GOOGL", start_time, googl_prices)); + all_bars.extend(create_test_bars("MSFT", start_time, msft_prices)); + + // Sort by timestamp to simulate realistic data flow + all_bars.sort_by_key(|bar| bar.timestamp); + + // Setup backtest + let config = BacktestConfig { + name: "MultiSymbolTest".to_string(), + strategy: None, + start_time, + end_time, + initial_capital: 100000.0, + commission: 0.001, + slippage: 0.0, + symbols: vec!["AAPL".to_string(), "GOOGL".to_string(), "MSFT".to_string()], + data_frequency: "1d".to_string(), + }; + + let time_provider = Box::new(SimulatedTime::new(start_time)); + let mut data_source = Box::new(HistoricalDataSource::new()); + data_source.load_data(all_bars); + + let fill_simulator = Box::new(BacktestFillSimulator::new()); + let execution_handler = Box::new(SimulatedExecution::new(fill_simulator)); + + let mode = TradingMode::Backtest { + start_time, + end_time, + speed_multiplier: 1.0, + }; + + let mut engine = + BacktestEngine::new(config, mode, time_provider, data_source, execution_handler); + + // Strategy that trades each symbol at different times + let strategy = PriceTrackingStrategy::new("MultiSymbolTracker").with_trades( + vec![ + ("AAPL".to_string(), 2), // Second bar: Jan 2, price 101 + ("GOOGL".to_string(), 3), // Third bar: Jan 3, price 148 + ("MSFT".to_string(), 4), // Fourth bar: Jan 4, price 206 + ], + vec![ + ("AAPL".to_string(), 4), // Fourth bar: Jan 4, price 103 + ("GOOGL".to_string(), 5), // Sell GOOGL at bar 5 (price 146) + ("MSFT".to_string(), 5), // Sell MSFT at bar 5 (price 208) + ], + ); + + engine.add_strategy(Box::new(strategy)); + + // Run backtest + let result = engine.run().await.unwrap(); + + // Verify each symbol traded at its own correct price + // Note: Trades execute at the close price of the bar when the signal is generated + let aapl_trades: Vec<_> = result + .trades + .iter() + .filter(|t| t.symbol == "AAPL") + .collect(); + assert_eq!(aapl_trades.len(), 2); + // Every listing retains its opening bar; strategy bar counts are one-based. + assert!( + (aapl_trades[0].price - 101.0).abs() < 0.1, + "AAPL buy price should be ~101 (bar 2)" + ); + assert!( + (aapl_trades[1].price - 103.0).abs() < 0.1, + "AAPL sell price should be ~103 (bar 4)" + ); + + let googl_trades: Vec<_> = result + .trades + .iter() + .filter(|t| t.symbol == "GOOGL") + .collect(); + assert_eq!(googl_trades.len(), 2); + // Third bar = Jan 3 = index 2 = price 148. + assert!( + (googl_trades[0].price - 148.0).abs() < 0.1, + "GOOGL buy price should be ~148 (bar 3)" + ); + // Sell at bar 5 or closing = price 146 + assert!( + (googl_trades[1].price - 146.0).abs() < 0.1, + "GOOGL sell price should be ~146 (closing)" + ); + + let msft_trades: Vec<_> = result + .trades + .iter() + .filter(|t| t.symbol == "MSFT") + .collect(); + assert_eq!(msft_trades.len(), 2); + // Fourth bar = Jan 4 = index 3 = price 206. + assert!( + (msft_trades[0].price - 206.0).abs() < 0.1, + "MSFT buy price should be ~206 (bar 4)" + ); + // Sell at bar 5 = end of data = price 208 + assert!( + (msft_trades[1].price - 208.0).abs() < 0.1, + "MSFT sell price should be ~208 (bar 5)" + ); + } + + #[tokio::test] + async fn test_closing_position_prices() { + let start_time = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap(); + let end_time = Utc.with_ymd_and_hms(2024, 1, 5, 0, 0, 0).unwrap(); + + // Prices that change significantly + let prices = vec![100.0, 110.0, 120.0, 130.0, 140.0]; + let bars = create_test_bars("TEST", start_time, prices); + + let config = BacktestConfig { + name: "ClosePositionTest".to_string(), + strategy: None, + start_time, + end_time, + initial_capital: 100000.0, + commission: 0.0, + slippage: 0.0, + symbols: vec!["TEST".to_string()], + data_frequency: "1d".to_string(), + }; + + let time_provider = Box::new(SimulatedTime::new(start_time)); + let mut data_source = Box::new(HistoricalDataSource::new()); + data_source.load_data(bars); + + let fill_simulator = Box::new(BacktestFillSimulator::new()); + let execution_handler = Box::new(SimulatedExecution::new(fill_simulator)); + + let mode = TradingMode::Backtest { + start_time, + end_time, + speed_multiplier: 1.0, + }; + + let mut engine = + BacktestEngine::new(config, mode, time_provider, data_source, execution_handler); + + // Buy early, never sell (position will be closed at end) + let strategy = PriceTrackingStrategy::new("ClosePositionTest").with_trades( + vec![("TEST".to_string(), 1)], // Buy at bar 1 (price 110) + vec![], // Never sell + ); + + engine.add_strategy(Box::new(strategy)); + + let result = engine.run().await.unwrap(); + + // Should have 2 trades: the buy and the closing trade + assert_eq!(result.trades.len(), 2, "Should have buy and closing trade"); + + let buy_trade = &result.trades[0]; + assert_eq!(buy_trade.side, "buy"); + // Buy at bar 1 executes at the first bar's price (100.0) + assert!( + (buy_trade.price - 100.0).abs() < 0.1, + "Buy price should be ~100 (bar 1)" + ); + + let close_trade = &result.trades[1]; + assert_eq!(close_trade.side, "sell"); + // Position should be closed at the last available price (140) + assert!( + (close_trade.price - 140.0).abs() < 0.1, + "Close price {} should be ~140 (last bar price)", + close_trade.price + ); + } +} diff --git a/apps/stock/engine/src/core/market_data_sources.rs b/apps/stock/engine/src/core/market_data_sources.rs index d88d3d9d..caa46d2f 100644 --- a/apps/stock/engine/src/core/market_data_sources.rs +++ b/apps/stock/engine/src/core/market_data_sources.rs @@ -1,152 +1,160 @@ -use crate::{MarketDataSource, MarketUpdate}; -use chrono::{DateTime, Utc}; -use parking_lot::Mutex; -use std::collections::VecDeque; -use super::mock_data_generator::MockDataGenerator; - -// Historical data source for backtesting -pub struct HistoricalDataSource { - data_queue: Mutex>, - current_position: Mutex, -} - -impl HistoricalDataSource { - pub fn new() -> Self { - Self { - data_queue: Mutex::new(VecDeque::new()), - current_position: Mutex::new(0), - } - } - - // This would be called by the orchestrator to load data - pub fn load_data(&self, data: Vec) { - eprintln!("HistoricalDataSource::load_data called with {} items", data.len()); - - // Log first few items - for (i, update) in data.iter().take(3).enumerate() { - eprintln!(" Item {}: symbol={}, time={}", i, update.symbol, update.timestamp); - } - - let mut queue = self.data_queue.lock(); - queue.clear(); - queue.extend(data); - *self.current_position.lock() = 0; - - eprintln!("Data loaded successfully. Queue size: {}", queue.len()); - } - - pub fn data_len(&self) -> usize { - self.data_queue.lock().len() - } - - // Generate mock data for testing - pub fn generate_mock_data( - &self, - symbol: String, - start_time: DateTime, - end_time: DateTime, - seed: Option - ) { - let mut generator = MockDataGenerator::new(seed.unwrap_or(42)); - let data = generator.generate_mixed_data(symbol, start_time, end_time); - self.load_data(data); - } -} - -#[async_trait::async_trait] -impl MarketDataSource for HistoricalDataSource { - async fn get_next_update(&mut self) -> Option { - let queue = self.data_queue.lock(); - let mut position = self.current_position.lock(); - - if *position < queue.len() { - let update = queue[*position].clone(); - *position += 1; - Some(update) - } else { - None - } - } - - fn seek_to_time(&mut self, timestamp: DateTime) -> Result<(), String> { - let queue = self.data_queue.lock(); - let mut position = self.current_position.lock(); - - eprintln!("HistoricalDataSource::seek_to_time called"); - eprintln!(" Target time: {}", timestamp); - eprintln!(" Queue size: {}", queue.len()); - - if queue.is_empty() { - eprintln!(" WARNING: Queue is empty!"); - return Ok(()); - } - - eprintln!(" First item time: {}", queue.front().map(|u| u.timestamp.to_string()).unwrap_or("N/A".to_string())); - eprintln!(" Last item time: {}", queue.back().map(|u| u.timestamp.to_string()).unwrap_or("N/A".to_string())); - - // Binary search for the timestamp - match queue.binary_search_by_key(×tamp, |update| update.timestamp) { - Ok(pos) => { - *position = pos; - eprintln!(" Found exact match at position {}", pos); - Ok(()) - } - Err(pos) => { - // Position where it would be inserted - *position = pos; - eprintln!(" No exact match, would insert at position {}", pos); - Ok(()) - } - } - } - - fn as_any(&self) -> &dyn std::any::Any { - self - } - - fn as_any_mut(&mut self) -> &mut dyn std::any::Any { - self - } -} - -// Live data source for paper and live trading -pub struct LiveDataSource { - // Channel to receive data from the orchestrator - data_receiver: tokio::sync::Mutex>>, -} - -impl LiveDataSource { - pub fn new() -> Self { - Self { - data_receiver: tokio::sync::Mutex::new(None), - } - } - - pub async fn set_receiver(&self, receiver: tokio::sync::mpsc::Receiver) { - *self.data_receiver.lock().await = Some(receiver); - } -} - -#[async_trait::async_trait] -impl MarketDataSource for LiveDataSource { - async fn get_next_update(&mut self) -> Option { - let mut receiver_guard = self.data_receiver.lock().await; - if let Some(receiver) = receiver_guard.as_mut() { - receiver.recv().await - } else { - None - } - } - - fn seek_to_time(&mut self, _timestamp: DateTime) -> Result<(), String> { - Err("Cannot seek in live data source".to_string()) - } - - fn as_any(&self) -> &dyn std::any::Any { - self - } - - fn as_any_mut(&mut self) -> &mut dyn std::any::Any { - self - } -} \ No newline at end of file +use super::mock_data_generator::MockDataGenerator; +use crate::{MarketDataSource, MarketUpdate}; +use chrono::{DateTime, Utc}; +use parking_lot::Mutex; +use std::collections::VecDeque; + +// Historical data source for backtesting +pub struct HistoricalDataSource { + data_queue: Mutex>, + current_position: Mutex, +} + +impl HistoricalDataSource { + pub fn new() -> Self { + Self { + data_queue: Mutex::new(VecDeque::new()), + current_position: Mutex::new(0), + } + } + + // This would be called by the orchestrator to load data + pub fn load_data(&self, data: Vec) { + eprintln!( + "HistoricalDataSource::load_data called with {} items", + data.len() + ); + + // Log first few items + for (i, update) in data.iter().take(3).enumerate() { + eprintln!( + " Item {}: symbol={}, time={}", + i, update.symbol, update.timestamp + ); + } + + let mut queue = self.data_queue.lock(); + queue.clear(); + queue.extend(data); + *self.current_position.lock() = 0; + + eprintln!("Data loaded successfully. Queue size: {}", queue.len()); + } + + pub fn data_len(&self) -> usize { + self.data_queue.lock().len() + } + + // Generate mock data for testing + pub fn generate_mock_data( + &self, + symbol: String, + start_time: DateTime, + end_time: DateTime, + seed: Option, + ) { + let mut generator = MockDataGenerator::new(seed.unwrap_or(42)); + let data = generator.generate_mixed_data(symbol, start_time, end_time); + self.load_data(data); + } +} + +#[async_trait::async_trait] +impl MarketDataSource for HistoricalDataSource { + async fn get_next_update(&mut self) -> Option { + let queue = self.data_queue.lock(); + let mut position = self.current_position.lock(); + + if *position < queue.len() { + let update = queue[*position].clone(); + *position += 1; + Some(update) + } else { + None + } + } + + fn seek_to_time(&mut self, timestamp: DateTime) -> Result<(), String> { + let queue = self.data_queue.lock(); + let mut position = self.current_position.lock(); + + eprintln!("HistoricalDataSource::seek_to_time called"); + eprintln!(" Target time: {}", timestamp); + eprintln!(" Queue size: {}", queue.len()); + + if queue.is_empty() { + eprintln!(" WARNING: Queue is empty!"); + return Ok(()); + } + + eprintln!( + " First item time: {}", + queue + .front() + .map(|u| u.timestamp.to_string()) + .unwrap_or("N/A".to_string()) + ); + eprintln!( + " Last item time: {}", + queue + .back() + .map(|u| u.timestamp.to_string()) + .unwrap_or("N/A".to_string()) + ); + + // Lower bound, not an arbitrary equal match: several listings can share the + // first timestamp, and seeking must not skip any of their opening bars. + *position = queue.partition_point(|update| update.timestamp < timestamp); + Ok(()) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn std::any::Any { + self + } +} + +// Live data source for paper and live trading +pub struct LiveDataSource { + // Channel to receive data from the orchestrator + data_receiver: tokio::sync::Mutex>>, +} + +impl LiveDataSource { + pub fn new() -> Self { + Self { + data_receiver: tokio::sync::Mutex::new(None), + } + } + + pub async fn set_receiver(&self, receiver: tokio::sync::mpsc::Receiver) { + *self.data_receiver.lock().await = Some(receiver); + } +} + +#[async_trait::async_trait] +impl MarketDataSource for LiveDataSource { + async fn get_next_update(&mut self) -> Option { + let mut receiver_guard = self.data_receiver.lock().await; + if let Some(receiver) = receiver_guard.as_mut() { + receiver.recv().await + } else { + None + } + } + + fn seek_to_time(&mut self, _timestamp: DateTime) -> Result<(), String> { + Err("Cannot seek in live data source".to_string()) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn std::any::Any { + self + } +} diff --git a/apps/stock/engine/src/positions/mod.rs b/apps/stock/engine/src/positions/mod.rs index 4c513c63..ca672ec7 100644 --- a/apps/stock/engine/src/positions/mod.rs +++ b/apps/stock/engine/src/positions/mod.rs @@ -316,10 +316,13 @@ impl PositionTracker { } pub fn get_all_positions(&self) -> Vec { - self.positions + let mut positions: Vec = self + .positions .iter() .map(|entry| entry.value().clone()) - .collect() + .collect(); + positions.sort_by(|a, b| a.symbol.cmp(&b.symbol)); + positions } pub fn get_open_positions(&self) -> Vec { @@ -348,7 +351,7 @@ impl PositionTracker { let mut realized = 0.0; let mut unrealized = 0.0; - for position in self.positions.iter() { + for position in self.get_all_positions() { realized += position.realized_pnl; unrealized += position.unrealized_pnl; } diff --git a/apps/stock/orchestrator/examples/debug-position-tracking.ts b/apps/stock/orchestrator/examples/debug-position-tracking.ts index 60b7fd47..d9113cda 100644 --- a/apps/stock/orchestrator/examples/debug-position-tracking.ts +++ b/apps/stock/orchestrator/examples/debug-position-tracking.ts @@ -17,7 +17,7 @@ async function debugPositionTracking() { startDate: '2023-06-01T00:00:00Z', endDate: '2023-09-01T00:00:00Z', // Just 3 months for debugging speed: 'max', - symbols: ['AAPL'], + symbols: ['AAPL.US'], initialCapital: 100000, dataFrequency: '1d', strategy: 'sma-crossover', @@ -36,7 +36,7 @@ async function debugPositionTracking() { mode: 'backtest' as const, name: 'Position Tracking Debug', strategy: 'sma-crossover', - symbols: ['AAPL'], + symbols: ['AAPL.US'], startDate: '2023-06-01T00:00:00Z', endDate: '2023-09-01T00:00:00Z', initialCapital: 100000, diff --git a/apps/stock/orchestrator/examples/force-both-trade-types.ts b/apps/stock/orchestrator/examples/force-both-trade-types.ts index 9dfe7bf9..48dabc1d 100644 --- a/apps/stock/orchestrator/examples/force-both-trade-types.ts +++ b/apps/stock/orchestrator/examples/force-both-trade-types.ts @@ -61,7 +61,7 @@ async function forceBothTradeTypes() { startDate: '2023-01-01T00:00:00Z', endDate: '2024-01-01T00:00:00Z', speed: 'max', - symbols: ['AAPL'], + symbols: ['AAPL.US'], initialCapital: 100000, dataFrequency: '1d', strategy: 'sma-crossover', @@ -75,7 +75,7 @@ async function forceBothTradeTypes() { mode: 'backtest' as const, name: 'Force Both Trade Types', strategy: 'sma-crossover', - symbols: ['AAPL'], + symbols: ['AAPL.US'], startDate: '2023-01-01T00:00:00Z', endDate: '2024-01-01T00:00:00Z', initialCapital: 100000, diff --git a/apps/stock/orchestrator/examples/show-order-flow.ts b/apps/stock/orchestrator/examples/show-order-flow.ts index 42148535..97e8607e 100644 --- a/apps/stock/orchestrator/examples/show-order-flow.ts +++ b/apps/stock/orchestrator/examples/show-order-flow.ts @@ -17,7 +17,7 @@ async function showOrderFlow() { startDate: '2023-07-01T00:00:00Z', endDate: '2023-08-01T00:00:00Z', // Just 1 month speed: 'max', - symbols: ['AAPL'], + symbols: ['AAPL.US'], initialCapital: 100000, dataFrequency: '1d', strategy: 'sma-crossover', @@ -31,7 +31,7 @@ async function showOrderFlow() { mode: 'backtest' as const, name: 'Order Flow Demo', strategy: 'sma-crossover', - symbols: ['AAPL'], + symbols: ['AAPL.US'], startDate: '2023-07-01T00:00:00Z', endDate: '2023-08-01T00:00:00Z', initialCapital: 100000, diff --git a/apps/stock/orchestrator/examples/simple-backtest-test.ts b/apps/stock/orchestrator/examples/simple-backtest-test.ts index 038ccca1..8577b3b0 100644 --- a/apps/stock/orchestrator/examples/simple-backtest-test.ts +++ b/apps/stock/orchestrator/examples/simple-backtest-test.ts @@ -20,7 +20,7 @@ async function runSimpleBacktest() { startDate: '2023-01-01T00:00:00Z', endDate: '2024-01-01T00:00:00Z', speed: 'max', - symbols: ['AAPL'], + symbols: ['AAPL.US'], initialCapital: 100000, dataFrequency: '1d', strategy: 'sma-crossover', @@ -34,7 +34,7 @@ async function runSimpleBacktest() { mode: 'backtest' as const, // Add mode field name: 'SMA Crossover Test', strategy: 'sma-crossover', - symbols: ['AAPL'], // Just one symbol for simplicity + symbols: ['AAPL.US'], // Just one symbol for simplicity startDate: '2023-01-01T00:00:00Z', // ISO datetime format endDate: '2024-01-01T00:00:00Z', // ISO datetime format initialCapital: 100000, diff --git a/apps/stock/orchestrator/examples/sophisticated-backtest.ts b/apps/stock/orchestrator/examples/sophisticated-backtest.ts index dba48750..00fae43d 100644 --- a/apps/stock/orchestrator/examples/sophisticated-backtest.ts +++ b/apps/stock/orchestrator/examples/sophisticated-backtest.ts @@ -30,7 +30,7 @@ async function runSophisticatedBacktest() { mode: 'backtest' as const, startDate: '2023-01-01T00:00:00Z', endDate: '2023-12-31T23:59:59Z', - symbols: ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'TSLA'], + symbols: ['AAPL.US', 'GOOGL.US', 'MSFT.US', 'AMZN.US', 'TSLA.US'], initialCapital: 1_000_000, dataFrequency: '5m' as const, // 5-minute bars for detailed analysis @@ -76,7 +76,7 @@ async function runSophisticatedBacktest() { type: 'MeanReversion', enabled: true, allocation: 0.5, - symbols: ['AAPL', 'GOOGL', 'MSFT'], + symbols: ['AAPL.US', 'GOOGL.US', 'MSFT.US'], parameters: { lookback: 20, entryZScore: 2.0, @@ -91,7 +91,7 @@ async function runSophisticatedBacktest() { type: 'MLEnhanced', enabled: true, allocation: 0.5, - symbols: ['AMZN', 'TSLA'], + symbols: ['AMZN.US', 'TSLA.US'], parameters: { modelPath: './models/ml_strategy_v1', updateFrequency: 1440, // Daily retraining diff --git a/apps/stock/orchestrator/examples/test-short-trades.ts b/apps/stock/orchestrator/examples/test-short-trades.ts index d2c213d6..1e05c958 100644 --- a/apps/stock/orchestrator/examples/test-short-trades.ts +++ b/apps/stock/orchestrator/examples/test-short-trades.ts @@ -17,7 +17,7 @@ async function testShortTrades() { startDate: '2023-01-01T00:00:00Z', endDate: '2024-01-01T00:00:00Z', speed: 'max', - symbols: ['AAPL'], + symbols: ['AAPL.US'], initialCapital: 100000, dataFrequency: '1d', strategy: 'sma-crossover', @@ -31,7 +31,7 @@ async function testShortTrades() { mode: 'backtest' as const, name: 'Short Trade Test', strategy: 'sma-crossover', - symbols: ['AAPL'], + symbols: ['AAPL.US'], startDate: '2023-01-01T00:00:00Z', endDate: '2024-01-01T00:00:00Z', initialCapital: 100000, diff --git a/apps/stock/orchestrator/examples/trace-short-positions.ts b/apps/stock/orchestrator/examples/trace-short-positions.ts index 893ddc7e..58a56dd1 100644 --- a/apps/stock/orchestrator/examples/trace-short-positions.ts +++ b/apps/stock/orchestrator/examples/trace-short-positions.ts @@ -30,7 +30,7 @@ async function traceShortPositions() { startDate: '2023-06-01T00:00:00Z', endDate: '2023-09-01T00:00:00Z', // 3 months speed: 'max', - symbols: ['AAPL'], + symbols: ['AAPL.US'], initialCapital: 100000, dataFrequency: '1d', strategy: 'sma-crossover', @@ -44,7 +44,7 @@ async function traceShortPositions() { mode: 'backtest' as const, name: 'Short Position Trace', strategy: 'sma-crossover', - symbols: ['AAPL'], + symbols: ['AAPL.US'], startDate: '2023-06-01T00:00:00Z', endDate: '2023-09-01T00:00:00Z', initialCapital: 100000, diff --git a/apps/stock/orchestrator/examples/verify-both-trade-types.ts b/apps/stock/orchestrator/examples/verify-both-trade-types.ts index 0fbf0ce5..41d689cd 100644 --- a/apps/stock/orchestrator/examples/verify-both-trade-types.ts +++ b/apps/stock/orchestrator/examples/verify-both-trade-types.ts @@ -17,7 +17,7 @@ async function verifyBothTradeTypes() { startDate: '2023-01-01T00:00:00Z', endDate: '2024-01-01T00:00:00Z', speed: 'max', - symbols: ['AAPL'], + symbols: ['AAPL.US'], initialCapital: 100000, dataFrequency: '1d', strategy: 'sma-crossover', @@ -31,7 +31,7 @@ async function verifyBothTradeTypes() { mode: 'backtest' as const, name: 'Trade Type Verification', strategy: 'sma-crossover', - symbols: ['AAPL'], + symbols: ['AAPL.US'], startDate: '2023-01-01T00:00:00Z', endDate: '2024-01-01T00:00:00Z', initialCapital: 100000, diff --git a/apps/stock/orchestrator/src/api/rest/backtest.ts b/apps/stock/orchestrator/src/api/rest/backtest.ts index 60b6fe36..0ddc87e4 100644 --- a/apps/stock/orchestrator/src/api/rest/backtest.ts +++ b/apps/stock/orchestrator/src/api/rest/backtest.ts @@ -1,6 +1,7 @@ import { Hono, type Handler } from 'hono'; import { z } from 'zod'; import { defined } from '@stock-bot/invariants'; +import { HistoricalDataRequestError } from '@stock-bot/types'; import { parseBacktestRequest } from '../../backtest/BacktestRunner'; import { BacktestCancelledError } from '../../backtest/execution-engine'; import { BacktestConflictError } from '../../backtest/run-repository'; @@ -43,6 +44,9 @@ export function createBacktestRoutes(container: IServiceContainer): Hono { 400 ); } + if (error instanceof HistoricalDataRequestError) { + return c.json({ error: error.message }, 400); + } container.logger.error('Error running backtest:', error); return c.json( diff --git a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts index 3cb0d91f..d0b2b0f3 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts @@ -3,6 +3,7 @@ import { defined } from '@stock-bot/invariants'; import { at } from '@stock-bot/utils'; import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer'; import { DataManager } from '../data/DataManager'; +import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; import { StorageService } from '../services/StorageService'; import type { Signal } from '../strategies/BaseStrategy'; import { StrategyManager } from '../strategies/StrategyManager'; @@ -62,7 +63,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng // this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital); } - async runBacktest(config: unknown): Promise { + async runBacktest(config: unknown, resolver?: DatasetResolver): Promise { // Validate config const validatedConfig = BacktestConfigSchema.parse(config); @@ -126,24 +127,20 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng } try { - // Load historical data with multi-resolution support - const dataMap = await this.dataManager.loadHistoricalData( - validatedConfig.symbols, - new Date(validatedConfig.startDate), - new Date(validatedConfig.endDate), - validatedConfig.dataFrequency, - true // Include extended hours - ); + // Both engines execute exactly these frozen, already-normalized bars. + const dataset = await resolveDataset(this.storageService, validatedConfig, resolver); + this.dataManager.inspectDataset(dataset); + this.marketSimulator.resetWithSeed(Number.parseInt(dataset.manifest.hash.slice(0, 8), 16)); // Load market microstructure for each symbol await this.loadMarketMicrostructure(validatedConfig.symbols); // Convert to flat array and sort by time - const marketData: MarketData[] = []; - dataMap.forEach((data, _symbol) => { - marketData.push(...data); - }); - marketData.sort((a, b) => a.data.timestamp - b.data.timestamp); + const marketData: MarketData[] = dataset.bars.map(bar => ({ + type: 'bar', + data: bar, + eventId: `${dataset.manifest.hash}:${bar.symbol}:${bar.timestamp}`, + })); this.container.logger.info(`Loaded ${marketData.length} market data points`); @@ -157,12 +154,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng allocation: 1 / (validatedConfig.strategies?.length ?? 1), })) || [ { - id: `${validatedConfig.strategy}-${Date.now()}`, + id: `${validatedConfig.strategy}-0`, name: validatedConfig.strategy, enabled: true, parameters: { symbols: validatedConfig.symbols, initialCapital: validatedConfig.initialCapital, + ...validatedConfig.config, // Add any default strategy parameters here }, symbols: validatedConfig.symbols, @@ -784,10 +782,10 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng for (const symbol of symbols) { const microstructure: MarketMicrostructure = { symbol, - avgSpreadBps: 2 + Math.random() * 3, // 2-5 bps - dailyVolume: 10_000_000 * (1 + Math.random() * 9), // 10-100M shares - avgTradeSize: 100 + Math.random() * 400, // 100-500 shares - volatility: 0.15 + Math.random() * 0.25, // 15-40% annual vol + avgSpreadBps: 3, + dailyVolume: 10_000_000, + avgTradeSize: 100, + volatility: 0.2, tickSize: 0.01, lotSize: 1, intradayVolumeProfile: this.generateIntradayProfile(), diff --git a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts index bfbdd835..a04f6ba2 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestRunner.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestRunner.ts @@ -1,7 +1,9 @@ import { EventEmitter } from 'node:events'; import { z } from 'zod'; import type { Logger } from '@stock-bot/services'; -import type { BacktestRunResult } from '@stock-bot/types'; +import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types'; +import { validateHistoricalDataRequest } from '@stock-bot/types'; +import { dataPolicy, validateDataset } from '../data/historical-dataset'; import { BacktestConfigSchema, type BacktestConfig } from '../types'; import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine'; import { normalizeBacktestResult } from './result'; @@ -14,6 +16,8 @@ import { export function parseBacktestRequest(input: unknown): BacktestConfig { const config = BacktestConfigSchema.parse(input); + validateHistoricalDataRequest(config); + dataPolicy(config); if (new Date(config.endDate) <= new Date(config.startDate)) { throw new z.ZodError([ { code: 'custom', path: ['endDate'], message: 'Backtest endDate must be after startDate' }, @@ -193,7 +197,24 @@ export class BacktestRunner extends EventEmitter { throw new BacktestCancelledError(); } this.phase = 'executing'; - const raw = await this.dependencies.engine.runBacktest(executionConfig); + let manifest: HistoricalDatasetManifest | undefined; + const claim = this.active; + const raw = await this.dependencies.engine.runBacktest(executionConfig, async load => { + const saved = await this.dependencies.repository.loadDataset( + claim.runId, + claim.attemptId, + executionConfig.datasetHash + ); + const dataset = validateDataset(saved ?? (await load()), executionConfig); + const frozen = + saved ?? + (await this.dependencies.repository.freezeDataset(claim.runId, claim.attemptId, dataset)); + manifest = frozen.manifest; + return frozen; + }); + if (!manifest) { + throw new Error('Backtest engine did not resolve frozen execution inputs'); + } if (this.leaseFailure) { throw this.leaseFailure; } @@ -206,7 +227,8 @@ export class BacktestRunner extends EventEmitter { executionConfig, this.active, performance.now() - started, - this.cancelled + this.cancelled, + manifest ); } catch (error) { throw new Error('Backtest engine returned an invalid result', { cause: error }); diff --git a/apps/stock/orchestrator/src/backtest/MarketSimulator.ts b/apps/stock/orchestrator/src/backtest/MarketSimulator.ts index 04ba1a03..411cb339 100644 --- a/apps/stock/orchestrator/src/backtest/MarketSimulator.ts +++ b/apps/stock/orchestrator/src/backtest/MarketSimulator.ts @@ -34,6 +34,20 @@ export class MarketSimulator { private liquidityProfiles: Map = new Map(); private lastTrades: Map = 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 = {}) { this.config = { @@ -158,12 +172,12 @@ export class MarketSimulator { // Hidden liquidity modeling const hiddenRatio = this.config.modelHiddenLiquidity - ? 1 + Math.random() * 2 // 1-3x visible size hidden + ? 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 + Math.random() * 0.4); + const bidSize = topQuote.bidSize * depthFactor * (0.8 + this.random() * 0.4); bids.push({ price: bidPrice, size: Math.round(bidSize / micro.lotSize) * micro.lotSize, @@ -173,7 +187,7 @@ export class MarketSimulator { // Ask levels const askPrice = topQuote.ask + i * micro.tickSize; - const askSize = topQuote.askSize * depthFactor * (0.8 + Math.random() * 0.4); + const askSize = topQuote.askSize * depthFactor * (0.8 + this.random() * 0.4); asks.push({ price: askPrice, size: Math.round(askSize / micro.lotSize) * micro.lotSize, @@ -218,7 +232,7 @@ export class MarketSimulator { 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); + 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; @@ -227,7 +241,7 @@ export class MarketSimulator { 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); + 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; @@ -285,7 +299,7 @@ export class MarketSimulator { // Calculate available liquidity including hidden let availableSize = level.size; if (level.hiddenSize && this.config.modelHiddenLiquidity) { - availableSize += level.hiddenSize * Math.random(); // Hidden liquidity probabilistic + availableSize += level.hiddenSize * this.random(); // Seeded hidden liquidity } const fillSize = Math.min(remainingSize, availableSize); @@ -293,7 +307,7 @@ export class MarketSimulator { // Simulate latency - price might move if (this.config.latencyMs > 0 && orderType === 'market') { const priceMovement = microstructure - ? (((Math.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price + ? (((this.random() - 0.5) * microstructure.avgSpreadBps) / 10000) * level.price : 0; level.price += priceMovement * multiplier; } @@ -319,7 +333,7 @@ export class MarketSimulator { // 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(); + const darkPoolSize = remainingSize * darkPoolPct * this.random(); if (darkPoolSize > 0) { const midPrice = (at(orderbook.bids, 0).price + at(orderbook.asks, 0).price) / 2; diff --git a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts index 76e6fe1d..56e2a8af 100644 --- a/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts +++ b/apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts @@ -1,7 +1,8 @@ import { randomUUID } from 'node:crypto'; import type { TransactionCallback } from '@stock-bot/postgres'; import type { PostgresClient } from '@stock-bot/services'; -import type { BacktestRunResult } from '@stock-bot/types'; +import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types'; +import { validateDataset } from '../data/historical-dataset'; import { BacktestConfigSchema, type BacktestConfig } from '../types'; import { BacktestCancelledError } from './execution-engine'; import { @@ -126,6 +127,93 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { }); } + async loadDataset( + runId: string, + attemptId: string, + requestedHash?: string + ): Promise { + return this.ownedTransaction(runId, async client => { + const owned = await client.query( + `SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2 + AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`, + [runId, attemptId] + ); + if (!owned.rows[0]) { + throw new BacktestLeaseLostError('Execution lease lost'); + } + const hash = owned.rows[0].dataset_hash ?? requestedHash; + if (!hash) { + return null; + } + if (requestedHash && requestedHash !== hash) { + throw new BacktestConflictError('Run dataset is already frozen'); + } + const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [ + hash, + ]); + if (!saved.rows[0]) { + throw new Error('Frozen dataset not found'); + } + const dataset = validateDataset(saved.rows[0].payload); + if (dataset.manifest.hash !== hash) { + throw new Error('Stored dataset identity mismatch'); + } + const pinned = await client.query( + `UPDATE runs SET dataset_hash = $2 WHERE id = $1 + AND attempt_id = $3 AND lease_expires_at > clock_timestamp() + AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`, + [runId, hash, attemptId] + ); + if (!pinned.rows.length) { + throw new BacktestLeaseLostError('Execution lease lost while pinning dataset'); + } + return dataset; + }); + } + + async freezeDataset( + runId: string, + attemptId: string, + input: HistoricalDataset + ): Promise { + const dataset = validateDataset(input); + return this.ownedTransaction(runId, async client => { + const owned = await client.query( + `SELECT dataset_hash FROM runs WHERE id = $1 AND attempt_id = $2 + AND lease_expires_at > clock_timestamp() AND status IN ('running', 'paused') AND NOT cancel_requested`, + [runId, attemptId] + ); + if (!owned.rows[0]) { + throw new BacktestLeaseLostError('Execution lease lost'); + } + const hash = dataset.manifest.hash; + if (owned.rows[0].dataset_hash && owned.rows[0].dataset_hash !== hash) { + throw new BacktestConflictError('Run dataset is already frozen'); + } + await client.query( + 'INSERT INTO backtest_datasets (hash, payload) VALUES ($1, $2::jsonb) ON CONFLICT (hash) DO NOTHING', + [hash, JSON.stringify(dataset)] + ); + const saved = await client.query('SELECT payload FROM backtest_datasets WHERE hash = $1', [ + hash, + ]); + const frozen = validateDataset(saved.rows[0]?.payload); + if (frozen.manifest.hash !== hash) { + throw new Error('Stored dataset identity mismatch'); + } + const pinned = await client.query( + `UPDATE runs SET dataset_hash = $2 WHERE id = $1 + AND attempt_id = $3 AND lease_expires_at > clock_timestamp() + AND status IN ('running', 'paused') AND NOT cancel_requested RETURNING id`, + [runId, hash, attemptId] + ); + if (!pinned.rows.length) { + throw new BacktestLeaseLostError('Execution lease lost while pinning dataset'); + } + return frozen; + }); + } + /** Lock first, then evaluate the lease against real DB time. UPDATE can evaluate its * predicate before waiting on a row lock, even when the predicate uses clock_timestamp(). */ private ownedTransaction(runId: string, work: TransactionCallback): Promise { @@ -156,7 +244,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { `UPDATE runs SET status = $2::run_status, progress = CASE WHEN $2::run_status = 'completed' THEN 100 ELSE progress END, completed_at = $3, updated_at = NOW(), error = NULL, lease_expires_at = NULL WHERE id = $1 AND backtest_id = $4 AND status IN ('running', 'paused') - AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id`, + AND attempt_id = $5 AND lease_expires_at > clock_timestamp() AND NOT cancel_requested RETURNING id, dataset_hash`, [result.runId, result.status, result.completedAt, result.backtestId, attemptId] ); if (!updated.rows.length) { @@ -171,6 +259,9 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository { } throw new BacktestLeaseLostError('Execution lease lost'); } + if (!result.config.dataset || result.config.dataset.hash !== updated.rows[0]?.dataset_hash) { + throw new BacktestConflictError('Result does not reference the run frozen dataset'); + } await client.query( `INSERT INTO backtest_results (run_id, completed_at, metrics, equity_curve, ohlc_data, trades, positions, analytics, execution_time, configuration, engine) diff --git a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts index 7b2838c1..20a30451 100644 --- a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts +++ b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts @@ -1,4 +1,5 @@ import { EventEmitter } from 'node:events'; +import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; import { StorageService } from '../services/StorageService'; import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types'; import { @@ -47,7 +48,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti ); } - async runBacktest(input: BacktestConfig): Promise { + async runBacktest( + input: BacktestConfig, + dataset?: DatasetResolver + ): Promise { if (this.closing || this.active) { throw new Error( this.closing ? 'Native backtest engine is shutting down' : 'Backtest already running' @@ -79,7 +83,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti resolveNativeStrategies(config); // Race the read too: a slow database must not prevent cancellation. A late read // cannot spawn a worker after the run has been stopped. - const data = await Promise.race([this.loadData(config, signal), aborted]); + const data = await Promise.race([this.loadData(config, signal, dataset), aborted]); signal.throwIfAborted(); const raw = await this.worker.execute({ type: 'run', config, data }, signal, progress => { this.progress = progress.progress; @@ -108,36 +112,13 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti private async loadData( config: BacktestConfig, - signal: AbortSignal + signal: AbortSignal, + resolver?: DatasetResolver ): Promise { - const data: NativeWorkerRequest['data'] = []; - for (const symbol of config.symbols) { - signal.throwIfAborted(); - const bars = await this.storageService.getHistoricalBars( - symbol, - new Date(config.startDate), - new Date(config.endDate), - config.dataFrequency - ); - signal.throwIfAborted(); - if (!bars.length) { - throw new Error(`No historical data for ${symbol}`); - } - for (const bar of bars) { - data.push({ - 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, - }); - } - } - return data; + signal.throwIfAborted(); + const dataset = await resolveDataset(this.storageService, config, resolver); + signal.throwIfAborted(); + return dataset.bars.map(bar => ({ ...bar, type: 'bar' })); } private publish(event: string, data: unknown): void { diff --git a/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts b/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts index f2498f16..0b58cda5 100644 --- a/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts +++ b/apps/stock/orchestrator/src/backtest/RustBacktestEngine.ts @@ -1,4 +1,5 @@ import { BacktestEngine as RustEngine } from '@stock-bot/engine'; +import { resolveDataset } from '../data/historical-dataset'; import { StorageService } from '../services/StorageService'; import { RustStrategy } from '../strategies/RustStrategy'; import type { BacktestConfig, OrchestratorServices as IServiceContainer } from '../types'; @@ -34,11 +35,13 @@ export interface RustBacktestResult { finalPositions: Record; } +/** @deprecated Diagnostic wrapper only. Use BacktestRunner for durable, isolated execution. */ export class RustBacktestEngine { private engine: RustEngine; private container: IServiceContainer; private storageService: StorageService; private config: RustBacktestConfig; + private readonly request: BacktestConfig; constructor( container: IServiceContainer, @@ -47,6 +50,7 @@ export class RustBacktestEngine { ) { this.container = container; this.storageService = storageService; + this.request = config; // Convert config for Rust const rustConfig: RustBacktestConfig = { @@ -75,38 +79,8 @@ export class RustBacktestEngine { * Load historical data for the backtest */ async loadData(): Promise { - // 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); - } + const dataset = await resolveDataset(this.storageService, this.request); + this.engine.loadMarketData(dataset.bars.map(bar => ({ ...bar, type: 'bar' }))); } /** diff --git a/apps/stock/orchestrator/src/backtest/execution-engine.ts b/apps/stock/orchestrator/src/backtest/execution-engine.ts index b79b46c0..d79413b0 100644 --- a/apps/stock/orchestrator/src/backtest/execution-engine.ts +++ b/apps/stock/orchestrator/src/backtest/execution-engine.ts @@ -1,11 +1,15 @@ import type { EventEmitter } from 'node:events'; +import type { DatasetResolver } from '../data/historical-dataset'; import type { BacktestConfig } from '../types'; import type { NativeBacktestResult } from './native-result'; import type { BacktestResult } from './typescript-result'; /** The runner depends on execution capabilities, not backend implementations. */ export interface BacktestExecutionEngine extends Pick { - runBacktest(config: BacktestConfig): Promise; + runBacktest( + config: BacktestConfig, + dataset?: DatasetResolver + ): Promise; stopBacktest(): Promise; pauseBacktest(): Promise; resumeBacktest(): Promise; diff --git a/apps/stock/orchestrator/src/backtest/result.ts b/apps/stock/orchestrator/src/backtest/result.ts index 028841bb..3984d36c 100644 --- a/apps/stock/orchestrator/src/backtest/result.ts +++ b/apps/stock/orchestrator/src/backtest/result.ts @@ -1,5 +1,6 @@ import { z } from 'zod'; -import type { BacktestRunResult } from '@stock-bot/types'; +import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types'; +import { datasetManifestSchema } from '../data/historical-dataset'; import type { BacktestConfig } from '../types'; import type { NativeBacktestResult } from './native-result'; import type { RunIdentity } from './run-repository'; @@ -31,6 +32,7 @@ export const backtestRunResultSchema: z.ZodType = z.object({ slippage: finite, dataFrequency: z.string(), parameters: z.record(z.unknown()), + dataset: datasetManifestSchema.optional(), riskLimits: z .object({ maxPositionSize: finite, @@ -115,7 +117,8 @@ export function normalizeBacktestResult( config: BacktestConfig, identity: RunIdentity, executionTime: number, - cancelled: boolean + cancelled: boolean, + dataset?: HistoricalDatasetManifest ): BacktestRunResult { if (raw.status !== 'completed' && raw.status !== 'cancelled') { throw new Error( @@ -186,6 +189,7 @@ export function normalizeBacktestResult( slippage: config.slippage ?? 0.0001, dataFrequency: config.dataFrequency, parameters: config.config ?? {}, + dataset, riskLimits: config.riskLimits, strategies: config.strategies, }, diff --git a/apps/stock/orchestrator/src/backtest/run-repository.ts b/apps/stock/orchestrator/src/backtest/run-repository.ts index 5e498e3a..c929b49a 100644 --- a/apps/stock/orchestrator/src/backtest/run-repository.ts +++ b/apps/stock/orchestrator/src/backtest/run-repository.ts @@ -1,4 +1,4 @@ -import type { BacktestRunResult } from '@stock-bot/types'; +import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types'; import type { BacktestConfig } from '../types'; export interface RunIdentity { @@ -16,6 +16,16 @@ export interface BacktestRunRepository { load(runId: string): Promise<{ status: string; config: unknown } | null>; rejectPending(runId: string, error: string): Promise; heartbeat(runId: string, attemptId: string): Promise<{ cancelRequested: boolean }>; + loadDataset( + runId: string, + attemptId: string, + requestedHash?: string + ): Promise; + freezeDataset( + runId: string, + attemptId: string, + dataset: HistoricalDataset + ): Promise; complete(result: BacktestRunResult, attemptId: string): Promise; updateProgress( runId: string, @@ -51,6 +61,12 @@ export class UnavailableBacktestRunRepository implements BacktestRunRepository { async heartbeat(_runId: string, _attemptId: string): Promise<{ cancelRequested: boolean }> { return this.unavailable(); } + async loadDataset(): Promise { + return this.unavailable(); + } + async freezeDataset(): Promise { + return this.unavailable(); + } async complete(_result: BacktestRunResult, _attemptId: string): Promise { this.unavailable(); } diff --git a/apps/stock/orchestrator/src/data/DataManager.ts b/apps/stock/orchestrator/src/data/DataManager.ts index d95d5221..5ec36982 100644 --- a/apps/stock/orchestrator/src/data/DataManager.ts +++ b/apps/stock/orchestrator/src/data/DataManager.ts @@ -1,6 +1,7 @@ import { EventEmitter } from 'events'; import { defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; +import type { HistoricalDataset } from '@stock-bot/types'; import { at } from '@stock-bot/utils'; import { StorageService, type HistoricalBar } from '../services/StorageService'; import { type Bar, type MarketData } from '../types'; @@ -12,15 +13,6 @@ export interface DataResolution { milliseconds: number; } -export interface CorporateAction { - symbol: string; - date: Date; - type: 'split' | 'dividend' | 'spinoff'; - factor?: number; - amount?: number; - newSymbol?: string; -} - export interface DataQualityIssue { timestamp: Date; symbol: string; @@ -47,7 +39,6 @@ export class DataManager extends EventEmitter { private dataCache: Map = new Map(); private aggregatedCache: Map> = new Map(); - private corporateActions: Map = new Map(); private dataQualityIssues: DataQualityIssue[] = []; constructor(private storageService: StorageService) { @@ -76,18 +67,10 @@ export class DataManager extends EventEmitter { if (!data.length) { throw new Error(`No historical data for ${symbol}`); } + this.recordQualityWarnings(symbol, data); - // Apply corporate actions - const adjustedData = await this.applyCorporateActions(symbol, data, startDate, endDate); - - // Quality checks - const cleanedData = this.performQualityChecks(symbol, adjustedData); - if (!cleanedData.length) { - throw new Error(`No valid historical data for ${symbol}`); - } - - // Convert to MarketData format - const marketData = this.convertToMarketData(symbol, cleanedData); + // Storage owns validation and adjustment. Never interpolate or adjust a second time. + const marketData = this.convertToMarketData(symbol, data); result.set(symbol, marketData); this.dataCache.set(`${symbol}:${resolution}`, marketData); @@ -104,140 +87,31 @@ export class DataManager extends EventEmitter { return result; } - async applyCorporateActions( - symbol: string, - data: HistoricalBar[], - startDate: Date, - endDate: Date - ): Promise { - // Load corporate actions for the period - const actions = await this.loadCorporateActions(symbol, startDate, endDate); - if (actions.length === 0) { - return data; + /** Observations only: never repair, interpolate, drop, or re-adjust execution inputs. */ + inspectDataset(dataset: HistoricalDataset): void { + this.clearCache(); + for (const instrument of dataset.manifest.instruments) { + this.recordQualityWarnings( + instrument.id, + dataset.bars + .filter(bar => bar.symbol === instrument.id) + .map(bar => ({ ...bar, timestamp: new Date(bar.timestamp) })) + ); } - - // Sort actions by date (newest first) - actions.sort((a, b) => b.date.getTime() - a.date.getTime()); - - // Apply adjustments - return data.map(bar => { - const barDate = new Date(bar.timestamp); - const adjustedBar = { ...bar }; - - for (const action of actions) { - if (barDate < action.date) { - switch (action.type) { - case 'split': - if (action.factor) { - adjustedBar.open /= action.factor; - adjustedBar.high /= action.factor; - adjustedBar.low /= action.factor; - adjustedBar.close /= action.factor; - adjustedBar.volume *= action.factor; - } - break; - - case 'dividend': - if (action.amount) { - // Adjust for dividends (simplified) - const adjustment = 1 - action.amount / adjustedBar.close; - adjustedBar.open *= adjustment; - adjustedBar.high *= adjustment; - adjustedBar.low *= adjustment; - adjustedBar.close *= adjustment; - } - break; - } - } - } - - return adjustedBar; - }); } - performQualityChecks(symbol: string, data: HistoricalBar[]): HistoricalBar[] { - const cleaned: HistoricalBar[] = []; - - for (let i = 0; i < data.length; i++) { - const bar = at(data, i); - const prevBar = i > 0 ? data[i - 1] : null; - const issues: string[] = []; - - // Check for missing data - if (!bar.open || !bar.high || !bar.low || !bar.close || bar.volume === undefined) { - issues.push('Missing OHLCV data'); - } - - // Check for invalid prices - if (bar.low > bar.high) { - issues.push('Low > High'); - } - if (bar.open > bar.high || bar.open < bar.low) { - issues.push('Open outside High/Low range'); - } - if (bar.close > bar.high || bar.close < bar.low) { - issues.push('Close outside High/Low range'); - } - - // Check for zero or negative prices - if (bar.open <= 0 || bar.high <= 0 || bar.low <= 0 || bar.close <= 0) { - issues.push('Zero or negative prices'); - } - - // Check for extreme price movements (>20% in one bar) - if (prevBar) { - const priceChange = Math.abs((bar.close - prevBar.close) / prevBar.close); - if (priceChange > 0.2) { - issues.push(`Extreme price movement: ${(priceChange * 100).toFixed(1)}%`); - } - } - - // Check for volume spikes (>10x average) - if (i >= 20) { - const avgVolume = data.slice(i - 20, i).reduce((sum, b) => sum + b.volume, 0) / 20; - if (bar.volume > avgVolume * 10) { - issues.push('Volume spike detected'); - } - } - - // Handle issues - if (issues.length > 0) { - const severity = issues.some(issue => issue.includes('Missing') || issue.includes('Zero')) - ? 'error' - : 'warning'; - + private recordQualityWarnings(symbol: string, bars: HistoricalBar[]): void { + bars.forEach((bar, index) => { + const previous = bars[index - 1]; + if (previous && Math.abs((bar.close - previous.close) / previous.close) > 0.2) { this.dataQualityIssues.push({ timestamp: new Date(bar.timestamp), symbol, - issue: issues.join(', '), - severity, - details: bar, + issue: 'Price movement exceeds 20%; prices retained unchanged', + severity: 'warning', }); - - // For errors, try to interpolate or skip - if (severity === 'error') { - if (prevBar && i < data.length - 1) { - // Interpolate from surrounding bars - const nextBar = at(data, i + 1); - cleaned.push({ - ...bar, - open: (prevBar.close + nextBar.open) / 2, - high: Math.max(prevBar.high, nextBar.high) * 0.9, - low: Math.min(prevBar.low, nextBar.low) * 1.1, - close: (prevBar.close + nextBar.close) / 2, - volume: (prevBar.volume + nextBar.volume) / 2, - interpolated: true, - }); - } - // Skip if we can't interpolate - continue; - } } - - cleaned.push(bar); - } - - return cleaned; + }); } aggregateData(data: MarketData[], fromResolution: string, toResolution: string): Bar[] { @@ -397,22 +271,6 @@ export class DataManager extends EventEmitter { })); } - private async loadCorporateActions( - symbol: string, - startDate: Date, - endDate: Date - ): Promise { - // Check cache first - const cached = this.corporateActions.get(symbol); - if (cached) { - return cached.filter(action => action.date >= startDate && action.date <= endDate); - } - - // In real implementation, load from database - // For now, return empty array - return []; - } - getDataQualityReport(): { totalIssues: number; bySymbol: Record; diff --git a/apps/stock/orchestrator/src/data/historical-dataset.ts b/apps/stock/orchestrator/src/data/historical-dataset.ts new file mode 100644 index 00000000..be1ee5be --- /dev/null +++ b/apps/stock/orchestrator/src/data/historical-dataset.ts @@ -0,0 +1,231 @@ +import { createHash } from 'node:crypto'; +import { z } from 'zod'; +import { + parseInstrumentId, + validateHistoricalDataRequest, + type HistoricalDataPolicy, + type HistoricalDataset, +} from '@stock-bot/types'; +import type { StorageService } from '../services/StorageService'; +import type { BacktestConfig } from '../types'; + +export const instrumentIdSchema = z.string().refine(id => { + try { + parseInstrumentId(id); + return true; + } catch { + return false; + } +}, 'Use an exchange-qualified instrument ID, for example AAPL.US'); +export const historicalDataPolicySchema = z + .object({ + adjustment: z.enum(['raw', 'provider-adjusted']), + timestamp: z.enum(['utc-session-date', 'utc-instant']), + }) + .strict(); +export const datasetHashSchema = z.string().regex(/^[a-f0-9]{64}$/); +const positive = z.number().finite().positive(); +export const datasetBarSchema = z + .object({ + symbol: instrumentIdSchema, + timestamp: z.number().int().nonnegative(), + open: positive, + high: positive, + low: positive, + close: positive, + volume: z.number().finite().nonnegative(), + vwap: positive, + }) + .strict(); +export const datasetManifestSchema = z + .object({ + version: z.literal(1), + hash: datasetHashSchema, + instruments: z + .array( + z.object({ id: instrumentIdSchema, symbol: z.string(), exchange: z.string() }).strict() + ) + .min(1), + startDate: z.string().datetime(), + endDate: z.string().datetime(), + interval: z.enum(['1m', '5m', '15m', '1h', '1d']), + policy: historicalDataPolicySchema, + volumePolicy: z.literal('reported'), + qualityPolicy: z.literal('reject-invalid-no-interpolation'), + sources: z.array( + z + .object({ + instrumentId: instrumentIdSchema, + provider: z.enum(['eod', 'questdb', 'synthetic']), + revision: z.string().min(1), + }) + .strict() + ), + barCount: z.number().int().positive(), + }) + .strict(); +const datasetSchema = z + .object({ manifest: datasetManifestSchema, bars: z.array(datasetBarSchema).min(1) }) + .strict(); + +export type DatasetResolver = ( + load: () => Promise +) => Promise; +export function dataPolicy( + config: Pick +): HistoricalDataPolicy { + const policy = config.dataPolicy ?? { + adjustment: 'raw', + timestamp: config.dataFrequency === '1d' ? 'utc-session-date' : 'utc-instant', + }; + if ((config.dataFrequency === '1d') !== (policy.timestamp === 'utc-session-date')) { + throw new Error('Daily bars require utc-session-date; intraday bars require utc-instant'); + } + return policy; +} + +function hashDataset(dataset: HistoricalDataset): string { + const { hash: _hash, ...manifest } = dataset.manifest; + return createHash('sha256') + .update(JSON.stringify({ manifest, bars: dataset.bars })) + .digest('hex'); +} + +/** Parsing reconstructs a fixed property order before hashing, independent of JSONB key order. */ +export function validateDataset(input: unknown, config?: BacktestConfig): HistoricalDataset { + const dataset = datasetSchema.parse(input); + const m = dataset.manifest; + const ids = m.instruments.map(i => i.id); + const idSet = new Set(ids); + const sortedIds = [...ids].sort(); + const start = Date.parse(m.startDate), + end = Date.parse(m.endDate); + validateHistoricalDataRequest({ + symbols: ids, + startDate: m.startDate, + endDate: m.endDate, + dataFrequency: m.interval, + dataPolicy: m.policy, + datasetHash: m.hash, + }); + if ( + ids.some((id, i) => id !== sortedIds[i]) || + m.instruments.some(i => JSON.stringify(i) !== JSON.stringify(parseInstrumentId(i.id))) || + m.sources.length !== ids.length || + m.sources.some((s, i) => s.instrumentId !== ids[i]) || + m.barCount !== dataset.bars.length + ) { + throw new Error('Invalid dataset manifest'); + } + const seen = new Set(); + let previous: HistoricalDataset['bars'][number] | undefined; + for (const bar of dataset.bars) { + if ( + !idSet.has(bar.symbol) || + bar.timestamp < start || + bar.timestamp >= end || + bar.high < Math.max(bar.open, bar.close) || + bar.low > Math.min(bar.open, bar.close) || + (m.policy.timestamp === 'utc-session-date' && bar.timestamp % 86400000 !== 0) || + (previous && + (bar.timestamp < previous.timestamp || + (bar.timestamp === previous.timestamp && bar.symbol <= previous.symbol))) + ) { + throw new Error('Invalid or unordered dataset bars'); + } + seen.add(bar.symbol); + previous = bar; + } + if (seen.size !== ids.length || hashDataset(dataset) !== m.hash) { + throw new Error('Dataset hash/content mismatch'); + } + if ( + config && + (JSON.stringify([...config.symbols].sort()) !== JSON.stringify(ids) || + new Date(config.startDate).toISOString() !== m.startDate || + new Date(config.endDate).toISOString() !== m.endDate || + config.dataFrequency !== m.interval || + JSON.stringify(dataPolicy(config)) !== JSON.stringify(m.policy) || + (config.datasetHash && config.datasetHash !== m.hash)) + ) { + throw new Error('Frozen dataset does not match the backtest request'); + } + return dataset; +} + +export async function loadDataset( + storage: StorageService, + config: BacktestConfig +): Promise { + const instruments = [...config.symbols].sort().map(parseInstrumentId); + const policy = dataPolicy(config); + const bars: HistoricalDataset['bars'] = []; + const sources: HistoricalDataset['manifest']['sources'] = []; + for (const instrument of instruments) { + const rows = await storage.getHistoricalBars( + instrument.id, + new Date(config.startDate), + new Date(config.endDate), + config.dataFrequency, + policy + ); + const source = rows[0]?.source; + if (!source || rows.some(row => row.source !== source)) { + throw new Error('Historical source provenance is missing or mixed'); + } + sources.push({ + instrumentId: instrument.id, + provider: source, + revision: 'historical-normalization-v1', + }); + for (const bar of rows) { + bars.push({ + symbol: instrument.id, + timestamp: bar.timestamp.getTime(), + 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, + }); + } + } + bars.sort( + (a, b) => a.timestamp - b.timestamp || (a.symbol < b.symbol ? -1 : a.symbol > b.symbol ? 1 : 0) + ); + const dataset: HistoricalDataset = { + manifest: { + version: 1, + hash: '0'.repeat(64), + instruments, + startDate: new Date(config.startDate).toISOString(), + endDate: new Date(config.endDate).toISOString(), + interval: config.dataFrequency, + policy, + volumePolicy: 'reported', + qualityPolicy: 'reject-invalid-no-interpolation', + sources, + barCount: bars.length, + }, + bars, + }; + // Canonicalize before hashing, including metadata key order. + const canonical = datasetSchema.parse(dataset); + canonical.manifest.hash = hashDataset(canonical); + return validateDataset(canonical, config); +} + +export async function resolveDataset( + storage: StorageService, + config: BacktestConfig, + resolver?: DatasetResolver +) { + if (config.datasetHash && !resolver) { + throw new Error('Dataset replay requires the durable backtest runner'); + } + return validateDataset( + await (resolver ? resolver(() => loadDataset(storage, config)) : loadDataset(storage, config)), + config + ); +} diff --git a/apps/stock/orchestrator/src/services/StorageService.ts b/apps/stock/orchestrator/src/services/StorageService.ts index cb1bd9b6..1227e8cb 100644 --- a/apps/stock/orchestrator/src/services/StorageService.ts +++ b/apps/stock/orchestrator/src/services/StorageService.ts @@ -4,6 +4,7 @@ import type { PostgresClient, QuestDBClient, } from '@stock-bot/services'; +import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types'; import type { MarketData, ModeConfig, PerformanceMetrics } from '../types'; export interface HistoricalBar { @@ -16,6 +17,8 @@ export interface HistoricalBar { volume: number; vwap?: number; interpolated?: boolean; + source?: 'eod' | 'questdb' | 'synthetic'; + adjustedClose?: number; } export class StorageService { private questdb: QuestDBClient | null = null; @@ -87,6 +90,7 @@ export class StorageService { for (const item of data) { try { + parseInstrumentId(item.data.symbol); switch (item.type) { case 'quote': await this.insertTimeSeries('quotes', { @@ -166,8 +170,13 @@ export class StorageService { symbol: string, startTime: Date, endTime: Date, - interval = '1m' + interval = '1m', + policy: HistoricalDataPolicy = { + adjustment: 'raw', + timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant', + } ): Promise { + parseInstrumentId(symbol); if ( !Number.isFinite(startTime.getTime()) || !Number.isFinite(endTime.getTime()) || @@ -178,9 +187,24 @@ export class StorageService { if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) { throw new Error('Unsupported historical interval'); } + if ( + (interval === '1d') !== (policy.timestamp === 'utc-session-date') || + (interval === '1d' && + (startTime.getTime() % 86400000 !== 0 || endTime.getTime() % 86400000 !== 0)) + ) { + throw new Error( + 'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants' + ); + } const rows = await this.readHistoricalBars(symbol, startTime, endTime, interval); const bars = rows .map(row => { + if (row.symbol !== symbol) { + throw new Error(`Historical instrument identity mismatch for ${symbol}`); + } + if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) { + throw new Error('Historical instants require an explicit UTC offset'); + } const timestamp = new Date(row.timestamp); const numeric = (value: unknown) => typeof value === 'number' @@ -188,22 +212,44 @@ export class StorageService { : typeof value === 'string' && value.trim() ? Number(value) : NaN; - const open = numeric(row.open), + let open = numeric(row.open), high = numeric(row.high), low = numeric(row.low), - close = numeric(row.close), - volume = numeric(row.volume); + close = numeric(row.close); + const volume = numeric(row.volume); if ( !Number.isFinite(timestamp.getTime()) || ![open, high, low, close, volume].every(Number.isFinite) || low <= 0 || high < Math.max(open, close) || low > Math.min(open, close) || - volume < 0 + volume < 0 || + (interval === '1d' && timestamp.getTime() % 86400000 !== 0) ) { throw new Error(`Invalid historical OHLCV data for ${symbol}`); } - return { ...row, symbol, timestamp, open, high, low, close, volume }; + let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap); + if (policy.adjustment === 'provider-adjusted') { + const adjustedClose = numeric(row.adjustedClose); + if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) { + throw new Error(`Provider-adjusted prices unavailable for ${symbol}`); + } + const factor = adjustedClose / close; + open *= factor; + high *= factor; + low *= factor; + close = adjustedClose; + if (vwap !== undefined) { + vwap *= factor; + } + } + if ( + ![open, high, low, close].every(value => Number.isFinite(value) && value > 0) || + (vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0)) + ) { + throw new Error(`Invalid adjusted historical data for ${symbol}`); + } + return { ...row, symbol, timestamp, open, high, low, close, volume, vwap }; }) .filter(bar => bar.timestamp >= startTime && bar.timestamp < endTime) .sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()); @@ -236,24 +282,30 @@ export class StorageService { `SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`, [symbol, startTime, endTime] ); - return result.rows; + return result.rows.map(row => ({ ...row, source: 'questdb' })); } if (this.mongodb) { if (interval !== '1d') { throw new Error('Daily provider storage cannot satisfy an intraday request'); } + const identity = parseInstrumentId(symbol); const prices = await this.mongodb.find<{ + symbol: string; + exchange: string; + eodSearchCode: string; + providerExchange?: string; date: string; open: number; high: number; low: number; close: number; volume: number; + adjustedClose?: number; }>( 'eodPrices', { - symbol, + eodSearchCode: identity.id, date: { $gte: startTime.toISOString().slice(0, 10), $lt: endTime.toISOString().slice(0, 10), @@ -261,22 +313,43 @@ export class StorageService { }, { sort: { date: 1 } } ); - return prices.map(price => ({ - symbol, - timestamp: new Date(price.date), - open: price.open, - high: price.high, - low: price.low, - close: price.close, - volume: price.volume, - })); + return prices.map(price => { + if ( + price.eodSearchCode !== identity.id || + price.symbol !== identity.symbol || + (price.providerExchange !== undefined && price.providerExchange !== identity.exchange) + ) { + throw new Error(`Historical instrument identity mismatch for ${symbol}`); + } + if ( + !/^\d{4}-\d{2}-\d{2}$/.test(price.date) || + !Number.isFinite(Date.parse(price.date)) || + new Date(price.date).toISOString().slice(0, 10) !== price.date + ) { + throw new Error(`Invalid historical session date for ${symbol}`); + } + return { + symbol, + timestamp: new Date(price.date), + open: price.open, + high: price.high, + low: price.low, + close: price.close, + volume: price.volume, + adjustedClose: price.adjustedClose, + source: 'eod' as const, + }; + }); } if (!this.options.allowSyntheticData) { throw new Error( 'No historical data store configured; synthetic data requires explicit opt-in' ); } - return this.generateMockBars(symbol, startTime, endTime, interval); + return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({ + ...bar, + source: 'synthetic', + })); } private generateMockBars( diff --git a/apps/stock/orchestrator/src/types.ts b/apps/stock/orchestrator/src/types.ts index c7c18faf..66055ecf 100644 --- a/apps/stock/orchestrator/src/types.ts +++ b/apps/stock/orchestrator/src/types.ts @@ -1,4 +1,9 @@ import { z } from 'zod'; +import { + datasetHashSchema, + historicalDataPolicySchema, + instrumentIdSchema, +} from './data/historical-dataset'; // Trading modes export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']); @@ -20,7 +25,12 @@ export const BacktestConfigSchema = z.object({ config: z.record(z.unknown()).optional(), startDate: z.string().datetime(), endDate: z.string().datetime(), - symbols: z.array(z.string().min(1)).min(1), + symbols: z + .array(instrumentIdSchema) + .min(1) + .refine(ids => new Set(ids).size === ids.length, 'Duplicate instruments'), + dataPolicy: historicalDataPolicySchema.optional(), + datasetHash: datasetHashSchema.optional(), initialCapital: z.number().positive(), dataFrequency: z.enum(['1m', '5m', '15m', '1h', '1d']), strategy: z.string(), diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 51bb2beb..78d9443d 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -46,7 +46,8 @@ export async function runMigrations(container: IServiceContainer): Promise (f.startsWith('001_') || f === '09-backtest-run-contract.sql' || f === '10-durable-backtest-dispatch.sql' || - f === '11-simulation-execution-ledger.sql') + f === '11-simulation-execution-ledger.sql' || + f === '12-historical-datasets.sql') ) // Explicit additive migration allowlist; never replay destructive init migrations .sort(); diff --git a/apps/stock/web-api/src/routes/backtest.routes.ts b/apps/stock/web-api/src/routes/backtest.routes.ts index 3bd35aa0..1755eefe 100644 --- a/apps/stock/web-api/src/routes/backtest.routes.ts +++ b/apps/stock/web-api/src/routes/backtest.routes.ts @@ -1,97 +1,104 @@ -import { Hono } from 'hono'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { BacktestService } from '../services/backtest.service'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('backtest-routes'); - -export function createBacktestRoutes(container: IServiceContainer) { - const backtestRoutes = new Hono(); - const backtestService = new BacktestService(container); - - // Create a new backtest - backtestRoutes.post('/api/backtests', async (c) => { - try { - const body = await c.req.json(); - - // Validate required fields - if (!body.strategy || !body.symbols || !body.startDate || !body.endDate) { - return c.json({ - error: 'Missing required fields: strategy, symbols, startDate, endDate' - }, 400); - } - - const backtest = await backtestService.createBacktest({ - ...body, - initialCapital: body.initialCapital || 100000, - }); - - return c.json(backtest, 201); - } catch (error) { - logger.error('Failed to create backtest', { error }); - return c.json({ error: 'Failed to create backtest' }, 500); - } - }); - - // Get backtest status - backtestRoutes.get('/api/backtests/:id', async (c) => { - try { - const id = c.req.param('id'); - const backtest = await backtestService.getBacktest(id); - - if (!backtest) { - return c.json({ error: 'Backtest not found' }, 404); - } - - return c.json(backtest); - } catch (error) { - logger.error('Failed to get backtest', { error }); - return c.json({ error: 'Failed to get backtest' }, 500); - } - }); - - // Get backtest results - backtestRoutes.get('/api/backtests/:id/results', async (c) => { - try { - const id = c.req.param('id'); - const results = await backtestService.getBacktestResults(id); - - if (!results) { - return c.json({ error: 'Results not found' }, 404); - } - - return c.json(results); - } catch (error) { - logger.error('Failed to get results', { error }); - return c.json({ error: 'Failed to get results' }, 500); - } - }); - - // List all backtests - backtestRoutes.get('/api/backtests', async (c) => { - try { - const limit = Number(c.req.query('limit')) || 50; - const offset = Number(c.req.query('offset')) || 0; - - const backtests = await backtestService.listBacktests({ limit, offset }); - return c.json(backtests); - } catch (error) { - logger.error('Failed to list backtests', { error }); - return c.json({ error: 'Failed to list backtests' }, 500); - } - }); - - // Cancel a backtest - backtestRoutes.post('/api/backtests/:id/cancel', async (c) => { - try { - const id = c.req.param('id'); - await backtestService.cancelBacktest(id); - return c.json({ message: 'Backtest cancelled' }); - } catch (error) { - logger.error('Failed to cancel backtest', { error }); - return c.json({ error: 'Failed to cancel backtest' }, 500); - } - }); - - return backtestRoutes; -} \ No newline at end of file +import { Hono } from 'hono'; +import type { IServiceContainer } from '@stock-bot/handlers'; +import { getLogger } from '@stock-bot/logger'; +import { HistoricalDataRequestError } from '@stock-bot/types'; +import { BacktestService } from '../services/backtest.service'; + +const logger = getLogger('backtest-routes'); + +export function createBacktestRoutes(container: IServiceContainer) { + const backtestRoutes = new Hono(); + const backtestService = new BacktestService(container); + + // Create a new backtest + backtestRoutes.post('/api/backtests', async c => { + try { + const body = await c.req.json(); + + // Validate required fields + if (!body.strategy || !body.symbols || !body.startDate || !body.endDate) { + return c.json( + { + error: 'Missing required fields: strategy, symbols, startDate, endDate', + }, + 400 + ); + } + + const backtest = await backtestService.createBacktest({ + ...body, + initialCapital: body.initialCapital || 100000, + }); + + return c.json(backtest, 201); + } catch (error) { + logger.error('Failed to create backtest', { error }); + if (error instanceof HistoricalDataRequestError) { + return c.json({ error: error.message }, 400); + } + return c.json({ error: 'Failed to create backtest' }, 500); + } + }); + + // Get backtest status + backtestRoutes.get('/api/backtests/:id', async c => { + try { + const id = c.req.param('id'); + const backtest = await backtestService.getBacktest(id); + + if (!backtest) { + return c.json({ error: 'Backtest not found' }, 404); + } + + return c.json(backtest); + } catch (error) { + logger.error('Failed to get backtest', { error }); + return c.json({ error: 'Failed to get backtest' }, 500); + } + }); + + // Get backtest results + backtestRoutes.get('/api/backtests/:id/results', async c => { + try { + const id = c.req.param('id'); + const results = await backtestService.getBacktestResults(id); + + if (!results) { + return c.json({ error: 'Results not found' }, 404); + } + + return c.json(results); + } catch (error) { + logger.error('Failed to get results', { error }); + return c.json({ error: 'Failed to get results' }, 500); + } + }); + + // List all backtests + backtestRoutes.get('/api/backtests', async c => { + try { + const limit = Number(c.req.query('limit')) || 50; + const offset = Number(c.req.query('offset')) || 0; + + const backtests = await backtestService.listBacktests({ limit, offset }); + return c.json(backtests); + } catch (error) { + logger.error('Failed to list backtests', { error }); + return c.json({ error: 'Failed to list backtests' }, 500); + } + }); + + // Cancel a backtest + backtestRoutes.post('/api/backtests/:id/cancel', async c => { + try { + const id = c.req.param('id'); + await backtestService.cancelBacktest(id); + return c.json({ message: 'Backtest cancelled' }); + } catch (error) { + logger.error('Failed to cancel backtest', { error }); + return c.json({ error: 'Failed to cancel backtest' }, 500); + } + }); + + return backtestRoutes; +} diff --git a/apps/stock/web-api/src/routes/backtests-v2.routes.ts b/apps/stock/web-api/src/routes/backtests-v2.routes.ts index 420660d4..880de594 100644 --- a/apps/stock/web-api/src/routes/backtests-v2.routes.ts +++ b/apps/stock/web-api/src/routes/backtests-v2.routes.ts @@ -1,6 +1,7 @@ import { Hono } from 'hono'; import type { IServiceContainer } from '@stock-bot/handlers'; import { getLogger } from '@stock-bot/logger'; +import { HistoricalDataRequestError } from '@stock-bot/types'; import { BacktestServiceV2 } from '../services/backtest-v2.service'; const logger = getLogger('backtests-v2-routes'); @@ -43,6 +44,9 @@ export function createBacktestV2Routes(container: IServiceContainer) { return c.json(backtest, 201); } catch (error) { logger.error('Failed to create backtest', error); + if (error instanceof HistoricalDataRequestError) { + return c.json({ error: error.message }, 400); + } return c.json({ error: 'Failed to create backtest' }, 500); } }); @@ -57,6 +61,9 @@ export function createBacktestV2Routes(container: IServiceContainer) { return c.json(backtest); } catch (error) { logger.error('Failed to update backtest', error); + if (error instanceof HistoricalDataRequestError) { + return c.json({ error: error.message }, 400); + } return c.json({ error: 'Failed to update backtest' }, 500); } }); @@ -93,6 +100,9 @@ export function createBacktestV2Routes(container: IServiceContainer) { return c.json(run, 202); } catch (error) { logger.error('Failed to create run', error); + if (error instanceof HistoricalDataRequestError) { + return c.json({ error: error.message }, 400); + } return c.json({ error: 'Failed to create run' }, 500); } }); diff --git a/apps/stock/web-api/src/services/backtest-v2.service.ts b/apps/stock/web-api/src/services/backtest-v2.service.ts index 6d2fb3b9..9bf21b00 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -4,7 +4,7 @@ import { authenticatedServiceFetch } from '@stock-bot/di'; import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import { requireServices, type IServiceContainer } from '@stock-bot/services'; -import type { BacktestRunResult } from '@stock-bot/types'; +import { validateHistoricalDataRequest, type BacktestRunResult } from '@stock-bot/types'; import { getWebSocketHandler } from '../websocket/run-updates'; import type { WebSocketHandler } from '../websocket/run-updates'; @@ -78,6 +78,12 @@ export class BacktestServiceV2 { request: BacktestRequest, options: { autoStart?: boolean } = {} ): Promise { + validateHistoricalDataRequest({ + ...request, + dataFrequency: request.config?.dataFrequency, + dataPolicy: request.config?.dataPolicy, + datasetHash: request.config?.datasetHash, + }); const backtestId = uuidv4(); const result = await this.container.postgres.query( @@ -130,6 +136,19 @@ export class BacktestServiceV2 { } async updateBacktest(id: string, request: Partial): Promise { + const existing = await this.getBacktest(id); + if (!existing) { + return null; + } + const next = { ...existing, ...request }; + validateHistoricalDataRequest({ + symbols: next.symbols, + startDate: new Date(next.startDate).toISOString(), + endDate: new Date(next.endDate).toISOString(), + dataFrequency: next.config?.dataFrequency, + dataPolicy: next.config?.dataPolicy, + datasetHash: next.config?.datasetHash, + }); const updates: string[] = []; const values: unknown[] = []; let paramCount = 1; @@ -209,6 +228,14 @@ export class BacktestServiceV2 { throw new Error('Backtest not found'); } const definition = this.mapBacktest(at(parent.rows, 0)); + validateHistoricalDataRequest({ + symbols: definition.symbols, + startDate: definition.startDate.toISOString(), + endDate: definition.endDate.toISOString(), + dataFrequency: definition.config.dataFrequency, + dataPolicy: definition.config.dataPolicy, + datasetHash: definition.config.datasetHash, + }); const multiplier = request.speedMultiplier ?? null; if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) { throw new Error('Speed multiplier must be positive or null'); @@ -225,6 +252,8 @@ export class BacktestServiceV2 { initialCapital: definition.initialCapital, config: definition.config, riskLimits: definition.config.riskLimits, + dataPolicy: definition.config.dataPolicy, + datasetHash: definition.config.datasetHash, dataFrequency: definition.config.dataFrequency ?? '1d', commission: definition.config.commission ?? 0.001, slippage: definition.config.slippage ?? 0.0001, diff --git a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx index 0194b368..7fb69c67 100644 --- a/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx +++ b/apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx @@ -138,13 +138,21 @@ export function BacktestDetailPageV2() { endDate: config.endDate.toISOString().split('T')[0], initialCapital: config.initialCapital, config: { + ...backtest?.config, commission: config.commission, slippage: config.slippage, speedMultiplier: config.speedMultiplier, + dataPolicy: { + adjustment: config.priceAdjustment ?? 'raw', + timestamp: + !backtest?.config?.dataFrequency || backtest.config.dataFrequency === '1d' + ? 'utc-session-date' + : 'utc-instant', + }, }, }); }, - [id, updateBacktest] + [id, updateBacktest, backtest] ); // Handle new run creation @@ -186,6 +194,13 @@ export function BacktestDetailPageV2() { speedMultiplier: 1, commission: Number(backtest.config?.commission ?? 0.001), slippage: Number(backtest.config?.slippage ?? 0.0001), + priceAdjustment: + backtest.config?.dataPolicy && + typeof backtest.config.dataPolicy === 'object' && + 'adjustment' in backtest.config.dataPolicy && + backtest.config.dataPolicy.adjustment === 'provider-adjusted' + ? 'provider-adjusted' + : 'raw', } : undefined; diff --git a/apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx b/apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx index e63ec65d..13f85353 100644 --- a/apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx +++ b/apps/stock/web-app/src/features/backtest/components/BacktestConfiguration.tsx @@ -1,268 +1,295 @@ -import { useState, useEffect } from 'react'; -import type { BacktestConfig } from '../types'; - -interface BacktestConfigurationProps { - onSubmit: (config: BacktestConfig) => void; - disabled?: boolean; - initialConfig?: BacktestConfig; -} - -export function BacktestConfiguration({ onSubmit, disabled, initialConfig }: BacktestConfigurationProps) { - const [formData, setFormData] = useState(initialConfig || { - name: '', - startDate: new Date(new Date().setMonth(new Date().getMonth() - 6)), // 6 months ago - endDate: new Date(), - initialCapital: 100000, - symbols: [], - strategy: 'sma-crossover', - speedMultiplier: 1, - commission: 0.001, // 0.1% - slippage: 0.0005, // 0.05% - }); - - const [symbolInput, setSymbolInput] = useState(''); - - useEffect(() => { - if (initialConfig) { - setFormData(initialConfig); - } - }, [initialConfig]); - - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault(); - if (formData.symbols.length === 0) { - alert('Please add at least one symbol'); - return; - } - onSubmit(formData); - }; - - const handleChange = (e: React.ChangeEvent) => { - const { name, value, type } = e.target; - setFormData(prev => ({ - ...prev, - [name]: type === 'number' ? parseFloat(value) : - type === 'date' ? new Date(value) : value - })); - }; - - const handleAddSymbol = () => { - const symbol = symbolInput.trim().toUpperCase(); - if (symbol && !formData.symbols.includes(symbol)) { - setFormData(prev => ({ - ...prev, - symbols: [...prev.symbols, symbol] - })); - setSymbolInput(''); - } - }; - - const handleRemoveSymbol = (symbol: string) => { - setFormData(prev => ({ - ...prev, - symbols: prev.symbols.filter(s => s !== symbol) - })); - }; - - const formatDate = (date: Date) => { - return date.toISOString().split('T')[0]; - }; - - return ( -
-
- - -
- -
-
- - -
- -
- - -
-
- -
- - -
- -
- -
- setSymbolInput(e.target.value)} - onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddSymbol())} - placeholder="AAPL" - className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - disabled={disabled} - /> - -
-
- {formData.symbols.map(symbol => ( - - {symbol} - - - ))} -
-
- -
- - -

- {formData.strategy === 'sma-crossover' && 'Trades on 10/20 day moving average crossovers'} - {formData.strategy === 'mean-reversion' && 'Trades when price deviates from mean by 2+ std devs'} - {formData.strategy === 'ml-enhanced' && 'Uses machine learning for signal generation'} - {formData.strategy === 'momentum' && 'Follows strong price trends'} - {formData.strategy === 'pairs-trading' && 'Trades correlated asset pairs'} -

-
- -
-
- - setFormData(prev => ({ ...prev, commission: parseFloat(e.target.value) / 100 }))} - min="0" - step="0.01" - className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - disabled={disabled} - /> -
- -
- - setFormData(prev => ({ ...prev, slippage: parseFloat(e.target.value) / 100 }))} - min="0" - step="0.01" - className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - disabled={disabled} - /> -
-
- -
- - -

1x = real-time, 10x = 10x faster

-
- - -
- ); -} \ No newline at end of file +import { useEffect, useState } from 'react'; +import { parseInstrumentId } from '@stock-bot/types'; +import type { BacktestConfig } from '../types'; + +interface BacktestConfigurationProps { + onSubmit: (config: BacktestConfig) => void; + disabled?: boolean; + initialConfig?: BacktestConfig; +} + +export function BacktestConfiguration({ + onSubmit, + disabled, + initialConfig, +}: BacktestConfigurationProps) { + const [formData, setFormData] = useState( + initialConfig || { + name: '', + startDate: new Date(new Date().setMonth(new Date().getMonth() - 6)), // 6 months ago + endDate: new Date(), + initialCapital: 100000, + symbols: [], + strategy: 'sma-crossover', + speedMultiplier: 1, + commission: 0.001, // 0.1% + slippage: 0.0005, // 0.05% + } + ); + + const [symbolInput, setSymbolInput] = useState(''); + + useEffect(() => { + if (initialConfig) { + setFormData(initialConfig); + } + }, [initialConfig]); + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault(); + if (formData.symbols.length === 0) { + alert('Please add at least one symbol'); + return; + } + onSubmit(formData); + }; + + const handleChange = (e: React.ChangeEvent) => { + const { name, value, type } = e.target; + setFormData(prev => ({ + ...prev, + [name]: type === 'number' ? parseFloat(value) : type === 'date' ? new Date(value) : value, + })); + }; + + const handleAddSymbol = () => { + const symbol = symbolInput.trim().toUpperCase(); + try { + parseInstrumentId(symbol); + } catch { + alert('Enter an exchange-qualified ID, for example AAPL.US'); + return; + } + if (symbol && !formData.symbols.includes(symbol)) { + setFormData(prev => ({ + ...prev, + symbols: [...prev.symbols, symbol], + })); + setSymbolInput(''); + } + }; + + const handleRemoveSymbol = (symbol: string) => { + setFormData(prev => ({ + ...prev, + symbols: prev.symbols.filter(s => s !== symbol), + })); + }; + + const formatDate = (date: Date) => { + return date.toISOString().split('T')[0]; + }; + + return ( +
+
+ + +
+ +
+ + +
+ +
+
+ + +
+ +
+ + +
+
+ +
+ + +
+ +
+ +
+ setSymbolInput(e.target.value)} + onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), handleAddSymbol())} + placeholder="AAPL.US" + className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + disabled={disabled} + /> + +
+
+ {formData.symbols.map(symbol => ( + + {symbol} + + + ))} +
+
+ +
+ + +

+ {formData.strategy === 'sma-crossover' && 'Trades on 10/20 day moving average crossovers'} + {formData.strategy === 'mean-reversion' && + 'Trades when price deviates from mean by 2+ std devs'} + {formData.strategy === 'ml-enhanced' && 'Uses machine learning for signal generation'} + {formData.strategy === 'momentum' && 'Follows strong price trends'} + {formData.strategy === 'pairs-trading' && 'Trades correlated asset pairs'} +

+
+ +
+
+ + + setFormData(prev => ({ ...prev, commission: parseFloat(e.target.value) / 100 })) + } + min="0" + step="0.01" + className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + disabled={disabled} + /> +
+ +
+ + + setFormData(prev => ({ ...prev, slippage: parseFloat(e.target.value) / 100 })) + } + min="0" + step="0.01" + className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" + disabled={disabled} + /> +
+
+ +
+ + +

1x = real-time, 10x = 10x faster

+
+ + +
+ ); +} diff --git a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx index d26c2754..5c165944 100644 --- a/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx +++ b/apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog.tsx @@ -1,5 +1,6 @@ import { XMarkIcon } from '@heroicons/react/24/solid'; import { useState } from 'react'; +import { parseInstrumentId } from '@stock-bot/types'; import type { Backtest } from '../services/backtestApiV2'; interface CreateBacktestDialogProps { @@ -11,12 +12,13 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog const [formData, setFormData] = useState({ name: '', strategy: 'moving-average', - symbols: ['AAPL'], + symbols: ['AAPL.US'], startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10), endDate: new Date().toISOString().slice(0, 10), initialCapital: 100000, commission: 0, slippage: 0, + priceAdjustment: 'raw' as 'raw' | 'provider-adjusted', }); const [symbolInput, setSymbolInput] = useState(''); @@ -31,12 +33,22 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog onCreate({ ...formData, - config: { commission: formData.commission, slippage: formData.slippage }, + config: { + commission: formData.commission, + slippage: formData.slippage, + dataPolicy: { adjustment: formData.priceAdjustment, timestamp: 'utc-session-date' }, + }, }); }; const addSymbol = () => { const symbol = symbolInput.trim().toUpperCase(); + try { + parseInstrumentId(symbol); + } catch { + alert('Enter an exchange-qualified ID, for example AAPL.US'); + return; + } if (symbol && !formData.symbols.includes(symbol)) { setFormData({ ...formData, symbols: [...formData.symbols, symbol] }); setSymbolInput(''); @@ -102,7 +114,7 @@ export function CreateBacktestDialog({ onClose, onCreate }: CreateBacktestDialog onChange={e => setSymbolInput(e.target.value)} onKeyPress={e => e.key === 'Enter' && (e.preventDefault(), addSymbol())} className="flex-1 px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500" - placeholder="Enter symbol (e.g., AAPL)" + placeholder="Instrument ID (e.g., AAPL.US)" />