Skip to main content

qualia_core_db/specialized_libs/financial_modeling/
execution.rs

1use super::*;
2
3/// Execution engine
4pub struct ExecutionEngine {
5    execution_strategies: HashMap<String, ExecutionStrategy>,
6    order_manager: OrderManager,
7    settlement_engine: SettlementEngine,
8}
9
10/// Execution strategies
11#[derive(Debug, Clone)]
12pub struct ExecutionStrategy {
13    pub strategy_id: String,
14    pub strategy_name: String,
15    pub strategy_type: ExecutionStrategyType,
16    pub parameters: ExecutionParameters,
17}
18
19/// Execution strategy types
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21pub enum ExecutionStrategyType {
22    MarketOrder,
23    LimitOrder,
24    VWAP,
25    TWAP,
26    ImplementationShortfall,
27}
28
29/// Execution parameters
30#[derive(Debug, Clone, Serialize, Deserialize)]
31pub struct ExecutionParameters {
32    pub order_size: f64,
33    pub price_limit: Option<f64>,
34    pub time_limit: Option<u64>,
35    pub participation_rate: Option<f64>,
36}
37
38/// Order manager
39pub struct OrderManager {
40    orders: HashMap<String, Order>,
41    order_validation: OrderValidation,
42    order_routing: OrderRouting,
43}
44
45/// Orders
46#[derive(Debug, Clone)]
47pub struct Order {
48    pub order_id: String,
49    pub portfolio_id: String,
50    pub asset_id: String,
51    pub order_type: OrderType,
52    pub side: OrderSide,
53    pub quantity: f64,
54    pub price: Option<f64>,
55    pub time_in_force: TimeInForce,
56    pub status: OrderStatus,
57    pub created_at: u64,
58    pub updated_at: u64,
59}
60
61/// Order types
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
63pub enum OrderType {
64    Market,
65    Limit,
66    Stop,
67    StopLimit,
68    TrailingStop,
69}
70
71/// Order sides
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
73pub enum OrderSide {
74    Buy,
75    Sell,
76}
77
78/// Time in force
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80pub enum TimeInForce {
81    Day,
82    GTC,
83    IOC,
84    FOK,
85}
86
87/// Order status
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89pub enum OrderStatus {
90    New,
91    PartiallyFilled,
92    Filled,
93    Cancelled,
94    Rejected,
95}
96
97/// Order validation
98pub struct OrderValidation {
99    validation_rules: Vec<OrderValidationRule>,
100    compliance_checker: OrderComplianceChecker,
101}
102
103/// Order validation rules
104#[derive(Debug, Clone)]
105pub struct OrderValidationRule {
106    pub rule_id: String,
107    pub rule_type: OrderValidationRuleType,
108    pub condition: String,
109    pub action: OrderValidationAction,
110}
111
112/// Order validation rule types
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114pub enum OrderValidationRuleType {
115    Size,
116    Price,
117    Liquidity,
118    Risk,
119    Compliance,
120}
121
122/// Order validation actions
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124pub enum OrderValidationAction {
125    Accept,
126    Reject,
127    Modify,
128    Escalate,
129}
130
131/// Order compliance checker
132pub struct OrderComplianceChecker {
133    compliance_rules: Vec<OrderComplianceRule>,
134    regulatory_limits: HashMap<String, RegulatoryLimit>,
135}
136
137/// Order compliance rules
138#[derive(Debug, Clone)]
139pub struct OrderComplianceRule {
140    pub rule_id: String,
141    pub rule_name: String,
142    pub conditions: Vec<OrderComplianceCondition>,
143    pub actions: Vec<OrderComplianceAction>,
144}
145
146/// Order compliance conditions
147#[derive(Debug, Clone)]
148pub struct OrderComplianceCondition {
149    pub condition_id: String,
150    pub field: String,
151    pub operator: ComparisonOperator,
152    pub value: OrderComplianceValue,
153}
154
155/// Order compliance values
156#[derive(Debug, Clone)]
157pub enum OrderComplianceValue {
158    String(String),
159    Number(f64),
160    Boolean(bool),
161}
162
163/// Order compliance actions
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165pub enum OrderComplianceAction {
166    Approve,
167    Reject,
168    Flag,
169    Escalate,
170}
171
172/// Regulatory limits
173#[derive(Debug, Clone)]
174pub struct RegulatoryLimit {
175    pub limit_id: String,
176    pub limit_type: RegulatoryLimitType,
177    pub limit_value: f64,
178    pub reset_period: u64,
179}
180
181/// Regulatory limit types
182#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
183pub enum RegulatoryLimitType {
184    Position,
185    Trading,
186    Exposure,
187    Leverage,
188}
189
190/// Order routing
191pub struct OrderRouting {
192    routing_strategies: HashMap<String, RoutingStrategy>,
193    venue_selector: VenueSelector,
194}
195
196/// Routing strategies
197#[derive(Debug, Clone)]
198pub struct RoutingStrategy {
199    pub strategy_id: String,
200    pub strategy_name: String,
201    pub strategy_type: RoutingStrategyType,
202    pub parameters: RoutingParameters,
203}
204
205/// Routing strategy types
206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
207pub enum RoutingStrategyType {
208    BestExecution,
209    CostMinimization,
210    SpeedOptimization,
211    LiquiditySeeking,
212}
213
214/// Routing parameters
215#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct RoutingParameters {
217    pub venues: Vec<String>,
218    pub priority_factors: Vec<PriorityFactor>,
219    pub cost_factors: Vec<CostFactor>,
220}
221
222/// Priority factors
223#[derive(Debug, Clone, Serialize, Deserialize)]
224pub struct PriorityFactor {
225    pub factor_name: String,
226    pub weight: f64,
227}
228
229/// Cost factors
230#[derive(Debug, Clone, Serialize, Deserialize)]
231pub struct CostFactor {
232    pub factor_name: String,
233    pub cost_per_share: f64,
234}
235
236/// Venue selector
237pub struct VenueSelector {
238    venues: HashMap<String, TradingVenue>,
239    venue_performance: HashMap<String, VenuePerformance>,
240}
241
242/// Trading venues
243#[derive(Debug, Clone)]
244pub struct TradingVenue {
245    pub venue_id: String,
246    pub venue_name: String,
247    pub venue_type: VenueType,
248    pub supported_assets: Vec<String>,
249    pub fee_structure: FeeStructure,
250}
251
252/// Venue types
253#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
254pub enum VenueType {
255    Exchange,
256    ECN,
257    DarkPool,
258    Internalizer,
259    OTC,
260}
261
262/// Fee structures
263#[derive(Debug, Clone)]
264pub struct FeeStructure {
265    pub commission_rate: f64,
266    pub clearing_fee: f64,
267    pub exchange_fee: f64,
268    pub regulatory_fee: f64,
269}
270
271/// Venue performance
272#[derive(Debug, Clone)]
273pub struct VenuePerformance {
274    pub venue_id: String,
275    pub fill_rate: f64,
276    pub average_fill_time: f64,
277    pub price_improvement: f64,
278    pub market_impact: f64,
279}
280
281impl ExecutionEngine {
282    /// Create a `ExecutionEngine` with default sub-components.
283    pub fn new() -> Self {
284        Self {
285            execution_strategies: HashMap::new(),
286            order_manager: OrderManager::new(),
287            settlement_engine: SettlementEngine::new(),
288        }
289    }
290
291    /// Initialise the `ExecutionEngine` sub-components; propagates the domain error.
292    pub fn initialize(&mut self) -> Result<(), FinancialError> {
293        self.order_manager.initialize()?;
294        self.settlement_engine.initialize()?;
295        Ok(())
296    }
297
298    /// Register `execution_strategy` in the `ExecutionEngine` collection.
299    pub fn add_execution_strategy(&mut self, strategy: ExecutionStrategy) {
300        self.execution_strategies
301            .insert(strategy.strategy_id.clone(), strategy);
302    }
303
304    /// Borrow `execution_strategy` by id, or `None` when absent.
305    pub fn get_execution_strategy(&self, strategy_id: &str) -> Option<&ExecutionStrategy> {
306        self.execution_strategies.get(strategy_id)
307    }
308
309    /// Ids of the `execution_strategies` currently registered.
310    pub fn list_execution_strategies(&self) -> Vec<String> {
311        self.execution_strategies.keys().cloned().collect()
312    }
313}
314
315impl OrderManager {
316    /// Create a `OrderManager` with default sub-components.
317    pub fn new() -> Self {
318        Self {
319            orders: HashMap::new(),
320            order_validation: OrderValidation::new(),
321            order_routing: OrderRouting::new(),
322        }
323    }
324
325    /// Initialise the `OrderManager` sub-components; propagates the domain error.
326    pub fn initialize(&mut self) -> Result<(), FinancialError> {
327        Ok(())
328    }
329
330    /// Register `order` in the `OrderManager` collection.
331    pub fn add_order(&mut self, order: Order) {
332        self.orders.insert(order.order_id.clone(), order);
333    }
334
335    /// Borrow `order` by id, or `None` when absent.
336    pub fn get_order(&self, order_id: &str) -> Option<&Order> {
337        self.orders.get(order_id)
338    }
339
340    /// Ids of the `orders` currently registered.
341    pub fn list_orders(&self) -> Vec<String> {
342        self.orders.keys().cloned().collect()
343    }
344
345    /// Borrow the `order_validation` component.
346    pub fn order_validation(&self) -> &OrderValidation {
347        &self.order_validation
348    }
349
350    /// Mutable borrow of the `order_validation` component.
351    pub fn order_validation_mut(&mut self) -> &mut OrderValidation {
352        &mut self.order_validation
353    }
354
355    /// Borrow the `order_routing` component.
356    pub fn order_routing(&self) -> &OrderRouting {
357        &self.order_routing
358    }
359
360    /// Mutable borrow of the `order_routing` component.
361    pub fn order_routing_mut(&mut self) -> &mut OrderRouting {
362        &mut self.order_routing
363    }
364}
365
366impl OrderValidation {
367    /// Create a `OrderValidation` with default sub-components.
368    pub fn new() -> Self {
369        Self {
370            validation_rules: Vec::new(),
371            compliance_checker: OrderComplianceChecker::new(),
372        }
373    }
374
375    /// Register `validation_rule` in the `OrderValidation` collection.
376    pub fn add_validation_rule(&mut self, rule: OrderValidationRule) {
377        self.validation_rules.push(rule);
378    }
379
380    /// Ids of the `validation_rules` currently registered.
381    pub fn list_validation_rules(&self) -> &[OrderValidationRule] {
382        &self.validation_rules
383    }
384
385    /// Borrow the `compliance_checker` component.
386    pub fn compliance_checker(&self) -> &OrderComplianceChecker {
387        &self.compliance_checker
388    }
389
390    /// Mutable borrow of the `compliance_checker` component.
391    pub fn compliance_checker_mut(&mut self) -> &mut OrderComplianceChecker {
392        &mut self.compliance_checker
393    }
394}
395
396impl OrderComplianceChecker {
397    /// Create a `OrderComplianceChecker` with default sub-components.
398    pub fn new() -> Self {
399        Self {
400            compliance_rules: Vec::new(),
401            regulatory_limits: HashMap::new(),
402        }
403    }
404
405    /// Register `compliance_rule` in the `OrderComplianceChecker` collection.
406    pub fn add_compliance_rule(&mut self, rule: OrderComplianceRule) {
407        self.compliance_rules.push(rule);
408    }
409
410    /// Ids of the `compliance_rules` currently registered.
411    pub fn list_compliance_rules(&self) -> &[OrderComplianceRule] {
412        &self.compliance_rules
413    }
414
415    /// Register `regulatory_limit` in the `OrderComplianceChecker` collection.
416    pub fn add_regulatory_limit(&mut self, limit: RegulatoryLimit) {
417        self.regulatory_limits.insert(limit.limit_id.clone(), limit);
418    }
419
420    /// Borrow `regulatory_limit` by id, or `None` when absent.
421    pub fn get_regulatory_limit(&self, limit_id: &str) -> Option<&RegulatoryLimit> {
422        self.regulatory_limits.get(limit_id)
423    }
424
425    /// Ids of the `regulatory_limits` currently registered.
426    pub fn list_regulatory_limits(&self) -> Vec<String> {
427        self.regulatory_limits.keys().cloned().collect()
428    }
429}
430
431impl OrderRouting {
432    /// Create a `OrderRouting` with default sub-components.
433    pub fn new() -> Self {
434        Self {
435            routing_strategies: HashMap::new(),
436            venue_selector: VenueSelector::new(),
437        }
438    }
439
440    /// Register `routing_strategy` in the `OrderRouting` collection.
441    pub fn add_routing_strategy(&mut self, strategy: RoutingStrategy) {
442        self.routing_strategies
443            .insert(strategy.strategy_id.clone(), strategy);
444    }
445
446    /// Borrow `routing_strategy` by id, or `None` when absent.
447    pub fn get_routing_strategy(&self, strategy_id: &str) -> Option<&RoutingStrategy> {
448        self.routing_strategies.get(strategy_id)
449    }
450
451    /// Ids of the `routing_strategies` currently registered.
452    pub fn list_routing_strategies(&self) -> Vec<String> {
453        self.routing_strategies.keys().cloned().collect()
454    }
455
456    /// Borrow the `venue_selector` component.
457    pub fn venue_selector(&self) -> &VenueSelector {
458        &self.venue_selector
459    }
460
461    /// Mutable borrow of the `venue_selector` component.
462    pub fn venue_selector_mut(&mut self) -> &mut VenueSelector {
463        &mut self.venue_selector
464    }
465}
466
467impl VenueSelector {
468    /// Create a `VenueSelector` with default sub-components.
469    pub fn new() -> Self {
470        Self {
471            venues: HashMap::new(),
472            venue_performance: HashMap::new(),
473        }
474    }
475
476    /// Register `venue` in the `VenueSelector` collection.
477    pub fn add_venue(&mut self, venue: TradingVenue) {
478        self.venues.insert(venue.venue_id.clone(), venue);
479    }
480
481    /// Borrow `venue` by id, or `None` when absent.
482    pub fn get_venue(&self, venue_id: &str) -> Option<&TradingVenue> {
483        self.venues.get(venue_id)
484    }
485
486    /// Ids of the `venues` currently registered.
487    pub fn list_venues(&self) -> Vec<String> {
488        self.venues.keys().cloned().collect()
489    }
490
491    /// Register `venue_performance` in the `VenueSelector` collection.
492    pub fn add_venue_performance(&mut self, performance: VenuePerformance) {
493        self.venue_performance
494            .insert(performance.venue_id.clone(), performance);
495    }
496
497    /// Borrow `venue_performance` by id, or `None` when absent.
498    pub fn get_venue_performance(&self, venue_id: &str) -> Option<&VenuePerformance> {
499        self.venue_performance.get(venue_id)
500    }
501}
502
503impl ExecutionStrategy {
504    /// Create a `ExecutionStrategy` with default sub-components.
505    pub fn new() -> Self {
506        Self {
507            strategy_id: "exec_1".to_string(),
508            strategy_name: "VWAP execution".to_string(),
509            strategy_type: ExecutionStrategyType::VWAP,
510            parameters: ExecutionParameters::new(),
511        }
512    }
513}
514
515impl ExecutionParameters {
516    /// Create a `ExecutionParameters` with default sub-components.
517    pub fn new() -> Self {
518        Self {
519            order_size: 10000.0,
520            price_limit: None,
521            time_limit: Some(3600), // 1 hour
522            participation_rate: Some(0.2),
523        }
524    }
525}
526
527impl Order {
528    /// Create a `Order` with default sub-components.
529    pub fn new() -> Self {
530        Self {
531            order_id: "order_1".to_string(),
532            portfolio_id: "portfolio_1".to_string(),
533            asset_id: "asset_1".to_string(),
534            order_type: OrderType::Market,
535            side: OrderSide::Buy,
536            quantity: 100.0,
537            price: None,
538            time_in_force: TimeInForce::Day,
539            status: OrderStatus::New,
540            created_at: 0,
541            updated_at: 0,
542        }
543    }
544}
545
546impl OrderValidationRule {
547    /// Create a `OrderValidationRule` with default sub-components.
548    pub fn new() -> Self {
549        Self {
550            rule_id: "rule_1".to_string(),
551            rule_type: OrderValidationRuleType::Size,
552            condition: "quantity > 0".to_string(),
553            action: OrderValidationAction::Accept,
554        }
555    }
556}
557
558impl OrderComplianceCondition {
559    /// Create a `OrderComplianceCondition` with default sub-components.
560    pub fn new() -> Self {
561        Self {
562            condition_id: "cond_1".to_string(),
563            field: "quantity".to_string(),
564            operator: ComparisonOperator::GreaterThan,
565            value: OrderComplianceValue::Number(0.0),
566        }
567    }
568}
569
570impl OrderComplianceRule {
571    /// Create a `OrderComplianceRule` with default sub-components.
572    pub fn new() -> Self {
573        Self {
574            rule_id: "rule_1".to_string(),
575            rule_name: "Size validation".to_string(),
576            conditions: vec![OrderComplianceCondition::new()],
577            actions: vec![OrderComplianceAction::Approve],
578        }
579    }
580}
581
582impl RegulatoryLimit {
583    /// Create a `RegulatoryLimit` with default sub-components.
584    pub fn new() -> Self {
585        Self {
586            limit_id: "limit_1".to_string(),
587            limit_type: RegulatoryLimitType::Position,
588            limit_value: 1000000.0,
589            reset_period: 86400, // 1 day
590        }
591    }
592}
593
594impl RoutingStrategy {
595    /// Create a `RoutingStrategy` with default sub-components.
596    pub fn new() -> Self {
597        Self {
598            strategy_id: "route_1".to_string(),
599            strategy_name: "Best execution".to_string(),
600            strategy_type: RoutingStrategyType::BestExecution,
601            parameters: RoutingParameters::new(),
602        }
603    }
604}
605
606impl RoutingParameters {
607    /// Create a `RoutingParameters` with default sub-components.
608    pub fn new() -> Self {
609        Self {
610            venues: vec!["venue_1".to_string()],
611            priority_factors: vec![PriorityFactor::new()],
612            cost_factors: vec![CostFactor::new()],
613        }
614    }
615}
616
617impl PriorityFactor {
618    /// Create a `PriorityFactor` with default sub-components.
619    pub fn new() -> Self {
620        Self {
621            factor_name: "Speed".to_string(),
622            weight: 0.5,
623        }
624    }
625}
626
627impl CostFactor {
628    /// Create a `CostFactor` with default sub-components.
629    pub fn new() -> Self {
630        Self {
631            factor_name: "Commission".to_string(),
632            cost_per_share: 0.001,
633        }
634    }
635}
636
637impl TradingVenue {
638    /// Create a `TradingVenue` with default sub-components.
639    pub fn new() -> Self {
640        Self {
641            venue_id: "venue_1".to_string(),
642            venue_name: "NASDAQ".to_string(),
643            venue_type: VenueType::Exchange,
644            supported_assets: vec!["AAPL".to_string()],
645            fee_structure: FeeStructure::new(),
646        }
647    }
648}
649
650impl FeeStructure {
651    /// Create a `FeeStructure` with default sub-components.
652    pub fn new() -> Self {
653        Self {
654            commission_rate: 0.001,
655            clearing_fee: 0.0001,
656            exchange_fee: 0.0002,
657            regulatory_fee: 0.0001,
658        }
659    }
660}
661
662impl VenuePerformance {
663    /// Create a `VenuePerformance` with default sub-components.
664    pub fn new() -> Self {
665        Self {
666            venue_id: "venue_1".to_string(),
667            fill_rate: 0.95,
668            average_fill_time: 100.0,
669            price_improvement: 0.001,
670            market_impact: 0.0005,
671        }
672    }
673}