diff --git a/README.md b/README.md index da75af38..9d43febf 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,66 @@ 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. +## Simulation order execution + +`ExecutionService` is the runtime order gateway for REST, Socket.IO (when enabled), and +TypeScript strategies. `PaperTradingManager` is a compatibility facade, not a separate +simulator. Strategies consume only the ordered batch stream; individual-event broadcasts +cannot submit the same order a second time. Each event is delivered serially, including +awaited order/fill notifications before the next event. The TypeScript backtest uses this +same gateway with an explicit run-local repository; it does not write the paper ledger. +The isolated native backtest retains its own Rust loop and enforces its configured risk +limits before submission. Its projected notional and accounting rules have golden tests. + +Paper execution requires PostgreSQL and additive migration +`database/postgres/init/11-simulation-execution-ledger.sql` (included in the web API migration +allowlist). Start the migrated web API before the orchestrator. New `simulation_accounts`, +`simulation_orders`, `simulation_fills`, and `simulation_events` tables are account-scoped. +The account snapshot (cash, positions, quotes, strategy quantities, risk state), order +reports, and uniquely identified fills commit on one checked-out connection under an +account row lock. No acceptance or fill notification is published before commit. +The snapshot is a bounded-by-instruments projection; normalized order/fill/event history is +kept separately. Historical rows in the old `orders`/`fills`/`positions` tables are preserved +but are **not automatically adopted into the new ledger**. Reconcile legacy paper holdings +explicitly before continuing an old account; this migration never infers an opening balance. +Unused direct financial writers were removed from `StorageService`. + +Paper configuration accepts `accountId` (default `paper-default`), `riskLimits`, `commission`, +`slippage`, and `maxQuoteAgeMs` (default 60000). Restarting the same account restores cash, +positions, per-strategy quantities, consumed quote liquidity, and unfilled orders; it never +resets capital. A different starting capital requires an explicit new account ID. Strategy +indicator state is not checkpointed; strategies still need their normal warm-up. Pending +orders retain the commission/slippage policy under which they were accepted. + +Order HTTP/Socket.IO submissions require a nonempty `clientOrderId`. Retrying an identical +request returns the existing order; reuse with different fields is a conflict (HTTP 409). +Strategies derive stable IDs from the strategy and source event. Supply a stable, unique +`eventId` on market data; identical replay is ignored, conflicting reuse is rejected. Without +an ID, a deterministic hash of the canonical event is used (identical same-timestamp payloads +are indistinguishable). Source events commit before strategy callbacks; a crash in that gap +can omit a signal, so this is not an exactly-once strategy-state recovery guarantee. + +The deterministic simulator supports market/limit orders and DAY/GTC/IOC/FOK. Quote depth +is consumed across orders, partial fills await fresh events, and limit orders never fill +through their limit. DAY expiry is UTC/event-driven, not exchange-calendar-aware. Missing, +stale, future, or invalid quotes cannot produce fills; unsupported stop orders are rejected. +Backtests use completed-bar close/volume as a documented simulation input, not exchange +execution guarantees. No random slippage or fabricated broker acknowledgements are used. + +Position/order limits are shares; symbol/gross exposure and daily loss are account-currency +amounts. Checks include projected positions, pending-order reservations, current marks, and +an unlevered capital budget. Risk-reducing closes remain possible after a loss-limit breach. +Daily loss rolls at UTC midnight, and each fill contributes its **delta**, never cumulative +realized P&L. Fees are charged once, cash/equity include signed position value, and partial +closes/reversals allocate entry/exit commissions proportionally. The paper model uses decimal +arithmetic rounded to eight decimal places; it is single-currency and does not model FX, +borrowing, interest, corporate actions, or exchange-specific settlement. + +Live mode, broker/exchange routing, and direct native `TradingEngine.submitOrder` are +explicitly unsupported. They fail closed instead of reporting mock acceptance. Position, +P&L, and risk endpoints read the gateway ledger rather than native paper projections. +This milestone does not connect a broker, place real orders, or make the project live-ready. + ## Backtest execution workflow The orchestrator's `BacktestRunner` is the application boundary for both HTTP and decorated diff --git a/apps/stock/engine/src/api/backtest.rs b/apps/stock/engine/src/api/backtest.rs index cfea7de6..457bb3a9 100644 --- a/apps/stock/engine/src/api/backtest.rs +++ b/apps/stock/engine/src/api/backtest.rs @@ -13,6 +13,21 @@ pub struct BacktestEngine { #[napi] impl BacktestEngine { + #[napi] + pub fn update_risk_limits(&self, input: napi::JsObject) -> Result<()> { + let limits = super::parse_risk_limits(input)?; + if !limits.valid() { + return Err(Error::from_reason( + "Risk limits must be positive finite numbers", + )); + } + let guard = self.inner.lock(); + let engine = guard + .as_ref() + .ok_or_else(|| Error::from_reason("Backtest engine unavailable"))?; + engine.update_risk_limits(limits); + Ok(()) + } #[napi(constructor)] pub fn new(config: napi::JsObject, env: Env) -> Result { let config = parse_backtest_config(config)?; diff --git a/apps/stock/engine/src/api/mod.rs b/apps/stock/engine/src/api/mod.rs index ce61cbc0..b7d5eb30 100644 --- a/apps/stock/engine/src/api/mod.rs +++ b/apps/stock/engine/src/api/mod.rs @@ -1,435 +1,523 @@ -mod indicators; -mod risk; -mod backtest; - -pub use indicators::{TechnicalIndicators, IncrementalSMA, IncrementalEMA, IncrementalRSI}; -pub use risk::{RiskAnalyzer, OrderbookAnalyzer}; -pub use backtest::BacktestEngine; - -use napi_derive::napi; -use napi::{bindgen_prelude::*, JsObject}; -use crate::{ - TradingCore, TradingMode, Order, OrderType, TimeInForce, Side, - MarketUpdate, Quote, Trade, - MarketMicrostructure, - core::{create_market_data_source, create_execution_handler, create_time_provider}, -}; -use crate::risk::RiskLimits; -use std::sync::Arc; -use parking_lot::Mutex; -use chrono::{DateTime, Utc}; - -#[napi] -pub struct TradingEngine { - core: Arc>, -} - -#[napi] -impl TradingEngine { - #[napi(constructor)] - pub fn new(mode: String, config: JsObject) -> Result { - let mode = parse_mode(&mode, config)?; - - let market_data_source = create_market_data_source(&mode); - let execution_handler = create_execution_handler(&mode); - let time_provider = create_time_provider(&mode); - - let core = TradingCore::new(mode, market_data_source, execution_handler, time_provider); - - Ok(Self { - core: Arc::new(Mutex::new(core)), - }) - } - - #[napi] - pub fn get_mode(&self) -> String { - let core = self.core.lock(); - match core.get_mode() { - TradingMode::Backtest { .. } => "backtest".to_string(), - TradingMode::Paper { .. } => "paper".to_string(), - TradingMode::Live { .. } => "live".to_string(), - } - } - - #[napi] - pub fn get_current_time(&self) -> i64 { - let core = self.core.lock(); - core.get_time().timestamp_millis() - } - - #[napi] - pub fn submit_order(&self, order_js: JsObject) -> Result { - let order = parse_order(order_js)?; - - // For now, return a mock result - in real implementation would queue the order - let result = crate::ExecutionResult { - order_id: order.id.clone(), - status: crate::OrderStatus::Accepted, - fills: vec![], - }; - - Ok(serde_json::to_string(&result).unwrap()) - } - - #[napi] - pub fn check_risk(&self, order_js: JsObject) -> Result { - let order = parse_order(order_js)?; - let core = self.core.lock(); - - // Get current position for the symbol - let position = core.position_tracker.get_position(&order.symbol); - let current_quantity = position.map(|p| p.quantity); - - let result = core.risk_engine.check_order(&order, current_quantity); - Ok(serde_json::to_string(&result).unwrap()) - } - - #[napi] - pub fn update_quote(&self, symbol: String, bid: f64, ask: f64, bid_size: f64, ask_size: f64) -> Result<()> { - let quote = Quote { bid, ask, bid_size, ask_size }; - let core = self.core.lock(); - let timestamp = core.get_time(); - - core.orderbooks.update_quote(&symbol, quote, timestamp); - - // Update unrealized P&L - let mid_price = (bid + ask) / 2.0; - core.position_tracker.update_unrealized_pnl(&symbol, mid_price); - - Ok(()) - } - - #[napi] - pub fn update_trade(&self, symbol: String, price: f64, size: f64, side: String) -> Result<()> { - let side = match side.as_str() { - "buy" | "Buy" => Side::Buy, - "sell" | "Sell" => Side::Sell, - _ => return Err(Error::from_reason("Invalid side")), - }; - - let trade = Trade { price, size, side }; - let core = self.core.lock(); - let timestamp = core.get_time(); - - core.orderbooks.update_trade(&symbol, trade, timestamp); - Ok(()) - } - - #[napi] - pub fn get_orderbook_snapshot(&self, symbol: String, depth: u32) -> Result { - let core = self.core.lock(); - let snapshot = core.orderbooks.get_snapshot(&symbol, depth as usize) - .ok_or_else(|| Error::from_reason("Symbol not found"))?; - - Ok(serde_json::to_string(&snapshot).unwrap()) - } - - #[napi] - pub fn get_best_bid_ask(&self, symbol: String) -> Result> { - let core = self.core.lock(); - let (bid, ask) = core.orderbooks.get_best_bid_ask(&symbol) - .ok_or_else(|| Error::from_reason("Symbol not found"))?; - - Ok(vec![bid, ask]) - } - - #[napi] - pub fn get_position(&self, symbol: String) -> Result> { - let core = self.core.lock(); - let position = core.position_tracker.get_position(&symbol); - - Ok(position.map(|p| serde_json::to_string(&p).unwrap())) - } - - #[napi] - pub fn get_all_positions(&self) -> Result { - let core = self.core.lock(); - let positions = core.position_tracker.get_all_positions(); - - Ok(serde_json::to_string(&positions).unwrap()) - } - - #[napi] - pub fn get_open_positions(&self) -> Result { - let core = self.core.lock(); - let positions = core.position_tracker.get_open_positions(); - - Ok(serde_json::to_string(&positions).unwrap()) - } - - #[napi] - pub fn get_total_pnl(&self) -> Result> { - let core = self.core.lock(); - let (realized, unrealized) = core.position_tracker.get_total_pnl(); - - Ok(vec![realized, unrealized]) - } - - #[napi] - pub fn process_fill(&self, symbol: String, price: f64, quantity: f64, side: String, commission: f64) -> Result { - self.process_fill_with_metadata(symbol, price, quantity, side, commission, None, None) - } - - #[napi] - pub fn process_fill_with_metadata( - &self, - symbol: String, - price: f64, - quantity: f64, - side: String, - commission: f64, - order_id: Option, - strategy_id: Option - ) -> Result { - let side = match side.as_str() { - "buy" | "Buy" => Side::Buy, - "sell" | "Sell" => Side::Sell, - _ => return Err(Error::from_reason("Invalid side")), - }; - - let core = self.core.lock(); - let timestamp = core.get_time(); - - let fill = crate::Fill { - timestamp, - price, - quantity, - commission, - }; - - let update = core.position_tracker.process_fill_with_tracking(&symbol, &fill, side, order_id, strategy_id); - - // Update risk engine with new position - core.risk_engine.update_position(&symbol, update.resulting_position.quantity); - - // Update daily P&L - if update.resulting_position.realized_pnl != 0.0 { - core.risk_engine.update_daily_pnl(update.resulting_position.realized_pnl); - } - - Ok(serde_json::to_string(&update).unwrap()) - } - - #[napi] - pub fn update_risk_limits(&self, limits_js: JsObject) -> Result<()> { - let limits = parse_risk_limits(limits_js)?; - let core = self.core.lock(); - core.risk_engine.update_limits(limits); - Ok(()) - } - - #[napi] - pub fn reset_daily_metrics(&self) -> Result<()> { - let core = self.core.lock(); - core.risk_engine.reset_daily_metrics(); - Ok(()) - } - - #[napi] - pub fn get_risk_metrics(&self) -> Result { - let core = self.core.lock(); - let metrics = core.risk_engine.get_risk_metrics(); - Ok(serde_json::to_string(&metrics).unwrap()) - } - - // Backtest-specific methods - #[napi] - pub fn advance_time(&self, to_timestamp: i64) -> Result<()> { - let core = self.core.lock(); - if let TradingMode::Backtest { .. } = core.get_mode() { - // Downcast time provider to SimulatedTime and advance it - if let Some(simulated_time) = core.time_provider.as_any().downcast_ref::() { - let new_time = DateTime::::from_timestamp_millis(to_timestamp) - .ok_or_else(|| Error::from_reason("Invalid timestamp"))?; - simulated_time.advance_to(new_time); - Ok(()) - } else { - Err(Error::from_reason("Failed to access simulated time provider")) - } - } else { - Err(Error::from_reason("Can only advance time in backtest mode")) - } - } - - #[napi] - pub fn set_microstructure(&self, symbol: String, microstructure_js: JsObject) -> Result<()> { - let microstructure = parse_microstructure(microstructure_js)?; - - let _core = self.core.lock(); - // Store microstructure for use in fill simulation - // In real implementation, would pass to execution handler - Ok(()) - } - - #[napi] - pub fn load_historical_data(&self, data_json: String) -> Result<()> { - let data: Vec = serde_json::from_str(&data_json) - .map_err(|e| Error::from_reason(format!("Failed to parse data: {}", e)))?; - - let core = self.core.lock(); - - // Downcast to HistoricalDataSource if in backtest mode - if let TradingMode::Backtest { .. } = core.get_mode() { - let mut data_source = core.market_data_source.write(); - if let Some(historical_source) = data_source.as_any_mut().downcast_mut::() { - historical_source.load_data(data); - } - } - - Ok(()) - } - - #[napi] - pub fn generate_mock_data(&self, symbol: String, start_time: i64, end_time: i64, seed: Option) -> Result<()> { - let core = self.core.lock(); - - // Only available in backtest mode - if let TradingMode::Backtest { .. } = core.get_mode() { - let mut data_source = core.market_data_source.write(); - if let Some(historical_source) = data_source.as_any_mut().downcast_mut::() { - let start_dt = DateTime::::from_timestamp_millis(start_time) - .ok_or_else(|| Error::from_reason("Invalid start time"))?; - let end_dt = DateTime::::from_timestamp_millis(end_time) - .ok_or_else(|| Error::from_reason("Invalid end time"))?; - - historical_source.generate_mock_data(symbol, start_dt, end_dt, seed.map(|s| s as u64)); - } else { - return Err(Error::from_reason("Failed to access historical data source")); - } - } else { - return Err(Error::from_reason("Mock data generation only available in backtest mode")); - } - - Ok(()) - } - - #[napi] - pub fn get_trade_history(&self) -> Result { - let core = self.core.lock(); - let trades = core.position_tracker.get_trade_history(); - Ok(serde_json::to_string(&trades).unwrap()) - } - - #[napi] - pub fn get_closed_trades(&self) -> Result { - let core = self.core.lock(); - let trades = core.position_tracker.get_closed_trades(); - Ok(serde_json::to_string(&trades).unwrap()) - } - - #[napi] - pub fn get_open_trades(&self) -> Result { - let core = self.core.lock(); - let trades = core.position_tracker.get_open_trades(); - Ok(serde_json::to_string(&trades).unwrap()) - } - - #[napi] - pub fn get_trade_count(&self) -> Result { - let core = self.core.lock(); - Ok(core.position_tracker.get_trade_count() as u32) - } - - #[napi] - pub fn get_closed_trade_count(&self) -> Result { - let core = self.core.lock(); - Ok(core.position_tracker.get_closed_trade_count() as u32) - } -} - -// Helper functions to parse JavaScript objects -fn parse_mode(mode_str: &str, config: JsObject) -> Result { - match mode_str { - "backtest" => { - let start_time: i64 = config.get_named_property("startTime")?; - let end_time: i64 = config.get_named_property("endTime")?; - let speed_multiplier: f64 = config.get_named_property("speedMultiplier") - .unwrap_or(1.0); - - Ok(TradingMode::Backtest { - start_time: DateTime::::from_timestamp_millis(start_time) - .ok_or_else(|| Error::from_reason("Invalid start time"))?, - end_time: DateTime::::from_timestamp_millis(end_time) - .ok_or_else(|| Error::from_reason("Invalid end time"))?, - speed_multiplier, - }) - } - "paper" => { - let starting_capital: f64 = config.get_named_property("startingCapital")?; - Ok(TradingMode::Paper { starting_capital }) - } - "live" => { - let broker: String = config.get_named_property("broker")?; - let account_id: String = config.get_named_property("accountId")?; - Ok(TradingMode::Live { broker, account_id }) - } - _ => Err(Error::from_reason("Invalid mode")), - } -} - -fn parse_order(order_js: JsObject) -> Result { - let id: String = order_js.get_named_property("id")?; - let symbol: String = order_js.get_named_property("symbol")?; - let side_str: String = order_js.get_named_property("side")?; - let side = match side_str.as_str() { - "buy" | "Buy" => Side::Buy, - "sell" | "Sell" => Side::Sell, - _ => return Err(Error::from_reason("Invalid side")), - }; - let quantity: f64 = order_js.get_named_property("quantity")?; - - let order_type_str: String = order_js.get_named_property("orderType")?; - let order_type = match order_type_str.as_str() { - "market" => OrderType::Market, - "limit" => { - let price: f64 = order_js.get_named_property("limitPrice")?; - OrderType::Limit { price } - } - _ => return Err(Error::from_reason("Invalid order type")), - }; - - let time_in_force_str: String = order_js.get_named_property("timeInForce") - .unwrap_or_else(|_| "DAY".to_string()); - let time_in_force = match time_in_force_str.as_str() { - "DAY" => TimeInForce::Day, - "GTC" => TimeInForce::GTC, - "IOC" => TimeInForce::IOC, - "FOK" => TimeInForce::FOK, - _ => TimeInForce::Day, - }; - - Ok(Order { - id, - symbol, - side, - quantity, - order_type, - time_in_force, - }) -} - -fn parse_risk_limits(limits_js: JsObject) -> Result { - Ok(RiskLimits { - max_position_size: limits_js.get_named_property("maxPositionSize")?, - max_order_size: limits_js.get_named_property("maxOrderSize")?, - max_daily_loss: limits_js.get_named_property("maxDailyLoss")?, - max_gross_exposure: limits_js.get_named_property("maxGrossExposure")?, - max_symbol_exposure: limits_js.get_named_property("maxSymbolExposure")?, - }) -} - -fn parse_microstructure(microstructure_js: JsObject) -> Result { - let intraday_volume_profile: Vec = microstructure_js.get_named_property("intradayVolumeProfile") - .unwrap_or_else(|_| vec![1.0/24.0; 24]); - - Ok(MarketMicrostructure { - symbol: microstructure_js.get_named_property("symbol")?, - avg_spread_bps: microstructure_js.get_named_property("avgSpreadBps")?, - daily_volume: microstructure_js.get_named_property("dailyVolume")?, - avg_trade_size: microstructure_js.get_named_property("avgTradeSize")?, - volatility: microstructure_js.get_named_property("volatility")?, - tick_size: microstructure_js.get_named_property("tickSize")?, - lot_size: microstructure_js.get_named_property("lotSize")?, - intraday_volume_profile, - }) -} \ No newline at end of file +mod backtest; +mod indicators; +mod risk; + +pub use backtest::BacktestEngine; +pub use indicators::{IncrementalEMA, IncrementalRSI, IncrementalSMA, TechnicalIndicators}; +pub use risk::{OrderbookAnalyzer, RiskAnalyzer}; + +use crate::risk::RiskLimits; +use crate::{ + core::{create_execution_handler, create_market_data_source, create_time_provider}, + MarketMicrostructure, MarketUpdate, Order, OrderType, Quote, Side, TimeInForce, Trade, + TradingCore, TradingMode, +}; +use chrono::{DateTime, Utc}; +use napi::{bindgen_prelude::*, JsObject}; +use napi_derive::napi; +use parking_lot::Mutex; +use std::sync::Arc; + +#[napi] +pub struct TradingEngine { + core: Arc>, +} + +#[napi] +impl TradingEngine { + #[napi(constructor)] + pub fn new(mode: String, config: JsObject) -> Result { + if mode == "live" { + return Err(Error::from_reason( + "Live trading is disabled: no real broker adapter exists", + )); + } + let mode = parse_mode(&mode, config)?; + + let market_data_source = create_market_data_source(&mode); + let execution_handler = create_execution_handler(&mode); + let time_provider = create_time_provider(&mode); + + let core = TradingCore::new(mode, market_data_source, execution_handler, time_provider); + + Ok(Self { + core: Arc::new(Mutex::new(core)), + }) + } + + #[napi] + pub fn get_mode(&self) -> String { + let core = self.core.lock(); + match core.get_mode() { + TradingMode::Backtest { .. } => "backtest".to_string(), + TradingMode::Paper { .. } => "paper".to_string(), + TradingMode::Live { .. } => "live".to_string(), + } + } + + #[napi] + pub fn get_current_time(&self) -> i64 { + let core = self.core.lock(); + core.get_time().timestamp_millis() + } + + #[napi] + pub fn submit_order(&self, order_js: JsObject) -> Result { + let _order = parse_order(order_js)?; + Err(Error::from_reason( + "Direct native submission is unsupported; use the execution gateway", + )) + } + + #[napi] + pub fn check_risk(&self, order_js: JsObject) -> Result { + let order = parse_order(order_js)?; + let core = self.core.lock(); + + // Get current position for the symbol + let position = core.position_tracker.get_position(&order.symbol); + let current_quantity = position.map(|p| p.quantity); + + let price = core + .orderbooks + .get_best_bid_ask(&order.symbol) + .map(|(bid, ask)| if order.side == Side::Buy { ask } else { bid }) + .unwrap_or(f64::NAN); + core.risk_engine.roll_day(core.get_time().date_naive()); + let result = core + .risk_engine + .check_order(&order, current_quantity, price); + Ok(serde_json::to_string(&result).unwrap()) + } + + #[napi] + pub fn update_quote( + &self, + symbol: String, + bid: f64, + ask: f64, + bid_size: f64, + ask_size: f64, + ) -> Result<()> { + let quote = Quote { + bid, + ask, + bid_size, + ask_size, + }; + let core = self.core.lock(); + let timestamp = core.get_time(); + + core.orderbooks.update_quote(&symbol, quote, timestamp); + + // Update unrealized P&L + let mid_price = (bid + ask) / 2.0; + core.position_tracker + .update_unrealized_pnl(&symbol, mid_price); + core.risk_engine.mark_price(&symbol, mid_price); + + Ok(()) + } + + #[napi] + pub fn update_trade(&self, symbol: String, price: f64, size: f64, side: String) -> Result<()> { + let side = match side.as_str() { + "buy" | "Buy" => Side::Buy, + "sell" | "Sell" => Side::Sell, + _ => return Err(Error::from_reason("Invalid side")), + }; + + let trade = Trade { price, size, side }; + let core = self.core.lock(); + let timestamp = core.get_time(); + + core.orderbooks.update_trade(&symbol, trade, timestamp); + core.risk_engine.mark_price(&symbol, price); + Ok(()) + } + + #[napi] + pub fn get_orderbook_snapshot(&self, symbol: String, depth: u32) -> Result { + let core = self.core.lock(); + let snapshot = core + .orderbooks + .get_snapshot(&symbol, depth as usize) + .ok_or_else(|| Error::from_reason("Symbol not found"))?; + + Ok(serde_json::to_string(&snapshot).unwrap()) + } + + #[napi] + pub fn get_best_bid_ask(&self, symbol: String) -> Result> { + let core = self.core.lock(); + let (bid, ask) = core + .orderbooks + .get_best_bid_ask(&symbol) + .ok_or_else(|| Error::from_reason("Symbol not found"))?; + + Ok(vec![bid, ask]) + } + + #[napi] + pub fn get_position(&self, symbol: String) -> Result> { + let core = self.core.lock(); + let position = core.position_tracker.get_position(&symbol); + + Ok(position.map(|p| serde_json::to_string(&p).unwrap())) + } + + #[napi] + pub fn get_all_positions(&self) -> Result { + let core = self.core.lock(); + let positions = core.position_tracker.get_all_positions(); + + Ok(serde_json::to_string(&positions).unwrap()) + } + + #[napi] + pub fn get_open_positions(&self) -> Result { + let core = self.core.lock(); + let positions = core.position_tracker.get_open_positions(); + + Ok(serde_json::to_string(&positions).unwrap()) + } + + #[napi] + pub fn get_total_pnl(&self) -> Result> { + let core = self.core.lock(); + let (realized, unrealized) = core.position_tracker.get_total_pnl(); + + Ok(vec![realized, unrealized]) + } + + #[napi] + pub fn process_fill( + &self, + symbol: String, + price: f64, + quantity: f64, + side: String, + commission: f64, + ) -> Result { + self.process_fill_with_metadata(symbol, price, quantity, side, commission, None, None) + } + + #[napi] + pub fn process_fill_with_metadata( + &self, + symbol: String, + price: f64, + quantity: f64, + side: String, + commission: f64, + order_id: Option, + strategy_id: Option, + ) -> Result { + let side = match side.as_str() { + "buy" | "Buy" => Side::Buy, + "sell" | "Sell" => Side::Sell, + _ => return Err(Error::from_reason("Invalid side")), + }; + + let core = self.core.lock(); + let timestamp = core.get_time(); + + let fill = crate::Fill { + timestamp, + price, + quantity, + commission, + }; + + if !price.is_finite() + || price <= 0.0 + || !quantity.is_finite() + || quantity <= 0.0 + || !commission.is_finite() + || commission < 0.0 + { + return Err(Error::from_reason("Invalid fill values")); + } + core.risk_engine.roll_day(timestamp.date_naive()); + let previous_pnl = core + .position_tracker + .get_position(&symbol) + .map(|p| p.realized_pnl) + .unwrap_or(0.0); + let update = core.position_tracker.process_fill_with_tracking( + &symbol, + &fill, + side, + order_id, + strategy_id, + ); + + // Update risk engine with new position + core.risk_engine + .update_position(&symbol, update.resulting_position.quantity, price); + + // Update daily P&L + if update.resulting_position.realized_pnl != previous_pnl { + core.risk_engine + .update_daily_pnl(update.resulting_position.realized_pnl - previous_pnl); + } + + Ok(serde_json::to_string(&update).unwrap()) + } + + #[napi] + pub fn update_risk_limits(&self, limits_js: JsObject) -> Result<()> { + let limits = parse_risk_limits(limits_js)?; + let core = self.core.lock(); + if !limits.valid() { + return Err(Error::from_reason( + "Risk limits must be positive finite numbers", + )); + } + core.risk_engine.update_limits(limits); + Ok(()) + } + + #[napi] + pub fn reset_daily_metrics(&self) -> Result<()> { + let core = self.core.lock(); + core.risk_engine.reset_daily_metrics(); + Ok(()) + } + + #[napi] + pub fn get_risk_metrics(&self) -> Result { + let core = self.core.lock(); + let metrics = core.risk_engine.get_risk_metrics(); + Ok(serde_json::to_string(&metrics).unwrap()) + } + + // Backtest-specific methods + #[napi] + pub fn advance_time(&self, to_timestamp: i64) -> Result<()> { + let core = self.core.lock(); + if let TradingMode::Backtest { .. } = core.get_mode() { + // Downcast time provider to SimulatedTime and advance it + if let Some(simulated_time) = + core.time_provider + .as_any() + .downcast_ref::() + { + let new_time = DateTime::::from_timestamp_millis(to_timestamp) + .ok_or_else(|| Error::from_reason("Invalid timestamp"))?; + simulated_time.advance_to(new_time); + Ok(()) + } else { + Err(Error::from_reason( + "Failed to access simulated time provider", + )) + } + } else { + Err(Error::from_reason("Can only advance time in backtest mode")) + } + } + + #[napi] + pub fn set_microstructure(&self, symbol: String, microstructure_js: JsObject) -> Result<()> { + let microstructure = parse_microstructure(microstructure_js)?; + + let _core = self.core.lock(); + // Store microstructure for use in fill simulation + // In real implementation, would pass to execution handler + Ok(()) + } + + #[napi] + pub fn load_historical_data(&self, data_json: String) -> Result<()> { + let data: Vec = serde_json::from_str(&data_json) + .map_err(|e| Error::from_reason(format!("Failed to parse data: {}", e)))?; + + let core = self.core.lock(); + + // Downcast to HistoricalDataSource if in backtest mode + if let TradingMode::Backtest { .. } = core.get_mode() { + let mut data_source = core.market_data_source.write(); + if let Some(historical_source) = data_source + .as_any_mut() + .downcast_mut::( + ) { + historical_source.load_data(data); + } + } + + Ok(()) + } + + #[napi] + pub fn generate_mock_data( + &self, + symbol: String, + start_time: i64, + end_time: i64, + seed: Option, + ) -> Result<()> { + let core = self.core.lock(); + + // Only available in backtest mode + if let TradingMode::Backtest { .. } = core.get_mode() { + let mut data_source = core.market_data_source.write(); + if let Some(historical_source) = data_source + .as_any_mut() + .downcast_mut::( + ) { + let start_dt = DateTime::::from_timestamp_millis(start_time) + .ok_or_else(|| Error::from_reason("Invalid start time"))?; + let end_dt = DateTime::::from_timestamp_millis(end_time) + .ok_or_else(|| Error::from_reason("Invalid end time"))?; + + historical_source.generate_mock_data( + symbol, + start_dt, + end_dt, + seed.map(|s| s as u64), + ); + } else { + return Err(Error::from_reason( + "Failed to access historical data source", + )); + } + } else { + return Err(Error::from_reason( + "Mock data generation only available in backtest mode", + )); + } + + Ok(()) + } + + #[napi] + pub fn get_trade_history(&self) -> Result { + let core = self.core.lock(); + let trades = core.position_tracker.get_trade_history(); + Ok(serde_json::to_string(&trades).unwrap()) + } + + #[napi] + pub fn get_closed_trades(&self) -> Result { + let core = self.core.lock(); + let trades = core.position_tracker.get_closed_trades(); + Ok(serde_json::to_string(&trades).unwrap()) + } + + #[napi] + pub fn get_open_trades(&self) -> Result { + let core = self.core.lock(); + let trades = core.position_tracker.get_open_trades(); + Ok(serde_json::to_string(&trades).unwrap()) + } + + #[napi] + pub fn get_trade_count(&self) -> Result { + let core = self.core.lock(); + Ok(core.position_tracker.get_trade_count() as u32) + } + + #[napi] + pub fn get_closed_trade_count(&self) -> Result { + let core = self.core.lock(); + Ok(core.position_tracker.get_closed_trade_count() as u32) + } +} + +// Helper functions to parse JavaScript objects +fn parse_mode(mode_str: &str, config: JsObject) -> Result { + match mode_str { + "backtest" => { + let start_time: i64 = config.get_named_property("startTime")?; + let end_time: i64 = config.get_named_property("endTime")?; + let speed_multiplier: f64 = config.get_named_property("speedMultiplier").unwrap_or(1.0); + + Ok(TradingMode::Backtest { + start_time: DateTime::::from_timestamp_millis(start_time) + .ok_or_else(|| Error::from_reason("Invalid start time"))?, + end_time: DateTime::::from_timestamp_millis(end_time) + .ok_or_else(|| Error::from_reason("Invalid end time"))?, + speed_multiplier, + }) + } + "paper" => { + let starting_capital: f64 = config.get_named_property("startingCapital")?; + Ok(TradingMode::Paper { starting_capital }) + } + "live" => { + let broker: String = config.get_named_property("broker")?; + let account_id: String = config.get_named_property("accountId")?; + Ok(TradingMode::Live { broker, account_id }) + } + _ => Err(Error::from_reason("Invalid mode")), + } +} + +fn parse_order(order_js: JsObject) -> Result { + let id: String = order_js.get_named_property("id")?; + let symbol: String = order_js.get_named_property("symbol")?; + let side_str: String = order_js.get_named_property("side")?; + let side = match side_str.as_str() { + "buy" | "Buy" => Side::Buy, + "sell" | "Sell" => Side::Sell, + _ => return Err(Error::from_reason("Invalid side")), + }; + let quantity: f64 = order_js.get_named_property("quantity")?; + + let order_type_str: String = order_js.get_named_property("orderType")?; + let order_type = match order_type_str.as_str() { + "market" => OrderType::Market, + "limit" => { + let price: f64 = order_js.get_named_property("limitPrice")?; + OrderType::Limit { price } + } + _ => return Err(Error::from_reason("Invalid order type")), + }; + + let time_in_force_str: String = order_js + .get_named_property("timeInForce") + .unwrap_or_else(|_| "DAY".to_string()); + let time_in_force = match time_in_force_str.as_str() { + "DAY" => TimeInForce::Day, + "GTC" => TimeInForce::GTC, + "IOC" => TimeInForce::IOC, + "FOK" => TimeInForce::FOK, + _ => TimeInForce::Day, + }; + + Ok(Order { + id, + symbol, + side, + quantity, + order_type, + time_in_force, + }) +} + +fn parse_risk_limits(limits_js: JsObject) -> Result { + Ok(RiskLimits { + max_position_size: limits_js.get_named_property("maxPositionSize")?, + max_order_size: limits_js.get_named_property("maxOrderSize")?, + max_daily_loss: limits_js.get_named_property("maxDailyLoss")?, + max_gross_exposure: limits_js.get_named_property("maxGrossExposure")?, + max_symbol_exposure: limits_js.get_named_property("maxSymbolExposure")?, + }) +} + +fn parse_microstructure(microstructure_js: JsObject) -> Result { + let intraday_volume_profile: Vec = microstructure_js + .get_named_property("intradayVolumeProfile") + .unwrap_or_else(|_| vec![1.0 / 24.0; 24]); + + Ok(MarketMicrostructure { + symbol: microstructure_js.get_named_property("symbol")?, + avg_spread_bps: microstructure_js.get_named_property("avgSpreadBps")?, + daily_volume: microstructure_js.get_named_property("dailyVolume")?, + avg_trade_size: microstructure_js.get_named_property("avgTradeSize")?, + volatility: microstructure_js.get_named_property("volatility")?, + tick_size: microstructure_js.get_named_property("tickSize")?, + lot_size: microstructure_js.get_named_property("lotSize")?, + intraday_volume_profile, + }) +} diff --git a/apps/stock/engine/src/backtest/engine.rs b/apps/stock/engine/src/backtest/engine.rs index 38f82ecb..ef374db0 100644 --- a/apps/stock/engine/src/backtest/engine.rs +++ b/apps/stock/engine/src/backtest/engine.rs @@ -1,20 +1,17 @@ +use chrono::{DateTime, Utc}; +use parking_lot::RwLock; +use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::sync::Arc; -use parking_lot::RwLock; -use chrono::{DateTime, Utc}; -use serde::{Serialize, Deserialize}; use crate::{ - TradingMode, MarketDataSource, ExecutionHandler, TimeProvider, - MarketUpdate, MarketDataType, Order, Fill, Side, - positions::PositionTracker, - risk::RiskEngine, - orderbook::OrderBookManager, + orderbook::OrderBookManager, positions::PositionTracker, risk::RiskEngine, ExecutionHandler, + Fill, MarketDataSource, MarketDataType, MarketUpdate, Order, Side, TimeProvider, TradingMode, }; use super::{ - BacktestConfig, BacktestState, EventQueue, BacktestEvent, EventType, - Strategy, Signal, SignalType, BacktestResult, TradeTracker, + BacktestConfig, BacktestEvent, BacktestResult, BacktestState, EventQueue, EventType, Signal, + SignalType, Strategy, TradeTracker, }; pub struct BacktestEngine { @@ -22,7 +19,7 @@ pub struct BacktestEngine { state: Arc>, event_queue: Arc>, strategies: Arc>>>, - + // Core components position_tracker: Arc, risk_engine: Arc, @@ -30,22 +27,22 @@ pub struct BacktestEngine { time_provider: Arc>, pub market_data_source: Arc>>, execution_handler: Arc>>, - + // Metrics total_trades: usize, profitable_trades: usize, total_pnl: f64, - + // Price tracking - single source of truth // Maps symbol -> (timestamp, price) last_prices: HashMap, f64)>, - + // Store latest bar data for each symbol to ensure accurate closing prices latest_bars: HashMap, - + // Store all OHLC data processed by the engine ohlc_history: HashMap, crate::Bar)>>, - + // Trade tracking trade_tracker: TradeTracker, } @@ -58,10 +55,11 @@ impl BacktestEngine { market_data_source: Box, execution_handler: Box, ) -> Self { - let state = Arc::new(RwLock::new( - BacktestState::new(config.initial_capital, config.start_time) - )); - + let state = Arc::new(RwLock::new(BacktestState::new( + config.initial_capital, + config.start_time, + ))); + Self { config, state, @@ -82,54 +80,56 @@ impl BacktestEngine { trade_tracker: TradeTracker::new(), } } - + + pub fn update_risk_limits(&self, limits: crate::RiskLimits) { + self.risk_engine.update_limits(limits); + } pub fn add_strategy(&mut self, strategy: Box) { self.strategies.write().push(strategy); } - + pub async fn run(&mut self) -> Result { - // Initialize start time - if let Some(simulated_time) = self.time_provider.as_any() - .downcast_ref::() + if let Some(simulated_time) = self + .time_provider + .as_any() + .downcast_ref::() { simulated_time.advance_to(self.config.start_time); } - + // Load market data self.load_market_data().await?; - + let queue_len = self.event_queue.read().len(); - + if queue_len == 0 { return Err("No market data loaded".to_string()); } - + // Main event loop - process events grouped by timestamp let mut iteration = 0; let mut last_update_time = self.config.start_time; - + while !self.event_queue.read().is_empty() { iteration += 1; - + // Get the next event's timestamp - let next_event_time = self.event_queue.read() - .peek_next() - .map(|e| e.timestamp); - + let next_event_time = self.event_queue.read().peek_next().map(|e| e.timestamp); + if let Some(event_time) = next_event_time { // Advance time to the next event self.advance_time(event_time); - + // Get all events at this timestamp let current_time = self.time_provider.now(); let events = self.event_queue.write().pop_until(current_time); - + // Process all events at this timestamp for event in events { self.process_event(event).await?; } - + // Only update portfolio value if time has actually advanced // This ensures we have prices for all symbols at this timestamp if current_time > last_update_time { @@ -141,31 +141,31 @@ impl BacktestEngine { break; } } - + // Close all open positions at market prices self.close_all_positions().await?; - + // Generate results Ok(self.generate_results()) } - + async fn load_market_data(&mut self) -> Result<(), String> { let mut data_source = self.market_data_source.write(); data_source.seek_to_time(self.config.start_time)?; - + // Load all data into event queue while let Some(update) = data_source.get_next_update().await { if update.timestamp > self.config.end_time { break; } - + let event = BacktestEvent::market_data(update.timestamp, update); self.event_queue.write().push(event); } - + Ok(()) } - + async fn process_event(&mut self, event: BacktestEvent) -> Result<(), String> { match event.event_type { EventType::MarketData(data) => { @@ -186,52 +186,66 @@ impl BacktestEngine { self.advance_time(time); } } - + Ok(()) } - + async fn process_market_data(&mut self, data: MarketUpdate) -> Result<(), String> { // Update price tracking - single source of truth let price = match &data.data { MarketDataType::Bar(bar) => { // Log OHLCV data for each tick - eprintln!("[TICK] {} @ {} - O:{:.2} H:{:.2} L:{:.2} C:{:.2} V:{:.0}", - data.symbol, - data.timestamp.format("%Y-%m-%d %H:%M:%S"), - bar.open, bar.high, bar.low, bar.close, bar.volume); - + eprintln!( + "[TICK] {} @ {} - O:{:.2} H:{:.2} L:{:.2} C:{:.2} V:{:.0}", + data.symbol, + data.timestamp.format("%Y-%m-%d %H:%M:%S"), + bar.open, + bar.high, + bar.low, + bar.close, + bar.volume + ); + // Store the complete bar data for accurate position closing self.latest_bars.insert(data.symbol.clone(), bar.clone()); - + // Store in OHLC history self.ohlc_history .entry(data.symbol.clone()) .or_insert_with(Vec::new) .push((data.timestamp, bar.clone())); - + // Debug: Log OHLC history size periodically - let history_len = self.ohlc_history.get(&data.symbol).map(|v| v.len()).unwrap_or(0); + let history_len = self + .ohlc_history + .get(&data.symbol) + .map(|v| v.len()) + .unwrap_or(0); if history_len == 1 || history_len % 100 == 0 { - eprintln!("[DEBUG] OHLC history for {}: {} bars stored", data.symbol, history_len); + eprintln!( + "[DEBUG] OHLC history for {}: {} bars stored", + data.symbol, history_len + ); } - + bar.close } MarketDataType::Quote(quote) => { // Use mid price for quotes (quote.bid + quote.ask) / 2.0 } - MarketDataType::Trade(trade) => { - trade.price - } + MarketDataType::Trade(trade) => trade.price, }; - + // Store price with timestamp - this is our source of truth - self.last_prices.insert(data.symbol.clone(), (data.timestamp, price)); - + self.last_prices + .insert(data.symbol.clone(), (data.timestamp, price)); + self.risk_engine.mark_price(&data.symbol, price); + self.risk_engine.roll_day(data.timestamp.date_naive()); + // Convert to simpler MarketData for strategies let market_data = self.convert_to_market_data(&data); - + // Send to strategies let mut all_signals = Vec::new(); { @@ -241,44 +255,44 @@ impl BacktestEngine { all_signals.extend(signals); } } - + // Process signals for signal in all_signals { self.process_signal(signal).await?; } - + // Check pending orders for fills self.check_pending_orders(&data).await?; - + // Don't update portfolio value here - wait until all events at this timestamp are processed - + Ok(()) } - + fn convert_to_market_data(&self, update: &MarketUpdate) -> MarketUpdate { // MarketData is a type alias for MarketUpdate update.clone() } - + async fn process_signal(&mut self, signal: Signal) -> Result<(), String> { // Only process strong signals if signal.strength.abs() < 0.7 { return Ok(()); } - + // Convert signal to order let order = self.signal_to_order(signal)?; - + // Submit order self.process_order_submission(order).await } - + fn signal_to_order(&self, signal: Signal) -> Result { let quantity = signal.quantity.unwrap_or_else(|| { // Calculate position size based on portfolio self.calculate_position_size(&signal.symbol, signal.strength) }); - + let side = match signal.signal_type { SignalType::Buy => Side::Buy, SignalType::Sell => Side::Sell, @@ -292,7 +306,7 @@ impl BacktestEngine { } } }; - + Ok(crate::Order { id: format!("order_{}", uuid::Uuid::new_v4()), symbol: signal.symbol, @@ -302,69 +316,90 @@ impl BacktestEngine { time_in_force: crate::TimeInForce::Day, }) } - + async fn process_order_submission(&mut self, order: Order) -> Result<(), String> { // Risk checks // Get current position for the symbol - let current_position = self.position_tracker + let current_position = self + .position_tracker .get_position(&order.symbol) .map(|p| p.quantity); - - let risk_check = self.risk_engine.check_order(&order, current_position); + + let price = self + .last_prices + .get(&order.symbol) + .map(|(_, price)| *price) + .unwrap_or(f64::NAN); + let price = if order.side == Side::Buy { + price * (1.0 + self.config.slippage) + } else { + price * (1.0 - self.config.slippage) + }; + let risk_check = self + .risk_engine + .check_order(&order, current_position, price); if !risk_check.passed { return Err(format!("Risk check failed: {:?}", risk_check.violations)); } - + // Add to pending orders self.state.write().add_pending_order(order.clone()); - + // For market orders in backtesting, fill immediately if matches!(order.order_type, crate::OrderType::Market) { self.check_order_fill(&order).await?; } - + Ok(()) } - + async fn check_pending_orders(&mut self, market_data: &MarketUpdate) -> Result<(), String> { let orders_to_check: Vec = { let state = self.state.read(); - state.pending_orders.values() + state + .pending_orders + .values() .filter(|o| o.symbol == market_data.symbol) .cloned() .collect() }; - + for order in orders_to_check { self.check_order_fill(&order).await?; } - + Ok(()) } - + async fn check_order_fill(&mut self, order: &Order) -> Result<(), String> { let current_time = self.time_provider.now(); - + // Get current market price - let (price_time, base_price) = self.last_prices.get(&order.symbol) + let (price_time, base_price) = self + .last_prices + .get(&order.symbol) .copied() .ok_or_else(|| format!("No price available for symbol: {}", order.symbol))?; - + // Apply slippage let fill_price = match order.side { crate::Side::Buy => base_price * (1.0 + self.config.slippage), crate::Side::Sell => base_price * (1.0 - self.config.slippage), }; - + // Get the OHLC data that was used let ohlc_info = if let Some(bar) = self.latest_bars.get(&order.symbol) { - format!("O:{:.2} H:{:.2} L:{:.2} C:{:.2}", bar.open, bar.high, bar.low, bar.close) + format!( + "O:{:.2} H:{:.2} L:{:.2} C:{:.2}", + bar.open, bar.high, bar.low, bar.close + ) } else { "No OHLC data".to_string() }; - + // Log trade execution - eprintln!("[TRADE] {} {} {} @ {:.2} | OHLC: {} | Time: {}", + eprintln!( + "[TRADE] {} {} {} @ {:.2} | OHLC: {} | Time: {}", match order.side { crate::Side::Buy => "BUY", crate::Side::Sell => "SELL", @@ -375,7 +410,7 @@ impl BacktestEngine { ohlc_info, current_time.format("%Y-%m-%d %H:%M:%S") ); - + // Create fill let fill = crate::Fill { timestamp: current_time, @@ -383,58 +418,74 @@ impl BacktestEngine { quantity: order.quantity, commission: order.quantity * fill_price * self.config.commission, }; - + // Process the fill self.process_fill(&order, fill).await } - - async fn process_fill(&mut self, order: &crate::Order, fill: crate::Fill) -> Result<(), String> { + + async fn process_fill( + &mut self, + order: &crate::Order, + fill: crate::Fill, + ) -> Result<(), String> { // Remove from pending orders self.state.write().remove_pending_order(&order.id); - + // Get position before the fill - let position_before = self.position_tracker + let position_before = self + .position_tracker .get_position(&order.symbol) .map(|p| p.quantity) .unwrap_or(0.0); - + + let previous_pnl = self + .position_tracker + .get_position(&order.symbol) + .map(|p| p.realized_pnl) + .unwrap_or(0.0); // Update positions - let update = self.position_tracker.process_fill( + let update = self + .position_tracker + .process_fill(&order.symbol, &fill, order.side); + + self.risk_engine.update_position( &order.symbol, - &fill, - order.side, + update.resulting_position.quantity, + fill.price, ); - + self.risk_engine + .update_daily_pnl(update.resulting_position.realized_pnl - previous_pnl); // Calculate P&L if position was reduced/closed let pnl = if update.resulting_position.realized_pnl != 0.0 { - Some(update.resulting_position.realized_pnl) + Some(update.resulting_position.realized_pnl - previous_pnl) } else { None }; - + // Get position after this fill let position_after = update.resulting_position.quantity; - + // Record the fill with position and P&L information self.state.write().record_fill( - order.symbol.clone(), - order.side, + order.symbol.clone(), + order.side, fill.clone(), position_after, position_before, - pnl + pnl, ); - + // Track trades - self.trade_tracker.process_fill(&order.symbol, order.side, &fill); - + self.trade_tracker + .process_fill(&order.symbol, order.side, &fill); + // Update cash let cash_change = match order.side { crate::Side::Buy => -(fill.quantity * fill.price + fill.commission), crate::Side::Sell => fill.quantity * fill.price - fill.commission, }; self.state.write().cash += cash_change; - + // Notify strategies { let mut strategies = self.strategies.write(); @@ -446,31 +497,37 @@ impl BacktestEngine { strategy.on_fill(&order.symbol, fill.quantity, fill.price, side_str); } } - - + // Update metrics self.total_trades += 1; if update.resulting_position.realized_pnl > 0.0 { self.profitable_trades += 1; } - self.total_pnl = update.resulting_position.realized_pnl; - + self.total_pnl = self + .position_tracker + .get_all_positions() + .iter() + .map(|p| p.realized_pnl) + .sum(); + Ok(()) } - + fn process_order_cancellation(&mut self, order_id: &str) -> Result<(), String> { self.state.write().remove_pending_order(order_id); Ok(()) } - + fn advance_time(&mut self, time: DateTime) { - if let Some(simulated_time) = self.time_provider.as_any() - .downcast_ref::() + if let Some(simulated_time) = self + .time_provider + .as_any() + .downcast_ref::() { simulated_time.advance_to(time); } self.state.write().current_time = time; - + // Forward-fill prices: Update timestamps for all symbols to current time // This ensures we don't use stale prices when not all symbols have data at every timestamp let symbols: Vec = self.last_prices.keys().cloned().collect(); @@ -483,124 +540,140 @@ impl BacktestEngine { } } } - + fn update_portfolio_value(&mut self) { let positions = self.position_tracker.get_all_positions(); let cash = self.state.read().cash; let mut portfolio_value = cash; - + for position in &positions { // Use last known price for the symbol - let price = self.last_prices.get(&position.symbol) + let price = self + .last_prices + .get(&position.symbol) .map(|(_, p)| *p) .unwrap_or(position.average_price); - + // Calculate market value correctly for long and short positions let market_value = if position.quantity > 0.0 { // Long position: value = quantity * current_price position.quantity * price } else { - // Short position: + // Short position: // We have a liability to buy back shares at current market price // This is a negative value that reduces portfolio value // Value = quantity * price (quantity is already negative) position.quantity * price }; - + portfolio_value += market_value; } - + self.state.write().update_portfolio_value(portfolio_value); } - + fn calculate_position_size(&self, symbol: &str, signal_strength: f64) -> f64 { let state = self.state.read(); let portfolio_value = state.portfolio_value; let cash = state.cash; - + // Use available cash, not total portfolio value for position sizing let allocation = 0.2; // 20% of available cash per position let position_value = cash.min(portfolio_value * allocation) * signal_strength.abs(); - - let price = self.last_prices.get(symbol) + + let price = self + .last_prices + .get(symbol) .map(|(_, p)| *p) .unwrap_or(100.0); (position_value / price).floor() } - + fn get_next_event_time(&self) -> Option> { // Get the timestamp of the next event in the queue - self.event_queue.read() + self.event_queue + .read() .peek_next() .map(|event| event.timestamp) } - + async fn close_all_positions(&mut self) -> Result<(), String> { // Ensure we have the most recent prices for symbols with positions let current_time = self.time_provider.now(); let positions = self.position_tracker.get_all_positions(); - + // First, ensure all positions have up-to-date prices for position in &positions { if position.quantity.abs() > 0.001 { // Check if we have bar data for this symbol if let Some(latest_bar) = self.latest_bars.get(&position.symbol) { // Use the close price from the latest bar - self.last_prices.insert(position.symbol.clone(), (current_time, latest_bar.close)); - } else if let Some((price_time, price)) = self.last_prices.get(&position.symbol).copied() { + self.last_prices + .insert(position.symbol.clone(), (current_time, latest_bar.close)); + } else if let Some((price_time, price)) = + self.last_prices.get(&position.symbol).copied() + { if price_time < current_time { // Update timestamp to current time for proper fill processing - self.last_prices.insert(position.symbol.clone(), (current_time, price)); + self.last_prices + .insert(position.symbol.clone(), (current_time, price)); } } } } - + for position in positions { if position.quantity.abs() > 0.001 { // Create market order to close position let order = crate::Order { id: format!("close_{}", uuid::Uuid::new_v4()), symbol: position.symbol.clone(), - side: if position.quantity > 0.0 { Side::Sell } else { Side::Buy }, + side: if position.quantity > 0.0 { + Side::Sell + } else { + Side::Buy + }, quantity: position.quantity.abs(), order_type: crate::OrderType::Market, time_in_force: crate::TimeInForce::Day, }; - + // Process the closing order self.check_order_fill(&order).await?; } } - + Ok(()) } - + fn generate_results(&self) -> BacktestResult { let state = self.state.read(); let start_time = self.config.start_time; - + // Get final positions - let final_positions = self.position_tracker.get_all_positions() + let final_positions = self + .position_tracker + .get_all_positions() .into_iter() .map(|p| (p.symbol.clone(), p)) .collect(); - + // Get completed trades from tracker let completed_trades = self.trade_tracker.get_completed_trades(); - + // Convert last_prices to simple HashMap for results - let simple_last_prices: HashMap = self.last_prices + let simple_last_prices: HashMap = self + .last_prices .iter() .map(|(symbol, (_, price))| (symbol.clone(), *price)) .collect(); - + // Debug: Log OHLC history size before generating results eprintln!("[DEBUG] Generating results with OHLC history:"); for (symbol, bars) in &self.ohlc_history { eprintln!(" {}: {} bars", symbol, bars.len()); } - + // Use simple results builder with proper trade data BacktestResult::from_engine_data_with_trades( self.config.clone(), @@ -616,4 +689,4 @@ impl BacktestEngine { } // Add uuid dependency -use uuid::Uuid; \ No newline at end of file +use uuid::Uuid; diff --git a/apps/stock/engine/src/backtest/trade_tracker.rs b/apps/stock/engine/src/backtest/trade_tracker.rs index ce98cf31..17c74043 100644 --- a/apps/stock/engine/src/backtest/trade_tracker.rs +++ b/apps/stock/engine/src/backtest/trade_tracker.rs @@ -1,269 +1,311 @@ -use std::collections::{HashMap, VecDeque}; -use chrono::{DateTime, Utc}; -use serde::{Serialize, Deserialize}; -use crate::{Fill, Side}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct CompletedTrade { - pub id: String, - pub symbol: String, - pub entry_time: DateTime, - pub exit_time: DateTime, - pub entry_price: f64, - pub exit_price: f64, - pub quantity: f64, - pub side: Side, // Side of the opening trade - pub pnl: f64, - pub pnl_percent: f64, - pub commission: f64, - pub duration_seconds: i64, -} - -#[derive(Debug, Clone)] -struct OpenPosition { - symbol: String, - side: Side, - quantity: f64, - entry_price: f64, - entry_time: DateTime, - commission: f64, -} - -/// Tracks fills and matches them into completed trades -pub struct TradeTracker { - open_positions: HashMap>, - completed_trades: Vec, - trade_counter: u64, -} - -impl TradeTracker { - pub fn new() -> Self { - Self { - open_positions: HashMap::new(), - completed_trades: Vec::new(), - trade_counter: 0, - } - } - - pub fn get_completed_trades(&self) -> Vec { - self.completed_trades.clone() - } - - pub fn process_fill(&mut self, symbol: &str, side: Side, fill: &Fill) { - let positions = self.open_positions.entry(symbol.to_string()).or_insert_with(VecDeque::new); - - // Check if this fill closes existing positions - let mut remaining_quantity = fill.quantity; - let mut fills_to_remove = Vec::new(); - - for (idx, open_pos) in positions.iter_mut().enumerate() { - // Only match against opposite side positions - if open_pos.side == side { - continue; - } - - if remaining_quantity <= 0.0 { - break; - } - - let matched_quantity = remaining_quantity.min(open_pos.quantity); - - // Calculate PnL - let (pnl, pnl_percent) = Self::calculate_pnl( - &open_pos, - fill.price, - matched_quantity, - fill.commission, - ); - - // Create completed trade - self.trade_counter += 1; - let completed_trade = CompletedTrade { - id: format!("trade-{}", self.trade_counter), - symbol: symbol.to_string(), - entry_time: open_pos.entry_time, - exit_time: fill.timestamp, - entry_price: open_pos.entry_price, - exit_price: fill.price, - quantity: matched_quantity, - side: open_pos.side.clone(), - pnl, - pnl_percent, - commission: open_pos.commission + (fill.commission * matched_quantity / fill.quantity), - duration_seconds: (fill.timestamp - open_pos.entry_time).num_seconds(), - }; - - eprintln!("📈 TRADE CLOSED: {} {} @ entry: ${:.2} ({}), exit: ${:.2} ({}) = P&L: ${:.2}", - symbol, - match open_pos.side { Side::Buy => "LONG", Side::Sell => "SHORT" }, - open_pos.entry_price, - open_pos.entry_time.format("%Y-%m-%d"), - fill.price, - fill.timestamp.format("%Y-%m-%d"), - pnl - ); - - self.completed_trades.push(completed_trade); - - // Update open position - open_pos.quantity -= matched_quantity; - remaining_quantity -= matched_quantity; - - if open_pos.quantity <= 0.0 { - fills_to_remove.push(idx); - } - } - - // Remove fully closed positions - for idx in fills_to_remove.iter().rev() { - positions.remove(*idx); - } - - // If there's remaining quantity, it opens a new position - if remaining_quantity > 0.0 { - let new_position = OpenPosition { - symbol: symbol.to_string(), - side, - quantity: remaining_quantity, - entry_price: fill.price, - entry_time: fill.timestamp, - commission: fill.commission * remaining_quantity / fill.quantity, - }; - positions.push_back(new_position); - } - } - - fn calculate_pnl(open_pos: &OpenPosition, exit_price: f64, quantity: f64, exit_commission: f64) -> (f64, f64) { - let entry_value = open_pos.entry_price * quantity; - let exit_value = exit_price * quantity; - - let gross_pnl = match open_pos.side { - Side::Buy => exit_value - entry_value, - Side::Sell => entry_value - exit_value, - }; - - let commission = open_pos.commission * (quantity / open_pos.quantity) + exit_commission * (quantity / open_pos.quantity); - let net_pnl = gross_pnl - commission; - let pnl_percent = (net_pnl / entry_value) * 100.0; - - (net_pnl, pnl_percent) - } - - - pub fn get_open_positions(&self) -> HashMap> { - let mut result = HashMap::new(); - - for (symbol, positions) in &self.open_positions { - let pos_info: Vec<(Side, f64, f64)> = positions - .iter() - .map(|p| (p.side.clone(), p.quantity, p.entry_price)) - .collect(); - - if !pos_info.is_empty() { - result.insert(symbol.clone(), pos_info); - } - } - - result - } - - pub fn get_net_position(&self, symbol: &str) -> f64 { - let positions = match self.open_positions.get(symbol) { - Some(pos) => pos, - None => return 0.0, - }; - - let mut net = 0.0; - for pos in positions { - match pos.side { - Side::Buy => net += pos.quantity, - Side::Sell => net -= pos.quantity, - } - } - - net - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_simple_round_trip() { - let mut tracker = TradeTracker::new(); - - // Buy 100 shares at $50 - let buy_fill = Fill { - timestamp: Utc::now(), - price: 50.0, - quantity: 100.0, - commission: 1.0, - }; - tracker.process_fill("AAPL", Side::Buy, &buy_fill); - - // Sell 100 shares at $55 - let sell_fill = Fill { - timestamp: Utc::now(), - price: 55.0, - quantity: 100.0, - commission: 1.0, - }; - tracker.process_fill("AAPL", Side::Sell, &sell_fill); - - let trades = tracker.get_completed_trades(); - assert_eq!(trades.len(), 1); - - let trade = &trades[0]; - assert_eq!(trade.symbol, "AAPL"); - assert_eq!(trade.quantity, 100.0); - assert_eq!(trade.entry_price, 50.0); - assert_eq!(trade.exit_price, 55.0); - assert_eq!(trade.pnl, 498.0); // (55-50)*100 - 2 commission - assert_eq!(trade.side, Side::Buy); - } - - #[test] - fn test_partial_fills() { - let mut tracker = TradeTracker::new(); - - // Buy 100 shares at $50 - let buy_fill = Fill { - timestamp: Utc::now(), - price: 50.0, - quantity: 100.0, - commission: 1.0, - }; - tracker.process_fill("AAPL", Side::Buy, &buy_fill); - - // Sell 60 shares at $55 - let sell_fill1 = Fill { - timestamp: Utc::now(), - price: 55.0, - quantity: 60.0, - commission: 0.6, - }; - tracker.process_fill("AAPL", Side::Sell, &sell_fill1); - - // Check we have one completed trade and remaining position - let trades = tracker.get_completed_trades(); - assert_eq!(trades.len(), 1); - assert_eq!(trades[0].quantity, 60.0); - - assert_eq!(tracker.get_net_position("AAPL"), 40.0); - - // Sell remaining 40 shares at $52 - let sell_fill2 = Fill { - timestamp: Utc::now(), - price: 52.0, - quantity: 40.0, - commission: 0.4, - }; - tracker.process_fill("AAPL", Side::Sell, &sell_fill2); - - // Now we should have 2 completed trades and no position - let trades = tracker.get_completed_trades(); - assert_eq!(trades.len(), 2); - assert_eq!(tracker.get_net_position("AAPL"), 0.0); - } -} \ No newline at end of file +use crate::{Fill, Side}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, VecDeque}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CompletedTrade { + pub id: String, + pub symbol: String, + pub entry_time: DateTime, + pub exit_time: DateTime, + pub entry_price: f64, + pub exit_price: f64, + pub quantity: f64, + pub side: Side, // Side of the opening trade + pub pnl: f64, + pub pnl_percent: f64, + pub commission: f64, + pub duration_seconds: i64, +} + +#[derive(Debug, Clone)] +struct OpenPosition { + symbol: String, + side: Side, + quantity: f64, + entry_price: f64, + entry_time: DateTime, + commission: f64, +} + +/// Tracks fills and matches them into completed trades +pub struct TradeTracker { + open_positions: HashMap>, + completed_trades: Vec, + trade_counter: u64, +} + +impl TradeTracker { + pub fn new() -> Self { + Self { + open_positions: HashMap::new(), + completed_trades: Vec::new(), + trade_counter: 0, + } + } + + pub fn get_completed_trades(&self) -> Vec { + self.completed_trades.clone() + } + + pub fn process_fill(&mut self, symbol: &str, side: Side, fill: &Fill) { + let positions = self + .open_positions + .entry(symbol.to_string()) + .or_insert_with(VecDeque::new); + + // Check if this fill closes existing positions + let mut remaining_quantity = fill.quantity; + let mut fills_to_remove = Vec::new(); + + for (idx, open_pos) in positions.iter_mut().enumerate() { + // Only match against opposite side positions + if open_pos.side == side { + continue; + } + + if remaining_quantity <= 0.0 { + break; + } + + let matched_quantity = remaining_quantity.min(open_pos.quantity); + + // Calculate PnL + let (pnl, pnl_percent) = Self::calculate_pnl( + &open_pos, + fill.price, + matched_quantity, + fill.commission * matched_quantity / fill.quantity, + ); + + // Create completed trade + self.trade_counter += 1; + let completed_trade = CompletedTrade { + id: format!("trade-{}", self.trade_counter), + symbol: symbol.to_string(), + entry_time: open_pos.entry_time, + exit_time: fill.timestamp, + entry_price: open_pos.entry_price, + exit_price: fill.price, + quantity: matched_quantity, + side: open_pos.side.clone(), + pnl, + pnl_percent, + commission: open_pos.commission * matched_quantity / open_pos.quantity + + (fill.commission * matched_quantity / fill.quantity), + duration_seconds: (fill.timestamp - open_pos.entry_time).num_seconds(), + }; + + eprintln!( + "📈 TRADE CLOSED: {} {} @ entry: ${:.2} ({}), exit: ${:.2} ({}) = P&L: ${:.2}", + symbol, + match open_pos.side { + Side::Buy => "LONG", + Side::Sell => "SHORT", + }, + open_pos.entry_price, + open_pos.entry_time.format("%Y-%m-%d"), + fill.price, + fill.timestamp.format("%Y-%m-%d"), + pnl + ); + + self.completed_trades.push(completed_trade); + + // Update open position + open_pos.commission *= 1.0 - matched_quantity / open_pos.quantity; + open_pos.quantity -= matched_quantity; + remaining_quantity -= matched_quantity; + + if open_pos.quantity <= 0.0 { + fills_to_remove.push(idx); + } + } + + // Remove fully closed positions + for idx in fills_to_remove.iter().rev() { + positions.remove(*idx); + } + + // If there's remaining quantity, it opens a new position + if remaining_quantity > 0.0 { + let new_position = OpenPosition { + symbol: symbol.to_string(), + side, + quantity: remaining_quantity, + entry_price: fill.price, + entry_time: fill.timestamp, + commission: fill.commission * remaining_quantity / fill.quantity, + }; + positions.push_back(new_position); + } + } + + fn calculate_pnl( + open_pos: &OpenPosition, + exit_price: f64, + quantity: f64, + exit_commission: f64, + ) -> (f64, f64) { + let entry_value = open_pos.entry_price * quantity; + let exit_value = exit_price * quantity; + + let gross_pnl = match open_pos.side { + Side::Buy => exit_value - entry_value, + Side::Sell => entry_value - exit_value, + }; + + let commission = open_pos.commission * (quantity / open_pos.quantity) + exit_commission; + let net_pnl = gross_pnl - commission; + let pnl_percent = (net_pnl / entry_value) * 100.0; + + (net_pnl, pnl_percent) + } + + pub fn get_open_positions(&self) -> HashMap> { + let mut result = HashMap::new(); + + for (symbol, positions) in &self.open_positions { + let pos_info: Vec<(Side, f64, f64)> = positions + .iter() + .map(|p| (p.side.clone(), p.quantity, p.entry_price)) + .collect(); + + if !pos_info.is_empty() { + result.insert(symbol.clone(), pos_info); + } + } + + result + } + + pub fn get_net_position(&self, symbol: &str) -> f64 { + let positions = match self.open_positions.get(symbol) { + Some(pos) => pos, + None => return 0.0, + }; + + let mut net = 0.0; + for pos in positions { + match pos.side { + Side::Buy => net += pos.quantity, + Side::Sell => net -= pos.quantity, + } + } + + net + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_simple_round_trip() { + let mut tracker = TradeTracker::new(); + + // Buy 100 shares at $50 + let buy_fill = Fill { + timestamp: Utc::now(), + price: 50.0, + quantity: 100.0, + commission: 1.0, + }; + tracker.process_fill("AAPL", Side::Buy, &buy_fill); + + // Sell 100 shares at $55 + let sell_fill = Fill { + timestamp: Utc::now(), + price: 55.0, + quantity: 100.0, + commission: 1.0, + }; + tracker.process_fill("AAPL", Side::Sell, &sell_fill); + + let trades = tracker.get_completed_trades(); + assert_eq!(trades.len(), 1); + + let trade = &trades[0]; + assert_eq!(trade.symbol, "AAPL"); + assert_eq!(trade.quantity, 100.0); + assert_eq!(trade.entry_price, 50.0); + assert_eq!(trade.exit_price, 55.0); + assert_eq!(trade.pnl, 498.0); // (55-50)*100 - 2 commission + assert_eq!(trade.side, Side::Buy); + } + + #[test] + fn test_partial_fills() { + let mut tracker = TradeTracker::new(); + + // Buy 100 shares at $50 + let buy_fill = Fill { + timestamp: Utc::now(), + price: 50.0, + quantity: 100.0, + commission: 1.0, + }; + tracker.process_fill("AAPL", Side::Buy, &buy_fill); + + // Sell 60 shares at $55 + let sell_fill1 = Fill { + timestamp: Utc::now(), + price: 55.0, + quantity: 60.0, + commission: 0.6, + }; + tracker.process_fill("AAPL", Side::Sell, &sell_fill1); + + // Check we have one completed trade and remaining position + let trades = tracker.get_completed_trades(); + assert_eq!(trades.len(), 1); + assert_eq!(trades[0].quantity, 60.0); + + assert_eq!(tracker.get_net_position("AAPL"), 40.0); + + // Sell remaining 40 shares at $52 + let sell_fill2 = Fill { + timestamp: Utc::now(), + price: 52.0, + quantity: 40.0, + commission: 0.4, + }; + tracker.process_fill("AAPL", Side::Sell, &sell_fill2); + + // Now we should have 2 completed trades and no position + let trades = tracker.get_completed_trades(); + assert_eq!(trades.len(), 2); + assert_eq!(tracker.get_net_position("AAPL"), 0.0); + } +} +#[cfg(test)] +mod commission_tests { + use super::*; + #[test] + fn partial_exits_allocate_each_entry_and_exit_commission_once() { + let mut tracker = TradeTracker::new(); + let now = Utc::now(); + for (side, price, quantity, commission) in [ + (Side::Buy, 100.0, 10.0, 1.0), + (Side::Sell, 110.0, 4.0, 0.4), + (Side::Sell, 90.0, 10.0, 1.0), + (Side::Buy, 80.0, 4.0, 0.4), + ] { + tracker.process_fill( + "A", + side, + &Fill { + timestamp: now, + price, + quantity, + commission, + }, + ); + } + let trades = tracker.get_completed_trades(); + assert!((trades.iter().map(|t| t.commission).sum::() - 2.8).abs() < 1e-8); + assert!((trades.iter().map(|t| t.pnl).sum::() - 17.2).abs() < 1e-8); + } +} diff --git a/apps/stock/engine/src/core/execution_handlers.rs b/apps/stock/engine/src/core/execution_handlers.rs index 78cd36b9..d6bf40e2 100644 --- a/apps/stock/engine/src/core/execution_handlers.rs +++ b/apps/stock/engine/src/core/execution_handlers.rs @@ -1,288 +1,286 @@ -use crate::{ExecutionHandler, FillSimulator, Order, ExecutionResult, OrderStatus, Fill, OrderBookSnapshot, OrderType, Side, MarketMicrostructure}; -use crate::analytics::{MarketImpactModel, ImpactModelType}; -use chrono::Utc; -use parking_lot::Mutex; -use std::collections::HashMap; - -// Simulated execution for backtest and paper trading -pub struct SimulatedExecution { - fill_simulator: Box, - pending_orders: Mutex>, -} - -impl SimulatedExecution { - pub fn new(fill_simulator: Box) -> Self { - Self { - fill_simulator, - pending_orders: Mutex::new(HashMap::new()), - } - } - - pub fn check_pending_orders(&self, orderbook: &OrderBookSnapshot) -> Vec { - let mut results = Vec::new(); - let mut pending = self.pending_orders.lock(); - - pending.retain(|order_id, order| { - if let Some(fill) = self.fill_simulator.simulate_fill(order, orderbook) { - results.push(ExecutionResult { - order_id: order_id.clone(), - status: OrderStatus::Filled, - fills: vec![fill], - }); - false // Remove from pending - } else { - true // Keep in pending - } - }); - - results - } -} - -#[async_trait::async_trait] -impl ExecutionHandler for SimulatedExecution { - async fn execute_order(&mut self, order: Order) -> Result { - // For market orders, execute immediately - // For limit orders, add to pending - match &order.order_type { - OrderType::Market => { - // In simulation, market orders always fill - // The orchestrator will provide the orderbook for realistic fills - Ok(ExecutionResult { - order_id: order.id.clone(), - status: OrderStatus::Pending, - fills: vec![], - }) - } - OrderType::Limit { .. } => { - self.pending_orders.lock().insert(order.id.clone(), order.clone()); - Ok(ExecutionResult { - order_id: order.id, - status: OrderStatus::Accepted, - fills: vec![], - }) - } - _ => Err("Order type not yet implemented".to_string()), - } - } - - fn get_fill_simulator(&self) -> Option<&dyn FillSimulator> { - Some(&*self.fill_simulator) - } -} - -// Backtest fill simulator - uses historical data -pub struct BacktestFillSimulator { - slippage_model: SlippageModel, - impact_model: MarketImpactModel, - microstructure_cache: Mutex>, - commission_rate: f64, - slippage_rate: f64, -} - -impl BacktestFillSimulator { - pub fn new() -> Self { - Self::with_config(0.001, 0.0001) // Default values - } - - pub fn with_config(commission_rate: f64, slippage_rate: f64) -> Self { - Self { - slippage_model: SlippageModel::default(), - impact_model: MarketImpactModel::new(ImpactModelType::SquareRoot), - microstructure_cache: Mutex::new(HashMap::new()), - commission_rate, - slippage_rate, - } - } - - pub fn with_impact_model(mut self, model_type: ImpactModelType) -> Self { - self.impact_model = MarketImpactModel::new(model_type); - self - } - - pub fn set_microstructure(&self, symbol: String, microstructure: MarketMicrostructure) { - self.microstructure_cache.lock().insert(symbol, microstructure); - } -} - -impl FillSimulator for BacktestFillSimulator { - fn simulate_fill(&self, order: &Order, orderbook: &OrderBookSnapshot) -> Option { - match &order.order_type { - OrderType::Market => { - // Get market microstructure if available - let microstructure_guard = self.microstructure_cache.lock(); - let maybe_microstructure = microstructure_guard.get(&order.symbol); - - // Calculate price with market impact - let (price, _impact) = if let Some(microstructure) = maybe_microstructure { - // Use sophisticated market impact model - let impact_estimate = self.impact_model.estimate_impact( - order.quantity, - order.side, - microstructure, - match order.side { - Side::Buy => &orderbook.asks, - Side::Sell => &orderbook.bids, - }, - Utc::now(), - ); - - let base_price = match order.side { - Side::Buy => orderbook.asks.first()?.price, - Side::Sell => orderbook.bids.first()?.price, - }; - - let impact_price = match order.side { - Side::Buy => base_price * (1.0 + impact_estimate.total_impact / 10000.0), - Side::Sell => base_price * (1.0 - impact_estimate.total_impact / 10000.0), - }; - - (impact_price, impact_estimate.total_impact) - } else { - // Fallback to simple slippage model - match order.side { - Side::Buy => { - let base_price = orderbook.asks.first()?.price; - let slippage = self.slippage_model.calculate_slippage(order.quantity, &orderbook.asks); - (base_price + slippage, slippage * 10000.0 / base_price) - } - Side::Sell => { - let base_price = orderbook.bids.first()?.price; - let slippage = self.slippage_model.calculate_slippage(order.quantity, &orderbook.bids); - (base_price - slippage, slippage * 10000.0 / base_price) - } - } - }; - - // Calculate commission using configured rate - let commission = order.quantity * price * self.commission_rate; - - Some(Fill { - timestamp: Utc::now(), // Will be overridden by backtest engine - price, - quantity: order.quantity, - commission, - }) - } - OrderType::Limit { price: limit_price } => { - // Check if limit can be filled - match order.side { - Side::Buy => { - if orderbook.asks.first()?.price <= *limit_price { - Some(Fill { - timestamp: Utc::now(), - price: *limit_price, - quantity: order.quantity, - commission: order.quantity * limit_price * self.commission_rate, - }) - } else { - None - } - } - Side::Sell => { - if orderbook.bids.first()?.price >= *limit_price { - Some(Fill { - timestamp: Utc::now(), - price: *limit_price, - quantity: order.quantity, - commission: order.quantity * limit_price * self.commission_rate, - }) - } else { - None - } - } - } - } - _ => None, - } - } -} - -// Paper trading fill simulator - uses real order book -pub struct PaperFillSimulator { - use_real_orderbook: bool, - add_latency_ms: u64, -} - -impl PaperFillSimulator { - pub fn new() -> Self { - Self { - use_real_orderbook: true, - add_latency_ms: 100, // Simulate 100ms latency - } - } -} - -impl FillSimulator for PaperFillSimulator { - fn simulate_fill(&self, order: &Order, orderbook: &OrderBookSnapshot) -> Option { - // Similar to backtest but with more realistic modeling - // Consider actual order book depth - // Add realistic latency simulation - // Respect position size limits based on actual liquidity - - // For now, similar implementation to backtest - BacktestFillSimulator::new().simulate_fill(order, orderbook) - } -} - -// Real broker execution for live trading -pub struct BrokerExecution { - broker: String, - account_id: String, - // In real implementation, would have broker API client -} - -impl BrokerExecution { - pub fn new(broker: String, account_id: String) -> Self { - Self { - broker, - account_id, - } - } -} - -#[async_trait::async_trait] -impl ExecutionHandler for BrokerExecution { - async fn execute_order(&mut self, order: Order) -> Result { - // In real implementation, would: - // 1. Connect to broker API - // 2. Submit order - // 3. Handle broker responses - // 4. Track order status - - // Placeholder for now - Ok(ExecutionResult { - order_id: order.id, - status: OrderStatus::Pending, - fills: vec![], - }) - } - - fn get_fill_simulator(&self) -> Option<&dyn FillSimulator> { - None // Real broker doesn't simulate - } -} - -// Slippage model for realistic fills -#[derive(Default)] -struct SlippageModel { - base_slippage_bps: f64, - impact_coefficient: f64, -} - -impl SlippageModel { - fn calculate_slippage(&self, quantity: f64, levels: &[crate::PriceLevel]) -> f64 { - // Simple linear impact model - // In reality would use square-root or more sophisticated model - let total_liquidity: f64 = levels.iter().map(|l| l.size).sum(); - let participation_rate = quantity / total_liquidity.max(1.0); - - let spread = if levels.len() >= 2 { - (levels[1].price - levels[0].price).abs() - } else { - levels[0].price * 0.0001 // 1 bps if only one level - }; - - spread * participation_rate * self.impact_coefficient - } -} \ No newline at end of file +use crate::analytics::{ImpactModelType, MarketImpactModel}; +use crate::{ + ExecutionHandler, ExecutionResult, Fill, FillSimulator, MarketMicrostructure, Order, + OrderBookSnapshot, OrderStatus, OrderType, Side, +}; +use chrono::Utc; +use parking_lot::Mutex; +use std::collections::HashMap; + +// Simulated execution for backtest and paper trading +pub struct SimulatedExecution { + fill_simulator: Box, + pending_orders: Mutex>, +} + +impl SimulatedExecution { + pub fn new(fill_simulator: Box) -> Self { + Self { + fill_simulator, + pending_orders: Mutex::new(HashMap::new()), + } + } + + pub fn check_pending_orders(&self, orderbook: &OrderBookSnapshot) -> Vec { + let mut results = Vec::new(); + let mut pending = self.pending_orders.lock(); + + pending.retain(|order_id, order| { + if let Some(fill) = self.fill_simulator.simulate_fill(order, orderbook) { + results.push(ExecutionResult { + order_id: order_id.clone(), + status: OrderStatus::Filled, + fills: vec![fill], + }); + false // Remove from pending + } else { + true // Keep in pending + } + }); + + results + } +} + +#[async_trait::async_trait] +impl ExecutionHandler for SimulatedExecution { + async fn execute_order(&mut self, order: Order) -> Result { + // For market orders, execute immediately + // For limit orders, add to pending + match &order.order_type { + OrderType::Market => { + // In simulation, market orders always fill + // The orchestrator will provide the orderbook for realistic fills + Ok(ExecutionResult { + order_id: order.id.clone(), + status: OrderStatus::Pending, + fills: vec![], + }) + } + OrderType::Limit { .. } => { + self.pending_orders + .lock() + .insert(order.id.clone(), order.clone()); + Ok(ExecutionResult { + order_id: order.id, + status: OrderStatus::Accepted, + fills: vec![], + }) + } + _ => Err("Order type not yet implemented".to_string()), + } + } + + fn get_fill_simulator(&self) -> Option<&dyn FillSimulator> { + Some(&*self.fill_simulator) + } +} + +// Backtest fill simulator - uses historical data +pub struct BacktestFillSimulator { + slippage_model: SlippageModel, + impact_model: MarketImpactModel, + microstructure_cache: Mutex>, + commission_rate: f64, + slippage_rate: f64, +} + +impl BacktestFillSimulator { + pub fn new() -> Self { + Self::with_config(0.001, 0.0001) // Default values + } + + pub fn with_config(commission_rate: f64, slippage_rate: f64) -> Self { + Self { + slippage_model: SlippageModel::default(), + impact_model: MarketImpactModel::new(ImpactModelType::SquareRoot), + microstructure_cache: Mutex::new(HashMap::new()), + commission_rate, + slippage_rate, + } + } + + pub fn with_impact_model(mut self, model_type: ImpactModelType) -> Self { + self.impact_model = MarketImpactModel::new(model_type); + self + } + + pub fn set_microstructure(&self, symbol: String, microstructure: MarketMicrostructure) { + self.microstructure_cache + .lock() + .insert(symbol, microstructure); + } +} + +impl FillSimulator for BacktestFillSimulator { + fn simulate_fill(&self, order: &Order, orderbook: &OrderBookSnapshot) -> Option { + match &order.order_type { + OrderType::Market => { + // Get market microstructure if available + let microstructure_guard = self.microstructure_cache.lock(); + let maybe_microstructure = microstructure_guard.get(&order.symbol); + + // Calculate price with market impact + let (price, _impact) = if let Some(microstructure) = maybe_microstructure { + // Use sophisticated market impact model + let impact_estimate = self.impact_model.estimate_impact( + order.quantity, + order.side, + microstructure, + match order.side { + Side::Buy => &orderbook.asks, + Side::Sell => &orderbook.bids, + }, + Utc::now(), + ); + + let base_price = match order.side { + Side::Buy => orderbook.asks.first()?.price, + Side::Sell => orderbook.bids.first()?.price, + }; + + let impact_price = match order.side { + Side::Buy => base_price * (1.0 + impact_estimate.total_impact / 10000.0), + Side::Sell => base_price * (1.0 - impact_estimate.total_impact / 10000.0), + }; + + (impact_price, impact_estimate.total_impact) + } else { + // Fallback to simple slippage model + match order.side { + Side::Buy => { + let base_price = orderbook.asks.first()?.price; + let slippage = self + .slippage_model + .calculate_slippage(order.quantity, &orderbook.asks); + (base_price + slippage, slippage * 10000.0 / base_price) + } + Side::Sell => { + let base_price = orderbook.bids.first()?.price; + let slippage = self + .slippage_model + .calculate_slippage(order.quantity, &orderbook.bids); + (base_price - slippage, slippage * 10000.0 / base_price) + } + } + }; + + // Calculate commission using configured rate + let commission = order.quantity * price * self.commission_rate; + + Some(Fill { + timestamp: Utc::now(), // Will be overridden by backtest engine + price, + quantity: order.quantity, + commission, + }) + } + OrderType::Limit { price: limit_price } => { + // Check if limit can be filled + match order.side { + Side::Buy => { + if orderbook.asks.first()?.price <= *limit_price { + Some(Fill { + timestamp: Utc::now(), + price: *limit_price, + quantity: order.quantity, + commission: order.quantity * limit_price * self.commission_rate, + }) + } else { + None + } + } + Side::Sell => { + if orderbook.bids.first()?.price >= *limit_price { + Some(Fill { + timestamp: Utc::now(), + price: *limit_price, + quantity: order.quantity, + commission: order.quantity * limit_price * self.commission_rate, + }) + } else { + None + } + } + } + } + _ => None, + } + } +} + +// Paper trading fill simulator - uses real order book +pub struct PaperFillSimulator { + use_real_orderbook: bool, + add_latency_ms: u64, +} + +impl PaperFillSimulator { + pub fn new() -> Self { + Self { + use_real_orderbook: true, + add_latency_ms: 100, // Simulate 100ms latency + } + } +} + +impl FillSimulator for PaperFillSimulator { + fn simulate_fill(&self, order: &Order, orderbook: &OrderBookSnapshot) -> Option { + // Similar to backtest but with more realistic modeling + // Consider actual order book depth + // Add realistic latency simulation + // Respect position size limits based on actual liquidity + + // For now, similar implementation to backtest + BacktestFillSimulator::new().simulate_fill(order, orderbook) + } +} + +// Real broker execution for live trading +pub struct BrokerExecution { + broker: String, + account_id: String, + // In real implementation, would have broker API client +} + +impl BrokerExecution { + pub fn new(broker: String, account_id: String) -> Self { + Self { broker, account_id } + } +} + +#[async_trait::async_trait] +impl ExecutionHandler for BrokerExecution { + async fn execute_order(&mut self, order: Order) -> Result { + let _ = order; + Err("Live trading is disabled: no real broker adapter exists".to_string()) + } + + fn get_fill_simulator(&self) -> Option<&dyn FillSimulator> { + None // Real broker doesn't simulate + } +} + +// Slippage model for realistic fills +#[derive(Default)] +struct SlippageModel { + base_slippage_bps: f64, + impact_coefficient: f64, +} + +impl SlippageModel { + fn calculate_slippage(&self, quantity: f64, levels: &[crate::PriceLevel]) -> f64 { + // Simple linear impact model + // In reality would use square-root or more sophisticated model + let total_liquidity: f64 = levels.iter().map(|l| l.size).sum(); + let participation_rate = quantity / total_liquidity.max(1.0); + + let spread = if levels.len() >= 2 { + (levels[1].price - levels[0].price).abs() + } else { + levels[0].price * 0.0001 // 1 bps if only one level + }; + + spread * participation_rate * self.impact_coefficient + } +} diff --git a/apps/stock/engine/src/positions/mod.rs b/apps/stock/engine/src/positions/mod.rs index 028c99c0..4c513c63 100644 --- a/apps/stock/engine/src/positions/mod.rs +++ b/apps/stock/engine/src/positions/mod.rs @@ -1,398 +1,431 @@ -use crate::{Fill, Side}; -use chrono::{DateTime, Utc}; -use dashmap::DashMap; -use serde::{Deserialize, Serialize}; -use std::sync::Arc; -use parking_lot::RwLock; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Position { - pub symbol: String, - pub quantity: f64, - pub average_price: f64, - pub realized_pnl: f64, - pub unrealized_pnl: f64, - pub total_cost: f64, - pub last_update: DateTime, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct PositionUpdate { - pub symbol: String, - pub fill: Fill, - pub resulting_position: Position, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct TradeRecord { - pub id: String, - pub symbol: String, - pub side: Side, - pub quantity: f64, - pub price: f64, - pub timestamp: DateTime, - pub commission: f64, - pub order_id: Option, - pub strategy_id: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct ClosedTrade { - pub id: String, - pub symbol: String, - pub entry_time: DateTime, - pub exit_time: DateTime, - pub entry_price: f64, - pub exit_price: f64, - pub quantity: f64, - pub side: Side, // Side of the opening trade - pub pnl: f64, - pub pnl_percent: f64, - pub commission: f64, - pub duration_ms: i64, - pub entry_fill_id: String, - pub exit_fill_id: String, -} - -pub struct PositionTracker { - positions: DashMap, - trade_history: Arc>>, - closed_trades: Arc>>, - open_trades: DashMap>, // Track open trades by symbol - next_trade_id: Arc>, -} - -impl PositionTracker { - pub fn new() -> Self { - Self { - positions: DashMap::new(), - trade_history: Arc::new(RwLock::new(Vec::new())), - closed_trades: Arc::new(RwLock::new(Vec::new())), - open_trades: DashMap::new(), - next_trade_id: Arc::new(RwLock::new(1)), - } - } - - fn generate_trade_id(&self) -> String { - let mut id = self.next_trade_id.write(); - let current_id = *id; - *id += 1; - format!("T{:08}", current_id) - } - - pub fn process_fill_with_tracking( - &self, - symbol: &str, - fill: &Fill, - side: Side, - order_id: Option, - strategy_id: Option - ) -> PositionUpdate { - // First process the fill normally - let update = self.process_fill(symbol, fill, side); - - // Create trade record - let trade_record = TradeRecord { - id: self.generate_trade_id(), - symbol: symbol.to_string(), - side, - quantity: fill.quantity, - price: fill.price, - timestamp: fill.timestamp, - commission: fill.commission, - order_id, - strategy_id, - }; - - // Add to trade history - self.trade_history.write().push(trade_record.clone()); - - // Handle trade matching for closed trades - match side { - Side::Buy => { - // For buy orders, try to match with open sell trades (closing shorts) - if let Some(mut open_trades) = self.open_trades.get_mut(symbol) { - let mut remaining_quantity = fill.quantity; - let mut trades_to_remove = Vec::new(); - - // FIFO matching against short positions - for (idx, open_trade) in open_trades.iter_mut().enumerate() { - if open_trade.side == Side::Sell && remaining_quantity > 0.0 { - let close_quantity = remaining_quantity.min(open_trade.quantity); - - // Create closed trade record for short position - let closed_trade = ClosedTrade { - id: format!("CT{}", self.generate_trade_id()), - symbol: symbol.to_string(), - entry_time: open_trade.timestamp, - exit_time: fill.timestamp, - entry_price: open_trade.price, - exit_price: fill.price, - quantity: close_quantity, - side: Side::Sell, // Opening side (short) - pnl: close_quantity * (open_trade.price - fill.price) - (open_trade.commission + fill.commission * close_quantity / fill.quantity), - pnl_percent: ((open_trade.price - fill.price) / open_trade.price) * 100.0, - commission: open_trade.commission + fill.commission * close_quantity / fill.quantity, - duration_ms: (fill.timestamp - open_trade.timestamp).num_milliseconds(), - entry_fill_id: open_trade.id.clone(), - exit_fill_id: trade_record.id.clone(), - }; - - self.closed_trades.write().push(closed_trade); - - // Update quantities - remaining_quantity -= close_quantity; - open_trade.quantity -= close_quantity; - - if open_trade.quantity <= 0.0 { - trades_to_remove.push(idx); - } - } - } - - // Remove fully closed trades - for idx in trades_to_remove.into_iter().rev() { - open_trades.remove(idx); - } - - // If we still have quantity left, it's a new long position - if remaining_quantity > 0.0 { - let long_trade = TradeRecord { - quantity: remaining_quantity, - ..trade_record.clone() - }; - open_trades.push(long_trade); - } - } else { - // No open trades, start a new long position - self.open_trades.entry(symbol.to_string()) - .or_insert_with(Vec::new) - .push(trade_record); - } - } - Side::Sell => { - // For sell orders, try to match with open buy trades - if let Some(mut open_trades) = self.open_trades.get_mut(symbol) { - let mut remaining_quantity = fill.quantity; - let mut trades_to_remove = Vec::new(); - - // FIFO matching - for (idx, open_trade) in open_trades.iter_mut().enumerate() { - if open_trade.side == Side::Buy && remaining_quantity > 0.0 { - let close_quantity = remaining_quantity.min(open_trade.quantity); - - // Create closed trade record - let closed_trade = ClosedTrade { - id: format!("CT{}", self.generate_trade_id()), - symbol: symbol.to_string(), - entry_time: open_trade.timestamp, - exit_time: fill.timestamp, - entry_price: open_trade.price, - exit_price: fill.price, - quantity: close_quantity, - side: Side::Buy, // Opening side - pnl: close_quantity * (fill.price - open_trade.price) - (open_trade.commission + fill.commission * close_quantity / fill.quantity), - pnl_percent: ((fill.price - open_trade.price) / open_trade.price) * 100.0, - commission: open_trade.commission + fill.commission * close_quantity / fill.quantity, - duration_ms: (fill.timestamp - open_trade.timestamp).num_milliseconds(), - entry_fill_id: open_trade.id.clone(), - exit_fill_id: trade_record.id.clone(), - }; - - self.closed_trades.write().push(closed_trade); - - // Update quantities - remaining_quantity -= close_quantity; - open_trade.quantity -= close_quantity; - - if open_trade.quantity <= 0.0 { - trades_to_remove.push(idx); - } - } - } - - // Remove fully closed trades - for idx in trades_to_remove.into_iter().rev() { - open_trades.remove(idx); - } - - // If we still have quantity left, it's a short position - if remaining_quantity > 0.0 { - let short_trade = TradeRecord { - quantity: remaining_quantity, - ..trade_record.clone() - }; - open_trades.push(short_trade); - } - } else { - // No open trades, start a new short position - self.open_trades.entry(symbol.to_string()) - .or_insert_with(Vec::new) - .push(trade_record); - } - } - } - - update - } - - pub fn process_fill(&self, symbol: &str, fill: &Fill, side: Side) -> PositionUpdate { - let mut entry = self.positions.entry(symbol.to_string()).or_insert_with(|| { - Position { - symbol: symbol.to_string(), - quantity: 0.0, - average_price: 0.0, - realized_pnl: 0.0, - unrealized_pnl: 0.0, - total_cost: 0.0, - last_update: fill.timestamp, - } - }); - - let position = entry.value_mut(); - let old_quantity = position.quantity; - let old_avg_price = position.average_price; - - // Calculate new position - match side { - Side::Buy => { - // Adding to position - position.quantity += fill.quantity; - if old_quantity >= 0.0 { - // Already long or flat, average up/down - position.total_cost += fill.price * fill.quantity; - position.average_price = if position.quantity > 0.0 { - position.total_cost / position.quantity - } else { - 0.0 - }; - } else { - // Was short, closing or flipping - let close_quantity = fill.quantity.min(-old_quantity); - let open_quantity = fill.quantity - close_quantity; - - // Realize P&L on closed portion - position.realized_pnl += close_quantity * (old_avg_price - fill.price); - - // Update position for remaining - if open_quantity > 0.0 { - position.total_cost = open_quantity * fill.price; - position.average_price = fill.price; - } else { - position.total_cost = (position.quantity.abs()) * old_avg_price; - } - } - } - Side::Sell => { - // Reducing position - position.quantity -= fill.quantity; - if old_quantity <= 0.0 { - // Already short or flat, average up/down - position.total_cost += fill.price * fill.quantity; - position.average_price = if position.quantity < 0.0 { - position.total_cost / position.quantity.abs() - } else { - 0.0 - }; - } else { - // Was long, closing or flipping - let close_quantity = fill.quantity.min(old_quantity); - let open_quantity = fill.quantity - close_quantity; - - // Realize P&L on closed portion - position.realized_pnl += close_quantity * (fill.price - old_avg_price); - - // Update position for remaining - if open_quantity > 0.0 { - position.total_cost = open_quantity * fill.price; - position.average_price = fill.price; - } else { - position.total_cost = (position.quantity.abs()) * old_avg_price; - } - } - } - } - - // Subtract commission from realized P&L - position.realized_pnl -= fill.commission; - position.last_update = fill.timestamp; - - PositionUpdate { - symbol: symbol.to_string(), - fill: fill.clone(), - resulting_position: position.clone(), - } - } - - pub fn get_position(&self, symbol: &str) -> Option { - self.positions.get(symbol).map(|p| p.clone()) - } - - pub fn get_all_positions(&self) -> Vec { - self.positions.iter().map(|entry| entry.value().clone()).collect() - } - - pub fn get_open_positions(&self) -> Vec { - self.positions - .iter() - .filter(|entry| entry.value().quantity.abs() > 0.0001) - .map(|entry| entry.value().clone()) - .collect() - } - - pub fn update_unrealized_pnl(&self, symbol: &str, current_price: f64) { - if let Some(mut position) = self.positions.get_mut(symbol) { - if position.quantity > 0.0 { - position.unrealized_pnl = position.quantity * (current_price - position.average_price); - } else if position.quantity < 0.0 { - position.unrealized_pnl = position.quantity * (current_price - position.average_price); - } else { - position.unrealized_pnl = 0.0; - } - } - } - - pub fn get_total_pnl(&self) -> (f64, f64) { - let mut realized = 0.0; - let mut unrealized = 0.0; - - for position in self.positions.iter() { - realized += position.realized_pnl; - unrealized += position.unrealized_pnl; - } - - (realized, unrealized) - } - - pub fn reset(&self) { - self.positions.clear(); - self.trade_history.write().clear(); - self.closed_trades.write().clear(); - self.open_trades.clear(); - *self.next_trade_id.write() = 1; - } - - pub fn get_trade_history(&self) -> Vec { - self.trade_history.read().clone() - } - - pub fn get_closed_trades(&self) -> Vec { - self.closed_trades.read().clone() - } - - pub fn get_open_trades(&self) -> Vec { - let mut all_open_trades = Vec::new(); - for entry in self.open_trades.iter() { - all_open_trades.extend(entry.value().clone()); - } - all_open_trades - } - - pub fn get_trade_count(&self) -> usize { - self.trade_history.read().len() - } - - pub fn get_closed_trade_count(&self) -> usize { - self.closed_trades.read().len() - } -} \ No newline at end of file +use crate::{Fill, Side}; +use chrono::{DateTime, Utc}; +use dashmap::DashMap; +use parking_lot::RwLock; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Position { + pub symbol: String, + pub quantity: f64, + pub average_price: f64, + pub realized_pnl: f64, + pub unrealized_pnl: f64, + pub total_cost: f64, + pub last_update: DateTime, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PositionUpdate { + pub symbol: String, + pub fill: Fill, + pub resulting_position: Position, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TradeRecord { + pub id: String, + pub symbol: String, + pub side: Side, + pub quantity: f64, + pub price: f64, + pub timestamp: DateTime, + pub commission: f64, + pub order_id: Option, + pub strategy_id: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ClosedTrade { + pub id: String, + pub symbol: String, + pub entry_time: DateTime, + pub exit_time: DateTime, + pub entry_price: f64, + pub exit_price: f64, + pub quantity: f64, + pub side: Side, // Side of the opening trade + pub pnl: f64, + pub pnl_percent: f64, + pub commission: f64, + pub duration_ms: i64, + pub entry_fill_id: String, + pub exit_fill_id: String, +} + +pub struct PositionTracker { + positions: DashMap, + trade_history: Arc>>, + closed_trades: Arc>>, + open_trades: DashMap>, // Track open trades by symbol + next_trade_id: Arc>, +} + +impl PositionTracker { + pub fn new() -> Self { + Self { + positions: DashMap::new(), + trade_history: Arc::new(RwLock::new(Vec::new())), + closed_trades: Arc::new(RwLock::new(Vec::new())), + open_trades: DashMap::new(), + next_trade_id: Arc::new(RwLock::new(1)), + } + } + + fn generate_trade_id(&self) -> String { + let mut id = self.next_trade_id.write(); + let current_id = *id; + *id += 1; + format!("T{:08}", current_id) + } + + pub fn process_fill_with_tracking( + &self, + symbol: &str, + fill: &Fill, + side: Side, + order_id: Option, + strategy_id: Option, + ) -> PositionUpdate { + // First process the fill normally + let update = self.process_fill(symbol, fill, side); + + // Create trade record + let trade_record = TradeRecord { + id: self.generate_trade_id(), + symbol: symbol.to_string(), + side, + quantity: fill.quantity, + price: fill.price, + timestamp: fill.timestamp, + commission: fill.commission, + order_id, + strategy_id, + }; + + // Add to trade history + self.trade_history.write().push(trade_record.clone()); + + // Handle trade matching for closed trades + match side { + Side::Buy => { + // For buy orders, try to match with open sell trades (closing shorts) + if let Some(mut open_trades) = self.open_trades.get_mut(symbol) { + let mut remaining_quantity = fill.quantity; + let mut trades_to_remove = Vec::new(); + + // FIFO matching against short positions + for (idx, open_trade) in open_trades.iter_mut().enumerate() { + if open_trade.side == Side::Sell && remaining_quantity > 0.0 { + let close_quantity = remaining_quantity.min(open_trade.quantity); + + let entry_commission = + open_trade.commission * close_quantity / open_trade.quantity; + let exit_commission = fill.commission * close_quantity / fill.quantity; + // Create closed trade record for short position + let closed_trade = ClosedTrade { + id: format!("CT{}", self.generate_trade_id()), + symbol: symbol.to_string(), + entry_time: open_trade.timestamp, + exit_time: fill.timestamp, + entry_price: open_trade.price, + exit_price: fill.price, + quantity: close_quantity, + side: Side::Sell, // Opening side (short) + pnl: close_quantity * (open_trade.price - fill.price) + - (entry_commission + exit_commission), + pnl_percent: ((open_trade.price - fill.price) / open_trade.price) + * 100.0, + commission: entry_commission + exit_commission, + duration_ms: (fill.timestamp - open_trade.timestamp) + .num_milliseconds(), + entry_fill_id: open_trade.id.clone(), + exit_fill_id: trade_record.id.clone(), + }; + + self.closed_trades.write().push(closed_trade); + + // Update quantities + remaining_quantity -= close_quantity; + open_trade.commission -= entry_commission; + open_trade.quantity -= close_quantity; + + if open_trade.quantity <= 0.0 { + trades_to_remove.push(idx); + } + } + } + + // Remove fully closed trades + for idx in trades_to_remove.into_iter().rev() { + open_trades.remove(idx); + } + + // If we still have quantity left, it's a new long position + if remaining_quantity > 0.0 { + let long_trade = TradeRecord { + quantity: remaining_quantity, + commission: fill.commission * remaining_quantity / fill.quantity, + ..trade_record.clone() + }; + open_trades.push(long_trade); + } + } else { + // No open trades, start a new long position + self.open_trades + .entry(symbol.to_string()) + .or_insert_with(Vec::new) + .push(trade_record); + } + } + Side::Sell => { + // For sell orders, try to match with open buy trades + if let Some(mut open_trades) = self.open_trades.get_mut(symbol) { + let mut remaining_quantity = fill.quantity; + let mut trades_to_remove = Vec::new(); + + // FIFO matching + for (idx, open_trade) in open_trades.iter_mut().enumerate() { + if open_trade.side == Side::Buy && remaining_quantity > 0.0 { + let close_quantity = remaining_quantity.min(open_trade.quantity); + + let entry_commission = + open_trade.commission * close_quantity / open_trade.quantity; + let exit_commission = fill.commission * close_quantity / fill.quantity; + // Create closed trade record + let closed_trade = ClosedTrade { + id: format!("CT{}", self.generate_trade_id()), + symbol: symbol.to_string(), + entry_time: open_trade.timestamp, + exit_time: fill.timestamp, + entry_price: open_trade.price, + exit_price: fill.price, + quantity: close_quantity, + side: Side::Buy, // Opening side + pnl: close_quantity * (fill.price - open_trade.price) + - (entry_commission + exit_commission), + pnl_percent: ((fill.price - open_trade.price) / open_trade.price) + * 100.0, + commission: entry_commission + exit_commission, + duration_ms: (fill.timestamp - open_trade.timestamp) + .num_milliseconds(), + entry_fill_id: open_trade.id.clone(), + exit_fill_id: trade_record.id.clone(), + }; + + self.closed_trades.write().push(closed_trade); + + // Update quantities + remaining_quantity -= close_quantity; + open_trade.commission -= entry_commission; + open_trade.quantity -= close_quantity; + + if open_trade.quantity <= 0.0 { + trades_to_remove.push(idx); + } + } + } + + // Remove fully closed trades + for idx in trades_to_remove.into_iter().rev() { + open_trades.remove(idx); + } + + // If we still have quantity left, it's a short position + if remaining_quantity > 0.0 { + let short_trade = TradeRecord { + quantity: remaining_quantity, + commission: fill.commission * remaining_quantity / fill.quantity, + ..trade_record.clone() + }; + open_trades.push(short_trade); + } + } else { + // No open trades, start a new short position + self.open_trades + .entry(symbol.to_string()) + .or_insert_with(Vec::new) + .push(trade_record); + } + } + } + + update + } + + pub fn process_fill(&self, symbol: &str, fill: &Fill, side: Side) -> PositionUpdate { + let mut entry = self + .positions + .entry(symbol.to_string()) + .or_insert_with(|| Position { + symbol: symbol.to_string(), + quantity: 0.0, + average_price: 0.0, + realized_pnl: 0.0, + unrealized_pnl: 0.0, + total_cost: 0.0, + last_update: fill.timestamp, + }); + + let position = entry.value_mut(); + let old_quantity = position.quantity; + let old_avg_price = position.average_price; + + let signed = if side == Side::Buy { + fill.quantity + } else { + -fill.quantity + }; + let new_quantity = old_quantity + signed; + let closing = old_quantity * signed < 0.0; + let closed = if closing { + old_quantity.abs().min(fill.quantity) + } else { + 0.0 + }; + position.realized_pnl += + closed * (fill.price - old_avg_price) * old_quantity.signum() - fill.commission; + position.average_price = if new_quantity.abs() < 1e-8 { + 0.0 + } else if !closing { + (old_quantity.abs() * old_avg_price + fill.quantity * fill.price) / new_quantity.abs() + } else if new_quantity.signum() != old_quantity.signum() { + fill.price + } else { + old_avg_price + }; + position.quantity = if new_quantity.abs() < 1e-8 { + 0.0 + } else { + new_quantity + }; + position.total_cost = position.quantity.abs() * position.average_price; + position.unrealized_pnl = position.quantity * (fill.price - position.average_price); + position.last_update = fill.timestamp; + + PositionUpdate { + symbol: symbol.to_string(), + fill: fill.clone(), + resulting_position: position.clone(), + } + } + + pub fn get_position(&self, symbol: &str) -> Option { + self.positions.get(symbol).map(|p| p.clone()) + } + + pub fn get_all_positions(&self) -> Vec { + self.positions + .iter() + .map(|entry| entry.value().clone()) + .collect() + } + + pub fn get_open_positions(&self) -> Vec { + self.positions + .iter() + .filter(|entry| entry.value().quantity.abs() > 0.0001) + .map(|entry| entry.value().clone()) + .collect() + } + + pub fn update_unrealized_pnl(&self, symbol: &str, current_price: f64) { + if let Some(mut position) = self.positions.get_mut(symbol) { + if position.quantity > 0.0 { + position.unrealized_pnl = + position.quantity * (current_price - position.average_price); + } else if position.quantity < 0.0 { + position.unrealized_pnl = + position.quantity * (current_price - position.average_price); + } else { + position.unrealized_pnl = 0.0; + } + } + } + + pub fn get_total_pnl(&self) -> (f64, f64) { + let mut realized = 0.0; + let mut unrealized = 0.0; + + for position in self.positions.iter() { + realized += position.realized_pnl; + unrealized += position.unrealized_pnl; + } + + (realized, unrealized) + } + + pub fn reset(&self) { + self.positions.clear(); + self.trade_history.write().clear(); + self.closed_trades.write().clear(); + self.open_trades.clear(); + *self.next_trade_id.write() = 1; + } + + pub fn get_trade_history(&self) -> Vec { + self.trade_history.read().clone() + } + + pub fn get_closed_trades(&self) -> Vec { + self.closed_trades.read().clone() + } + + pub fn get_open_trades(&self) -> Vec { + let mut all_open_trades = Vec::new(); + for entry in self.open_trades.iter() { + all_open_trades.extend(entry.value().clone()); + } + all_open_trades + } + + pub fn get_trade_count(&self) -> usize { + self.trade_history.read().len() + } + + pub fn get_closed_trade_count(&self) -> usize { + self.closed_trades.read().len() + } +} +#[cfg(test)] +mod accounting_tests { + use super::*; + fn fill( + tracker: &PositionTracker, + side: Side, + price: f64, + quantity: f64, + commission: f64, + ) -> PositionUpdate { + tracker.process_fill_with_tracking( + "A", + &Fill { + price, + quantity, + commission, + timestamp: Utc::now(), + }, + side, + None, + None, + ) + } + #[test] + fn long_partial_close_reversal_cover_and_flat_average() { + let tracker = PositionTracker::new(); + fill(&tracker, Side::Buy, 100.0, 10.0, 1.0); + let partial = fill(&tracker, Side::Sell, 110.0, 4.0, 0.4); + assert!((partial.resulting_position.realized_pnl - 38.6).abs() < 1e-8); + let reversed = fill(&tracker, Side::Sell, 90.0, 10.0, 1.0); + assert_eq!(reversed.resulting_position.quantity, -4.0); + assert_eq!(reversed.resulting_position.average_price, 90.0); + let flat = fill(&tracker, Side::Buy, 80.0, 4.0, 0.4); + assert_eq!(flat.resulting_position.quantity, 0.0); + assert_eq!(flat.resulting_position.average_price, 0.0); + assert!((flat.resulting_position.realized_pnl - 17.2).abs() < 1e-8); + let closed = tracker.get_closed_trades(); + assert!((closed.iter().map(|t| t.commission).sum::() - 2.8).abs() < 1e-8); + assert!((closed.iter().map(|t| t.pnl).sum::() - 17.2).abs() < 1e-8); + } +} diff --git a/apps/stock/engine/src/risk/mod.rs b/apps/stock/engine/src/risk/mod.rs index a887d03e..62c9e0f8 100644 --- a/apps/stock/engine/src/risk/mod.rs +++ b/apps/stock/engine/src/risk/mod.rs @@ -1,195 +1,240 @@ -pub mod portfolio; -pub mod bet_sizing; - -use crate::{Order, Side}; -use dashmap::DashMap; -use parking_lot::RwLock; -use serde::{Deserialize, Serialize}; -use std::sync::Arc; - -pub use portfolio::{PortfolioRisk, RiskModel, CorrelationMatrix, ConcentrationMetrics}; -pub use bet_sizing::{BetSizer, BetSizingParameters, PositionSize, MarketRegime, DynamicSizer}; - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RiskLimits { - pub max_position_size: f64, - pub max_order_size: f64, - pub max_daily_loss: f64, - pub max_gross_exposure: f64, - pub max_symbol_exposure: f64, -} - -impl Default for RiskLimits { - fn default() -> Self { - Self { - max_position_size: 100_000.0, - max_order_size: 10_000.0, - max_daily_loss: 5_000.0, - max_gross_exposure: 1_000_000.0, - max_symbol_exposure: 50_000.0, - } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RiskCheckResult { - pub passed: bool, - pub violations: Vec, - pub checks: RiskChecks, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RiskChecks { - pub order_size: bool, - pub position_size: bool, - pub daily_loss: bool, - pub gross_exposure: bool, - pub symbol_exposure: bool, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct RiskMetrics { - pub current_exposure: f64, - pub daily_pnl: f64, - pub position_count: usize, - pub gross_exposure: f64, - pub max_position_size: f64, - pub utilization_pct: f64, -} - -pub struct RiskEngine { - limits: Arc>, - symbol_exposures: DashMap, - daily_pnl: Arc>, -} - -impl RiskEngine { - pub fn new() -> Self { - Self::with_limits(RiskLimits::default()) - } - - pub fn with_limits(limits: RiskLimits) -> Self { - Self { - limits: Arc::new(RwLock::new(limits)), - symbol_exposures: DashMap::new(), - daily_pnl: Arc::new(RwLock::new(0.0)), - } - } - - pub fn update_limits(&self, new_limits: RiskLimits) { - *self.limits.write() = new_limits; - } - - pub fn check_order(&self, order: &Order, current_position: Option) -> RiskCheckResult { - let mut violations = Vec::new(); - let limits = self.limits.read(); - - // Check order size - if order.quantity > limits.max_order_size { - violations.push(format!( - "Order size {} exceeds limit {}", - order.quantity, limits.max_order_size - )); - } - - // Check position size after order - let current_pos = current_position.unwrap_or(0.0); - let new_position = match order.side { - Side::Buy => current_pos + order.quantity, - Side::Sell => current_pos - order.quantity, - }; - - if new_position.abs() > limits.max_position_size { - violations.push(format!( - "Position size {} would exceed limit {}", - new_position.abs(), limits.max_position_size - )); - } - - // Check symbol exposure - let symbol_exposure = self.symbol_exposures - .get(&order.symbol) - .map(|e| *e) - .unwrap_or(0.0); - - let new_exposure = symbol_exposure + order.quantity; - if new_exposure > limits.max_symbol_exposure { - violations.push(format!( - "Symbol exposure {} would exceed limit {}", - new_exposure, limits.max_symbol_exposure - )); - } - - // Check daily loss - let daily_pnl = *self.daily_pnl.read(); - if daily_pnl < -limits.max_daily_loss { - violations.push(format!( - "Daily loss {} exceeds limit {}", - -daily_pnl, limits.max_daily_loss - )); - } - - // Calculate gross exposure - let gross_exposure = self.calculate_gross_exposure(); - if gross_exposure > limits.max_gross_exposure { - violations.push(format!( - "Gross exposure {} exceeds limit {}", - gross_exposure, limits.max_gross_exposure - )); - } - - RiskCheckResult { - passed: violations.is_empty(), - violations, - checks: RiskChecks { - order_size: order.quantity <= limits.max_order_size, - position_size: new_position.abs() <= limits.max_position_size, - daily_loss: daily_pnl >= -limits.max_daily_loss, - gross_exposure: gross_exposure <= limits.max_gross_exposure, - symbol_exposure: new_exposure <= limits.max_symbol_exposure, - }, - } - } - - pub fn update_position(&self, symbol: &str, new_position: f64) { - if new_position.abs() < 0.0001 { - self.symbol_exposures.remove(symbol); - } else { - self.symbol_exposures.insert(symbol.to_string(), new_position.abs()); - } - } - - pub fn update_daily_pnl(&self, pnl_change: f64) { - let mut daily_pnl = self.daily_pnl.write(); - *daily_pnl += pnl_change; - } - - pub fn reset_daily_metrics(&self) { - *self.daily_pnl.write() = 0.0; - } - - fn calculate_gross_exposure(&self) -> f64 { - self.symbol_exposures - .iter() - .map(|entry| *entry.value()) - .sum() - } - - fn calculate_total_exposure(&self) -> f64 { - self.calculate_gross_exposure() - } - - pub fn get_risk_metrics(&self) -> RiskMetrics { - let limits = self.limits.read(); - let gross_exposure = self.calculate_gross_exposure(); - - RiskMetrics { - current_exposure: 0.0, - daily_pnl: *self.daily_pnl.read(), - position_count: self.symbol_exposures.len(), - gross_exposure, - max_position_size: limits.max_position_size, - utilization_pct: (gross_exposure / limits.max_gross_exposure * 100.0).min(100.0), - } - } -} \ No newline at end of file +pub mod bet_sizing; +pub mod portfolio; +use crate::{Order, Side}; +pub use bet_sizing::{BetSizer, BetSizingParameters, DynamicSizer, MarketRegime, PositionSize}; +use dashmap::DashMap; +use parking_lot::RwLock; +pub use portfolio::{ConcentrationMetrics, CorrelationMatrix, PortfolioRisk, RiskModel}; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RiskLimits { + pub max_position_size: f64, + pub max_order_size: f64, + pub max_daily_loss: f64, + pub max_gross_exposure: f64, + pub max_symbol_exposure: f64, +} +impl RiskLimits { + pub fn valid(&self) -> bool { + [ + self.max_position_size, + self.max_order_size, + self.max_daily_loss, + self.max_gross_exposure, + self.max_symbol_exposure, + ] + .iter() + .all(|v| v.is_finite() && *v > 0.0) + } +} +impl Default for RiskLimits { + fn default() -> Self { + Self { + max_position_size: 100_000.0, + max_order_size: 10_000.0, + max_daily_loss: 5_000.0, + max_gross_exposure: 1_000_000.0, + max_symbol_exposure: 50_000.0, + } + } +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RiskCheckResult { + pub passed: bool, + pub violations: Vec, + pub checks: RiskChecks, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RiskChecks { + pub order_size: bool, + pub position_size: bool, + pub daily_loss: bool, + pub gross_exposure: bool, + pub symbol_exposure: bool, +} +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RiskMetrics { + pub current_exposure: f64, + pub daily_pnl: f64, + pub position_count: usize, + pub gross_exposure: f64, + pub max_position_size: f64, + pub utilization_pct: f64, +} + +/// Position/order size limits are shares; exposure/loss limits are currency notional. +pub struct RiskEngine { + limits: Arc>, + positions: DashMap, + daily_pnl: Arc>, + day: RwLock>, +} +impl RiskEngine { + pub fn new() -> Self { + Self::with_limits(RiskLimits::default()) + } + pub fn with_limits(limits: RiskLimits) -> Self { + Self { + limits: Arc::new(RwLock::new(limits)), + positions: DashMap::new(), + day: RwLock::new(None), + daily_pnl: Arc::new(RwLock::new(0.0)), + } + } + pub fn update_limits(&self, limits: RiskLimits) { + *self.limits.write() = limits; + } + pub fn check_order( + &self, + order: &Order, + current_position: Option, + price: f64, + ) -> RiskCheckResult { + let limits = self.limits.read(); + let current = current_position.unwrap_or(0.0); + let signed = if order.side == Side::Buy { + order.quantity + } else { + -order.quantity + }; + let next = current + signed; + let reducing = current * signed < 0.0 && order.quantity <= current.abs(); + let valid = limits.valid() + && order.quantity.is_finite() + && order.quantity > 0.0 + && current.is_finite() + && price.is_finite() + && price > 0.0; + let other_gross: f64 = self + .positions + .iter() + .filter(|p| p.key() != &order.symbol) + .map(|p| p.value().0.abs() * p.value().1) + .sum(); + let exposure = next.abs() * price; + let gross = other_gross + exposure; + let checks = RiskChecks { + order_size: valid && order.quantity <= limits.max_order_size, + position_size: valid && (next.abs() <= limits.max_position_size || reducing), + daily_loss: valid && (*self.daily_pnl.read() > -limits.max_daily_loss || reducing), + gross_exposure: valid && (gross <= limits.max_gross_exposure || reducing), + symbol_exposure: valid && (exposure <= limits.max_symbol_exposure || reducing), + }; + let mut violations = Vec::new(); + for (passed, label) in [ + (checks.order_size, "Order size/validity"), + (checks.position_size, "Projected position size"), + (checks.daily_loss, "Daily loss"), + (checks.gross_exposure, "Projected gross notional"), + (checks.symbol_exposure, "Projected symbol notional"), + ] { + if !passed { + violations.push(label.to_string()); + } + } + RiskCheckResult { + passed: violations.is_empty(), + violations, + checks, + } + } + pub fn update_position(&self, symbol: &str, quantity: f64, price: f64) { + if quantity.abs() < 1e-8 { + self.positions.remove(symbol); + } else { + self.positions.insert(symbol.to_string(), (quantity, price)); + } + } + pub fn mark_price(&self, symbol: &str, price: f64) { + if let Some(mut p) = self.positions.get_mut(symbol) { + if price.is_finite() && price > 0.0 { + p.1 = price; + } + } + } + pub fn update_daily_pnl(&self, change: f64) { + *self.daily_pnl.write() += change; + } + pub fn roll_day(&self, day: chrono::NaiveDate) { + let mut previous = self.day.write(); + if previous.map(|p| day > p).unwrap_or(true) { + self.reset_daily_metrics(); + *previous = Some(day); + } + } + pub fn reset_daily_metrics(&self) { + *self.daily_pnl.write() = 0.0; + } + fn calculate_gross_exposure(&self) -> f64 { + self.positions + .iter() + .map(|p| p.value().0.abs() * p.value().1) + .sum() + } + pub fn get_risk_metrics(&self) -> RiskMetrics { + let limits = self.limits.read(); + let gross = self.calculate_gross_exposure(); + RiskMetrics { + current_exposure: gross, + daily_pnl: *self.daily_pnl.read(), + position_count: self.positions.len(), + gross_exposure: gross, + max_position_size: limits.max_position_size, + utilization_pct: gross / limits.max_gross_exposure * 100.0, + } + } +} +#[cfg(test)] +mod tests { + use super::*; + fn order(side: Side, quantity: f64) -> Order { + Order { + id: "test".into(), + symbol: "A".into(), + side, + quantity, + order_type: crate::OrderType::Market, + time_in_force: crate::TimeInForce::Day, + } + } + fn engine() -> RiskEngine { + RiskEngine::with_limits(RiskLimits { + max_position_size: 100.0, + max_order_size: 100.0, + max_daily_loss: 10.0, + max_gross_exposure: 1000.0, + max_symbol_exposure: 800.0, + }) + } + #[test] + fn projected_notional_includes_new_order_and_other_symbols() { + let risk = engine(); + risk.update_position("B", 5.0, 100.0); + assert!(!risk.check_order(&order(Side::Buy, 6.0), None, 100.0).passed); + assert!(risk.check_order(&order(Side::Buy, 5.0), None, 100.0).passed); + assert!( + !risk + .check_order(&order(Side::Buy, 1.0), None, f64::NAN) + .passed + ); + } + #[test] + fn covers_reduce_short_exposure_and_daily_loss_blocks_new_risk() { + let risk = engine(); + risk.update_position("A", -8.0, 100.0); + risk.update_daily_pnl(-10.0); + assert!( + risk.check_order(&order(Side::Buy, 8.0), Some(-8.0), 100.0) + .passed + ); + assert!( + !risk + .check_order(&order(Side::Sell, 1.0), Some(-8.0), 100.0) + .passed + ); + risk.mark_price("A", 120.0); + assert_eq!(risk.get_risk_metrics().gross_exposure, 960.0); + } +} diff --git a/apps/stock/orchestrator/package.json b/apps/stock/orchestrator/package.json index 9f697197..23e1c007 100644 --- a/apps/stock/orchestrator/package.json +++ b/apps/stock/orchestrator/package.json @@ -15,6 +15,7 @@ "build:rust": "cd ../engine && cargo build --release && napi build --platform --release" }, "dependencies": { + "decimal.js-light": "2.5.1", "@stock-bot/engine": "*", "@stock-bot/cache": "*", "@stock-bot/config": "*", diff --git a/apps/stock/orchestrator/src/api/rest/orders.ts b/apps/stock/orchestrator/src/api/rest/orders.ts index 565f1f23..1ff2c016 100644 --- a/apps/stock/orchestrator/src/api/rest/orders.ts +++ b/apps/stock/orchestrator/src/api/rest/orders.ts @@ -1,6 +1,7 @@ import { Hono } from 'hono'; import { z } from 'zod'; -import { ExecutionService } from '../../services/ExecutionService'; +import { ExecutionConflictError } from '../../execution/repository'; +import { ExecutionService, UnsupportedExecutionError } from '../../services/ExecutionService'; import type { OrchestratorServices as IServiceContainer } from '../../types'; import { OrderRequestSchema } from '../../types'; @@ -16,12 +17,20 @@ export function createOrderRoutes(container: IServiceContainer): Hono { app.post('/', async c => { try { const body = await c.req.json(); - const orderRequest = OrderRequestSchema.parse(body); + const orderRequest = OrderRequestSchema.extend({ + clientOrderId: z.string().min(1).max(256), + }).parse(body); const result = await executionService.submitOrder(orderRequest); return c.json(result, 201); } catch (error) { + if (error instanceof ExecutionConflictError) { + return c.json({ error: error.message }, 409); + } + if (error instanceof UnsupportedExecutionError) { + return c.json({ error: error.message }, 503); + } if (error instanceof z.ZodError) { return c.json( { @@ -92,7 +101,9 @@ export function createOrderRoutes(container: IServiceContainer): Hono { app.post('/batch', async c => { try { const body = await c.req.json(); - const orders = z.array(OrderRequestSchema).parse(body); + const orders = z + .array(OrderRequestSchema.extend({ clientOrderId: z.string().min(1).max(256) })) + .parse(body); const results = await Promise.allSettled( orders.map(order => executionService.submitOrder(order)) diff --git a/apps/stock/orchestrator/src/api/rest/positions.ts b/apps/stock/orchestrator/src/api/rest/positions.ts index ec092740..fb5edb33 100644 --- a/apps/stock/orchestrator/src/api/rest/positions.ts +++ b/apps/stock/orchestrator/src/api/rest/positions.ts @@ -1,5 +1,6 @@ import { Hono } from 'hono'; import { z } from 'zod'; +import { defined } from '@stock-bot/invariants'; import { ModeManager } from '../../core/ModeManager'; import type { OrchestratorServices as IServiceContainer } from '../../types'; @@ -9,13 +10,21 @@ const SymbolSchema = z.object({ export function createPositionRoutes(container: IServiceContainer): Hono { const app = new Hono(); + const execution = defined(container.custom?.ExecutionService); + const positionsFromLedger = async () => + (await execution.getPositions()).map(p => ({ + symbol: p.symbol, + quantity: p.quantity, + average_price: p.averagePrice, + realized_pnl: p.realizedPnl, + unrealized_pnl: p.unrealizedPnl, + })); const modeManager = container.custom?.ModeManager as ModeManager; // Get all positions app.get('/', async c => { try { - const tradingEngine = modeManager.getTradingEngine(); - const positions = JSON.parse(tradingEngine.getAllPositions()); + const positions = await positionsFromLedger(); return c.json({ mode: modeManager.getCurrentMode(), @@ -35,8 +44,7 @@ export function createPositionRoutes(container: IServiceContainer): Hono { // Get open positions only app.get('/open', async c => { try { - const tradingEngine = modeManager.getTradingEngine(); - const positions = JSON.parse(tradingEngine.getOpenPositions()); + const positions = (await positionsFromLedger()).filter(p => p.quantity !== 0); return c.json({ mode: modeManager.getCurrentMode(), @@ -57,10 +65,7 @@ export function createPositionRoutes(container: IServiceContainer): Hono { app.get('/:symbol', async c => { try { const { symbol } = SymbolSchema.parse(c.req.param()); - const tradingEngine = modeManager.getTradingEngine(); - - const positionJson = tradingEngine.getPosition(symbol); - const position = positionJson ? JSON.parse(positionJson) : null; + const position = (await positionsFromLedger()).find(p => p.symbol === symbol); if (position) { return c.json({ @@ -90,8 +95,9 @@ export function createPositionRoutes(container: IServiceContainer): Hono { // Get P&L summary app.get('/pnl/summary', async c => { try { - const tradingEngine = modeManager.getTradingEngine(); - const [realizedPnl = 0, unrealizedPnl = 0] = tradingEngine.getTotalPnl(); + const account = await execution.getAccount(); + const realizedPnl = account.realizedPnl, + unrealizedPnl = account.unrealizedPnl; return c.json({ mode: modeManager.getCurrentMode(), @@ -116,8 +122,13 @@ export function createPositionRoutes(container: IServiceContainer): Hono { // Get risk metrics app.get('/risk/metrics', async c => { try { - const tradingEngine = modeManager.getTradingEngine(); - const metrics = JSON.parse(tradingEngine.getRiskMetrics()); + const account = await execution.getAccount(); + const metrics = { + gross_exposure: account.grossExposure, + daily_pnl: account.dailyPnl, + position_count: Object.values(account.positions).filter(p => p.quantity !== 0).length, + limits: account.limits, + }; return c.json({ mode: modeManager.getCurrentMode(), diff --git a/apps/stock/orchestrator/src/api/websocket/index.ts b/apps/stock/orchestrator/src/api/websocket/index.ts index 80d037c7..9b2b8db1 100644 --- a/apps/stock/orchestrator/src/api/websocket/index.ts +++ b/apps/stock/orchestrator/src/api/websocket/index.ts @@ -4,7 +4,7 @@ import { defined } from '@stock-bot/invariants'; import { ModeManager } from '../../core/ModeManager'; import { ExecutionService } from '../../services/ExecutionService'; import { MarketDataService } from '../../services/MarketDataService'; -import type { OrchestratorServices as IServiceContainer } from '../../types'; +import { OrderRequestSchema, type OrchestratorServices as IServiceContainer } from '../../types'; const SubscribeSchema = z.object({ symbols: z.array(z.string()), @@ -102,7 +102,9 @@ export function setupWebSocketHandlers(io: SocketIOServer, container: IServiceCo // Handle order submission via WebSocket socket.on('submitOrder', async (order, callback?: Function) => { try { - const result = await executionService.submitOrder(order); + const result = await executionService.submitOrder( + OrderRequestSchema.extend({ clientOrderId: z.string().min(1).max(256) }).parse(order) + ); if (callback) { callback({ success: true, result }); } @@ -120,8 +122,7 @@ export function setupWebSocketHandlers(io: SocketIOServer, container: IServiceCo // Handle position queries socket.on('getPositions', async (callback?: Function) => { try { - const tradingEngine = modeManager.getTradingEngine(); - const positions = JSON.parse(tradingEngine.getAllPositions()); + const positions = await executionService.getPositions(); if (callback) { callback({ success: true, positions }); @@ -165,10 +166,12 @@ export function setupWebSocketHandlers(io: SocketIOServer, container: IServiceCo }); // Forward market data to subscribed clients - marketDataService.on('marketData', data => { - for (const [clientId, subscriptions] of clientSubscriptions) { - if (subscriptions.has(data.data.symbol)) { - io.to(clientId).emit('marketData', data); + marketDataService.on('marketDataBatch', batch => { + for (const data of batch) { + for (const [clientId, subscriptions] of clientSubscriptions) { + if (subscriptions.has(data.data.symbol)) { + io.to(clientId).emit('marketData', data); + } } } }); diff --git a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts index ac22a8d2..3cb0d91f 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts @@ -3,11 +3,10 @@ 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 type { StrategyFill } from '../services/ExecutionService'; import { StorageService } from '../services/StorageService'; import type { Signal } from '../strategies/BaseStrategy'; import { StrategyManager } from '../strategies/StrategyManager'; -import type { OrchestratorServices as IServiceContainer, OrderRequest } from '../types'; +import type { OrchestratorServices as IServiceContainer } from '../types'; import { BacktestConfigSchema, type MarketData, type MarketMicrostructure } from '../types'; import type { BacktestExecutionEngine } from './execution-engine'; import { MarketSimulator } from './MarketSimulator'; @@ -17,14 +16,7 @@ import type { BacktestResult, OHLCBar } from './typescript-result'; type BacktestEvent = { timestamp: number } & ( | { type: 'market_data'; data: MarketData } | { type: 'strategy_signal'; data: Signal } - | { type: 'order_fill'; data: StrategyFill } ); -interface PendingOrder { - strategyId: string; - orderId: string; - order: OrderRequest; - timestamp: number; -} interface ExportResult { summary: PerformanceMetrics; trades: ClosedTrade[]; @@ -51,8 +43,6 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng private initialCapital: number = 100000; private commission: number = 0.001; // Default 0.1% private slippage: number = 0.0001; // Default 0.01% - private pendingOrders: Map = new Map(); - private ordersListenerSetup = false; constructor( container: IServiceContainer, @@ -70,9 +60,6 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng }); // Don't create performance analyzer here - wait for runBacktest // this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital); - - // Set up order listener immediately - this.setupOrderListener(); } async runBacktest(config: unknown): Promise { @@ -408,10 +395,6 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng case 'strategy_signal': await this.processStrategySignal(event.data); break; - - case 'order_fill': - await this.processFill(event.data); - break; } // Update equity curve periodically @@ -518,9 +501,6 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng ); await this.strategyManager.onMarketData(data); - // Check for any pending orders that should be filled - await this.checkAndFillOrders(data); - // Track performance this.performanceAnalyzer.addEquityPoint( new Date(this.currentTime), @@ -533,69 +513,6 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng // This is here for future extensions } - private async processFill(fill: StrategyFill): Promise { - this.container.logger.info( - `[BacktestEngine] Processing fill: ${fill.side} ${fill.quantity} ${fill.symbol} @ ${fill.price} with timestamp ${fill.timestamp}` - ); - - // Process fill in trading engine for position tracking - const tradingEngine = this.strategyManager.getTradingEngine(); - if (tradingEngine) { - this.container.logger.info(`[BacktestEngine] Trading engine available, processing fill`); - this.container.logger.info( - `[BacktestEngine] Current time in trading engine before advance: ${tradingEngine.getCurrentTime()}` - ); - - // Make sure time is properly advanced - if (fill.timestamp) { - await tradingEngine.advanceTime(fill.timestamp); - this.container.logger.info( - `[BacktestEngine] Advanced trading engine time to ${fill.timestamp}, current time now: ${tradingEngine.getCurrentTime()}` - ); - } - - // Use the new process_fill_with_metadata method if available - if (tradingEngine.processFillWithMetadata) { - const fillResult = await tradingEngine.processFillWithMetadata( - fill.symbol, - fill.price, - fill.quantity, - fill.side, - fill.commission || 0, - fill.orderId || null, - fill.strategyId || null - ); - this.container.logger.debug('Fill processed with tracking:', { value: fillResult }); - } else { - // Fallback to old method - const fillResult = await tradingEngine.processFill( - fill.symbol, - fill.price, - fill.quantity, - fill.side, - fill.commission || 0 - ); - this.container.logger.debug('Fill processed:', { value: fillResult }); - } - } else { - this.container.logger.warn(`[BacktestEngine] No trading engine available to process fill!`); - } - - // Notify strategies of fill - const strategy = fill.strategyId ? this.strategyManager.getStrategy(fill.strategyId) : null; - if (strategy) { - await strategy.onOrderUpdate({ - orderId: fill.orderId, - symbol: fill.symbol, - side: fill.side, - status: 'filled', - fills: [fill], - }); - } - - // Simulated fills are persisted only inside the runner's backtest result, not the trading ledger. - } - private async updateEquityCurve(): Promise { const totalEquity = await this.getPortfolioValue(); @@ -854,8 +771,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng this.eventQueue = []; this.currentTime = 0; this.equityCurve = []; - this.pendingOrders.clear(); - this.ordersListenerSetup = false; + this.isPaused = false; this.speedMultiplier = 1; this.lastProcessTime = 0; @@ -1046,127 +962,6 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng return ohlcData; } - private setupOrderListener(): void { - if (this.ordersListenerSetup) { - return; - } - - // Listen for orders from strategy manager - this.strategyManager.on('order', async (orderEvent: PendingOrder) => { - this.container.logger.info('[BacktestEngine] Order from StrategyManager:', orderEvent); - this.pendingOrders.set(orderEvent.orderId, { - ...orderEvent, - timestamp: this.currentTime, - }); - }); - - this.ordersListenerSetup = true; - } - - private setupStrategyOrderListeners(): void { - // Listen for orders directly from strategies - const strategies = this.strategyManager.getAllStrategies(); - this.container.logger.info(`Setting up order listeners for ${strategies.length} strategies`); - - strategies.forEach(strategy => { - this.container.logger.info( - `Setting up order listener for strategy: ${strategy.getConfig().id}` - ); - - const orderHandler = async (order: OrderRequest) => { - const orderId = `${strategy.getConfig().id}-${Date.now()}-${Math.random()}`; - this.container.logger.info( - `[BacktestEngine] 🔔 Order from strategy ${strategy.getConfig().id}:`, - order - ); - this.container.logger.info( - `[BacktestEngine] Adding order ${orderId} to pendingOrders. Current size: ${this.pendingOrders.size}` - ); - this.pendingOrders.set(orderId, { - strategyId: strategy.getConfig().id, - orderId, - order, - timestamp: this.currentTime, - }); - this.container.logger.info( - `[BacktestEngine] After adding, pendingOrders size: ${this.pendingOrders.size}` - ); - }; - - strategy.on('order', orderHandler); - - // Also listen for signals - strategy.on('signal', signal => { - this.container.logger.info( - `[BacktestEngine] 📊 Signal from strategy ${strategy.getConfig().id}:`, - signal - ); - }); - }); - } - - private async checkAndFillOrders(data: MarketData): Promise { - if (data.type !== 'bar') { - return; - } - - const symbol = data.data.symbol; - const currentPrice = data.data.close; - - // Check pending orders for this symbol - const ordersToFill: string[] = []; - - this.container.logger.info( - `[checkAndFillOrders] Checking ${this.pendingOrders.size} pending orders for ${symbol}` - ); - - for (const [orderId, orderEvent] of this.pendingOrders) { - if (orderEvent.order.symbol === symbol) { - // For market orders, fill immediately at current price - if (orderEvent.order.orderType === 'market') { - this.container.logger.info( - `[checkAndFillOrders] Found market order ${orderId} for ${symbol}` - ); - ordersToFill.push(orderId); - } - } - } - - // Process fills - for (const orderId of ordersToFill) { - const orderEvent = this.pendingOrders.get(orderId); - if (!orderEvent) { - continue; - } - - const fillPrice = - orderEvent.order.side === 'buy' - ? currentPrice * (1 + this.slippage) - : currentPrice * (1 - this.slippage); - - const fill = { - orderId, - symbol: orderEvent.order.symbol, - side: orderEvent.order.side, - quantity: orderEvent.order.quantity, - price: fillPrice, - timestamp: this.currentTime, - commission: orderEvent.order.quantity * fillPrice * this.commission, - strategyId: orderEvent.strategyId, - }; - - this.container.logger.info( - `✅ Filling ${orderEvent.order.side} order for ${symbol} @ ${fillPrice} at timestamp ${this.currentTime} (${new Date(this.currentTime).toISOString()})` - ); - - // Remove from pending BEFORE processing to avoid duplicate fills - this.pendingOrders.delete(orderId); - - // Process the fill (this will update trading engine AND notify strategies) - await this.processFill(fill); - } - } - // Playback control methods async pauseBacktest(): Promise { this.isPaused = true; diff --git a/apps/stock/orchestrator/src/backtest/native-worker.ts b/apps/stock/orchestrator/src/backtest/native-worker.ts index 8249554c..053e30f3 100644 --- a/apps/stock/orchestrator/src/backtest/native-worker.ts +++ b/apps/stock/orchestrator/src/backtest/native-worker.ts @@ -27,6 +27,7 @@ process.once('message', async (input: unknown) => { slippage: config.slippage ?? 0.0001, dataFrequency: config.dataFrequency, }); + if (config.riskLimits) {engine.updateRiskLimits(config.riskLimits);} for (const { strategy, name, id, parameters } of resolveNativeStrategies(config)) { engine.addNativeStrategy(strategy, name, id, parameters); } diff --git a/apps/stock/orchestrator/src/backtest/result.ts b/apps/stock/orchestrator/src/backtest/result.ts index 53c0bdbf..028841bb 100644 --- a/apps/stock/orchestrator/src/backtest/result.ts +++ b/apps/stock/orchestrator/src/backtest/result.ts @@ -31,6 +31,15 @@ export const backtestRunResultSchema: z.ZodType = z.object({ slippage: finite, dataFrequency: z.string(), parameters: z.record(z.unknown()), + riskLimits: z + .object({ + maxPositionSize: finite, + maxOrderSize: finite, + maxDailyLoss: finite, + maxGrossExposure: finite, + maxSymbolExposure: finite, + }) + .optional(), strategies: z .array( z.object({ @@ -177,6 +186,7 @@ export function normalizeBacktestResult( slippage: config.slippage ?? 0.0001, dataFrequency: config.dataFrequency, parameters: config.config ?? {}, + riskLimits: config.riskLimits, strategies: config.strategies, }, metrics, diff --git a/apps/stock/orchestrator/src/core/ModeManager.ts b/apps/stock/orchestrator/src/core/ModeManager.ts index c049ae37..e01bc32a 100644 --- a/apps/stock/orchestrator/src/core/ModeManager.ts +++ b/apps/stock/orchestrator/src/core/ModeManager.ts @@ -7,7 +7,6 @@ import { StorageService } from '../services/StorageService'; import type { OrchestratorServices as IServiceContainer } from '../types'; import { BacktestConfigSchema, - LiveConfigSchema, PaperConfigSchema, type ModeConfig, type TradingMode, @@ -31,6 +30,9 @@ export class ModeManager extends EventEmitter { } async initializeMode(config: ModeConfig): Promise { + if (config.mode === 'live') { + throw new Error('Live trading is disabled: no real broker adapter exists'); + } // Validate config based on mode switch (config.mode) { case 'backtest': @@ -39,9 +41,6 @@ export class ModeManager extends EventEmitter { case 'paper': PaperConfigSchema.parse(config); break; - case 'live': - LiveConfigSchema.parse(config); - break; } // Shutdown current mode if initialized @@ -104,14 +103,13 @@ export class ModeManager extends EventEmitter { } private async initializeServices(config: ModeConfig): Promise { - // Configure market data service - await this.marketDataService.initialize(config); - // Configure execution service await this.executionService.initialize(config, defined(this.tradingEngine)); // Configure storage await this.storageService.initialize(config); + // Admission is ready before a real-time feed can deliver events. + await this.marketDataService.initialize(config); } getCurrentMode(): TradingMode { @@ -146,22 +144,10 @@ export class ModeManager extends EventEmitter { toMode: TradingMode, config: ModeConfig ): Promise { - if (fromMode === 'paper' && toMode === 'live') { - // Special handling for paper to live transition - this.container.logger.info('Transitioning from paper to live trading...'); - - // 1. Get current paper positions - const paperPositions = await defined(this.tradingEngine).getOpenPositions(); - - // 2. Initialize new mode - await this.initializeMode(config); - - // 3. Reconcile positions (this would be handled by a reconciliation service) - this.container.logger.info(`Paper positions to reconcile: ${paperPositions}`); - } else { - // Standard mode switch - await this.initializeMode(config); + if (config.mode !== toMode || fromMode !== this.mode) { + throw new Error('Mode transition does not match current mode or configuration'); } + await this.initializeMode(config); } async shutdown(): Promise { diff --git a/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts b/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts new file mode 100644 index 00000000..29ac9015 --- /dev/null +++ b/apps/stock/orchestrator/src/execution/PostgresExecutionRepository.ts @@ -0,0 +1,113 @@ +import type { PostgresClient } from '@stock-bot/services'; +import type { Account, Fill, StoredOrder } from './model'; +import { + ExecutionConflictError, + type ExecutionRepository, + type ExecutionTransaction, +} from './repository'; + +export class PostgresExecutionRepository implements ExecutionRepository { + constructor(private readonly postgres: Pick) {} + async initialize(id: string, initial: Account) { + await this.postgres.transaction(async client => { + await client.query( + `INSERT INTO simulation_accounts (id, state) VALUES ($1,$2::jsonb) ON CONFLICT (id) DO NOTHING`, + [id, JSON.stringify(initial)] + ); + const result = await client.query( + 'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE', + [id] + ); + const account: Account = result.rows[0].state; + if (account.initialCapital !== initial.initialCapital) { + throw new ExecutionConflictError( + 'Existing account capital differs; use a new account ID, not an implicit reset' + ); + } + Object.assign(account, { + limits: initial.limits, + commission: initial.commission, + slippage: initial.slippage, + maxQuoteAgeMs: initial.maxQuoteAgeMs, + }); + await client.query('UPDATE simulation_accounts SET state = $2::jsonb WHERE id = $1', [ + id, + JSON.stringify(account), + ]); + }); + } + transact(id: string, work: (tx: ExecutionTransaction) => Promise): Promise { + return this.postgres.transaction(async client => { + const state = await client.query( + 'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE', + [id] + ); + if (!state.rows[0]) { + throw new Error('Execution account is not initialized'); + } + const readOrder = async (column: 'id' | 'client_order_id', key: string) => { + const result = await client.query( + `SELECT payload FROM simulation_orders WHERE account_id = $1 AND ${column} = $2`, + [id, key] + ); + return result.rows[0]?.payload as StoredOrder | undefined; + }; + const result = await work({ + account: state.rows[0].state as Account, + findOrder: key => readOrder('client_order_id', key), + getOrder: key => readOrder('id', key), + async openOrders() { + const result = await client.query( + `SELECT payload FROM simulation_orders WHERE account_id = $1 AND status IN ('accepted','partiallyFilled') ORDER BY created_at,id`, + [id] + ); + return result.rows.map(r => r.payload as StoredOrder); + }, + async putOrder(order) { + await client.query( + `INSERT INTO simulation_orders (id,account_id,client_order_id,status,payload) + VALUES ($1,$2,$3,$4,$5::jsonb) ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`, + [ + order.report.orderId, + id, + order.report.clientOrderId, + order.report.status, + JSON.stringify(order), + ] + ); + }, + async insertFill(orderId: string, fill: Fill) { + const inserted = await client.query( + `INSERT INTO simulation_fills (account_id,id,order_id,payload) + VALUES ($1,$2,$3,$4::jsonb) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`, + [id, fill.id, orderId, JSON.stringify(fill)] + ); + return inserted.rows.length > 0; + }, + async recordEvent(eventId, hash) { + const inserted = await client.query( + `INSERT INTO simulation_events (account_id,id,fingerprint) + VALUES ($1,$2,$3) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`, + [id, eventId, hash] + ); + if (inserted.rows.length) { + return true; + } + const previous = await client.query( + 'SELECT fingerprint FROM simulation_events WHERE account_id = $1 AND id = $2', + [id, eventId] + ); + if (previous.rows[0]?.fingerprint !== hash) { + throw new ExecutionConflictError('Conflicting market event identity'); + } + return false; + }, + }); + await client.query( + 'UPDATE simulation_accounts SET state = $2::jsonb,updated_at = NOW() WHERE id = $1', + [id, JSON.stringify(state.rows[0].state)] + ); + return result; + }); + } +} diff --git a/apps/stock/orchestrator/src/execution/model.ts b/apps/stock/orchestrator/src/execution/model.ts new file mode 100644 index 00000000..fc60826d --- /dev/null +++ b/apps/stock/orchestrator/src/execution/model.ts @@ -0,0 +1,232 @@ +import { createHash } from 'node:crypto'; +import Decimal from 'decimal.js-light'; +import type { MarketData, OrderRequest } from '../types'; + +export interface RiskLimits { + maxPositionSize: number; + maxOrderSize: number; + maxDailyLoss: number; + maxGrossExposure: number; + maxSymbolExposure: number; +} +export const defaultRiskLimits: RiskLimits = { + maxPositionSize: 10000, + maxOrderSize: 1000, + maxDailyLoss: 5000, + maxGrossExposure: 200000, + maxSymbolExposure: 50000, +}; +export interface Fill { + id: string; + price: number; + quantity: number; + commission: number; + timestamp: number; + pnl: number; +} +export interface ExecutionReport { + orderId: string; + clientOrderId: string; + symbol: string; + side: 'buy' | 'sell'; + quantity: number; + status: 'pending' | 'accepted' | 'partiallyFilled' | 'filled' | 'cancelled' | 'rejected'; + fills: Fill[]; + rejectionReason?: string; + timestamp: number; + strategyId?: string; +} +export interface Position { + symbol: string; + quantity: number; + averagePrice: number; + realizedPnl: number; +} +export interface Quote { + bid: number; + ask: number; + bidSize: number; + askSize: number; + timestamp: number; + eventId: string; +} +export interface Account { + initialCapital: number; + cash: number; + realizedPnl: number; + dailyPnl: number; + day: string; + commission: number; + slippage: number; + limits: RiskLimits; + maxQuoteAgeMs: number; + positions: Record; + quotes: Record; + strategyPositions: Record>; +} +export interface StoredOrder { + request: OrderRequest; + report: ExecutionReport; + fingerprint: string; + policy: { commission: number; slippage: number }; +} +export const terminal = (status: ExecutionReport['status']) => + ['filled', 'cancelled', 'rejected'].includes(status); +type DecimalValue = ConstructorParameters[0]; +export const decimal = (value: DecimalValue) => new Decimal(value); +export function amount(value: DecimalValue) { + const result = decimal(value).toDecimalPlaces(8).toNumber(); + if (!Number.isFinite(result)) { + throw new Error('Non-finite accounting value'); + } + return result; +} +export function identity(data: MarketData): string { + return data.eventId ?? createHash('sha256').update(JSON.stringify(data)).digest('hex'); +} +export function fingerprint(order: OrderRequest, strategyId?: string) { + return JSON.stringify([ + order.symbol, + order.side, + order.quantity, + order.orderType, + order.limitPrice ?? null, + order.stopPrice ?? null, + order.timeInForce, + strategyId ?? null, + ]); +} +export function applyFill( + account: Account, + symbol: string, + side: 'buy' | 'sell', + fill: Omit +): Fill { + const old = account.positions[symbol] ?? { symbol, quantity: 0, averagePrice: 0, realizedPnl: 0 }; + const signed = decimal(fill.quantity).times(side === 'buy' ? 1 : -1); + const next = decimal(old.quantity).plus(signed); + const closes = old.quantity !== 0 && Math.sign(old.quantity) !== Math.sign(signed.toNumber()); + const closed = closes ? Math.min(Math.abs(old.quantity), fill.quantity) : 0; + const pnl = amount( + decimal(fill.price) + .minus(old.averagePrice) + .times(closed) + .times(Math.sign(old.quantity)) + .minus(fill.commission) + ); + let averagePrice = old.averagePrice; + if (next.isZero()) { + averagePrice = 0; + } else if (!closes) { + averagePrice = amount( + decimal(old.averagePrice) + .times(Math.abs(old.quantity)) + .plus(decimal(fill.price).times(fill.quantity)) + .div(next.abs()) + ); + } else if (Math.sign(next.toNumber()) !== Math.sign(old.quantity)) { + averagePrice = fill.price; + } + account.positions[symbol] = { + symbol, + quantity: amount(next), + averagePrice, + realizedPnl: amount(decimal(old.realizedPnl).plus(pnl)), + }; + account.cash = amount( + decimal(account.cash).minus(signed.times(fill.price)).minus(fill.commission) + ); + account.realizedPnl = amount(decimal(account.realizedPnl).plus(pnl)); + account.dailyPnl = amount(decimal(account.dailyPnl).plus(pnl)); + return { ...fill, pnl }; +} +export function accountMetrics(account: Account) { + let marketValue = decimal(0), + grossExposure = decimal(0), + unrealized = decimal(0); + for (const position of Object.values(account.positions)) { + const quote = account.quotes[position.symbol]; + const mark = quote ? (quote.bid + quote.ask) / 2 : position.averagePrice; + marketValue = marketValue.plus(decimal(position.quantity).times(mark)); + grossExposure = grossExposure.plus(decimal(position.quantity).abs().times(mark)); + unrealized = unrealized.plus( + decimal(mark).minus(position.averagePrice).times(position.quantity) + ); + } + return { + cash: account.cash, + realizedPnl: account.realizedPnl, + unrealizedPnl: amount(unrealized), + equity: amount(decimal(account.cash).plus(marketValue)), + grossExposure: amount(grossExposure), + dailyPnl: account.dailyPnl, + }; +} +/** Quantities are shares; exposure/loss limits are account-currency notional amounts. */ +export function riskViolations( + account: Account, + request: OrderRequest, + reservations: StoredOrder[], + price: number, + timestamp: number +): string[] { + const violations: string[] = []; + if (request.quantity > account.limits.maxOrderSize) { + violations.push('Order quantity limit'); + } + const current = account.positions[request.symbol]?.quantity ?? 0; + const signed = request.side === 'buy' ? request.quantity : -request.quantity; + const reducing = current * signed < 0 && Math.abs(signed) <= Math.abs(current); + if (account.dailyPnl <= -account.limits.maxDailyLoss && !reducing) { + violations.push('Daily loss limit'); + } + const quantities = new Map(); + for (const p of Object.values(account.positions)) { + quantities.set(p.symbol, { long: p.quantity, short: p.quantity }); + } + const proposed = current + signed; + quantities.set(request.symbol, { long: proposed, short: proposed }); + for (const order of reservations) { + const qty = amount( + decimal(order.request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0)) + ); + const q = quantities.get(order.request.symbol) ?? { long: 0, short: 0 }; + if (order.request.side === 'buy') { + q.long = amount(decimal(q.long).plus(qty)); + } else { + q.short = amount(decimal(q.short).minus(qty)); + } + quantities.set(order.request.symbol, q); + } + let gross = decimal(0); + for (const [symbol, q] of quantities) { + const quantity = Math.max(Math.abs(q.long), Math.abs(q.short)); + if (!quantity) { + continue; + } + const quote = account.quotes[symbol]; + if (quote && timestamp - quote.timestamp > account.maxQuoteAgeMs && !reducing) { + violations.push(`Stale valuation for ${symbol}`); + } + const mark = symbol === request.symbol ? Math.max(price, quote?.ask ?? price) : quote?.ask; + if (!mark || !Number.isFinite(mark)) { + violations.push(`Missing valuation for ${symbol}`); + continue; + } + const exposure = decimal(quantity).times(mark); + if (quantity > account.limits.maxPositionSize && !(reducing && symbol === request.symbol)) { + violations.push(`Position quantity limit: ${symbol}`); + } + if (exposure.gt(account.limits.maxSymbolExposure) && !(reducing && symbol === request.symbol)) { + violations.push(`Symbol notional limit: ${symbol}`); + } + gross = gross.plus(exposure); + } + if (gross.gt(account.limits.maxGrossExposure) && !reducing) { + violations.push('Gross notional limit'); + } + if (gross.gt(Math.max(0, accountMetrics(account).equity)) && !reducing) { + violations.push('Unlevered capital exposure limit'); + } + return violations; +} diff --git a/apps/stock/orchestrator/src/execution/repository.ts b/apps/stock/orchestrator/src/execution/repository.ts new file mode 100644 index 00000000..ee48d3b5 --- /dev/null +++ b/apps/stock/orchestrator/src/execution/repository.ts @@ -0,0 +1,76 @@ +import type { Account, Fill, StoredOrder } from './model'; + +export interface ExecutionTransaction { + account: Account; + findOrder(clientOrderId: string): Promise; + getOrder(orderId: string): Promise; + openOrders(): Promise; + putOrder(order: StoredOrder): Promise; + insertFill(orderId: string, fill: Fill): Promise; + recordEvent(eventId: string, fingerprint: string): Promise; +} +export interface ExecutionRepository { + initialize(accountId: string, initial: Account): Promise; + transact(accountId: string, work: (tx: ExecutionTransaction) => Promise): Promise; +} +export class ExecutionConflictError extends Error {} + +/** Explicit run-local backtest store, never a fallback for paper or live execution. */ +export class BacktestExecutionRepository implements ExecutionRepository { + private state?: { + account: Account; + orders: Record; + fills: Record; + events: Record; + }; + private tail: Promise = Promise.resolve(); + async initialize(_id: string, account: Account) { + this.state = { account: structuredClone(account), orders: {}, fills: {}, events: {} }; + } + transact(_id: string, work: (tx: ExecutionTransaction) => Promise): Promise { + const task = this.tail.then(async () => { + if (!this.state) { + throw new Error('Execution account is not initialized'); + } + const state = structuredClone(this.state); + const result = await work({ + account: state.account, + async findOrder(id) { + return Object.values(state.orders).find(o => o.report.clientOrderId === id); + }, + async getOrder(id) { + return state.orders[id]; + }, + async openOrders() { + return Object.values(state.orders).filter(o => + ['accepted', 'partiallyFilled'].includes(o.report.status) + ); + }, + async putOrder(order) { + state.orders[order.report.orderId] = order; + }, + async insertFill(_orderId, fill) { + if (state.fills[fill.id]) { + return false; + } + state.fills[fill.id] = fill; + return true; + }, + async recordEvent(id, hash) { + if (state.events[id] && state.events[id] !== hash) { + throw new ExecutionConflictError('Conflicting market event identity'); + } + if (state.events[id]) { + return false; + } + state.events[id] = hash; + return true; + }, + }); + this.state = state; + return structuredClone(result); + }); + this.tail = task.catch(() => {}); + return task; + } +} diff --git a/apps/stock/orchestrator/src/paper/PaperTradingManager.ts b/apps/stock/orchestrator/src/paper/PaperTradingManager.ts index ba9a7584..deedd9bf 100644 --- a/apps/stock/orchestrator/src/paper/PaperTradingManager.ts +++ b/apps/stock/orchestrator/src/paper/PaperTradingManager.ts @@ -1,384 +1,60 @@ -import { EventEmitter } from 'events'; -import { defined } from '@stock-bot/invariants'; -import { ExecutionService } from '../services/ExecutionService'; -import { MarketDataService } from '../services/MarketDataService'; -import { StorageService } from '../services/StorageService'; -import type { OrchestratorServices as IServiceContainer } from '../types'; -import { type OrderRequest } from '../types'; - -interface VirtualAccount { - balance: number; - buyingPower: number; - positions: Map; - orders: Map; - trades: VirtualTrade[]; - equity: number; - marginUsed: number; -} - -interface VirtualPosition { - symbol: string; - quantity: number; - averagePrice: number; - marketValue: number; - unrealizedPnl: number; - realizedPnl: number; -} - -interface VirtualOrder { - id: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - orderType: string; - limitPrice?: number; - status: string; - submittedAt: Date; -} - -interface VirtualTrade { - orderId: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - price: number; - commission: number; - timestamp: Date; - pnl?: number; -} +import { EventEmitter } from 'node:events'; +import type { ExecutionService } from '../services/ExecutionService'; +import type { MarketDataService } from '../services/MarketDataService'; +import type { StorageService } from '../services/StorageService'; +import type { OrchestratorServices, OrderRequest } from '../types'; +/** Compatibility facade: no independent simulator, balance, or position book. */ export class PaperTradingManager extends EventEmitter { - private account: VirtualAccount; - private marketPrices = new Map(); - private readonly COMMISSION_RATE = 0.001; // 0.1% - private readonly MARGIN_REQUIREMENT = 0.25; // 25% margin requirement - private container: IServiceContainer; - constructor( - container: IServiceContainer, - private storageService: StorageService, - private marketDataService: MarketDataService, - private executionService: ExecutionService, - initialBalance: number = 100000 + _container: OrchestratorServices, + _storage: StorageService, + _market: MarketDataService, + private readonly execution: ExecutionService, + _initialBalance = 100000 ) { super(); - this.container = container; - - this.account = { - balance: initialBalance, - buyingPower: initialBalance * (1 / this.MARGIN_REQUIREMENT), - positions: new Map(), - orders: new Map(), - trades: [], - equity: initialBalance, - marginUsed: 0, - }; - - this.setupEventListeners(); } - - private setupEventListeners(): void { - // Listen for market data updates to track prices - // In real implementation, would connect to market data service + executeOrder(order: OrderRequest) { + return this.execution.submitOrder(order); } - - updateMarketPrice(symbol: string, bid: number, ask: number): void { - this.marketPrices.set(symbol, { bid, ask }); - - // Update position values - const position = this.account.positions.get(symbol); - if (position) { - const midPrice = (bid + ask) / 2; - position.marketValue = position.quantity * midPrice; - position.unrealizedPnl = position.quantity * (midPrice - position.averagePrice); - } - - // Update account equity - this.updateAccountEquity(); - } - - async executeOrder(order: OrderRequest) { - // Validate order - const validation = this.validateOrder(order); - if (!validation.valid) { - return { - status: 'rejected', - reason: validation.reason, - }; - } - - // Check buying power - const requiredCapital = this.calculateRequiredCapital(order); - if (requiredCapital > this.account.buyingPower) { - return { - status: 'rejected', - reason: 'Insufficient buying power', - }; - } - - // Create virtual order - const virtualOrder: VirtualOrder = { - id: `paper_${Date.now()}`, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - orderType: order.orderType, - limitPrice: order.limitPrice, - status: 'pending', - submittedAt: new Date(), - }; - - this.account.orders.set(virtualOrder.id, virtualOrder); - - // Simulate order execution based on type - if (order.orderType === 'market') { - await this.executeMarketOrder(virtualOrder); - } else if (order.orderType === 'limit') { - // Limit orders would be checked periodically - virtualOrder.status = 'accepted'; - } - - return { - orderId: virtualOrder.id, - status: virtualOrder.status, - }; - } - - private async executeMarketOrder(order: VirtualOrder): Promise { - const marketPrice = this.marketPrices.get(order.symbol); - if (!marketPrice) { - order.status = 'rejected'; - this.emit('orderUpdate', { - orderId: order.id, - status: 'rejected', - reason: 'No market data available', - }); - return; - } - - // Simulate realistic fill with slippage - const fillPrice = - order.side === 'buy' - ? marketPrice.ask * (1 + this.getSlippage(order.quantity)) - : marketPrice.bid * (1 - this.getSlippage(order.quantity)); - - const commission = fillPrice * order.quantity * this.COMMISSION_RATE; - - // Create trade - const trade: VirtualTrade = { - orderId: order.id, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - price: fillPrice, - commission, - timestamp: new Date(), - }; - - // Update position - this.updatePosition(trade); - - // Update account - const totalCost = fillPrice * order.quantity + commission; - if (order.side === 'buy') { - this.account.balance -= totalCost; - } else { - this.account.balance += fillPrice * order.quantity - commission; - } - - // Record trade - this.account.trades.push(trade); - order.status = 'filled'; - - // Update buying power and margin - this.updateBuyingPower(); - - // Emit events - this.emit('fill', { - orderId: order.id, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - price: fillPrice, - commission, - timestamp: new Date(), - }); - - this.emit('orderUpdate', { - orderId: order.id, - status: 'filled', + updateMarketPrice( + symbol: string, + bid: number, + ask: number, + eventId: string, + timestamp: number, + size: number + ) { + return this.execution.onMarketData({ + type: 'quote', + eventId, + data: { symbol, bid, ask, bidSize: size, askSize: size, timestamp }, }); } - - private updatePosition(trade: VirtualTrade): void { - const position = this.account.positions.get(trade.symbol) || { - symbol: trade.symbol, - quantity: 0, - averagePrice: 0, - marketValue: 0, - unrealizedPnl: 0, - realizedPnl: 0, - }; - - const oldQuantity = position.quantity; - const oldAvgPrice = position.averagePrice; - - if (trade.side === 'buy') { - // Adding to position - const newQuantity = oldQuantity + trade.quantity; - position.averagePrice = - oldQuantity >= 0 - ? (oldQuantity * oldAvgPrice + trade.quantity * trade.price) / newQuantity - : trade.price; - position.quantity = newQuantity; - } else { - // Reducing position - const newQuantity = oldQuantity - trade.quantity; - - if (oldQuantity > 0) { - // Realize P&L on closed portion - const realizedPnl = trade.quantity * (trade.price - oldAvgPrice) - trade.commission; - position.realizedPnl += realizedPnl; - trade.pnl = realizedPnl; - } - - position.quantity = newQuantity; - - if (Math.abs(newQuantity) < 0.0001) { - // Position closed - this.account.positions.delete(trade.symbol); - return; - } - } - - this.account.positions.set(trade.symbol, position); + getAccount() { + return this.execution.getAccount(); } - - private validateOrder(order: OrderRequest): { valid: boolean; reason?: string } { - if (order.quantity <= 0) { - return { valid: false, reason: 'Invalid quantity' }; - } - - if (order.orderType === 'limit' && !order.limitPrice) { - return { valid: false, reason: 'Limit price required for limit orders' }; - } - - return { valid: true }; + getAllPositions() { + return this.execution.getPositions(); } - - private calculateRequiredCapital(order: OrderRequest): number { - const marketPrice = this.marketPrices.get(order.symbol); - if (!marketPrice) { - return Infinity; - } - - const price = order.side === 'buy' ? marketPrice.ask : marketPrice.bid; - const notional = price * order.quantity; - const commission = notional * this.COMMISSION_RATE; - const marginRequired = notional * this.MARGIN_REQUIREMENT; - - return order.side === 'buy' ? marginRequired + commission : commission; + async getPosition(symbol: string) { + return (await this.getAllPositions()).find(p => p.symbol === symbol); } - - private updateBuyingPower(): void { - let totalMarginUsed = 0; - - for (const position of this.account.positions.values()) { - totalMarginUsed += Math.abs(position.marketValue) * this.MARGIN_REQUIREMENT; - } - - this.account.marginUsed = totalMarginUsed; - this.account.buyingPower = (this.account.equity - totalMarginUsed) / this.MARGIN_REQUIREMENT; - } - - private updateAccountEquity(): void { - let totalUnrealizedPnl = 0; - - for (const position of this.account.positions.values()) { - totalUnrealizedPnl += position.unrealizedPnl; - } - - this.account.equity = this.account.balance + totalUnrealizedPnl; - } - - private getSlippage(quantity: number): number { - // Simple slippage model - increases with order size - const baseSlippage = 0.0001; // 1 basis point - const sizeImpact = quantity / 10000; // Impact increases with size - return baseSlippage + sizeImpact * 0.0001; - } - - checkLimitOrders(): void { - // Called periodically to check if limit orders can be filled - for (const [_orderId, order] of this.account.orders) { - if (order.status !== 'accepted' || order.orderType !== 'limit') { - continue; - } - - const marketPrice = this.marketPrices.get(order.symbol); - if (!marketPrice) { - continue; - } - - const canFill = - order.side === 'buy' - ? marketPrice.ask <= defined(order.limitPrice) - : marketPrice.bid >= defined(order.limitPrice); - - if (canFill) { - this.executeMarketOrder(order); - } - } - } - - getAccount(): VirtualAccount { - return { ...this.account }; - } - - getPosition(symbol: string): VirtualPosition | undefined { - return this.account.positions.get(symbol); - } - - getAllPositions(): VirtualPosition[] { - return Array.from(this.account.positions.values()); - } - - getPerformanceMetrics() { - const totalTrades = this.account.trades.length; - const winningTrades = this.account.trades.filter(t => t.pnl && t.pnl > 0); - const losingTrades = this.account.trades.filter(t => t.pnl && t.pnl < 0); - - const totalPnl = this.account.trades.reduce((sum, t) => sum + (t.pnl || 0), 0); - const totalCommission = this.account.trades.reduce((sum, t) => sum + t.commission, 0); - + async getPerformanceMetrics() { + const account = await this.getAccount(); return { - totalTrades, - winningTrades: winningTrades.length, - losingTrades: losingTrades.length, - winRate: totalTrades > 0 ? (winningTrades.length / totalTrades) * 100 : 0, - totalPnl, - totalCommission, - netPnl: totalPnl - totalCommission, - currentEquity: this.account.equity, - currentPositions: this.account.positions.size, + cash: account.cash, + currentEquity: account.equity, + netPnl: account.realizedPnl + account.unrealizedPnl, + realizedPnl: account.realizedPnl, + unrealizedPnl: account.unrealizedPnl, }; } - - reset(): void { - const initialBalance = - this.account.balance + - Array.from(this.account.positions.values()).reduce((sum, p) => sum + p.marketValue, 0); - - this.account = { - balance: initialBalance, - buyingPower: initialBalance * (1 / this.MARGIN_REQUIREMENT), - positions: new Map(), - orders: new Map(), - trades: [], - equity: initialBalance, - marginUsed: 0, - }; - - this.container.logger.info('Paper trading account reset'); + checkPendingOrders() { + throw new Error('Pending orders are processed only by ordered market events'); + } + reset() { + throw new Error('Implicit paper account reset is disabled; use a new account ID'); } } diff --git a/apps/stock/orchestrator/src/services/ExecutionService.ts b/apps/stock/orchestrator/src/services/ExecutionService.ts index 1a15a613..bec97316 100644 --- a/apps/stock/orchestrator/src/services/ExecutionService.ts +++ b/apps/stock/orchestrator/src/services/ExecutionService.ts @@ -1,34 +1,43 @@ -import { EventEmitter } from 'events'; -import { randomUUID as uuidv4 } from 'node:crypto'; -import { TradingEngine } from '@stock-bot/engine'; -import type { OrchestratorServices as IServiceContainer } from '../types'; -import { OrderRequestSchema, type ModeConfig, type OrderRequest } from '../types'; -import { StorageService } from './StorageService'; +import { createHash, randomUUID } from 'node:crypto'; +import { EventEmitter } from 'node:events'; +import type { TradingEngine } from '@stock-bot/engine'; +import { defined } from '@stock-bot/invariants'; +import { + accountMetrics, + amount, + applyFill, + decimal, + defaultRiskLimits, + fingerprint, + identity, + riskViolations, + terminal, + type Account, + type ExecutionReport, + type Fill, + type Quote, + type StoredOrder, +} from '../execution/model'; +import { PostgresExecutionRepository } from '../execution/PostgresExecutionRepository'; +import { + BacktestExecutionRepository, + ExecutionConflictError, + type ExecutionRepository, + type ExecutionTransaction, +} from '../execution/repository'; +import { + MarketDataSchema, + ModeConfigSchema, + OrderRequestSchema, + type MarketData, + type ModeConfig, + type OrchestratorServices, + type OrderRequest, +} from '../types'; +import type { StorageService } from './StorageService'; -export interface ExecutionReport { - orderId: string; - clientOrderId: string; - symbol: string; - side: 'buy' | 'sell'; - quantity: number; - status: 'pending' | 'accepted' | 'partiallyFilled' | 'filled' | 'cancelled' | 'rejected'; - fills: Fill[]; - rejectionReason?: string; - timestamp: number; -} - -export interface Fill { - price: number; - quantity: number; - commission: number; - timestamp: number; - pnl?: number; -} - -export type StrategyOrderUpdate = Pick< - ExecutionReport, - 'orderId' | 'symbol' | 'side' | 'status' | 'fills' ->; +export type { ExecutionReport, Fill } from '../execution/model'; +export type StrategyOrderUpdate = ExecutionReport; export interface StrategyFill extends Fill { orderId: string; symbol: string; @@ -36,294 +45,453 @@ export interface StrategyFill extends Fill { strategyId?: string; positionUpdate?: unknown; } +type Change = { report: ExecutionReport; fills: Fill[] }; +export class UnsupportedExecutionError extends Error {} +/** Sole runtime order gateway. Paper state commits atomically; backtests opt into a run-local ledger. */ export class ExecutionService extends EventEmitter { - private mode: 'backtest' | 'paper' | 'live' = 'paper'; - private tradingEngine: TradingEngine | null = null; - private brokerClient: { cancelOrder(orderId: string): Promise } | null = null; // Would be specific broker API client - private pendingOrders = new Map(); - private container: IServiceContainer; - private storageService: StorageService; - - constructor(container: IServiceContainer, storageService: StorageService) { + private repository?: ExecutionRepository; + private accountId = ''; + private mode: 'paper' | 'backtest' | undefined; + private engine?: TradingEngine; + private observer?: (report: ExecutionReport, fills: StrategyFill[]) => Promise; + private tail: Promise = Promise.resolve(); + private closing = false; + constructor( + private readonly container: OrchestratorServices, + _storage: StorageService, + private readonly options: { repository?: ExecutionRepository; clock?: () => number } = {} + ) { super(); - this.container = container; - this.storageService = storageService; } - async initialize(config: ModeConfig, tradingEngine: TradingEngine): Promise { - this.mode = config.mode; - this.tradingEngine = tradingEngine; - + setObserver(observer: (report: ExecutionReport, fills: StrategyFill[]) => Promise) { + this.observer = observer; + } + async initialize(input: ModeConfig, engine: TradingEngine): Promise { + const config = ModeConfigSchema.parse(input); if (config.mode === 'live') { - // Initialize broker connection - await this.initializeBroker(config.broker, config.accountId); + throw new UnsupportedExecutionError( + 'Live trading is disabled: no real broker adapter exists' + ); + } + await this.tail; + this.closing = false; + this.mode = undefined; + const repository = + this.options.repository ?? + (config.mode === 'backtest' + ? new BacktestExecutionRepository() + : this.container.postgres + ? new PostgresExecutionRepository(this.container.postgres) + : undefined); + if (!repository) { + throw new UnsupportedExecutionError( + 'Paper execution requires the PostgreSQL simulation ledger' + ); + } + if (config.mode === 'paper' && repository instanceof BacktestExecutionRepository) { + throw new UnsupportedExecutionError('Run-local storage cannot back a paper account'); + } + const now = this.options.clock?.() ?? Date.now(); + const initialCapital = config.mode === 'paper' ? config.startingCapital : config.initialCapital; + const account: Account = { + initialCapital, + cash: initialCapital, + realizedPnl: 0, + dailyPnl: 0, + day: new Date(now).toISOString().slice(0, 10), + commission: config.commission ?? 0.001, + slippage: config.slippage ?? 0.0001, + limits: config.riskLimits ?? { ...defaultRiskLimits }, + maxQuoteAgeMs: + config.mode === 'paper' ? (config.maxQuoteAgeMs ?? 60000) : Number.MAX_SAFE_INTEGER, + positions: {}, + quotes: {}, + strategyPositions: {}, + }; + const id = + config.mode === 'paper' + ? (config.accountId ?? 'paper-default') + : (config.runId ?? randomUUID()); + await repository.initialize(id, account); + this.repository = repository; + this.accountId = id; + this.mode = config.mode; + this.engine = engine; + engine.updateRiskLimits(account.limits); + } + private serialized(work: () => Promise): Promise { + const result = this.tail.then(work); + this.tail = result.catch(() => {}); + return result; + } + private store() { + if (!this.repository || !this.mode || this.closing) { + throw new UnsupportedExecutionError( + 'Execution gateway is not initialized or is shutting down' + ); + } + return this.repository; + } + private now(quote?: Quote) { + return this.mode === 'backtest' + ? (quote?.timestamp ?? 0) + : (this.options.clock?.() ?? Date.now()); + } + private rollDay(account: Account, time: number) { + const day = new Date(time).toISOString().slice(0, 10); + if (day > account.day || (this.mode === 'backtest' && !Object.keys(account.quotes).length)) { + account.day = day; + account.dailyPnl = 0; } } - - private async initializeBroker(broker: string, accountId: string): Promise { - // In real implementation, would initialize specific broker API - // For example: Alpaca, Interactive Brokers, etc. - this.container.logger.info(`Initializing ${broker} broker connection for account ${accountId}`); + async submitOrder( + input: OrderRequest, + context: { strategyId?: string } = {} + ): Promise { + const request = OrderRequestSchema.parse(input); + // The API must supply stable IDs for retried requests; strategy IDs are derived from source events. + request.clientOrderId ??= randomUUID(); + return this.serialized(async () => { + const change = await this.store().transact(this.accountId, async tx => { + const hash = fingerprint(request, context.strategyId); + const existing = await tx.findOrder(defined(request.clientOrderId)); + if (existing) { + if (existing.fingerprint !== hash) { + throw new ExecutionConflictError('Client order ID reused with a different request'); + } + return { report: existing.report, fills: [] }; + } + const quote = tx.account.quotes[request.symbol]; + const timestamp = this.now(quote); + this.rollDay(tx.account, timestamp); + const order: StoredOrder = { + request, + fingerprint: hash, + policy: { commission: tx.account.commission, slippage: tx.account.slippage }, + report: { + orderId: randomUUID(), + clientOrderId: defined(request.clientOrderId), + strategyId: context.strategyId, + symbol: request.symbol, + side: request.side, + quantity: request.quantity, + status: 'accepted', + fills: [], + timestamp, + }, + }; + const invalid = !['market', 'limit'].includes(request.orderType) + ? 'Unsupported order type' + : !['DAY', 'GTC', 'IOC', 'FOK'].includes(request.timeInForce) + ? 'Unsupported time in force' + : request.orderType === 'limit' && + (!request.limitPrice || + !Number.isFinite(request.limitPrice) || + request.limitPrice <= 0) + ? 'Valid limit price required' + : !quote || + timestamp - quote.timestamp > tx.account.maxQuoteAgeMs || + quote.timestamp > timestamp + ? 'Missing, stale, or future market quote' + : undefined; + const price = quote && !invalid ? this.fillPrice(tx.account, order, quote) : 0; + const violations = invalid + ? [invalid] + : riskViolationsFor(tx, request, await tx.openOrders(), price, timestamp); + if (violations.length) { + order.report.status = 'rejected'; + order.report.rejectionReason = violations.join('; '); + } + await tx.putOrder(order); // Fill FK and acknowledgement are in the same transaction. + const fills = + order.report.status === 'rejected' || !quote + ? [] + : await this.fill(tx, order, quote, await tx.openOrders()); + await tx.putOrder(order); + return { report: order.report, fills }; + }); + await this.publish(change); + return change.report; + }); } - - async submitOrder(orderRequest: OrderRequest): Promise { - // Validate order request - const validatedOrder = OrderRequestSchema.parse(orderRequest); - - // Generate order ID - const orderId = uuidv4(); - const clientOrderId = validatedOrder.clientOrderId || orderId; - - // Store pending order - this.pendingOrders.set(orderId, validatedOrder); - - try { - // Check risk before submitting - const riskResult = await this.checkRisk(validatedOrder); - if (!riskResult.passed) { - return this.createRejectionReport( - orderId, - clientOrderId, - validatedOrder, - `Risk check failed: ${riskResult.violations.join(', ')}` + private fillPrice(_account: Account, order: StoredOrder, quote: Quote) { + const raw = + order.request.side === 'buy' + ? quote.ask * (1 + order.policy.slippage) + : quote.bid * (1 - order.policy.slippage); + return amount( + order.request.orderType === 'limit' + ? order.request.side === 'buy' + ? Math.min(raw, defined(order.request.limitPrice)) + : Math.max(raw, defined(order.request.limitPrice)) + : raw + ); + } + private async fill( + tx: ExecutionTransaction, + order: StoredOrder, + quote: Quote, + reservations: StoredOrder[] + ): Promise { + if (terminal(order.report.status)) { + return []; + } + const request = order.request; + if ( + request.timeInForce === 'DAY' && + new Date(order.report.timestamp).toISOString().slice(0, 10) !== + new Date(quote.timestamp).toISOString().slice(0, 10) + ) { + order.report.status = 'cancelled'; + return []; + } + const crosses = + request.orderType === 'market' || + (request.side === 'buy' + ? quote.ask <= defined(request.limitPrice) + : quote.bid >= defined(request.limitPrice)); + const remaining = amount( + decimal(request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0)) + ); + const available = request.side === 'buy' ? quote.askSize : quote.bidSize; + const quantity = crosses ? Math.min(remaining, available) : 0; + if (!quantity || (request.timeInForce === 'FOK' && quantity < remaining)) { + if (request.timeInForce === 'IOC' || request.timeInForce === 'FOK') { + order.report.status = 'cancelled'; + } + return []; + } + const price = this.fillPrice(tx.account, order, quote); + const violations = riskViolationsFor( + tx, + { ...request, quantity: remaining }, + reservations.filter(o => o.report.orderId !== order.report.orderId), + price, + this.now(quote) + ); + if (violations.length) { + order.report.status = 'cancelled'; + order.report.rejectionReason = violations.join('; '); + return []; + } + const fill = { + id: order.report.orderId + ':' + quote.eventId, + price, + quantity, + commission: amount(decimal(quantity).times(price).times(order.policy.commission)), + timestamp: quote.timestamp, + pnl: 0, + }; + const projected = structuredClone(tx.account); + const applied = applyFill(projected, request.symbol, request.side, fill); + if (!(await tx.insertFill(order.report.orderId, applied))) { + return []; + } + // Keep the same quote object so consumed liquidity is persisted with the accounting change. + Object.assign(tx.account, { ...projected, quotes: tx.account.quotes }); + if (order.report.strategyId) { + const book = (tx.account.strategyPositions[order.report.strategyId] ??= {}); + book[request.symbol] = amount( + decimal(book[request.symbol] ?? 0).plus(request.side === 'buy' ? quantity : -quantity) + ); + } + // Store the actual delta, not cumulative realized P&L. + // The returned fill is also appended to the durable report in this transaction. + order.report.fills.push(applied); + if (request.side === 'buy') { + quote.askSize = amount(decimal(quote.askSize).minus(quantity)); + } else { + quote.bidSize = amount(decimal(quote.bidSize).minus(quantity)); + } + order.report.status = + quantity >= remaining + ? 'filled' + : request.timeInForce === 'IOC' + ? 'cancelled' + : 'partiallyFilled'; + return [applied]; + } + async onMarketData(input: MarketData): Promise { + const data = MarketDataSchema.parse(input); + return this.serialized(async () => { + const outcome = await this.store().transact(this.accountId, async tx => { + const key = identity(data); + const hash = createHash('sha256').update(JSON.stringify(data)).digest('hex'); + if (!(await tx.recordEvent(key, hash))) { + return { processed: false, changes: [] as Change[] }; + } + const previous = tx.account.quotes[data.data.symbol]; + if (previous && data.data.timestamp < previous.timestamp) { + throw new ExecutionConflictError('Out-of-order market data'); + } + const quote: Quote = + data.type === 'quote' + ? { ...data.data, eventId: key } + : data.type === 'bar' + ? { + bid: data.data.close, + ask: data.data.close, + bidSize: data.data.volume, + askSize: data.data.volume, + timestamp: data.data.timestamp, + eventId: key, + } + : { + bid: data.data.price, + ask: data.data.price, + bidSize: data.data.size, + askSize: data.data.size, + timestamp: data.data.timestamp, + eventId: key, + }; + if ( + ![quote.bid, quote.ask, quote.bidSize, quote.askSize, quote.timestamp].every( + Number.isFinite + ) || + quote.bid <= 0 || + quote.ask < quote.bid || + quote.bidSize < 0 || + quote.askSize < 0 + ) { + throw new Error('Invalid market quote/liquidity'); + } + const time = this.now(quote); + if ( + this.mode === 'paper' && + (time - quote.timestamp > tx.account.maxQuoteAgeMs || quote.timestamp > time) + ) { + throw new Error('Stale or future market data'); + } + this.rollDay(tx.account, quote.timestamp); + tx.account.quotes[data.data.symbol] = quote; + const orders = await tx.openOrders(); + const changes: Change[] = []; + for (const order of orders) { + const before = order.report.status; + const expired = + order.request.timeInForce === 'DAY' && + new Date(order.report.timestamp).toISOString().slice(0, 10) < + new Date(quote.timestamp).toISOString().slice(0, 10); + if (expired) { + order.report.status = 'cancelled'; + } + const fills = + !expired && order.request.symbol === data.data.symbol + ? await this.fill(tx, order, quote, orders) + : []; + await tx.putOrder(order); + if (fills.length || before !== order.report.status) { + changes.push({ report: order.report, fills }); + } + } + return { processed: true, changes }; + }); + for (const change of outcome.changes) { + await this.publish(change); + } + return outcome.processed; + }); + } + async cancelOrder(id: string): Promise { + return this.serialized(async () => { + const change = await this.store().transact(this.accountId, async tx => { + const order = await tx.getOrder(id); + if (!order || terminal(order.report.status)) { + return undefined; + } + order.report.status = 'cancelled'; + await tx.putOrder(order); + return { report: order.report, fills: [] }; + }); + if (change) { + await this.publish(change); + } + return !!change; + }); + } + async getOrderStatus(id: string) { + return this.store().transact( + this.accountId, + async tx => (await tx.getOrder(id))?.report ?? null + ); + } + async getAccount() { + return this.store().transact(this.accountId, async tx => ({ + ...tx.account, + ...accountMetrics(tx.account), + })); + } + async getStrategySnapshot(id: string) { + return this.store().transact(this.accountId, async tx => ({ + positions: tx.account.strategyPositions[id] ?? {}, + orders: (await tx.openOrders()).filter(o => o.report.strategyId === id), + })); + } + async getPositions() { + const account = await this.getAccount(); + return Object.values(account.positions).map(p => ({ + ...p, + unrealizedPnl: amount( + decimal( + account.quotes[p.symbol] + ? (defined(account.quotes[p.symbol]).bid + defined(account.quotes[p.symbol]).ask) / 2 + : p.averagePrice + ) + .minus(p.averagePrice) + .times(p.quantity) + ), + })); + } + private async publish(change: Change) { + const fills = change.fills.map(fill => ({ + ...fill, + orderId: change.report.orderId, + symbol: change.report.symbol, + side: change.report.side, + strategyId: change.report.strategyId, + })); + // Native analytics is a run-local projection only. Paper positions always read the SQL ledger. + if (this.mode === 'backtest') { + for (const fill of fills) { + defined(this.engine).advanceTime(fill.timestamp); + defined(this.engine).processFillWithMetadata( + fill.symbol, + fill.price, + fill.quantity, + fill.side, + fill.commission, + fill.orderId, + fill.strategyId ?? null ); } - - // Submit based on mode - let result: ExecutionReport; - - switch (this.mode) { - case 'backtest': - case 'paper': - result = await this.submitToSimulation(orderId, clientOrderId, validatedOrder); - break; - case 'live': - result = await this.submitToBroker(orderId, clientOrderId, validatedOrder); - break; - } - - // Emit order event - this.emit('orderUpdate', result); - - // If filled, update positions - if (result.fills.length > 0) { - await this.processFills(result); - } - - return result; - } catch (error) { - this.container.logger.error('Error submitting order:', error); - return this.createRejectionReport( - orderId, - clientOrderId, - validatedOrder, - error instanceof Error ? error.message : 'Unknown error' - ); } - } - - private async checkRisk(order: OrderRequest) { - if (!this.tradingEngine) { - throw new Error('Trading engine not initialized'); - } - - // Convert to engine format - const engineOrder = { - id: uuidv4(), - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - orderType: order.orderType, - limitPrice: order.limitPrice, - timeInForce: order.timeInForce, - }; - - const result = this.tradingEngine.checkRisk(engineOrder); - return JSON.parse(result); - } - - private async submitToSimulation( - orderId: string, - clientOrderId: string, - order: OrderRequest - ): Promise { - if (!this.tradingEngine) { - throw new Error('Trading engine not initialized'); - } - - // Convert to engine format - const engineOrder = { - id: orderId, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - orderType: order.orderType, - limitPrice: order.limitPrice, - timeInForce: order.timeInForce, - }; - - // Submit to engine - const result = await this.tradingEngine.submitOrder(engineOrder); - const engineResult = JSON.parse(result); - - // Convert back to our format - return { - orderId, - clientOrderId, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - status: this.mapEngineStatus(engineResult.status), - fills: engineResult.fills || [], - timestamp: Date.now(), - }; - } - - private async submitToBroker( - orderId: string, - clientOrderId: string, - order: OrderRequest - ): Promise { - // In real implementation, would submit to actual broker - // This is a placeholder - this.container.logger.info(`Submitting order ${orderId} to broker`); - - // Simulate broker response - return { - orderId, - clientOrderId, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - status: 'pending', - fills: [], - timestamp: Date.now(), - }; - } - - async cancelOrder(orderId: string): Promise { - const order = this.pendingOrders.get(orderId); - if (!order) { - this.container.logger.warn(`Order ${orderId} not found`); - return false; - } - try { - switch (this.mode) { - case 'backtest': - case 'paper': - // Cancel in simulation - if (this.tradingEngine) { - throw new Error('The native simulation engine does not support order cancellation'); - } - break; - case 'live': - // Cancel with broker - if (this.brokerClient) { - await this.brokerClient.cancelOrder(orderId); - } - break; + await this.observer?.(change.report, fills); + this.emit('orderUpdate', change.report); + for (const fill of fills) { + this.emit('fill', fill); } - - this.pendingOrders.delete(orderId); - - // Emit cancellation event - this.emit('orderUpdate', { - orderId, - status: 'cancelled', - timestamp: Date.now(), - }); - - return true; } catch (error) { - this.container.logger.error(`Error cancelling order ${orderId}:`, error); - return false; + this.container.logger.error('Execution observer failed after commit', { error }); } } - - private async processFills(executionReport: ExecutionReport): Promise { - if (!this.tradingEngine) { - return; - } - - for (const fill of executionReport.fills) { - // Update position in engine - const result = this.tradingEngine.processFill( - executionReport.symbol, - fill.price, - fill.quantity, - executionReport.side, - fill.commission - ); - - // Emit fill event - this.emit('fill', { - orderId: executionReport.orderId, - symbol: executionReport.symbol, - side: executionReport.side, - ...fill, - positionUpdate: JSON.parse(result), - }); - } + async routeOrderToExchange(_order: OrderRequest, _exchange: string): Promise { + throw new UnsupportedExecutionError('Exchange/broker routing is disabled'); } - - private createRejectionReport( - orderId: string, - clientOrderId: string, - order: OrderRequest, - reason: string - ): ExecutionReport { - return { - orderId, - clientOrderId, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - status: 'rejected', - fills: [], - rejectionReason: reason, - timestamp: Date.now(), - }; - } - - private mapEngineStatus(engineStatus: string): ExecutionReport['status'] { - const statusMap: Record = { - Pending: 'pending', - Accepted: 'accepted', - PartiallyFilled: 'partiallyFilled', - Filled: 'filled', - Cancelled: 'cancelled', - Rejected: 'rejected', - }; - - return statusMap[engineStatus] || 'rejected'; - } - - async routeOrderToExchange(order: OrderRequest, exchange: string): Promise { - // This would route orders to specific exchanges in live mode - // For now, just a placeholder - this.container.logger.info(`Routing order to ${exchange}:`, order); - } - - async getOrderStatus(_orderId: string): Promise { - // In real implementation, would query broker or internal state - return null; - } - - async shutdown(): Promise { - // Cancel all pending orders - for (const orderId of this.pendingOrders.keys()) { - await this.cancelOrder(orderId); - } - - // Disconnect from broker - if (this.brokerClient) { - // await this.brokerClient.disconnect(); - this.brokerClient = null; - } - - this.tradingEngine = null; - this.removeAllListeners(); + async shutdown() { + this.closing = true; + await this.tail; + this.mode = undefined; + this.engine = undefined; } } + +const riskViolationsFor = ( + tx: ExecutionTransaction, + request: OrderRequest, + reservations: StoredOrder[], + price: number, + timestamp: number +) => riskViolations(tx.account, request, reservations, price, timestamp); diff --git a/apps/stock/orchestrator/src/services/MarketDataService.ts b/apps/stock/orchestrator/src/services/MarketDataService.ts index 9071c075..aa82d477 100644 --- a/apps/stock/orchestrator/src/services/MarketDataService.ts +++ b/apps/stock/orchestrator/src/services/MarketDataService.ts @@ -2,7 +2,14 @@ import { EventEmitter } from 'events'; import { io, Socket } from 'socket.io-client'; import { defined } from '@stock-bot/invariants'; import type { OrchestratorServices as IServiceContainer } from '../types'; -import { BarSchema, QuoteSchema, TradeSchema, type MarketData, type ModeConfig } from '../types'; +import { + BarSchema, + MarketDataSchema, + QuoteSchema, + TradeSchema, + type MarketData, + type ModeConfig, +} from '../types'; export class MarketDataService extends EventEmitter { private mode: 'backtest' | 'paper' | 'live' = 'paper'; @@ -79,16 +86,25 @@ export class MarketDataService extends EventEmitter { this.container.logger.debug(`Unsubscribed from ${symbol}`); } + ingest(input: unknown): void { + this.handleMarketData(input); + } + async flush(): Promise { + this.processBatch(); + await this.container.custom?.StrategyManager?.drain(); + } private handleMarketData(input: unknown): void { - if (!input || typeof input !== 'object') { - throw new Error('Invalid market data'); - } - const data = input as Record; try { + if (!input || typeof input !== 'object') { + throw new Error('Invalid market data'); + } + const data = input as Record; // Validate and transform data let marketData: MarketData; - if (data.bid !== undefined && data.ask !== undefined) { + if ('type' in data && 'data' in data) { + marketData = MarketDataSchema.parse(data); + } else if (data.bid !== undefined && data.ask !== undefined) { const quote = QuoteSchema.parse({ symbol: data.symbol, bid: data.bid, @@ -125,6 +141,9 @@ export class MarketDataService extends EventEmitter { } // Add to batch buffer + if (typeof data.eventId === 'string') { + marketData.eventId = data.eventId; + } this.batchBuffer.push(marketData); // Process batch if size threshold reached @@ -155,11 +174,6 @@ export class MarketDataService extends EventEmitter { this.batchBuffer = []; this.emit('marketDataBatch', batch); - - // Also emit individual events for strategies that need them - batch.forEach(data => { - this.emit('marketData', data); - }); } async loadHistoricalData( @@ -202,18 +216,13 @@ export class MarketDataService extends EventEmitter { this.batchTimer = null; } - // Process any remaining data - if (this.batchBuffer.length > 0) { - this.processBatch(); - } - // Disconnect from data ingestion if (this.dataIngestionSocket) { this.dataIngestionSocket.disconnect(); this.dataIngestionSocket = null; } + await this.flush(); this.subscriptions.clear(); - this.removeAllListeners(); } } diff --git a/apps/stock/orchestrator/src/services/StorageService.ts b/apps/stock/orchestrator/src/services/StorageService.ts index 759026ba..cb1bd9b6 100644 --- a/apps/stock/orchestrator/src/services/StorageService.ts +++ b/apps/stock/orchestrator/src/services/StorageService.ts @@ -4,7 +4,7 @@ import type { PostgresClient, QuestDBClient, } from '@stock-bot/services'; -import type { MarketData, ModeConfig, OrderRequest, PerformanceMetrics, Position } from '../types'; +import type { MarketData, ModeConfig, PerformanceMetrics } from '../types'; export interface HistoricalBar { symbol: string; @@ -17,16 +17,6 @@ export interface HistoricalBar { vwap?: number; interpolated?: boolean; } -export interface StoredFill { - orderId: string; - symbol: string; - price: number; - quantity: number; - commission: number; - side: string; - timestamp: number; -} - export class StorageService { private questdb: QuestDBClient | null = null; private postgres: PostgresClient | null = null; @@ -58,55 +48,6 @@ export class StorageService { private async createTables(): Promise { // Create tables if they don't exist if (this.postgres) { - // Orders table - await this.postgres.query(` - CREATE TABLE IF NOT EXISTS orders ( - id UUID PRIMARY KEY, - client_order_id VARCHAR(255), - symbol VARCHAR(50) NOT NULL, - side VARCHAR(10) NOT NULL, - quantity DECIMAL(20, 8) NOT NULL, - order_type VARCHAR(20) NOT NULL, - limit_price DECIMAL(20, 8), - stop_price DECIMAL(20, 8), - time_in_force VARCHAR(10) NOT NULL, - status VARCHAR(20) NOT NULL, - created_at TIMESTAMP NOT NULL DEFAULT NOW(), - updated_at TIMESTAMP NOT NULL DEFAULT NOW(), - mode VARCHAR(10) NOT NULL - ) - `); - - // Fills table - await this.postgres.query(` - CREATE TABLE IF NOT EXISTS fills ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - order_id UUID NOT NULL REFERENCES orders(id), - symbol VARCHAR(50) NOT NULL, - price DECIMAL(20, 8) NOT NULL, - quantity DECIMAL(20, 8) NOT NULL, - commission DECIMAL(20, 8) NOT NULL, - side VARCHAR(10) NOT NULL, - timestamp TIMESTAMP NOT NULL, - mode VARCHAR(10) NOT NULL - ) - `); - - // Positions table - await this.postgres.query(` - CREATE TABLE IF NOT EXISTS positions ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - symbol VARCHAR(50) NOT NULL, - quantity DECIMAL(20, 8) NOT NULL, - average_price DECIMAL(20, 8) NOT NULL, - realized_pnl DECIMAL(20, 8) NOT NULL DEFAULT 0, - unrealized_pnl DECIMAL(20, 8) NOT NULL DEFAULT 0, - updated_at TIMESTAMP NOT NULL DEFAULT NOW(), - mode VARCHAR(10) NOT NULL, - UNIQUE(symbol, mode) - ) - `); - // Strategy performance table await this.postgres.query(` CREATE TABLE IF NOT EXISTS strategy_performance ( @@ -189,125 +130,6 @@ export class StorageService { } } - async storeOrder(order: OrderRequest & { id: string; status: string }): Promise { - if (!this.postgres) { - return; - } - - await this.postgres.query( - ` - INSERT INTO orders ( - id, client_order_id, symbol, side, quantity, - order_type, limit_price, stop_price, time_in_force, - status, mode - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) - `, - [ - order.id, - order.clientOrderId, - order.symbol, - order.side, - order.quantity, - order.orderType, - order.limitPrice || null, - order.stopPrice || null, - order.timeInForce, - order.status, - this.mode, - ] - ); - } - - async updateOrderStatus(orderId: string, status: string): Promise { - if (!this.postgres) { - return; - } - - await this.postgres.query( - ` - UPDATE orders - SET status = $1, updated_at = NOW() - WHERE id = $2 - `, - [status, orderId] - ); - } - - async storeFill(fill: StoredFill): Promise { - if (!this.postgres) { - return; - } - - await this.postgres.query( - ` - INSERT INTO fills ( - order_id, symbol, price, quantity, commission, side, timestamp, mode - ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) - `, - [ - fill.orderId, - fill.symbol, - fill.price, - fill.quantity, - fill.commission, - fill.side, - new Date(fill.timestamp), - this.mode, - ] - ); - } - - async updatePosition(position: Position): Promise { - if (!this.postgres) { - return; - } - - await this.postgres.query( - ` - INSERT INTO positions ( - symbol, quantity, average_price, realized_pnl, unrealized_pnl, mode - ) VALUES ($1, $2, $3, $4, $5, $6) - ON CONFLICT (symbol, mode) DO UPDATE SET - quantity = $2, - average_price = $3, - realized_pnl = $4, - unrealized_pnl = $5, - updated_at = NOW() - `, - [ - position.symbol, - position.quantity, - position.averagePrice, - position.realizedPnl, - position.unrealizedPnl, - this.mode, - ] - ); - } - - async getPositions(): Promise { - if (!this.postgres) { - return []; - } - - const result = await this.postgres.query( - ` - SELECT * FROM positions WHERE mode = $1 - `, - [this.mode] - ); - - return result.rows.map(row => ({ - symbol: row.symbol, - quantity: parseFloat(row.quantity), - averagePrice: parseFloat(row.average_price), - realizedPnl: parseFloat(row.realized_pnl), - unrealizedPnl: parseFloat(row.unrealized_pnl), - totalCost: parseFloat(row.quantity) * parseFloat(row.average_price), - lastUpdate: row.updated_at, - })); - } - async storeStrategyPerformance( strategyId: string, metrics: Pick< diff --git a/apps/stock/orchestrator/src/strategies/BaseStrategy.ts b/apps/stock/orchestrator/src/strategies/BaseStrategy.ts index 2e9e7ee7..5e855b9b 100644 --- a/apps/stock/orchestrator/src/strategies/BaseStrategy.ts +++ b/apps/stock/orchestrator/src/strategies/BaseStrategy.ts @@ -1,4 +1,5 @@ import { EventEmitter } from 'events'; +import { createHash } from 'node:crypto'; import { defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import { ModeManager } from '../core/ModeManager'; @@ -19,6 +20,11 @@ export interface Signal { export abstract class BaseStrategy extends EventEmitter { protected config: StrategyConfig; protected isActive = false; + private eventIdentity?: string; + private readonly seenFills = new Set(); + setMarketEvent(eventId: string) { + this.eventIdentity = eventId; + } protected positions = new Map(); protected pendingOrders = new Map(); protected performance = { @@ -42,6 +48,13 @@ export abstract class BaseStrategy extends EventEmitter { async initialize(): Promise { logger.info(`Initializing strategy: ${this.config.name}`); + const snapshot = await this.executionService.getStrategySnapshot(this.config.id); + this.positions = new Map( + Object.entries(snapshot.positions).filter(([, quantity]) => quantity !== 0) + ); + this.pendingOrders = new Map( + snapshot.orders.map(order => [order.report.orderId, order.request]) + ); // Subscribe to symbols for (const symbol of this.config.symbols) { // Note: In real implementation, would subscribe through market data service @@ -96,7 +109,14 @@ export abstract class BaseStrategy extends EventEmitter { // Convert signal to order if strong enough const order = await this.signalToOrder(signal); if (order) { - this.emit('order', order); + const clientOrderId = createHash('sha256') + .update(JSON.stringify([this.config.id, this.eventIdentity, order])) + .digest('hex'); + const report = await this.executionService.submitOrder( + { ...order, clientOrderId }, + { strategyId: this.config.id } + ); + this.emit('order', report); // Observation only; no second submission path. } } } catch (error) { @@ -124,29 +144,16 @@ export abstract class BaseStrategy extends EventEmitter { async onOrderUpdate(update: StrategyOrderUpdate): Promise { logger.debug(`Strategy ${this.config.id} order update:`, update); - if (update.status === 'filled') { - // Remove from pending - this.pendingOrders.delete(update.orderId); - - // Update position tracking - const fill = update.fills[0]; // Assuming single fill for simplicity - if (fill) { - const currentPos = this.positions.get(update.symbol) || 0; - const newPos = - update.side === 'buy' ? currentPos + fill.quantity : currentPos - fill.quantity; - - logger.info( - `[BaseStrategy] Position update for ${update.symbol}: ${currentPos} -> ${newPos} (${update.side} ${fill.quantity})` - ); - - if (Math.abs(newPos) < 0.0001) { - this.positions.delete(update.symbol); - } else { - this.positions.set(update.symbol, newPos); - } - } - } else if (update.status === 'rejected' || update.status === 'cancelled') { + if (['filled', 'rejected', 'cancelled'].includes(update.status)) { this.pendingOrders.delete(update.orderId); + } else { + this.pendingOrders.set(update.orderId, { + symbol: update.symbol, + side: update.side, + quantity: update.quantity, + orderType: 'market', + timeInForce: 'DAY', + }); } } @@ -156,6 +163,18 @@ export abstract class BaseStrategy extends EventEmitter { } async onFill(fill: StrategyFill): Promise { + if (this.seenFills.has(fill.id)) { + return; + } + this.seenFills.add(fill.id); + const quantity = + (this.positions.get(fill.symbol) ?? 0) + + (fill.side === 'buy' ? fill.quantity : -fill.quantity); + if (Math.abs(quantity) < 1e-8) { + this.positions.delete(fill.symbol); + } else { + this.positions.set(fill.symbol, quantity); + } // Update performance metrics this.performance.trades++; @@ -174,7 +193,9 @@ export abstract class BaseStrategy extends EventEmitter { this.performance.currentDrawdown = 0; } else { this.performance.currentDrawdown = - (this.performance.peakEquity - currentEquity) / this.performance.peakEquity; + this.performance.peakEquity > 0 + ? (this.performance.peakEquity - currentEquity) / this.performance.peakEquity + : 0; this.performance.maxDrawdown = Math.max( this.performance.maxDrawdown, this.performance.currentDrawdown diff --git a/apps/stock/orchestrator/src/strategies/StrategyManager.ts b/apps/stock/orchestrator/src/strategies/StrategyManager.ts index ca8d394d..578f885a 100644 --- a/apps/stock/orchestrator/src/strategies/StrategyManager.ts +++ b/apps/stock/orchestrator/src/strategies/StrategyManager.ts @@ -1,9 +1,9 @@ import { EventEmitter } from 'events'; import { TradingEngine } from '@stock-bot/engine'; import { defined } from '@stock-bot/invariants'; -import type { StrategyFill } from '../services/ExecutionService'; +import { identity } from '../execution/model'; import type { OrchestratorServices as IServiceContainer } from '../types'; -import { type MarketData, type OrderRequest, type StrategyConfig } from '../types'; +import { type MarketData, type StrategyConfig } from '../types'; import type { Signal } from './BaseStrategy'; import { BaseStrategy } from './BaseStrategy'; @@ -12,6 +12,14 @@ export class StrategyManager extends EventEmitter { private activeStrategies = new Set(); private tradingEngine: TradingEngine | null = null; private container: IServiceContainer; + private delivery: Promise = Promise.resolve(); + private listening = false; + private marketSource?: import('../services/MarketDataService').MarketDataService; + private readonly onBatch = (batch: MarketData[]) => { + void this.deliverBatch(batch).catch(error => + this.container.logger.error('Market delivery failed', { error }) + ); + }; constructor(container: IServiceContainer) { super(); @@ -27,20 +35,36 @@ export class StrategyManager extends EventEmitter { return; } - // Listen for market data - marketDataService.on('marketData', (data: MarketData) => { - this.handleMarketData(data); + if (this.listening) { + return; + } + this.listening = true; + this.marketSource = marketDataService; + marketDataService.on('marketDataBatch', this.onBatch); + executionService.setObserver(async (report, fills) => { + const strategy = report.strategyId ? this.strategies.get(report.strategyId) : undefined; + if (!strategy) { + return; + } + for (const fill of fills) { + await strategy.onFill(fill); + } + await strategy.onOrderUpdate(report); }); + } - // Listen for market data batches (more efficient) - marketDataService.on('marketDataBatch', (batch: MarketData[]) => { - this.handleMarketDataBatch(batch); + private deliverBatch(batch: MarketData[]): Promise { + const work = this.delivery.then(async () => { + for (const data of batch) { + await this.handleMarketData(data); + } }); + this.delivery = work.catch(() => {}); + return work; + } - // Listen for fills - executionService.on('fill', fill => { - this.handleFill(fill); - }); + async drain(): Promise { + await this.delivery; } async initializeStrategies(configs: StrategyConfig[]): Promise { @@ -122,10 +146,6 @@ export class StrategyManager extends EventEmitter { this.handleStrategySignal(config.id, signal); }); - strategy.on('order', order => { - this.handleStrategyOrder(config.id, order); - }); - strategy.on('error', (error: Error) => { this.container.logger.error(`Strategy ${config.id} error:`, error); }); @@ -157,21 +177,16 @@ export class StrategyManager extends EventEmitter { } private async handleMarketData(data: MarketData): Promise { - // Forward to all active strategies - if (this.activeStrategies.size === 0) { - this.container.logger.info( - `[StrategyManager] No active strategies to process market data! All strategies: ${Array.from(this.strategies.keys()).join(', ')}` - ); - } else { - this.container.logger.info( - `[StrategyManager] Forwarding market data to ${this.activeStrategies.size} active strategies: ${Array.from(this.activeStrategies).join(', ')}` - ); + const execution = defined(this.container.custom?.ExecutionService); + if (!(await execution.onMarketData(data))) { + return; } for (const strategyId of this.activeStrategies) { const strategy = this.strategies.get(strategyId); - if (strategy) { + if (strategy && strategy.isInterestedInSymbol(data.data.symbol)) { try { + strategy.setMarketEvent(identity(data)); await strategy.onMarketData(data); } catch (error) { this.container.logger.error( @@ -183,88 +198,13 @@ export class StrategyManager extends EventEmitter { } } - private async handleMarketDataBatch(batch: MarketData[]): Promise { - // Process batch more efficiently - for (const strategyId of this.activeStrategies) { - const strategy = this.strategies.get(strategyId); - if (strategy) { - try { - await strategy.onMarketDataBatch(batch); - } catch (error) { - this.container.logger.error( - `Error processing market data batch for strategy ${strategyId}:`, - error - ); - } - } - } - } - - private async handleFill(fill: StrategyFill): Promise { - // Forward fill to the strategy that created the order - for (const [strategyId, strategy] of this.strategies) { - if (strategy.hasOrder(fill.orderId)) { - try { - await strategy.onFill(fill); - } catch (error) { - this.container.logger.error(`Error processing fill for strategy ${strategyId}:`, error); - } - break; - } - } - } - private async handleStrategySignal(strategyId: string, signal: Signal): Promise { this.container.logger.info(`Strategy ${strategyId} generated signal:`, signal); // Signals are informational - strategies will convert strong signals to orders } - private async handleStrategyOrder(strategyId: string, order: OrderRequest): Promise { - this.container.logger.info(`Strategy ${strategyId} generated order:`, order); - - // Submit order through trading engine (for backtesting) - if (this.tradingEngine) { - try { - // Create order object for Rust API - const orderObj = { - id: `${strategyId}-${Date.now()}`, - symbol: order.symbol, - side: order.side, - quantity: order.quantity, - orderType: order.orderType, - limitPrice: order.limitPrice, - timeInForce: order.timeInForce || 'DAY', - }; - - const orderResult = await this.tradingEngine.submitOrder(orderObj); - const result = JSON.parse(orderResult); - this.container.logger.info(`Order placed for strategy ${strategyId}: ${result.order_id}`); - - // Emit order event - this.emit('order', { - strategyId, - orderId: result.order_id, - order, - }); - } catch (error) { - this.container.logger.error(`Failed to place order for strategy ${strategyId}:`, error); - } - } else { - // Use execution service for paper/live trading - const executionService = this.container.custom?.ExecutionService; - if (executionService) { - try { - const result = await executionService.submitOrder(order); - this.container.logger.info(`Order submitted for strategy ${strategyId}:`, result); - } catch (error) { - this.container.logger.error(`Failed to submit order for strategy ${strategyId}:`, error); - } - } - } - } - async onMarketData(data: MarketData): Promise { - await this.handleMarketData(data); + await this.deliverBatch([data]); } getTradingEngine(): TradingEngine | null { @@ -286,6 +226,11 @@ export class StrategyManager extends EventEmitter { async shutdown(): Promise { this.container.logger.info('Shutting down strategy manager...'); + if (this.marketSource) { + this.marketSource.off('marketDataBatch', this.onBatch); + } + this.listening = false; + await this.drain(); // Disable all strategies for (const strategyId of this.activeStrategies) { await this.disableStrategy(strategyId); diff --git a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts index 7fa6e77f..525557b1 100644 --- a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts +++ b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossover.ts @@ -167,7 +167,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy { ); // Calculate position size - const positionSize = this.calculateCrossoverPositionSize(currentPrice); + const positionSize = await this.calculateCrossoverPositionSize(currentPrice); logger.info(` Opening long position: ${positionSize} shares`); const signal: Signal = { @@ -232,7 +232,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy { // Open short position for long/short strategy logger.info(` No current position, opening short`); - const positionSize = this.calculateCrossoverPositionSize(currentPrice); + const positionSize = await this.calculateCrossoverPositionSize(currentPrice); logger.info(` Opening short position: ${positionSize} shares`); const signal: Signal = { @@ -290,25 +290,8 @@ export class SimpleMovingAverageCrossover extends BaseStrategy { return sma; } - private calculateCrossoverPositionSize(price: number): number { - // Get account balance from trading engine - const tradingEngine = this.modeManager?.getTradingEngine(); - if (!tradingEngine) { - logger.warn('No trading engine available, using default position size'); - return 100; - } - - // Try to get account balance from trading engine - let accountBalance = 100000; // Default - try { - { - const [realized = 0, unrealized = 0] = tradingEngine.getTotalPnl(); - accountBalance = 100000 + realized + unrealized; // Assuming 100k initial - } - } catch (error) { - logger.warn('Could not get account balance', { error }); - } - + private async calculateCrossoverPositionSize(price: number): Promise { + const accountBalance = (await this.executionService.getAccount()).equity; const positionValue = accountBalance * this.POSITION_SIZE; const shares = Math.floor(positionValue / price); diff --git a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts index 07f1f931..9d47403c 100644 --- a/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts +++ b/apps/stock/orchestrator/src/strategies/examples/SimpleMovingAverageCrossoverFixed.ts @@ -141,7 +141,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy { logger.info(`🟢 Opening LONG position - Bullish trend after golden cross`); logger.info(` Current position: 0 shares`); - const positionSize = this.calculateCrossoverPositionSize(currentPrice); + const positionSize = await this.calculateCrossoverPositionSize(currentPrice); logger.info(` Opening long position: ${positionSize} shares`); const signal: Signal = { @@ -169,7 +169,7 @@ export class SimpleMovingAverageCrossover extends BaseStrategy { logger.info(`🔴 Opening SHORT position - Bearish trend after death cross`); logger.info(` Current position: 0 shares`); - const positionSize = this.calculateCrossoverPositionSize(currentPrice); + const positionSize = await this.calculateCrossoverPositionSize(currentPrice); logger.info(` Opening short position: ${positionSize} shares`); const signal: Signal = { @@ -276,27 +276,8 @@ export class SimpleMovingAverageCrossover extends BaseStrategy { return sma; } - private calculateCrossoverPositionSize(price: number): number { - // Get account balance from trading engine - const tradingEngine = this.modeManager?.getTradingEngine(); - if (!tradingEngine) { - logger.warn('No trading engine available, using default position size'); - return 100; - } - - // Try to get account balance from trading engine - // Use initial capital from config parameters if available - let accountBalance = Number(this.config.parameters?.initialCapital ?? 100000); - try { - { - const [realized = 0, unrealized = 0] = tradingEngine.getTotalPnl(); - accountBalance = - Number(this.config.parameters?.initialCapital ?? 100000) + realized + unrealized; - } - } catch (error) { - logger.warn('Could not get account balance', { error }); - } - + private async calculateCrossoverPositionSize(price: number): Promise { + const accountBalance = (await this.executionService.getAccount()).equity; const positionValue = accountBalance * this.POSITION_SIZE; const shares = Math.floor(positionValue / price); diff --git a/apps/stock/orchestrator/src/types.ts b/apps/stock/orchestrator/src/types.ts index 52f5a126..c7c18faf 100644 --- a/apps/stock/orchestrator/src/types.ts +++ b/apps/stock/orchestrator/src/types.ts @@ -3,6 +3,13 @@ import { z } from 'zod'; // Trading modes export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']); export type TradingMode = z.infer; +export const RiskLimitsSchema = z.object({ + maxPositionSize: z.number().finite().positive(), + maxOrderSize: z.number().finite().positive(), + maxDailyLoss: z.number().finite().positive(), + maxGrossExposure: z.number().finite().positive(), + maxSymbolExposure: z.number().finite().positive(), +}); // Mode configurations export const BacktestConfigSchema = z.object({ @@ -26,8 +33,8 @@ export const BacktestConfigSchema = z.object({ }) ) .optional(), - commission: z.number().optional(), - slippage: z.number().optional(), + commission: z.number().finite().min(0).max(0.1).optional(), + slippage: z.number().finite().min(0).max(0.1).optional(), fillModel: z .object({ slippage: z.enum(['zero', 'conservative', 'realistic', 'aggressive']), @@ -36,11 +43,17 @@ export const BacktestConfigSchema = z.object({ }) .optional(), speed: z.enum(['max', 'realtime', '2x', '5x', '10x']).default('max'), + riskLimits: RiskLimitsSchema.optional(), }); export const PaperConfigSchema = z.object({ mode: z.literal('paper'), startingCapital: z.number().positive(), + accountId: z.string().min(1).max(128).optional(), + riskLimits: RiskLimitsSchema.optional(), + commission: z.number().finite().min(0).max(0.1).optional(), + slippage: z.number().finite().min(0).max(0.1).optional(), + maxQuoteAgeMs: z.number().int().positive().optional(), fillModel: z .object({ useRealOrderBook: z.boolean().default(true), @@ -118,9 +131,21 @@ export const BarSchema = z.object({ }); export const MarketDataSchema = z.discriminatedUnion('type', [ - z.object({ type: z.literal('quote'), data: QuoteSchema }), - z.object({ type: z.literal('trade'), data: TradeSchema }), - z.object({ type: z.literal('bar'), data: BarSchema }), + z.object({ + type: z.literal('quote'), + data: QuoteSchema, + eventId: z.string().min(1).max(256).optional(), + }), + z.object({ + type: z.literal('trade'), + data: TradeSchema, + eventId: z.string().min(1).max(256).optional(), + }), + z.object({ + type: z.literal('bar'), + data: BarSchema, + eventId: z.string().min(1).max(256).optional(), + }), ]); export type MarketData = z.infer; @@ -134,14 +159,14 @@ export const OrderTypeSchema = z.enum(['market', 'limit', 'stop', 'stop_limit']) export const TimeInForceSchema = z.enum(['DAY', 'GTC', 'IOC', 'FOK']); export const OrderRequestSchema = z.object({ - symbol: z.string(), + symbol: z.string().trim().min(1).max(50), side: OrderSideSchema, - quantity: z.number().positive(), + quantity: z.number().finite().min(1e-8).max(1e9), orderType: OrderTypeSchema, - limitPrice: z.number().positive().optional(), - stopPrice: z.number().positive().optional(), + limitPrice: z.number().finite().positive().optional(), + stopPrice: z.number().finite().positive().optional(), timeInForce: TimeInForceSchema.default('DAY'), - clientOrderId: z.string().optional(), + clientOrderId: z.string().min(1).max(256).optional(), }); export type OrderRequest = z.infer; diff --git a/apps/stock/web-api/src/migrations/migration-runner.ts b/apps/stock/web-api/src/migrations/migration-runner.ts index 348292e3..51bb2beb 100644 --- a/apps/stock/web-api/src/migrations/migration-runner.ts +++ b/apps/stock/web-api/src/migrations/migration-runner.ts @@ -45,7 +45,8 @@ export async function runMigrations(container: IServiceContainer): Promise f.endsWith('.sql') && (f.startsWith('001_') || f === '09-backtest-run-contract.sql' || - f === '10-durable-backtest-dispatch.sql') + f === '10-durable-backtest-dispatch.sql' || + f === '11-simulation-execution-ledger.sql') ) // Explicit additive migration allowlist; never replay destructive init migrations .sort(); 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 b55cf102..6d2fb3b9 100644 --- a/apps/stock/web-api/src/services/backtest-v2.service.ts +++ b/apps/stock/web-api/src/services/backtest-v2.service.ts @@ -224,6 +224,7 @@ export class BacktestServiceV2 { endDate: definition.endDate.toISOString(), initialCapital: definition.initialCapital, config: definition.config, + riskLimits: definition.config.riskLimits, dataFrequency: definition.config.dataFrequency ?? '1d', commission: definition.config.commission ?? 0.001, slippage: definition.config.slippage ?? 0.0001, diff --git a/bun.lock b/bun.lock index ba7bcb1d..7ff848cd 100644 --- a/bun.lock +++ b/bun.lock @@ -142,6 +142,7 @@ "@stock-bot/types": "workspace:*", "@stock-bot/utils": "*", "axios": "^1.6.0", + "decimal.js-light": "2.5.1", "hono": "^4.0.0", "simple-statistics": "^7.8.3", "socket.io": "^4.7.2", diff --git a/database/postgres/init/11-simulation-execution-ledger.sql b/database/postgres/init/11-simulation-execution-ledger.sql new file mode 100644 index 00000000..e607214f --- /dev/null +++ b/database/postgres/init/11-simulation-execution-ledger.sql @@ -0,0 +1,22 @@ +-- Separate, account-scoped paper ledger. Existing trading/backtest history is untouched. +CREATE TABLE IF NOT EXISTS simulation_accounts ( + id TEXT PRIMARY KEY, state JSONB NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); +CREATE TABLE IF NOT EXISTS simulation_orders ( + id UUID PRIMARY KEY, account_id TEXT NOT NULL REFERENCES simulation_accounts(id), + client_order_id TEXT NOT NULL, status TEXT NOT NULL, + payload JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE(account_id,client_order_id), UNIQUE(account_id,id), + CHECK(status IN ('accepted','partiallyFilled','filled','cancelled','rejected')) +); +CREATE INDEX IF NOT EXISTS simulation_open_orders ON simulation_orders(account_id,status); +CREATE TABLE IF NOT EXISTS simulation_fills ( + account_id TEXT NOT NULL, id TEXT NOT NULL, order_id UUID NOT NULL, payload JSONB NOT NULL, + PRIMARY KEY(account_id,id), + FOREIGN KEY(account_id,order_id) REFERENCES simulation_orders(account_id,id) +); +CREATE TABLE IF NOT EXISTS simulation_events ( + account_id TEXT NOT NULL REFERENCES simulation_accounts(id), id TEXT NOT NULL, + fingerprint TEXT NOT NULL, PRIMARY KEY(account_id,id) +); diff --git a/libs/core/types/src/backtest-run.ts b/libs/core/types/src/backtest-run.ts index 20a87a8e..92bcce09 100644 --- a/libs/core/types/src/backtest-run.ts +++ b/libs/core/types/src/backtest-run.ts @@ -10,6 +10,13 @@ export interface BacktestRunConfiguration { slippage: number; dataFrequency: string; parameters: Record; + riskLimits?: { + maxPositionSize: number; + maxOrderSize: number; + maxDailyLoss: number; + maxGrossExposure: number; + maxSymbolExposure: number; + }; strategies?: { name: string; enabled: boolean; config?: Record }[]; } diff --git a/scripts/test/native-bindings.test.ts b/scripts/test/native-bindings.test.ts index 088f1730..5507a5d8 100644 --- a/scripts/test/native-bindings.test.ts +++ b/scripts/test/native-bindings.test.ts @@ -1,8 +1,64 @@ import { createRequire } from 'node:module'; import { describe, expect, it } from 'bun:test'; -import { BacktestEngine, IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine'; +import { + BacktestEngine, + IncrementalSMA, + TechnicalIndicators, + TradingEngine, +} from '@stock-bot/engine'; describe('generated native bindings', () => { + it('fill P&L is an incremental delta and native FIFO commissions are allocated once', () => { + const start = Date.parse('2024-01-01T00:00:00Z'); + const engine = new TradingEngine('backtest', { + startTime: start, + endTime: start + 86400000, + speedMultiplier: 0, + initialCapital: 10000, + }); + for (const [side, price, quantity, commission] of [ + ['buy', 100, 10, 1], + ['sell', 110, 4, 0.4], + ['sell', 90, 10, 1], + ['buy', 80, 4, 0.4], + ] as const) { + engine.processFillWithMetadata('A', price, quantity, side, commission, 'order', 'strategy'); + } + expect(engine.getTotalPnl()[0]).toBeCloseTo(17.2, 8); + expect(JSON.parse(engine.getRiskMetrics()).daily_pnl).toBeCloseTo(17.2, 8); + const trades = JSON.parse(engine.getClosedTrades()) as { commission: number; pnl: number }[]; + expect(trades.reduce((n, t) => n + t.commission, 0)).toBeCloseTo(2.8, 8); + expect(trades.reduce((n, t) => n + t.pnl, 0)).toBeCloseTo(17.2, 8); + engine.processFill('A', 100, 1, 'buy', 0.1); + expect(JSON.parse(engine.getRiskMetrics()).daily_pnl).toBeCloseTo(17.1, 8); + engine.advanceTime(start + 86400000); + engine.processFill('A', 100, 1, 'sell', 0.1); + expect(JSON.parse(engine.getRiskMetrics()).daily_pnl).toBeCloseTo(-0.1, 8); + }); + + it('native risk checks use configured projected notionals and reject invalid fills', () => { + const start = Date.parse('2024-01-01T00:00:00Z'); + const engine = new TradingEngine('backtest', { + startTime: start, + endTime: start + 86400000, + speedMultiplier: 0, + initialCapital: 10000, + }); + engine.updateRiskLimits({ + maxOrderSize: 100, + maxPositionSize: 100, + maxDailyLoss: 100, + maxGrossExposure: 1000, + maxSymbolExposure: 800, + }); + engine.updateQuote('A', 100, 100, 100, 100); + const result = JSON.parse( + engine.checkRisk({ id: 'id', symbol: 'A', side: 'buy', quantity: 9, orderType: 'market' }) + ); + expect(result.passed).toBe(false); + expect(result.checks.symbol_exposure).toBe(false); + expect(() => engine.processFill('A', NaN, 1, 'buy', 0)).toThrow('Invalid fill'); + }); it('ESM loads the generated artifact and exposes the documented constructor aliases', () => { const sma = new IncrementalSMA(2); sma.update(10); @@ -20,7 +76,9 @@ describe('generated native bindings', () => { const indicators = new TechnicalIndicators(); const prices = Array.from({ length: 80 }, (_, index) => 100 + index); const result = JSON.parse(indicators.calculateMacd(prices, 12, 26, 9)) as { - macd: number[]; signal: number[]; histogram: number[]; + macd: number[]; + signal: number[]; + histogram: number[]; }; const fast = indicators.calculateEma(prices, 12); const slow = indicators.calculateEma(prices, 26); @@ -33,9 +91,30 @@ describe('generated native bindings', () => { }); it('invalid SMA periods throw before entering the native event loop', () => { - const engine = new BacktestEngine({ name: 'validation', symbols: ['TEST'], startDate: '2023-01-01T00:00:00Z', endDate: '2023-02-01T00:00:00Z', initialCapital: 100000, commission: 0, slippage: 0, dataFrequency: '1d' }); - expect(() => engine.addTypescriptStrategy('unsupported', 'unsupported', {}, () => '{}')).toThrow('TypeScript strategy callbacks are not supported'); - expect(() => engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: 0, slowPeriod: 20 })).toThrow('SMA periods must satisfy'); - expect(() => engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: 20, slowPeriod: 10 })).toThrow('SMA periods must satisfy'); + const engine = new BacktestEngine({ + name: 'validation', + symbols: ['TEST'], + startDate: '2023-01-01T00:00:00Z', + endDate: '2023-02-01T00:00:00Z', + initialCapital: 100000, + commission: 0, + slippage: 0, + dataFrequency: '1d', + }); + expect(() => + engine.addTypescriptStrategy('unsupported', 'unsupported', {}, () => '{}') + ).toThrow('TypeScript strategy callbacks are not supported'); + expect(() => + engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { + fastPeriod: 0, + slowPeriod: 20, + }) + ).toThrow('SMA periods must satisfy'); + expect(() => + engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { + fastPeriod: 20, + slowPeriod: 10, + }) + ).toThrow('SMA periods must satisfy'); }); }); diff --git a/test/fixtures/execution.ts b/test/fixtures/execution.ts new file mode 100644 index 00000000..10707058 --- /dev/null +++ b/test/fixtures/execution.ts @@ -0,0 +1,55 @@ +import { TradingEngine } from '@stock-bot/engine'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository'; +import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; +import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; +import { + BacktestConfigSchema, + type MarketData, + type OrderRequest, +} from '../../apps/stock/orchestrator/src/types'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +export const logger = getLogger('execution-test'); +export const start = Date.parse('2024-01-01T00:00:00Z'); +export const config = BacktestConfigSchema.parse({ + mode: 'backtest', + strategy: 'sma-crossover', + symbols: ['A', 'B'], + startDate: new Date(start).toISOString(), + endDate: '2025-01-01T00:00:00Z', + initialCapital: 10000, + dataFrequency: '1d', + commission: 0.001, + slippage: 0, +}); +export function quote( + id: string, + price = 100, + size = 100, + timestamp = start, + symbol = 'A' +): MarketData { + return { + type: 'quote', + eventId: id, + data: { symbol, bid: price, ask: price, bidSize: size, askSize: size, timestamp }, + }; +} +export function order( + clientOrderId: string, + side: 'buy' | 'sell' = 'buy', + quantity = 10 +): OrderRequest { + return { symbol: 'A', side, quantity, orderType: 'market', timeInForce: 'DAY', clientOrderId }; +} +export function makeExecution(repository?: ExecutionRepository, clock = () => start) { + const engine = new TradingEngine('backtest', { + startTime: start, + endTime: Date.parse(config.endDate), + speedMultiplier: 0, + initialCapital: 10000, + }); + const execution = new ExecutionService({ logger }, {} as StorageService, { repository, clock }); + return { execution, engine }; +} diff --git a/test/integration/order-execution.test.ts b/test/integration/order-execution.test.ts new file mode 100644 index 00000000..736c666c --- /dev/null +++ b/test/integration/order-execution.test.ts @@ -0,0 +1,240 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { TradingEngine } from '@stock-bot/engine'; +import { createOrderRoutes } from '../../apps/stock/orchestrator/src/api/rest/orders'; +import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; +import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository'; +import type { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; +import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService'; +import { + BaseStrategy, + type Signal, +} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy'; +import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; +import type { MarketData, OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; +import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution'; + +const cleanup: (() => Promise)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) await close(); +}); +async function fixture() { + const runtime = makeExecution(); + await runtime.execution.initialize(config, runtime.engine); + cleanup.push(() => runtime.execution.shutdown()); + return runtime; +} +describe('one simulation execution gateway', () => { + test('identical client IDs return one order/fill; conflicting retries cannot mutate accounting', async () => { + const { execution } = await fixture(); + await execution.onMarketData(quote('q1')); + const reports = await Promise.all([ + execution.submitOrder(order('id')), + execution.submitOrder(order('id')), + ]); + expect(reports[0]).toEqual(reports[1]); + expect(reports[0]!.status).toBe('filled'); + expect((await execution.getPositions())[0]?.quantity).toBe(10); + await expect(execution.submitOrder(order('id', 'buy', 11))).rejects.toBeInstanceOf( + ExecutionConflictError + ); + expect((await execution.getAccount()).cash).toBe(8999); + }); + test('quote liquidity is consumed once; partial fills complete across distinct events only', async () => { + const { execution } = await fixture(); + await execution.onMarketData(quote('q1', 100, 3)); + const first = await execution.submitOrder(order('partial', 'buy', 10)); + expect(first.status).toBe('partiallyFilled'); + expect(first.fills[0]?.quantity).toBe(3); + expect(await execution.onMarketData(quote('q1', 100, 3))).toBe(false); + await execution.onMarketData(quote('q2', 100, 4, start + 1)); + expect((await execution.getOrderStatus(first.orderId))?.fills.map(f => f.quantity)).toEqual([ + 3, 4, + ]); + await execution.onMarketData(quote('q3', 100, 50, start + 2)); + const report = await execution.getOrderStatus(first.orderId); + expect(report?.status).toBe('filled'); + expect(report?.fills.map(f => f.quantity)).toEqual([3, 4, 3]); + expect((await execution.getAccount()).cash).toBe(8999); + expect((await execution.getPositions())[0]?.quantity).toBe(10); + }); + test('long/short partial closes and reversals conserve equity and charge commission exactly once', async () => { + const { execution, engine } = await fixture(); + for (const [i, side, price, quantity] of [ + [0, 'buy', 100, 10], + [1, 'sell', 110, 4], + [2, 'sell', 90, 10], + [3, 'buy', 80, 4], + ] as const) { + await execution.onMarketData(quote('q' + i, price, 100, start + i)); + await execution.submitOrder(order('o' + i, side, quantity)); + } + const account = await execution.getAccount(); + expect(account.cash).toBeCloseTo(10017.34, 8); + expect(account.equity).toBe(account.cash); + expect(account.realizedPnl).toBeCloseTo(17.34, 8); + expect(account.dailyPnl).toBe(account.realizedPnl); + expect(account.positions.A?.quantity).toBe(0); + expect(account.positions.A?.averagePrice).toBe(0); + const [native] = engine.getTotalPnl(); + expect(native).toBeCloseTo(account.realizedPnl, 8); + }); + test('pending reservations and projected notional enforce limits across symbols', async () => { + const { execution, engine } = await fixture(); + await execution.initialize( + { + ...config, + riskLimits: { + maxOrderSize: 100, + maxPositionSize: 100, + maxDailyLoss: 100, + maxSymbolExposure: 800, + maxGrossExposure: 1000, + }, + }, + engine + ); + await execution.onMarketData(quote('a', 100, 0)); + await execution.onMarketData(quote('b', 100, 0, start, 'B')); + expect((await execution.submitOrder(order('pending', 'buy', 6))).status).toBe('accepted'); + expect((await execution.submitOrder(order('over', 'buy', 3))).status).toBe('rejected'); + const other = { ...order('b', 'buy', 5), symbol: 'B' }; + expect((await execution.submitOrder(other)).status).toBe('rejected'); + expect(await execution.getPositions()).toHaveLength(0); + }); + test('IOC/FOK and limits have truthful states; cancellations cannot cancel an already filled order', async () => { + const { execution } = await fixture(); + await execution.onMarketData(quote('q', 100, 3)); + const fok = await execution.submitOrder({ ...order('fok'), timeInForce: 'FOK' }); + expect(fok.status).toBe('cancelled'); + expect(fok.fills).toHaveLength(0); + const ioc = await execution.submitOrder({ ...order('ioc'), timeInForce: 'IOC' }); + expect(ioc.status).toBe('cancelled'); + expect(ioc.fills[0]?.quantity).toBe(3); + const limit = await execution.submitOrder({ + ...order('limit', 'buy', 1), + orderType: 'limit', + limitPrice: 90, + }); + expect(limit.status).toBe('accepted'); + expect(await execution.cancelOrder(limit.orderId)).toBe(true); + await execution.onMarketData(quote('q2', 80, 100, start + 1)); + expect((await execution.getOrderStatus(limit.orderId))?.fills).toHaveLength(0); + const filled = await execution.submitOrder(order('filled', 'buy', 1)); + expect(await execution.cancelOrder(filled.orderId)).toBe(false); + }); + test('invalid/stale state cannot masquerade as acceptance and event conflicts roll back', async () => { + const { execution } = await fixture(); + expect((await execution.submitOrder(order('missing'))).status).toBe('rejected'); + await execution.onMarketData(quote('q')); + await expect(execution.onMarketData(quote('q', 101))).rejects.toBeInstanceOf( + ExecutionConflictError + ); + await expect( + execution.onMarketData(quote('older', 100, 100, start - 1)) + ).rejects.toBeInstanceOf(ExecutionConflictError); + const stop = await execution.submitOrder({ + ...order('stop'), + orderType: 'stop', + stopPrice: 100, + }); + expect(stop.status).toBe('rejected'); + expect(stop.rejectionReason).toContain('Unsupported'); + expect((await execution.getAccount()).cash).toBe(10000); + }); + test('HTTP requires an idempotency ID and returns conflict for mismatched reuse', async () => { + const { execution } = await fixture(); + await execution.onMarketData(quote('q')); + const routes = createOrderRoutes({ logger, custom: { ExecutionService: execution } }); + const send = (body: object) => + routes.request('/', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + const { clientOrderId: _, ...missing } = order('id'); + expect((await send(missing)).status).toBe(400); + expect((await send(order('id'))).status).toBe(201); + expect((await send(order('id', 'buy', 20))).status).toBe(409); + }); + test('unsupported live initialization cannot alter an existing simulation account', async () => { + const { execution, engine } = await fixture(); + const live = { + mode: 'live' as const, + broker: 'none', + accountId: 'none', + accountType: 'cash' as const, + riskLimits: { + maxOrderSize: 10, + maxPositionSize: 10, + maxDailyLoss: 10, + maxSymbolExposure: 100, + maxGrossExposure: 100, + }, + }; + await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled'); + expect((await execution.getAccount()).cash).toBe(10000); + const mode = new ModeManager({ logger }, {} as never, execution, {} as never); + await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled'); + expect(() => new TradingEngine('live', { broker: 'none', accountId: 'none' })).toThrow( + 'Live trading is disabled' + ); + expect(() => engine.submitOrder({ ...order('direct'), id: 'direct' })).toThrow( + 'execution gateway' + ); + }); + test('batch delivery is ordered, subscribed once, deduplicated, and routes every strategy order through risk', async () => { + const { execution } = await fixture(); + class Strategy extends BaseStrategy { + calls: number[] = []; + protected updateIndicators(data: MarketData) { + this.calls.push(data.data.timestamp); + } + protected async generateSignal(data: MarketData): Promise { + await new Promise(resolve => setTimeout(resolve, 5)); + return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } }; + } + protected async onStart() {} + protected async onStop() {} + protected onConfigUpdate() {} + } + const services: OrchestratorServices = { logger, custom: { ExecutionService: execution } }; + const market = new MarketDataService(services); + services.custom!.MarketDataService = market; + const manager = new StrategyManager(services); + services.custom!.StrategyManager = manager; + manager.setupEventListeners(); + manager.setupEventListeners(); + const strategy = new Strategy( + { + id: 'strategy', + name: 'fixture', + enabled: true, + parameters: {}, + symbols: ['A'], + allocation: 1, + }, + {} as ModeManager, + execution + ); + await strategy.initialize(); + await strategy.start(); + // Inject only the strategy fixture; market delivery, gateway, accounting, and native projection are real. + Object.defineProperty(manager, 'strategies', { value: new Map([['strategy', strategy]]) }); + Object.defineProperty(manager, 'activeStrategies', { value: new Set(['strategy']) }); + cleanup.push(() => manager.shutdown()); + const first = quote('1'); + const second = quote('2', 100, 100, start + 1); + market.emit('marketDataBatch', [first]); + market.emit('marketData', first); + market.emit('marketDataBatch', [first, second]); + await manager.drain(); + expect(strategy.calls).toEqual([start, start + 1]); + expect(strategy.getPosition('A')).toBe(2); + expect((await execution.getAccount()).strategyPositions.strategy?.A).toBe(2); + expect(market.listenerCount('marketDataBatch')).toBe(1); + market.ingest(quote('3', 100, 100, start + 2)); + await market.flush(); + expect(strategy.calls).toEqual([start, start + 1, start + 2]); + expect(strategy.getPosition('A')).toBe(3); + }); +}); diff --git a/test/postgres/order-execution.test.ts b/test/postgres/order-execution.test.ts new file mode 100644 index 00000000..b3619829 --- /dev/null +++ b/test/postgres/order-execution.test.ts @@ -0,0 +1,229 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository'; +import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository'; +import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution'; + +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const cleanup: (() => Promise)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) await close(); +}); +async function fixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) + throw new Error('Dedicated safety database required'); + const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', ''); + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + const sql = readFileSync( + new URL('../../database/postgres/init/11-simulation-execution-ledger.sql', import.meta.url), + 'utf8' + ); + await pool.query(sql); + await pool.query(sql); + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); + Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) }); + let now = start; + const make = async ( + limits = { + maxOrderSize: 100, + maxPositionSize: 100, + maxDailyLoss: 100, + maxGrossExposure: 10000, + maxSymbolExposure: 10000, + } + ) => { + const runtime = makeExecution(new PostgresExecutionRepository(postgres), () => now); + await runtime.execution.initialize( + { + mode: 'paper', + accountId: 'fixture', + startingCapital: config.initialCapital, + commission: 0.001, + slippage: 0, + maxQuoteAgeMs: 1000, + riskLimits: limits, + }, + runtime.engine + ); + cleanup.push(() => runtime.execution.shutdown()); + return runtime.execution; + }; + const execution = await make(); + return { + pool, + postgres, + execution, + make, + setTime(time: number) { + now = time; + }, + }; +} +describe.skipIf(!url)('paper execution ledger on real PostgreSQL', () => { + test('competing service instances deduplicate the same client ID, fill and account transaction', async () => { + const f = await fixture(); + const second = await f.make(); + await f.execution.onMarketData(quote('q')); + const reports = await Promise.all([ + f.execution.submitOrder(order('id')), + second.submitOrder(order('id')), + ]); + expect(reports[0]).toEqual(reports[1]); + expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1); + const fills = (await f.pool.query('SELECT payload FROM simulation_fills')).rows; + expect(fills).toHaveLength(1); + expect(fills[0].payload.pnl).toBe(-1); + expect((await second.getAccount()).cash).toBe(8999); + expect((await second.getPositions())[0]?.quantity).toBe(10); + await expect(second.submitOrder(order('id', 'buy', 11))).rejects.toBeInstanceOf( + ExecutionConflictError + ); + }); + test('a fill-write failure rolls back acceptance and cash/positions together; retry has no phantom fill', async () => { + const f = await fixture(); + await f.execution.onMarketData(quote('q')); + let events = 0; + f.execution.on('fill', () => events++); + await f.pool.query(`CREATE FUNCTION reject_fill() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN + RAISE EXCEPTION 'injected fill failure'; END $$; + CREATE TRIGGER reject_fill BEFORE INSERT ON simulation_fills FOR EACH ROW EXECUTE FUNCTION reject_fill();`); + await expect(f.execution.submitOrder(order('id'))).rejects.toThrow('injected fill failure'); + expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(0); + expect((await f.execution.getAccount()).cash).toBe(10000); + expect(events).toBe(0); + await f.pool.query('DROP TRIGGER reject_fill ON simulation_fills'); + expect((await f.execution.submitOrder(order('id'))).status).toBe('filled'); + expect(events).toBe(1); + }); + test('restart restores partial orders, consumed liquidity, cash and strategy positions without refilling duplicates', async () => { + const f = await fixture(); + await f.execution.onMarketData(quote('q1', 100, 3)); + const first = await f.execution.submitOrder(order('id'), { strategyId: 'strategy' }); + expect(first.status).toBe('partiallyFilled'); + await f.execution.shutdown(); + const second = await f.make(); + expect((await second.getStrategySnapshot('strategy')).positions.A).toBe(3); + expect((await second.getStrategySnapshot('strategy')).orders).toHaveLength(1); + expect(await second.onMarketData(quote('q1', 100, 3))).toBe(false); + f.setTime(start + 1); + await second.onMarketData(quote('q2', 100, 7, start + 1)); + expect((await second.getOrderStatus(first.orderId))?.status).toBe('filled'); + expect((await second.getAccount()).cash).toBe(8999); + expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(2); + }); + test('account locking serializes projected-risk reservations across producers', async () => { + const f = await fixture(); + const limits = { + maxOrderSize: 100, + maxPositionSize: 100, + maxDailyLoss: 100, + maxGrossExposure: 1000, + maxSymbolExposure: 1000, + }; + const first = await f.make(limits), + second = await f.make(limits); + await first.onMarketData(quote('q', 100, 0)); + const reports = await Promise.all([ + first.submitOrder(order('a', 'buy', 7)), + second.submitOrder(order('b', 'buy', 7)), + ]); + expect(reports.map(r => r.status).sort()).toEqual(['accepted', 'rejected']); + expect((await f.execution.getAccount()).cash).toBe(10000); + }); + test('duplicate and conflicting market IDs cannot reapply fills, even after a restart', async () => { + const f = await fixture(); + await f.execution.onMarketData(quote('q', 100, 3)); + const report = await f.execution.submitOrder(order('id')); + const second = await f.make(); + await expect(second.onMarketData(quote('q', 200, 3))).rejects.toBeInstanceOf( + ExecutionConflictError + ); + expect(await second.onMarketData(quote('q', 100, 3))).toBe(false); + expect((await second.getOrderStatus(report.orderId))?.fills).toHaveLength(1); + expect((await second.getAccount()).cash).toBe(9699.7); + }); + test('daily P&L uses deltas; loss limit blocks new risk but permits reduction and resets at UTC midnight', async () => { + const f = await fixture(); + const e = await f.make({ + maxOrderSize: 100, + maxPositionSize: 100, + maxDailyLoss: 1, + maxGrossExposure: 10000, + maxSymbolExposure: 10000, + }); + await e.onMarketData(quote('q')); + await e.submitOrder(order('open')); + expect((await e.submitOrder(order('blocked', 'buy', 1))).status).toBe('rejected'); + expect((await e.submitOrder(order('close', 'sell', 10))).status).toBe('filled'); + expect((await e.getAccount()).dailyPnl).toBe(-2); + f.setTime(start + 86400000); + await e.onMarketData(quote('new-day', 100, 100, start + 86400000)); + expect((await e.getAccount()).dailyPnl).toBe(0); + expect((await e.submitOrder(order('new-day-order', 'buy', 1))).status).toBe('filled'); + }); + test('stale quotes reject submission; day orders expire and unfilled cancellation survives restart', async () => { + const f = await fixture(); + await f.execution.onMarketData(quote('q', 100, 0)); + const day = await f.execution.submitOrder(order('day')); + const gtc = await f.execution.submitOrder({ ...order('gtc'), timeInForce: 'GTC' }); + f.setTime(start + 2000); + expect((await f.execution.submitOrder(order('stale'))).rejectionReason).toContain('stale'); + await expect(f.execution.onMarketData(quote('old', 100, 100, start + 1))).rejects.toThrow( + 'Stale' + ); + f.setTime(start + 86400000); + await f.execution.onMarketData(quote('next', 100, 0, start + 86400000)); + expect((await f.execution.getOrderStatus(day.orderId))?.status).toBe('cancelled'); + expect(await f.execution.cancelOrder(gtc.orderId)).toBe(true); + const second = await f.make(); + expect((await second.getOrderStatus(gtc.orderId))?.status).toBe('cancelled'); + }); + test('observer exceptions cannot change committed fills into reported failure or trigger another fill', async () => { + const f = await fixture(); + await f.execution.onMarketData(quote('q')); + f.execution.setObserver(async () => { + throw new Error('observer disconnected'); + }); + const report = await f.execution.submitOrder(order('id')); + expect(report.status).toBe('filled'); + expect((await f.execution.submitOrder(order('id'))).orderId).toBe(report.orderId); + expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1); + }); + + test('pending orders retain their accepted commission policy after account configuration changes', async () => { + const f = await fixture(); + await f.execution.onMarketData(quote('q1', 100, 3)); + const original = await f.execution.submitOrder(order('pending')); + const changed = makeExecution(new PostgresExecutionRepository(f.postgres), () => start + 1); + await changed.execution.initialize( + { + mode: 'paper', + accountId: 'fixture', + startingCapital: 10000, + commission: 0.01, + slippage: 0, + }, + changed.engine + ); + cleanup.push(() => changed.execution.shutdown()); + await changed.execution.onMarketData(quote('q2', 100, 10, start + 1)); + const report = await changed.execution.getOrderStatus(original.orderId); + expect(report?.fills.reduce((n, fill) => n + fill.commission, 0)).toBe(1); + const next = await changed.execution.submitOrder(order('new', 'buy', 1)); + expect(next.fills[0]?.commission).toBe(1); + }); +});