Skip to main content

qualia_core_db/specialized_libs/financial_modeling/
trading.rs

1use super::*;
2
3/// Trading engine
4pub struct TradingEngine {
5    order_manager: OrderManager,
6    execution_engine: ExecutionEngine,
7    position_manager: PositionManager,
8}
9
10/// Position manager
11pub struct PositionManager {
12    positions: HashMap<String, Position>,
13    position_limits: HashMap<String, PositionLimit>,
14    margin_calculator: MarginCalculator,
15}
16
17/// Positions
18#[derive(Debug, Clone)]
19pub struct Position {
20    pub position_id: String,
21    pub portfolio_id: String,
22    pub asset_id: String,
23    pub quantity: f64,
24    pub average_cost: f64,
25    pub market_value: f64,
26    pub unrealized_pnl: f64,
27    pub realized_pnl: f64,
28    pub last_updated: u64,
29}
30
31/// Position limits
32#[derive(Debug, Clone)]
33pub struct PositionLimit {
34    pub limit_id: String,
35    pub asset_id: String,
36    pub max_position: f64,
37    pub min_position: f64,
38    pub warning_threshold: f64,
39}
40
41/// Margin calculator
42pub struct MarginCalculator {
43    margin_methods: HashMap<String, MarginMethod>,
44    margin_requirements: MarginRequirements,
45}
46
47/// Margin methods
48#[derive(Debug, Clone)]
49pub struct MarginMethod {
50    pub method_id: String,
51    pub method_type: MarginMethodType,
52    pub parameters: MarginMethodParameters,
53}
54
55/// Margin method types
56#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
57pub enum MarginMethodType {
58    SPAN,
59    TIMS,
60    PortfolioMargin,
61    RegT,
62}
63
64/// Margin method parameters
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct MarginMethodParameters {
67    pub volatility_multiplier: f64,
68    pub concentration_factor: f64,
69    pub stress_period: u32,
70}
71
72impl TradingEngine {
73    /// Creates a `TradingEngine` with empty registries / default configuration.
74    pub fn new() -> Self {
75        Self {
76            order_manager: OrderManager::new(),
77            execution_engine: ExecutionEngine::new(),
78            position_manager: PositionManager::new(),
79        }
80    }
81
82    /// Readies the `TradingEngine` sub-components; registers/populates any built-in defaults.
83    pub fn initialize(&mut self) -> Result<(), FinancialError> {
84        self.order_manager.initialize()?;
85        self.execution_engine.initialize()?;
86        Ok(())
87    }
88
89    /// Validates order quantity (must be positive) and price (positive when
90    /// present); errors with `ValidationError` on violations.
91    pub fn validate_order(&self, order: &Order) -> Result<(), FinancialError> {
92        if order.quantity <= 0.0 {
93            return Err(FinancialError::ValidationError(
94                "Order quantity must be positive".to_string(),
95            ));
96        }
97        if let Some(price) = order.price {
98            if price <= 0.0 {
99                return Err(FinancialError::ValidationError(
100                    "Order price must be positive".to_string(),
101                ));
102            }
103        }
104        Ok(())
105    }
106
107    /// **Intentionally refuses to execute.** There is no broker/exchange
108    /// connection and this system must not place orders or move money; it
109    /// returns `NotImplemented` rather than reporting a fabricated fill.
110    pub fn execute_trade(&mut self, _order: &Order) -> Result<TradeResult, FinancialError> {
111        // NOT IMPLEMENTED — and this one must never fabricate. The previous body returned a
112        // `TradeResult { status: Filled, executed_price: order.price.unwrap_or(100.0) }` — a
113        // *fake fill* at a fabricated default price for a trade that never executed. Reporting a
114        // filled trade that did not happen is dangerous. Real execution requires a broker/exchange
115        // connection and order-management — and as a matter of policy this system must not place
116        // real orders or move money. It therefore refuses, explicitly.
117        Err(FinancialError::NotImplemented(
118            "trade execution (execute_trade): no broker/exchange connection; this system does not \
119             place orders or move money. Refusing to report a fabricated fill."
120                .to_string(),
121        ))
122    }
123
124    /// Returns a reference to the inner `position_manager` sub-component.
125    pub fn position_manager(&self) -> &PositionManager {
126        &self.position_manager
127    }
128
129    /// Mutable access to the inner `position_manager` sub-component.
130    pub fn position_manager_mut(&mut self) -> &mut PositionManager {
131        &mut self.position_manager
132    }
133}
134
135impl PositionManager {
136    /// Creates a `PositionManager` with empty registries / default configuration.
137    pub fn new() -> Self {
138        Self {
139            positions: HashMap::new(),
140            position_limits: HashMap::new(),
141            margin_calculator: MarginCalculator::new(),
142        }
143    }
144
145    /// Registers `position` in the registry (keyed by its id).
146    pub fn add_position(&mut self, position: Position) {
147        self.positions
148            .insert(position.position_id.clone(), position);
149    }
150
151    /// Looks up `position` by id; `None` if not registered.
152    pub fn get_position(&self, position_id: &str) -> Option<&Position> {
153        self.positions.get(position_id)
154    }
155
156    /// Iterates over all registered `positions` entries.
157    pub fn list_positions(&self) -> Vec<String> {
158        self.positions.keys().cloned().collect()
159    }
160
161    /// Registers `position limit` in the registry (keyed by its id).
162    pub fn add_position_limit(&mut self, limit: PositionLimit) {
163        self.position_limits.insert(limit.limit_id.clone(), limit);
164    }
165
166    /// Looks up `position limit` by id; `None` if not registered.
167    pub fn get_position_limit(&self, limit_id: &str) -> Option<&PositionLimit> {
168        self.position_limits.get(limit_id)
169    }
170
171    /// Returns a reference to the inner `margin_calculator` sub-component.
172    pub fn margin_calculator(&self) -> &MarginCalculator {
173        &self.margin_calculator
174    }
175
176    /// Mutable access to the inner `margin_calculator` sub-component.
177    pub fn margin_calculator_mut(&mut self) -> &mut MarginCalculator {
178        &mut self.margin_calculator
179    }
180}
181
182impl MarginCalculator {
183    /// Creates a `MarginCalculator` with empty registries / default configuration.
184    pub fn new() -> Self {
185        Self {
186            margin_methods: HashMap::new(),
187            margin_requirements: MarginRequirements::new(),
188        }
189    }
190
191    /// Registers `margin method` in the registry (keyed by its id).
192    pub fn add_margin_method(&mut self, method: MarginMethod) {
193        self.margin_methods.insert(method.method_id.clone(), method);
194    }
195
196    /// Looks up `margin method` by id; `None` if not registered.
197    pub fn get_margin_method(&self, method_id: &str) -> Option<&MarginMethod> {
198        self.margin_methods.get(method_id)
199    }
200
201    /// Iterates over all registered `margin methods` entries.
202    pub fn list_margin_methods(&self) -> Vec<String> {
203        self.margin_methods.keys().cloned().collect()
204    }
205
206    /// Returns the configured margin requirements for the calculator.
207    pub fn margin_requirements(&self) -> &MarginRequirements {
208        &self.margin_requirements
209    }
210}