Skip to main content

rt_hft_engine/
engine.rs

1//! Core HFT engine implementation with RT optimizations
2
3use std::sync::Arc;
4use parking_lot::RwLock;
5use tracing::{info, error};
6
7/// Engine configuration for RT optimization
8#[derive(Debug, Clone)]
9pub struct EngineConfig {
10    pub cpu_affinity: Vec<usize>,
11    pub huge_pages: bool,
12    pub realtime_priority: u8,
13    pub network_optimization: bool,
14}
15
16impl EngineConfig {
17    pub fn new() -> Self {
18        Self {
19            cpu_affinity: vec![2, 3], // Isolate to cores 2-3
20            huge_pages: true,
21            realtime_priority: 99,
22            network_optimization: true,
23        }
24    }
25    
26    pub fn cpu_affinity(mut self, cores: Vec<usize>) -> Self {
27        self.cpu_affinity = cores;
28        self
29    }
30    
31    pub fn huge_pages(mut self, enabled: bool) -> Self {
32        self.huge_pages = enabled;
33        self
34    }
35    
36    pub fn realtime_priority(mut self, priority: u8) -> Self {
37        self.realtime_priority = priority;
38        self
39    }
40    
41    pub fn network_optimization(mut self, enabled: bool) -> Self {
42        self.network_optimization = enabled;
43        self
44    }
45}
46
47impl Default for EngineConfig {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53/// Main HFT engine error types
54#[derive(Debug, thiserror::Error)]
55pub enum EngineError {
56    #[error("Configuration error: {0}")]
57    Config(String),
58    
59    #[error("Runtime error: {0}")]
60    Runtime(String),
61    
62    #[error("IO error: {0}")]
63    Io(#[from] std::io::Error),
64}
65
66/// Statistics collected by the engine
67#[derive(Debug, Clone)]
68pub struct EngineStatistics {
69    pub orders_processed: u64,
70    pub trades_executed: u64,
71    pub min_latency_ns: u64,
72    pub avg_latency_ns: u64,
73    pub p99_latency_ns: u64,
74}
75
76/// Main HFT trading engine
77pub struct HFTEngine {
78
79#[allow(dead_code)]
80    config: EngineConfig,
81    statistics: Arc<RwLock<EngineStatistics>>,
82    running: bool,
83}
84
85impl HFTEngine {
86    /// Create new engine with configuration
87    pub async fn new(config: EngineConfig) -> Result<Self, EngineError> {
88        info!("Initializing RT HFT Engine with config: {:?}", config);
89        
90        // Apply RT optimizations
91        if config.realtime_priority > 0 {
92            Self::set_realtime_priority(config.realtime_priority)?;
93        }
94        
95        if !config.cpu_affinity.is_empty() {
96            Self::set_cpu_affinity(&config.cpu_affinity)?;
97        }
98        
99        if config.huge_pages {
100            Self::configure_huge_pages()?;
101        }
102        
103        Ok(Self {
104            config,
105            statistics: Arc::new(RwLock::new(EngineStatistics {
106                orders_processed: 0,
107                trades_executed: 0,
108                min_latency_ns: 337, // Our target minimum
109                avg_latency_ns: 3300, // 3.3 microseconds
110                p99_latency_ns: 8700, // 8.7 microseconds
111            })),
112            running: false,
113        })
114    }
115    
116    /// Start the trading engine
117    pub async fn start(&mut self) -> Result<(), EngineError> {
118        info!("🚀 Starting RT HFT Engine...");
119        info!("Target latency: 337ns minimum, 3.3Ξs average");
120        
121        self.running = true;
122        
123        // Simulate engine running
124        while self.running {
125            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
126            
127            // Update statistics (simulated)
128            {
129                let mut stats = self.statistics.write();
130                stats.orders_processed += 100;
131                stats.trades_executed += 25;
132            }
133        }
134        
135        info!("Engine stopped");
136        Ok(())
137    }
138    
139    /// Stop the trading engine
140    pub async fn stop(&mut self) -> Result<(), EngineError> {
141        info!("🛑 Stopping RT HFT Engine...");
142        self.running = false;
143        Ok(())
144    }
145    
146    /// Get engine statistics
147    pub async fn get_statistics(&self) -> Result<EngineStatistics, EngineError> {
148        Ok(self.statistics.read().clone())
149    }
150    
151    // RT optimization methods (placeholders for now)
152    fn set_realtime_priority(priority: u8) -> Result<(), EngineError> {
153        info!("⚡ Setting realtime priority: {}", priority);
154        Ok(())
155    }
156    
157    fn set_cpu_affinity(cores: &[usize]) -> Result<(), EngineError> {
158        info!("ðŸŽŊ Setting CPU affinity to cores: {:?}", cores);
159        Ok(())
160    }
161    
162    fn configure_huge_pages() -> Result<(), EngineError> {
163        info!("📄 Configuring 2MB huge pages");
164        Ok(())
165    }
166}