diff --git a/adaptive-strategy/src/execution/mod.rs b/adaptive-strategy/src/execution/mod.rs index 4fce8cca3..35e893abd 100644 --- a/adaptive-strategy/src/execution/mod.rs +++ b/adaptive-strategy/src/execution/mod.rs @@ -565,9 +565,8 @@ impl ExecutionEngine { crate::config::ExecutionAlgorithm::IS => "ImplementationShortfall", crate::config::ExecutionAlgorithm::ImplementationShortfall => "ImplementationShortfall", crate::config::ExecutionAlgorithm::ArrivalPrice => "TWAP", // Use TWAP as fallback - crate::config::ExecutionAlgorithm::POV => "VWAP", // Use VWAP for POV (Percentage of Volume) - }; }; - + crate::config::ExecutionAlgorithm::POV => "VWAP", // Use VWAP for POV (Percentage of Volume) + }; // Execute using selected algorithm let request_clone = request.clone(); let child_orders = if let Some(algorithm) = self.algorithms.get_mut(algorithm_name) { diff --git a/adaptive-strategy/src/models/tlob_model.rs b/adaptive-strategy/src/models/tlob_model.rs index af8ac7282..3eb203d48 100644 --- a/adaptive-strategy/src/models/tlob_model.rs +++ b/adaptive-strategy/src/models/tlob_model.rs @@ -24,12 +24,12 @@ use tracing::{debug, instrument, warn}; pub type FeatureVector = Vec; pub type TLOBFeatures = Vec; #[derive(Debug, Clone)] -pub struct TLOBConfig; - -impl Clone for TLOBConfig { - fn clone(&self) -> Self { - Self - } +pub struct TLOBConfig { + pub model_path: String, + pub feature_dim: usize, + pub prediction_horizon: usize, + pub batch_size: usize, + pub device: String, } pub struct TLOBTransformer; diff --git a/adaptive-strategy/src/regime/mod.rs b/adaptive-strategy/src/regime/mod.rs index b129af67e..74dc8626e 100644 --- a/adaptive-strategy/src/regime/mod.rs +++ b/adaptive-strategy/src/regime/mod.rs @@ -573,6 +573,9 @@ impl RegimeDetector { RegimeDetectionMethod::MLClassification => Ok(Box::new( MLClassifierRegimeDetector::new("default".to_string()).await?, )), + RegimeDetectionMethod::GMM => { + Ok(Box::new(GMMRegimeDetector::new(5)?)) // 5 components GMM + } } } diff --git a/adaptive-strategy/src/risk/mod.rs b/adaptive-strategy/src/risk/mod.rs index 500353581..17989395d 100644 --- a/adaptive-strategy/src/risk/mod.rs +++ b/adaptive-strategy/src/risk/mod.rs @@ -27,6 +27,7 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; use tracing::{debug, info, warn}; use num_traits::ToPrimitive; +use uuid::Uuid; // Add missing core types use crate::config::{PositionSizingMethod, RiskConfig}; @@ -479,14 +480,22 @@ impl RiskManager { pub async fn check_trade_risk(&self, symbol: &str, size: f64, price: f64) -> Result { // Create temporary position to test let test_position = Position { + id: uuid::Uuid::new_v4(), symbol: symbol.into(), - quantity: Quantity::from_f64(size).unwrap_or_default(), - avg_cost: Price::from_f64(price).unwrap_or_default(), - average_price: Price::from_f64(price).unwrap_or_default(), - realized_pnl: Decimal::ZERO, + quantity: rust_decimal::Decimal::from_f64(size).unwrap_or_else(|| rust_decimal::Decimal::ZERO), + avg_price: rust_decimal::Decimal::from_f64(price).unwrap_or_else(|| rust_decimal::Decimal::ZERO), + avg_cost: rust_decimal::Decimal::from_f64(price).unwrap_or_else(|| rust_decimal::Decimal::ZERO), + basis: rust_decimal::Decimal::from_f64(size * price).unwrap_or_else(|| rust_decimal::Decimal::ZERO), + average_price: rust_decimal::Decimal::from_f64(price).unwrap_or_else(|| rust_decimal::Decimal::ZERO), + market_value: rust_decimal::Decimal::from_f64(size * price).unwrap_or_else(|| rust_decimal::Decimal::ZERO), unrealized_pnl: Decimal::ZERO, - market_value: Price::from_f64(size * price).unwrap_or_default(), + realized_pnl: Decimal::ZERO, + created_at: chrono::Utc::now(), + updated_at: chrono::Utc::now(), last_updated: chrono::Utc::now(), + current_price: Some(rust_decimal::Decimal::from_f64(price).unwrap_or_else(|| rust_decimal::Decimal::ZERO)), + notional_value: rust_decimal::Decimal::from_f64(size * price).unwrap_or_else(|| rust_decimal::Decimal::ZERO), + margin_requirement: rust_decimal::Decimal::from_f64(size * price * 0.1).unwrap_or_else(|| rust_decimal::Decimal::ZERO), }; // Check against risk limits @@ -900,19 +909,18 @@ impl PositionSizer { PositionSizingMethod::FixedFraction => { self.calculate_fixed_fraction_size(symbol, price) } - PositionSizingMethod::Kelly => self.calculate_kelly_size(expected_return, confidence), - PositionSizingMethod::RiskParity => self.calculate_risk_parity_size(symbol), - PositionSizingMethod::VolatilityTarget => { - self.calculate_volatility_target_size(symbol, price) + PositionSizingMethod::FixedFractional(fraction) => { + self.calculate_fixed_fractional_size(*fraction, symbol, price) } + PositionSizingMethod::EqualWeight => { + self.calculate_equal_weight_size(symbol, price) + } + PositionSizingMethod::Kelly => self.calculate_kelly_size(expected_return, confidence), PositionSizingMethod::PPO => { // PPO position sizing is handled through the ppo_sizer // This is a fallback for when PPO sizer is not available self.calculate_fixed_fraction_size(symbol, price) } - PositionSizingMethod::Custom(method) => { - self.calculate_custom_size(method, symbol, expected_return, confidence, price) - } } } @@ -922,6 +930,19 @@ impl PositionSizer { Ok(1000.0) // Fixed size } + /// Fixed fractional position sizing + fn calculate_fixed_fractional_size(&self, fraction: f64, _symbol: &str, _price: f64) -> Result { + let portfolio_value = self.portfolio_monitor.get_portfolio_value(); + Ok(portfolio_value * fraction.clamp(0.0, 1.0)) + } + + /// Equal weight position sizing + fn calculate_equal_weight_size(&self, _symbol: &str, _price: f64) -> Result { + let portfolio_value = self.portfolio_monitor.get_portfolio_value(); + let position_count = self.portfolio_monitor.positions.len().max(1); + Ok(portfolio_value / position_count as f64) + } + /// Kelly criterion position sizing (enhanced version available via KellyPositionSizer) fn calculate_kelly_size(&self, expected_return: f64, confidence: f64) -> Result { if self.historical_returns.is_empty() { @@ -1048,7 +1069,7 @@ impl PortfolioRiskMonitor { /// Check if position violates limits pub fn check_position_limits(&self, position: &Position) -> Result { let portfolio_value = self.get_portfolio_value(); - let position_value = position.quantity.abs().to_f64() * position.average_price.to_f64(); + let position_value = position.quantity.abs().to_f64().unwrap_or(0.0) * position.average_price.to_f64().unwrap_or(0.0); let position_fraction = position_value / portfolio_value; Ok(position_fraction <= self.risk_limits.max_position_size) @@ -1067,7 +1088,7 @@ impl PortfolioRiskMonitor { let total_exposure: f64 = self .positions .values() - .map(|p| p.quantity.abs().to_f64() * p.average_price.to_f64()) + .map(|p| p.quantity.abs().to_f64().unwrap_or(0.0) * p.average_price.to_f64().unwrap_or(0.0)) .sum(); let leverage = total_exposure / portfolio_value; @@ -1089,7 +1110,7 @@ impl PortfolioRiskMonitor { let total_value: f64 = self .positions .values() - .map(|p| (p.quantity.abs().to_f64() * p.average_price.to_f64())) + .map(|p| (p.quantity.abs().to_f64().unwrap_or(0.0) * p.average_price.to_f64().unwrap_or(0.0))) .sum(); self.pnl_tracker.portfolio_value = total_value; @@ -1104,7 +1125,7 @@ impl PortfolioRiskMonitor { let total_exposure: f64 = self .positions .values() - .map(|p| p.quantity.abs().to_f64() * p.average_price.to_f64()) + .map(|p| p.quantity.abs().to_f64().unwrap_or(0.0) * p.average_price.to_f64().unwrap_or(0.0)) .sum(); if portfolio_value == 0.0 { @@ -1145,7 +1166,7 @@ impl PortfolioRiskMonitor { let max_position_value = self .positions .values() - .map(|p| (p.quantity.abs().to_f64() * p.average_price.to_f64()).abs()) + .map(|p| (p.quantity.abs().to_f64().unwrap_or(0.0) * p.average_price.to_f64().unwrap_or(0.0)).abs()) .fold(0.0f64, f64::max); Ok(max_position_value / portfolio_value) diff --git a/adaptive-strategy/src/risk/ppo_position_sizer.rs b/adaptive-strategy/src/risk/ppo_position_sizer.rs index be38d1de0..81dbc727b 100644 --- a/adaptive-strategy/src/risk/ppo_position_sizer.rs +++ b/adaptive-strategy/src/risk/ppo_position_sizer.rs @@ -46,6 +46,7 @@ pub struct ContinuousPPOConfig { pub state_dim: usize, pub action_dim: usize, pub learning_rate: f64, + pub policy_config: ContinuousPolicyConfig, } #[derive(Debug, Clone)] @@ -64,6 +65,28 @@ pub struct ContinuousPPO { config: ContinuousPPOConfig, } +impl ContinuousPPO { + pub fn new(config: ContinuousPPOConfig) -> Result { + Ok(Self { config }) + } + + pub fn act_with_log_prob(&self, _state: &[f32]) -> Result<(ContinuousAction, f32, f32), MLError> { + Ok((ContinuousAction { value: 0.5 }, 0.0, 0.0)) + } + + pub fn get_exploration_param(&self, _state: &[f32]) -> Result { + Ok(-1.0) // log std + } + + pub fn set_exploration_param(&mut self, _log_std: f32) -> Result<(), MLError> { + Ok(()) + } + + pub fn update(&mut self, _batch: &mut ContinuousTrajectoryBatch) -> Result<(f32, f32), MLError> { + Ok((0.1, 0.05)) // policy_loss, value_loss + } +} + #[derive(Debug, Clone)] pub struct ContinuousTrajectory { pub states: Vec>, @@ -74,11 +97,27 @@ pub struct ContinuousTrajectory { pub dones: Vec, } +impl ContinuousTrajectory { + pub fn len(&self) -> usize { + self.states.len() + } +} + +pub fn from_trajectories(trajectories: Vec) -> ContinuousTrajectoryBatch { + ContinuousTrajectoryBatch { trajectories } +} + #[derive(Debug, Clone)] pub struct ContinuousAction { pub value: f64, } +impl ContinuousAction { + pub fn position_size(&self) -> f64 { + self.value.clamp(0.0, 1.0) + } +} + #[derive(Debug, Clone)] pub struct ContinuousTrajectoryStep { pub state: Vec, @@ -94,6 +133,12 @@ pub struct ContinuousTrajectoryBatch { pub trajectories: Vec, } +impl ContinuousTrajectoryBatch { + pub fn from_trajectories(trajectories: Vec, _advantages: Vec, _returns: Vec) -> Self { + Self { trajectories } + } +} + // Stub for ML error type #[derive(Debug, thiserror::Error)] pub enum MLError { diff --git a/common/src/lib.rs b/common/src/lib.rs index d1be9bd4f..3c7f5ea37 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -40,9 +40,13 @@ pub use types::{ // Trading types Order, Position, Execution, OrderSide, OrderStatus, OrderType, TimeInForce, // ID types - OrderId, ExecutionId, Symbol, Currency, Exchange, + OrderId, ExecutionId, Symbol, Currency, Exchange, AssetId, // Additional types MarketTick, BrokerType, TradeEvent, QuoteEvent, + // Market data types + MarketDataEvent, BarEvent, OrderBookEvent, Level2Update, MarketStatus, + ConnectionEvent, ErrorEvent, Aggregate, DataType, Subscription, PriceLevel, ConnectionStatus, + MarketRegime, // Error types CommonTypeError, }; diff --git a/data/src/brokers/common.rs b/data/src/brokers/common.rs index 0aa2a007a..6d7c64d2e 100644 --- a/data/src/brokers/common.rs +++ b/data/src/brokers/common.rs @@ -276,14 +276,14 @@ mod tests { use super::*; use crate::types::*; use trading_engine::types::events::OrderEventType; - use common::types::dec; -use common::types::Decimal; -use common::types::OrderId; -use common::types::OrderSide; -use common::types::OrderStatus; -use common::types::OrderType; -use common::types::Quantity; -use common::types::Symbol; + use common::dec; +use common::Decimal; +use common::OrderId; +use common::OrderSide; +use common::OrderStatus; +use common::OrderType; +use common::Quantity; +use common::Symbol; #[test] diff --git a/data/src/brokers/interactive_brokers.rs b/data/src/brokers/interactive_brokers.rs index 3551dbe47..ad1e3c2e3 100644 --- a/data/src/brokers/interactive_brokers.rs +++ b/data/src/brokers/interactive_brokers.rs @@ -26,7 +26,7 @@ use tokio::sync::{Mutex, RwLock}; use tokio::time::timeout; use tracing::{debug, error, info, warn}; -// Import broker traits +// Import broker traits and types use crate::brokers::common::{BrokerClient, BrokerResult}; use trading_engine::trading::data_interface::{BrokerConnectionStatus, BrokerError, ExecutionReport}; use trading_engine::trading_operations::TradingOrder; @@ -36,8 +36,8 @@ use trading_engine::trading_operations::TradingOrder; use num_traits::ToPrimitive; // Import missing types from common crate -use common::types::{ - OrderSide, OrderType, OrderStatus, Symbol, Quantity, Price, HftTimestamp +use common::{ + OrderSide, OrderType, OrderStatus, Symbol, Quantity, Price, HftTimestamp, OrderId, Position, Order }; /// Interactive Brokers configuration diff --git a/data/src/brokers/mod.rs b/data/src/brokers/mod.rs index 163346e67..2253d4c63 100644 --- a/data/src/brokers/mod.rs +++ b/data/src/brokers/mod.rs @@ -10,14 +10,13 @@ pub mod common; pub mod interactive_brokers; // Re-export commonly used types -pub use common::types::BrokerClient; -use common::types::BrokerConfig; -use common::types::BrokerResult; +// Note: Using direct imports from common crate instead of broker-specific types pub use interactive_brokers::{IBConfig, InteractiveBrokersAdapter}; pub use trading_engine::trading::data_interface::BrokerError; // Create alias for BrokerAdapter (used in examples) -pub type BrokerAdapter = Box; +// TODO: Re-enable when BrokerClient trait is implemented +// pub type BrokerAdapter = Box; /// Supported broker types #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] diff --git a/data/src/error.rs b/data/src/error.rs index ef445b72e..75dfee9c9 100644 --- a/data/src/error.rs +++ b/data/src/error.rs @@ -165,7 +165,7 @@ pub enum DataError { /// Trading engine errors #[error("Trading engine error: {0}")] - TradingEngine(#[from] common::types::CommonTypeError), + TradingEngine(#[from] common::CommonTypeError), /// Configuration module errors #[error("Config error: {0}")] diff --git a/data/src/features.rs b/data/src/features.rs index 397aa6e28..2277e5431 100644 --- a/data/src/features.rs +++ b/data/src/features.rs @@ -14,6 +14,7 @@ use config::{ }; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap, VecDeque}; +use common::{OrderSide, PriceLevel}; /// Feature vector for ML model training #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/data/src/lib.rs b/data/src/lib.rs index 7a7db8b85..a491d1a6e 100644 --- a/data/src/lib.rs +++ b/data/src/lib.rs @@ -154,9 +154,10 @@ pub use error::{DataError, Result}; // === Broker Integration === // Note: Broker clients moved to trading_engine module in monolithic architecture pub use brokers::{ - BrokerClient, BrokerConfig, BrokerResult, BrokerAdapter, BrokerType, BrokerFactory, + BrokerType, BrokerFactory, InteractiveBrokersAdapter, IBConfig }; +pub use trading_engine::trading::data_interface::BrokerError; // === Data Providers === // Databento provider - only available when feature is enabled @@ -186,9 +187,12 @@ pub use crate::providers::common::{ // === Data Types === pub use crate::types::{ - MarketDataEvent, Subscription, TradeEvent, QuoteEvent, OrderBookEvent, - TimeRange, MarketDataType, Aggregate, Level2Update, - Position, Account, ConnectionEvent, ErrorEvent + MarketDataEvent, TimeRange, MarketDataType, + Position, Account +}; +pub use common::{ + Subscription, TradeEvent, QuoteEvent, OrderBookEvent, + Aggregate, Level2Update, ConnectionEvent, ErrorEvent }; // === Feature Engineering === diff --git a/data/src/parquet_persistence.rs b/data/src/parquet_persistence.rs index dee6560cb..9d7835bd6 100644 --- a/data/src/parquet_persistence.rs +++ b/data/src/parquet_persistence.rs @@ -236,12 +236,12 @@ impl ParquetMarketDataWriter { // Update metrics let duration_us: u64 = duration.as_micros().try_into().unwrap_or(0); if duration_us > 0 { - common::types::metrics::LATENCY_HISTOGRAMS + common::metrics::LATENCY_HISTOGRAMS .with_label_values(&["parquet_write", "data_service"]) .observe(duration_us as f64 / 1_000_000.0); } - common::types::metrics::THROUGHPUT_COUNTERS + common::metrics::THROUGHPUT_COUNTERS .with_label_values(&["parquet_events", "data_service"]) .inc_by(events_count as u64); diff --git a/data/src/providers/benzinga/integration.rs b/data/src/providers/benzinga/integration.rs index d006875bd..ca1964375 100644 --- a/data/src/providers/benzinga/integration.rs +++ b/data/src/providers/benzinga/integration.rs @@ -19,7 +19,7 @@ //! ```rust,no_run //! use data::providers::benzinga::integration::BenzingaHFTIntegration; //! use config::ConfigManager; -//! use common::types::Symbol; +//! use common::Symbol; //! //! # async fn example() -> anyhow::Result<()> { //! // Initialize with configuration @@ -66,7 +66,7 @@ use crate::providers::benzinga::{ use crate::providers::traits::RealTimeProvider; use config::{ConfigManager, TrainingBenzingaConfig, ConfigCategory}; use rust_decimal::Decimal; -use common::types::Symbol; +use common::Symbol; use tokio_stream::StreamExt; use tokio::sync::{mpsc, RwLock, Mutex}; use std::collections::{HashMap, VecDeque}; diff --git a/data/src/providers/benzinga/ml_integration.rs b/data/src/providers/benzinga/ml_integration.rs index 9e20c1e8d..3aeedd5a3 100644 --- a/data/src/providers/benzinga/ml_integration.rs +++ b/data/src/providers/benzinga/ml_integration.rs @@ -28,7 +28,7 @@ use std::sync::{ }; use tokio::sync::RwLock; use tracing::{debug, info, instrument}; -use common::types::Symbol; +use common::Symbol; /// Configuration for ML integration #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/data/src/providers/benzinga/mod.rs b/data/src/providers/benzinga/mod.rs index c2baaf5ef..fd63f0d35 100644 --- a/data/src/providers/benzinga/mod.rs +++ b/data/src/providers/benzinga/mod.rs @@ -28,7 +28,7 @@ //! ```rust,no_run //! use data::providers::benzinga::{ProductionBenzingaProvider, ProductionBenzingaConfig}; //! use data::providers::traits::RealTimeProvider; -//! use common::types::Symbol; +//! use common::Symbol; //! //! # async fn example() -> anyhow::Result<()> { //! let config = ProductionBenzingaConfig { @@ -107,7 +107,7 @@ //! use data::providers::benzinga::{BenzingaMLExtractor, BenzingaMLConfig}; //! use data::providers::common::MarketDataEvent; //! use chrono::Utc; -//! use common::types::Symbol; +//! use common::Symbol; //! //! # async fn example() -> anyhow::Result<()> { //! let config = BenzingaMLConfig { @@ -144,7 +144,7 @@ //! ```rust,no_run //! use data::providers::benzinga::{BenzingaHFTIntegration, BenzingaIntegrationConfig, TradingSignal, TradingSignalType}; //! use config::ConfigManager; -//! use common::types::Symbol; +//! use common::Symbol; //! use std::sync::Arc; //! //! # async fn example() -> anyhow::Result<()> { @@ -425,7 +425,7 @@ mod tests { #[tokio::test] async fn test_hft_integration_creation() { - use common::types::Symbol; + use common::Symbol; let config = BenzingaStreamingConfig { api_key: "test-key".to_string(), diff --git a/data/src/providers/benzinga/production_historical.rs b/data/src/providers/benzinga/production_historical.rs index 756744a0a..b0c65a7dd 100644 --- a/data/src/providers/benzinga/production_historical.rs +++ b/data/src/providers/benzinga/production_historical.rs @@ -36,8 +36,8 @@ use std::time::{Duration, Instant}; use tokio::sync::{RwLock, Semaphore}; use tracing::{debug, info, instrument, warn}; use rust_decimal::Decimal; -use common::types::Symbol; -use common::types::MarketDataEvent; +use common::Symbol; +use common::MarketDataEvent; use async_trait::async_trait; /// Production Benzinga historical provider configuration diff --git a/data/src/providers/benzinga/production_streaming.rs b/data/src/providers/benzinga/production_streaming.rs index ca6eeec95..10c79fe2a 100644 --- a/data/src/providers/benzinga/production_streaming.rs +++ b/data/src/providers/benzinga/production_streaming.rs @@ -16,7 +16,7 @@ use crate::providers::common::{ SentimentEvent, SentimentPeriod, UnusualOptionsEvent, UnusualOptionsType, }; use crate::types::ExtendedMarketDataEvent; -use common::types::MarketDataEvent; +use common::MarketDataEvent; use crate::providers::traits::{ ConnectionState as TraitConnectionState, ConnectionStatus, RealTimeProvider, }; @@ -45,7 +45,7 @@ use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; use tungstenite::Message; use tracing::{debug, error, info, instrument, warn}; use rust_decimal::Decimal; -use common::types::Symbol; +use common::Symbol; /// Production Benzinga streaming provider configuration #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/data/src/providers/benzinga/streaming.rs b/data/src/providers/benzinga/streaming.rs index 81dcb6e0e..0c4a0a5a1 100644 --- a/data/src/providers/benzinga/streaming.rs +++ b/data/src/providers/benzinga/streaming.rs @@ -18,7 +18,7 @@ //! ```rust,no_run //! use data::providers::benzinga::streaming::BenzingaStreamingProvider; //! use data::providers::traits::RealTimeProvider; -//! use common::types::Symbol; +//! use common::Symbol; //! //! # async fn example() -> anyhow::Result<()> { //! let config = BenzingaStreamingConfig { @@ -49,9 +49,9 @@ use crate::providers::traits::{ ConnectionState as TraitConnectionState, ConnectionStatus, RealTimeProvider, }; use crate::types::ExtendedMarketDataEvent; -use common::types::ConnectionStatus as EventConnectionStatus; -use common::types::MarketDataEvent; -use crate::types::ConnectionEvent; +use common::ConnectionStatus as EventConnectionStatus; +use common::MarketDataEvent; +use common::ConnectionEvent; use async_trait::async_trait; use chrono::{DateTime, Utc}; use futures_util::{SinkExt, StreamExt}; @@ -66,7 +66,7 @@ use std::pin::Pin; use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream}; use tracing::{debug, error, info, warn}; use rust_decimal::Decimal; -use common::types::Symbol; +use common::Symbol; /// Configuration for Benzinga streaming provider #[derive(Debug, Clone, Serialize, Deserialize)] @@ -592,7 +592,7 @@ impl BenzingaStreamingProvider { // Send error event if let Some(tx) = event_tx.lock().await.as_ref() { - let error_event = ExtendedMarketDataEvent::Core(MarketDataEvent::Error(common::types::ErrorEvent { + let error_event = ExtendedMarketDataEvent::Core(MarketDataEvent::Error(common::ErrorEvent { provider: "benzinga".to_string(), message: "Heartbeat timeout".to_string(), category: ErrorCategory::Connection, diff --git a/data/src/providers/common.rs b/data/src/providers/common.rs index 313c4732a..72ff314b6 100644 --- a/data/src/providers/common.rs +++ b/data/src/providers/common.rs @@ -14,9 +14,10 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; - -// Re-export the canonical MarketDataEvent and event types from types module -pub use crate::types::{MarketDataEvent, TradeEvent, QuoteEvent}; +use common::{Symbol, Decimal, Volume}; +// Re-export the canonical MarketDataEvent and event types +pub use crate::types::MarketDataEvent; +pub use common::{TradeEvent, QuoteEvent}; // Re-export ErrorCategory for provider modules pub use common::error::ErrorCategory; @@ -73,14 +74,14 @@ pub struct OrderBookUpdate { pub struct PriceLevelExt { /// Core price level data #[serde(flatten)] - pub inner: common::types::PriceLevel, + pub inner: common::PriceLevel, /// Number of orders at this price (MBO only) pub order_count: Option, } /// Type alias for backward compatibility during transition -#[deprecated(note = "Use PriceLevelExt for extended functionality or common::types::PriceLevel for core data")] +#[deprecated(note = "Use PriceLevelExt for extended functionality or common::PriceLevel for core data")] pub type PriceLevel = PriceLevelExt; /// Change to a price level diff --git a/data/src/providers/databento/client.rs b/data/src/providers/databento/client.rs index 6b317a2d4..4a31244cd 100644 --- a/data/src/providers/databento/client.rs +++ b/data/src/providers/databento/client.rs @@ -29,6 +29,8 @@ use crate::error::{DataError, Result}; use crate::providers::common::MarketDataEvent; use crate::providers::traits::{RealTimeProvider, HistoricalProvider, HistoricalSchema}; use crate::types::TimeRange; +use common::Symbol; +use chrono::{DateTime, Utc}; use super::{ types::*, websocket_client::{DatabentoWebSocketClient, WebSocketMetricsSnapshot}, @@ -55,6 +57,7 @@ use std::time::Duration; use serde_json; use tracing::{debug, info, warn, error, instrument}; + /// Unified Databento client for streaming and historical data pub struct DatabentoClient { /// Configuration diff --git a/data/src/providers/databento/dbn_parser.rs b/data/src/providers/databento/dbn_parser.rs index b485f4400..34d3e2a7e 100644 --- a/data/src/providers/databento/dbn_parser.rs +++ b/data/src/providers/databento/dbn_parser.rs @@ -20,15 +20,16 @@ //! - **Status Messages**: Market status and trading halts use crate::error::{DataError, Result}; -use common::types::Decimal; -use common::types::OrderSide; +use common::Decimal; +use common::OrderSide; +use common::Price; use trading_engine::{ lockfree::{LockFreeRingBuffer, HftMessage}, simd::{SafeSimdDispatcher, SimdMarketDataOps}, timing::HardwareTimestamp, types::prelude::*, events::{TradingEvent, EventProcessor}, - prelude::SystemEventType, + events::SystemEventType, }; use serde::{Deserialize, Serialize}; use std::sync::{Arc, atomic::{AtomicU64, Ordering}}; diff --git a/data/src/providers/databento/mod.rs b/data/src/providers/databento/mod.rs index 47dc6756c..1461b29ba 100644 --- a/data/src/providers/databento/mod.rs +++ b/data/src/providers/databento/mod.rs @@ -113,12 +113,13 @@ pub use self::{ // Re-export from parent modules for convenience pub use crate::providers::{ traits::{RealTimeProvider, HistoricalProvider, HistoricalSchema, ConnectionStatus, ConnectionState}, - common::{self, MarketDataEvent}, + common::MarketDataEvent, }; // Import dependencies use crate::error::{DataError, Result}; use crate::types::TimeRange; +use common::types::{Symbol, TradeEvent, QuoteEvent, Decimal}; use trading_engine::{ types::prelude::*, events::EventProcessor, @@ -128,7 +129,7 @@ use tokio_stream::Stream; use std::pin::Pin; use std::sync::Arc; use tracing::{info, warn, error, debug}; - +use chrono::Utc; /// Production-ready Databento streaming provider /// /// Implements the RealTimeProvider trait with enterprise-grade features: diff --git a/data/src/providers/databento/parser.rs b/data/src/providers/databento/parser.rs index c457c855d..a52ddc0ce 100644 --- a/data/src/providers/databento/parser.rs +++ b/data/src/providers/databento/parser.rs @@ -28,8 +28,8 @@ use crate::error::{DataError, Result}; use crate::providers::common::MarketDataEvent; -use common::types::{Level2Update, PriceLevel}; -use common::types::Decimal; +use common::{Level2Update, PriceLevel}; +use common::Decimal; use super::{ types::*, dbn_parser::{DbnParser, ProcessedMessage, DbnParserMetricsSnapshot}, diff --git a/data/src/providers/databento/types.rs b/data/src/providers/databento/types.rs index 0890701d6..718f4195a 100644 --- a/data/src/providers/databento/types.rs +++ b/data/src/providers/databento/types.rs @@ -21,6 +21,7 @@ use serde::{Deserialize, Serialize}; use std::fmt; use std::time::Duration; use chrono::{DateTime, Utc}; +use common::Symbol; /// Primary configuration for Databento integration #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/data/src/providers/databento_old.rs b/data/src/providers/databento_old.rs index 4b41623e2..51cf15cd2 100644 --- a/data/src/providers/databento_old.rs +++ b/data/src/providers/databento_old.rs @@ -4,8 +4,9 @@ //! Provides access to normalized, exchange-quality market data with nanosecond timestamps. use crate::error::{DataError, Result}; -use common::types::BarEvent; -use crate::types::{MarketDataEvent, QuoteEvent, TradeEvent}; +use common::{BarEvent, Decimal, OrderSide}; +use crate::types::MarketDataEvent; +use common::types::{QuoteEvent, TradeEvent}; use chrono::{DateTime, Utc}; use reqwest::Client; use serde::{Deserialize, Serialize}; diff --git a/data/src/providers/databento_streaming.rs b/data/src/providers/databento_streaming.rs index 4a41c620c..603747096 100644 --- a/data/src/providers/databento_streaming.rs +++ b/data/src/providers/databento_streaming.rs @@ -15,13 +15,13 @@ use tokio::sync::broadcast; use tokio_tungstenite::{connect_async, tungstenite::Message}; use tracing::{debug, error, info, warn}; use trading_engine::trading::data_interface::MarketDataEvent as CoreMarketDataEvent; -use common::types::OrderBookEvent; -use common::types::QuoteEvent; -use common::types::TradeEvent; -use common::types::Price; -use common::types::Quantity; -use common::types::Symbol; -use common::types::Decimal; +use common::OrderBookEvent; +use common::QuoteEvent; +use common::TradeEvent; +use common::Price; +use common::Quantity; +use common::Symbol; +use common::Decimal; use url::Url; /// Databento WebSocket client for real-time market data diff --git a/data/src/providers/mod.rs b/data/src/providers/mod.rs index 1168334eb..b84796c5d 100644 --- a/data/src/providers/mod.rs +++ b/data/src/providers/mod.rs @@ -42,7 +42,7 @@ mod databento_old; pub mod databento_streaming; // Re-export the new traits and common types -pub use common::types::MarketDataEvent; +pub use common::MarketDataEvent; pub use traits::{ ConnectionState, ConnectionStatus, HistoricalProvider, HistoricalSchema, RealTimeProvider, }; @@ -52,7 +52,7 @@ use crate::types::TimeRange; use async_trait::async_trait; use serde::{Deserialize, Serialize}; use tokio::sync::mpsc; -// use common::types::Symbol; +// use common::Symbol; /// Configuration for market data providers #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/data/src/providers/traits.rs b/data/src/providers/traits.rs index 6537a67d3..8d82d2aa2 100644 --- a/data/src/providers/traits.rs +++ b/data/src/providers/traits.rs @@ -23,7 +23,7 @@ use serde::{Deserialize, Serialize}; use std::time::Duration; use futures_core::Stream; use std::pin::Pin; -use common::types::Symbol; +use common::Symbol; /// Real-time streaming data provider trait for WebSocket/TCP feeds /// @@ -34,7 +34,7 @@ use common::types::Symbol; /// /// ```no_run /// # use async_trait::async_trait; -/// # use common::types::Symbol; +/// # use common::Symbol; /// # use tokio_stream::Stream; /// # struct MyProvider; /// # impl MyProvider { @@ -148,7 +148,7 @@ pub trait RealTimeProvider: Send + Sync { /// /// ```no_run /// # use chrono::{DateTime, Utc}; -/// # use common::types::Symbol; +/// # use common::Symbol; /// # struct MyHistoricalProvider; /// # impl MyHistoricalProvider { /// # async fn fetch(&self, symbol: &Symbol, schema: HistoricalSchema, range: TimeRange) -> Result, Box> { Ok(vec![]) } diff --git a/data/src/training_pipeline.rs b/data/src/training_pipeline.rs index 179f01c40..dbb1ca962 100644 --- a/data/src/training_pipeline.rs +++ b/data/src/training_pipeline.rs @@ -16,11 +16,13 @@ use crate::error::Result; // REMOVED: Polygon imports - replaced with Databento use chrono::{DateTime, Utc}; +use common::PriceLevel; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::sync::Arc; use tokio::sync::RwLock; use tracing::info; +use common::{Decimal, OrderSide}; // Import shared training configuration from common crate use config::{ diff --git a/data/src/types.rs b/data/src/types.rs index 5b24222f3..54955503b 100644 --- a/data/src/types.rs +++ b/data/src/types.rs @@ -1,6 +1,7 @@ //! Data types for market data and broker integration use serde::{Deserialize, Serialize}; +use rust_decimal::Decimal; /// Time range for historical data queries #[derive(Debug, Clone, Copy, Serialize, Deserialize)] @@ -27,7 +28,7 @@ pub enum MarketDataType { } // Use canonical MarketDataEvent from common crate -pub use common::types::MarketDataEvent; +pub use common::MarketDataEvent; /// Extended market data event types with provider-specific events #[derive(Debug, Clone, Serialize, Deserialize)] @@ -45,19 +46,19 @@ pub enum ExtendedMarketDataEvent { } // Use canonical event types from common crate -pub use common::types::QuoteEvent; -use common::types::TradeEvent; -use common::types::Aggregate; -use common::types::BarEvent; -use common::types::Level2Update; -use common::types::MarketStatus; -use common::types::ConnectionEvent; -use common::types::ErrorEvent; -use common::types::OrderBookEvent; -use common::types::DataType; -use common::types::Subscription; -use common::types::PriceLevel; -use common::types::ConnectionStatus; +pub use common::QuoteEvent; +use common::TradeEvent; +use common::Aggregate; +use common::BarEvent; +use common::Level2Update; +use common::MarketStatus; +use common::ConnectionEvent; +use common::ErrorEvent; +use common::OrderBookEvent; +use common::DataType; +use common::Subscription; +use common::PriceLevel; +use common::ConnectionStatus; use common::error::ErrorCategory; /// Quote data structure (legacy compatibility) #[derive(Debug, Clone, Serialize, Deserialize)] @@ -96,7 +97,7 @@ pub struct Trade { pub timestamp: chrono::DateTime, } -// Aggregate moved to common::types::Aggregate +// Aggregate moved to common::Aggregate // Level2Update, PriceLevel, and MarketStatus moved to common::types @@ -105,10 +106,10 @@ pub struct Trade { // ConnectionEvent, ConnectionStatus, and ErrorEvent moved to common::types // OrderEvent is imported from common::prelude as part of the canonical event system -// See: common::types::events::OrderEvent +// See: common::events::OrderEvent // OrderStatus is imported from common::prelude as part of the canonical type system -// See: common::types::basic::OrderStatus +// See: common::basic::OrderStatus /// Position information #[derive(Debug, Clone, Serialize, Deserialize)] @@ -217,7 +218,7 @@ pub fn get_event_timestamp(event: &MarketDataEvent) -> Option for MLError { // UNIFIED ERROR HANDLING: Convert all ML errors to CommonError for workspace consistency impl From for CommonError { fn from(err: MLError) -> Self { - use common::error::{CommonError, ErrorCategory}; match err { MLError::ConfigError { reason } => CommonError::config( format!("ML configuration error: {}", reason) @@ -319,8 +321,8 @@ impl From for CommonError { } // Convert common type errors to MLError (for backward compatibility) -impl From for MLError { - fn from(err: common::types::CommonTypeError) -> Self { +impl From for MLError { + fn from(err: CommonTypeError) -> Self { MLError::ModelError(format!("Common type error: {}", err)) } } diff --git a/ml/src/liquid/mod.rs b/ml/src/liquid/mod.rs index 664fe6c9d..a15b11ce8 100644 --- a/ml/src/liquid/mod.rs +++ b/ml/src/liquid/mod.rs @@ -155,7 +155,7 @@ pub enum NetworkType { Mixed, // Combination of LTC and CfC layers } -// REMOVED: MarketRegime enum - now using common::types::MarketRegime instead +// REMOVED: MarketRegime enum - now using common::MarketRegime instead // This eliminates the type conflict and ensures consistency across the entire system /// Performance metrics for liquid networks diff --git a/ml/src/microstructure/roll_spread.rs b/ml/src/microstructure/roll_spread.rs index 4a7c815d0..f7d08136f 100644 --- a/ml/src/microstructure/roll_spread.rs +++ b/ml/src/microstructure/roll_spread.rs @@ -21,7 +21,7 @@ use std::collections::VecDeque; use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; use serde::{Deserialize, Serialize}; -use common::types::Price; +use common::Price; use super::*; use super::{ diff --git a/ml/src/risk/circuit_breakers.rs b/ml/src/risk/circuit_breakers.rs index 0473ead54..930e63013 100644 --- a/ml/src/risk/circuit_breakers.rs +++ b/ml/src/risk/circuit_breakers.rs @@ -8,6 +8,7 @@ use std::collections::{HashMap, VecDeque}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; +use common::{Price, Volume}; use crate::{MLError, MLResult as Result}; diff --git a/ml/src/risk/graph_risk_model.rs b/ml/src/risk/graph_risk_model.rs index cb09c5fe2..0f7716ecf 100644 --- a/ml/src/risk/graph_risk_model.rs +++ b/ml/src/risk/graph_risk_model.rs @@ -16,6 +16,7 @@ use std::collections::HashMap; use chrono::{DateTime, Utc}; use ndarray::{Array1, Array2, Array3}; use serde::{Deserialize, Serialize}; +use common::AssetId; use crate::MLResult; diff --git a/ml/src/risk/kelly_optimizer.rs b/ml/src/risk/kelly_optimizer.rs index 1e1791fa7..ae114736d 100644 --- a/ml/src/risk/kelly_optimizer.rs +++ b/ml/src/risk/kelly_optimizer.rs @@ -5,6 +5,7 @@ use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; +use common::Price; use crate::{MLError, MLResult as Result}; diff --git a/ml/src/risk/monitor.rs b/ml/src/risk/monitor.rs index a9d76a15c..18bba2398 100644 --- a/ml/src/risk/monitor.rs +++ b/ml/src/risk/monitor.rs @@ -37,7 +37,7 @@ impl Default for MonitorConfig { } // NO DUPLICATES - SINGLE TYPE SYSTEM -pub use common::types::Position; +pub use common::Position; /// Exposure metrics #[derive(Debug, Clone)] diff --git a/ml/src/stress_testing/market_simulator.rs b/ml/src/stress_testing/market_simulator.rs index 6ab8d29c5..686ba755b 100644 --- a/ml/src/stress_testing/market_simulator.rs +++ b/ml/src/stress_testing/market_simulator.rs @@ -1,7 +1,7 @@ //! Realistic market data simulation for stress testing -use common::types::Price; -use common::types::Decimal; +use common::Price; +use common::Decimal; use anyhow::Result; use rand::prelude::*; diff --git a/ml/src/stress_testing/mod.rs b/ml/src/stress_testing/mod.rs index 14cdab083..10d0f91df 100644 --- a/ml/src/stress_testing/mod.rs +++ b/ml/src/stress_testing/mod.rs @@ -13,8 +13,8 @@ use serde::{Deserialize, Serialize}; use std::time::{Duration, Instant}; use tokio::sync::mpsc; -use common::types::Price; -use common::types::Decimal; +use common::Price; +use common::Decimal; use rust_decimal::prelude::ToPrimitive; use crate::{Features, MLModel, ModelPrediction, ModelType}; diff --git a/ml/src/tft/hft_optimizations.rs b/ml/src/tft/hft_optimizations.rs index 91b1841c5..95c4dde5d 100644 --- a/ml/src/tft/hft_optimizations.rs +++ b/ml/src/tft/hft_optimizations.rs @@ -27,7 +27,7 @@ use tracing::{info, instrument, warn}; use super::TemporalFusionTransformer; use crate::MLError; -use common::types::Price; // Import Price for financial predictions +use common::Price; // Import Price for financial predictions use crate::liquid::FixedPoint; // Import FixedPoint for financial precision /// HFT-specific configuration for ultra-low latency inference diff --git a/ml/src/training/unified_data_loader.rs b/ml/src/training/unified_data_loader.rs index ab090a90b..03e87b03b 100644 --- a/ml/src/training/unified_data_loader.rs +++ b/ml/src/training/unified_data_loader.rs @@ -26,9 +26,9 @@ pub struct OrderLevel { pub quantity: f64, } use crate::{MLError, MLResult}; -use common::types::Price; -use common::types::Symbol; -use common::types::Volume; +use common::Price; +use common::Symbol; +use common::Volume; /// Configuration for the unified data loader #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/ml/src/transformers/features.rs b/ml/src/transformers/features.rs index b2c1ceac8..2e65a1b41 100644 --- a/ml/src/transformers/features.rs +++ b/ml/src/transformers/features.rs @@ -25,8 +25,8 @@ use candle_core::{Device, Result as CandleResult, Tensor}; use chrono::Utc; use chrono::{DateTime, Datelike, Timelike, Utc}; use serde::{Deserialize, Serialize}; -use common::types::Quantity; -use common::types::Symbol; +use common::Quantity; +use common::Symbol; use super::*; // use crate::safe_operations; // DISABLED - module not found diff --git a/ml/src/transformers/temporal_fusion.rs b/ml/src/transformers/temporal_fusion.rs index 51e6e7f11..6fc9abdd8 100644 --- a/ml/src/transformers/temporal_fusion.rs +++ b/ml/src/transformers/temporal_fusion.rs @@ -16,10 +16,10 @@ use candle_core::Device; use candle_core::{Device, Tensor, Result as CandleResult}; use candle_nn::{Linear, LayerNorm, VarBuilder, Activation}; use serde::{Serialize, Deserialize}; -use common::types::MLModelMetadata; -use common::types::MLModelType; -use common::types::TensorSpec; -use common::types::TensorDType; +use common::MLModelMetadata; +use common::MLModelType; +use common::TensorSpec; +use common::TensorDType; use super::*; // use crate::safe_operations; // DISABLED - module not found diff --git a/risk/src/circuit_breaker.rs b/risk/src/circuit_breaker.rs index 1988109ab..3f05b8b82 100644 --- a/risk/src/circuit_breaker.rs +++ b/risk/src/circuit_breaker.rs @@ -18,6 +18,7 @@ use std::sync::{ use async_trait::async_trait; use chrono::{DateTime, Utc}; use redis::{AsyncCommands, RedisResult}; +use common::types::{Position, Symbol, Price, Decimal, Quantity}; // REMOVED: Direct Decimal usage - use canonical types use serde::{Deserialize, Serialize}; use tokio::sync::RwLock; diff --git a/risk/src/compliance.rs b/risk/src/compliance.rs index 17f552904..8c41d4e46 100644 --- a/risk/src/compliance.rs +++ b/risk/src/compliance.rs @@ -14,6 +14,7 @@ use serde::{Deserialize, Serialize}; use tokio::sync::{broadcast, RwLock}; use tracing::{error, info, warn}; use uuid::Uuid; +use common::types::{Price, Decimal, Symbol}; // Removed config module - not available in this simplified risk crate use crate::error::{decimal_to_f64_safe, f64_to_price_safe, parse_env_var, RiskError, RiskResult}; diff --git a/risk/src/lib.rs b/risk/src/lib.rs index 8963462df..2861af68e 100644 --- a/risk/src/lib.rs +++ b/risk/src/lib.rs @@ -344,6 +344,8 @@ pub fn validate_risk_config(config: &SafetyConfig) -> Result<(), String> { Ok(()) } +use common::types::Price; + /// Get default configuration for development/testing #[must_use] pub fn development_config() -> SafetyConfig { diff --git a/risk/src/risk_engine.rs b/risk/src/risk_engine.rs index d732f6dde..61b4d76e5 100644 --- a/risk/src/risk_engine.rs +++ b/risk/src/risk_engine.rs @@ -19,7 +19,7 @@ use uuid::Uuid; use std::marker::Send; use std::sync::Arc; use crate::prelude::*; -use common::types::Position; +use common::types::{Position, Symbol, Price, Decimal, OrderSide}; use std::time::Instant; use tokio::sync::broadcast; use tracing::{debug, info, warn}; diff --git a/risk/src/safety/mod.rs b/risk/src/safety/mod.rs index 111d2e54d..9995ffc5f 100644 --- a/risk/src/safety/mod.rs +++ b/risk/src/safety/mod.rs @@ -38,6 +38,7 @@ use std::time::Duration; // Removed foxhunt_infrastructure - not available in this simplified risk crate use serde::{Deserialize, Serialize}; +use common::types::Price; // CANONICAL TYPE IMPORTS - ENFORCED BY TYPE SYSTEM AGENT /// Safety system configuration diff --git a/risk/src/safety/safety_coordinator.rs b/risk/src/safety/safety_coordinator.rs index ac2af217c..a5cb941f6 100644 --- a/risk/src/safety/safety_coordinator.rs +++ b/risk/src/safety/safety_coordinator.rs @@ -14,6 +14,7 @@ use std::sync::Arc; use redis::aio::Connection; // REMOVED: Direct Decimal usage - use canonical types +use common::types::{Price, Decimal, Position, Symbol}; use serde::{Deserialize, Serialize}; use tokio::sync::{broadcast, RwLock}; use tracing::{debug, error, info, warn}; diff --git a/risk/src/stress_tester.rs b/risk/src/stress_tester.rs index 4764373cf..e272c04fa 100644 --- a/risk/src/stress_tester.rs +++ b/risk/src/stress_tester.rs @@ -14,7 +14,7 @@ use tracing::{debug, info, warn}; use crate::error::{RiskError, RiskResult}; use crate::risk_types::{InstrumentId, StressScenario, StressTestResult}; -use common::types::{Position, Symbol}; +use common::types::{Position, Symbol, Price, Decimal}; // CANONICAL TYPE IMPORTS - All types from core /// Stress testing engine for portfolio risk analysis diff --git a/risk/src/var_calculator/expected_shortfall.rs b/risk/src/var_calculator/expected_shortfall.rs index b3fed36fd..37538246d 100644 --- a/risk/src/var_calculator/expected_shortfall.rs +++ b/risk/src/var_calculator/expected_shortfall.rs @@ -5,6 +5,7 @@ use std::collections::HashMap; // REMOVED: Direct Decimal usage - use canonical types use anyhow::Result; use tracing::warn; +use common::types::{Price, Decimal, Symbol}; // Removed types::operations - using common::types::prelude instead diff --git a/risk/src/var_calculator/historical_simulation.rs b/risk/src/var_calculator/historical_simulation.rs index 6d7345fc5..b93b119f1 100644 --- a/risk/src/var_calculator/historical_simulation.rs +++ b/risk/src/var_calculator/historical_simulation.rs @@ -6,6 +6,7 @@ use crate::error::{RiskError, RiskResult}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use common::types::{Price, Decimal, Symbol}; // Removed broker_integration - not available in this simplified risk crate use crate::var_calculator::var_engine::{HistoricalPrice, PositionInfo}; diff --git a/risk/src/var_calculator/monte_carlo.rs b/risk/src/var_calculator/monte_carlo.rs index bfa255dd7..23c201884 100644 --- a/risk/src/var_calculator/monte_carlo.rs +++ b/risk/src/var_calculator/monte_carlo.rs @@ -8,6 +8,7 @@ use num::{FromPrimitive, ToPrimitive}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use tracing::warn; +use common::types::{Price, Decimal, Symbol}; // Removed broker_integration - not available in this simplified risk crate use crate::var_calculator::var_engine::{HistoricalPrice, PositionInfo}; // CANONICAL TYPE IMPORTS - ENFORCED BY TYPE SYSTEM AGENT diff --git a/risk/src/var_calculator/parametric.rs b/risk/src/var_calculator/parametric.rs index bcc9d043a..639ae0bd6 100644 --- a/risk/src/var_calculator/parametric.rs +++ b/risk/src/var_calculator/parametric.rs @@ -2,11 +2,11 @@ //! Production implementation for risk management use std::collections::HashMap; -// REMOVED: Direct Decimal usage - use canonical types use anyhow::Result; use nalgebra::{DMatrix, DVector}; use num::FromPrimitive; - +use common::types::Price; +use common::Decimal; /// Parametric `VaR` calculator using variance-covariance method #[derive(Debug)] pub struct ParametricVaR { @@ -193,7 +193,7 @@ impl ParametricVaR { let component_var = weight_i * marginal_var * z_score * portfolio_value_f64; component_vars - .push(Decimal::from_f64_retain(component_var.abs()).unwrap_or(Decimal::ZERO)); + .push(Price::from_f64(component_var.abs()).unwrap_or(Price::ZERO)); } Ok(component_vars.into_iter().map(Into::into).collect()) diff --git a/risk/src/var_calculator/var_engine.rs b/risk/src/var_calculator/var_engine.rs index 15cebb9d9..143d1d748 100644 --- a/risk/src/var_calculator/var_engine.rs +++ b/risk/src/var_calculator/var_engine.rs @@ -13,6 +13,8 @@ use num::{FromPrimitive, ToPrimitive}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use tracing::error; +use common::types::{Price, Quantity, Symbol}; +use common::Decimal; // Removed broker_integration - types not available in simplified risk crate // Define minimal replacements for compilation diff --git a/tli/src/dashboard/trading.rs b/tli/src/dashboard/trading.rs index 5a7c862e1..93347d75b 100644 --- a/tli/src/dashboard/trading.rs +++ b/tli/src/dashboard/trading.rs @@ -13,7 +13,7 @@ use crate::dashboard::events::{ }; use common::types::Order as OrderRequest; use common::types::OrderType; -use common::types::Side as OrderSide; +use common::types::OrderSide; use common::types::Symbol; use common::types::Quantity; use common::types::TimeInForce;