refactor(engine): retire abandoned architecture scaffolding (CL15)
This commit is contained in:
parent
7481d02c6c
commit
bc2b8a89da
31 changed files with 76 additions and 3043 deletions
|
|
@ -1,162 +0,0 @@
|
|||
// Placeholder types for new event system (will be replaced when domain module is activated)
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NewEvent {
|
||||
pub timestamp: chrono::DateTime<chrono::Utc>,
|
||||
pub source: String,
|
||||
pub event_type: NewEventType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NewEventType {
|
||||
MarketData {
|
||||
symbol: String,
|
||||
data: crate::MarketDataType,
|
||||
},
|
||||
OrderFilled {
|
||||
order_id: String,
|
||||
fill: crate::Fill,
|
||||
},
|
||||
OrderSubmitted {
|
||||
order_id: String,
|
||||
},
|
||||
OrderCancelled {
|
||||
order_id: String,
|
||||
},
|
||||
PositionUpdated {
|
||||
symbol: String,
|
||||
update: crate::PositionUpdate,
|
||||
},
|
||||
RiskLimitExceeded {
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
use std::collections::HashMap;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
// Placeholder EventBus type (will be replaced when events module is activated)
|
||||
pub struct NewEventBus {
|
||||
sender: mpsc::UnboundedSender<NewEvent>,
|
||||
}
|
||||
|
||||
impl NewEventBus {
|
||||
pub async fn publish(&mut self, event: NewEvent) {
|
||||
let _ = self.sender.send(event);
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps between old and new event types
|
||||
pub struct EventAdapter;
|
||||
|
||||
impl EventAdapter {
|
||||
/// Convert from new event to old event format if needed
|
||||
pub fn from_new_event(event: &NewEvent) -> Option<OldEventFormat> {
|
||||
match &event.event_type {
|
||||
NewEventType::MarketData { symbol, data } => {
|
||||
Some(OldEventFormat::MarketUpdate {
|
||||
symbol: symbol.clone(),
|
||||
timestamp: event.timestamp,
|
||||
data: data.clone(),
|
||||
})
|
||||
}
|
||||
NewEventType::OrderFilled { order_id, fill } => {
|
||||
Some(OldEventFormat::OrderFill {
|
||||
order_id: order_id.clone(),
|
||||
fill: fill.clone(),
|
||||
})
|
||||
}
|
||||
_ => None, // Other event types may not have old equivalents
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert from old event to new event format
|
||||
pub fn to_new_event(old_event: &OldEventFormat) -> NewEvent {
|
||||
match old_event {
|
||||
OldEventFormat::MarketUpdate { symbol, timestamp, data } => {
|
||||
NewEvent {
|
||||
timestamp: *timestamp,
|
||||
source: "legacy".to_string(),
|
||||
event_type: NewEventType::MarketData {
|
||||
symbol: symbol.clone(),
|
||||
data: data.clone(),
|
||||
},
|
||||
}
|
||||
}
|
||||
OldEventFormat::OrderFill { order_id, fill } => {
|
||||
NewEvent {
|
||||
timestamp: fill.timestamp,
|
||||
source: "legacy".to_string(),
|
||||
event_type: NewEventType::OrderFilled {
|
||||
order_id: order_id.clone(),
|
||||
fill: fill.clone(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Placeholder for old event format (to be defined based on actual old implementation)
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum OldEventFormat {
|
||||
MarketUpdate {
|
||||
symbol: String,
|
||||
timestamp: chrono::DateTime<chrono::Utc>,
|
||||
data: crate::MarketDataType,
|
||||
},
|
||||
OrderFill {
|
||||
order_id: String,
|
||||
fill: crate::Fill,
|
||||
},
|
||||
}
|
||||
|
||||
/// Event bus adapter to bridge old and new event systems
|
||||
pub struct EventBusAdapter {
|
||||
new_event_bus: Option<NewEventBus>,
|
||||
old_handlers: HashMap<String, Vec<Box<dyn Fn(&OldEventFormat) + Send + Sync>>>,
|
||||
}
|
||||
|
||||
impl EventBusAdapter {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
new_event_bus: None,
|
||||
old_handlers: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_new_event_bus(mut self, event_bus: NewEventBus) -> Self {
|
||||
self.new_event_bus = Some(event_bus);
|
||||
self
|
||||
}
|
||||
|
||||
/// Subscribe to events using old-style handler
|
||||
pub fn subscribe_old<F>(&mut self, event_type: &str, handler: F)
|
||||
where
|
||||
F: Fn(&OldEventFormat) + Send + Sync + 'static,
|
||||
{
|
||||
self.old_handlers
|
||||
.entry(event_type.to_string())
|
||||
.or_insert_with(Vec::new)
|
||||
.push(Box::new(handler));
|
||||
}
|
||||
|
||||
/// Publish event in old format (converts to new format if new bus available)
|
||||
pub async fn publish_old(&mut self, event: OldEventFormat) {
|
||||
// Call old handlers
|
||||
let event_type = match &event {
|
||||
OldEventFormat::MarketUpdate { .. } => "market_update",
|
||||
OldEventFormat::OrderFill { .. } => "order_fill",
|
||||
};
|
||||
|
||||
if let Some(handlers) = self.old_handlers.get(event_type) {
|
||||
for handler in handlers {
|
||||
handler(&event);
|
||||
}
|
||||
}
|
||||
|
||||
// Convert and publish to new event bus if available
|
||||
if let Some(ref mut new_bus) = self.new_event_bus {
|
||||
let new_event = EventAdapter::to_new_event(&event);
|
||||
new_bus.publish(new_event).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
pub mod events;
|
||||
pub mod strategy;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use crate::{Order, ExecutionResult, OrderStatus, Fill, OrderBookSnapshot, FillSimulator};
|
||||
use std::sync::Arc;
|
||||
use parking_lot::RwLock;
|
||||
|
||||
/// Adapter to bridge between old and new ExecutionHandler implementations
|
||||
pub struct ExecutionHandlerAdapter<T> {
|
||||
inner: Arc<RwLock<T>>,
|
||||
}
|
||||
|
||||
impl<T> ExecutionHandlerAdapter<T> {
|
||||
pub fn new(handler: T) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(RwLock::new(handler)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// New-style ExecutionHandler trait (from modular design)
|
||||
#[async_trait]
|
||||
pub trait NewExecutionHandler: Send + Sync {
|
||||
async fn submit_order(&mut self, order: Order) -> Result<String, String>;
|
||||
async fn cancel_order(&mut self, order_id: &str) -> Result<(), String>;
|
||||
async fn get_order_status(&self, order_id: &str) -> Result<OrderStatus, String>;
|
||||
}
|
||||
|
||||
/// Implement old ExecutionHandler for adapters wrapping new handlers
|
||||
#[async_trait]
|
||||
impl<T: NewExecutionHandler + 'static> crate::ExecutionHandler for ExecutionHandlerAdapter<T> {
|
||||
async fn execute_order(&mut self, order: Order) -> Result<ExecutionResult, String> {
|
||||
// For now, provide a simplified implementation
|
||||
// In a real implementation, you'd need proper async handling
|
||||
|
||||
// Create a synthetic execution result
|
||||
let fill = Fill {
|
||||
timestamp: chrono::Utc::now(),
|
||||
price: 100.0, // This would come from market data
|
||||
quantity: order.quantity,
|
||||
commission: 0.0,
|
||||
};
|
||||
|
||||
Ok(ExecutionResult {
|
||||
order_id: order.id,
|
||||
status: OrderStatus::Filled,
|
||||
fills: vec![fill],
|
||||
})
|
||||
}
|
||||
|
||||
fn get_fill_simulator(&self) -> Option<&dyn FillSimulator> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Simplified sync wrapper for cases where async isn't needed
|
||||
pub struct SyncExecutionHandlerAdapter<T> {
|
||||
inner: T,
|
||||
}
|
||||
|
||||
impl<T> SyncExecutionHandlerAdapter<T> {
|
||||
pub fn new(handler: T) -> Self {
|
||||
Self { inner: handler }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: crate::ExecutionHandler + Send + Sync> NewExecutionHandler for SyncExecutionHandlerAdapter<T> {
|
||||
async fn submit_order(&mut self, order: Order) -> Result<String, String> {
|
||||
let result = self.inner.execute_order(order).await?;
|
||||
Ok(result.order_id)
|
||||
}
|
||||
|
||||
async fn cancel_order(&mut self, _order_id: &str) -> Result<(), String> {
|
||||
// Old interface doesn't support cancellation
|
||||
Err("Cancellation not supported".to_string())
|
||||
}
|
||||
|
||||
async fn get_order_status(&self, _order_id: &str) -> Result<OrderStatus, String> {
|
||||
// Old interface doesn't support status queries
|
||||
Ok(OrderStatus::Filled)
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the original adapter logic but commented out for future reference
|
||||
/*
|
||||
#[async_trait]
|
||||
impl<T: NewExecutionHandler> crate::ExecutionHandler for ExecutionHandlerAdapter<T> {
|
||||
async fn execute_order(&mut self, order: Order) -> Result<ExecutionResult, String> {
|
||||
// This would require tokio::spawn or similar to properly handle
|
||||
// the async boundaries with parking_lot RwLock
|
||||
todo!("Complex async adapter implementation")
|
||||
}
|
||||
|
||||
fn get_fill_simulator(&self) -> Option<&dyn FillSimulator> {
|
||||
None
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
|
@ -1,231 +0,0 @@
|
|||
use async_trait::async_trait;
|
||||
use crate::{MarketUpdate, Fill, OrderType};
|
||||
use crate::backtest::Strategy as OldStrategy;
|
||||
use crate::risk::RiskLimits;
|
||||
use std::sync::Arc;
|
||||
use parking_lot::RwLock;
|
||||
|
||||
// Placeholder types for new strategy framework (will be replaced when framework module is activated)
|
||||
#[async_trait]
|
||||
pub trait NewStrategy: Send + Sync {
|
||||
async fn init(&mut self, context: &StrategyContext) -> Result<(), String>;
|
||||
async fn on_data(&mut self, data: &MarketUpdate, context: &StrategyContext) -> Vec<Signal>;
|
||||
async fn on_fill(&mut self, order_id: &str, fill: &Fill, context: &StrategyContext);
|
||||
async fn shutdown(&mut self, context: &StrategyContext) -> Result<(), String>;
|
||||
fn get_state(&self) -> serde_json::Value;
|
||||
}
|
||||
|
||||
pub struct StrategyContext {
|
||||
pub account_id: String,
|
||||
pub starting_capital: f64,
|
||||
}
|
||||
|
||||
impl StrategyContext {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
account_id: "default".to_string(),
|
||||
starting_capital: 100_000.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Signal {
|
||||
Buy {
|
||||
symbol: String,
|
||||
quantity: f64,
|
||||
order_type: OrderType,
|
||||
},
|
||||
Sell {
|
||||
symbol: String,
|
||||
quantity: f64,
|
||||
order_type: OrderType,
|
||||
},
|
||||
CancelOrder {
|
||||
order_id: String,
|
||||
},
|
||||
UpdateRiskLimits {
|
||||
limits: RiskLimits,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// Adapter to use new strategies with old interface
|
||||
pub struct NewToOldStrategyAdapter {
|
||||
inner: Arc<RwLock<Box<dyn NewStrategy>>>,
|
||||
context: Arc<StrategyContext>,
|
||||
}
|
||||
|
||||
impl NewToOldStrategyAdapter {
|
||||
pub fn new(strategy: Box<dyn NewStrategy>, context: Arc<StrategyContext>) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(RwLock::new(strategy)),
|
||||
context,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl OldStrategy for NewToOldStrategyAdapter {
|
||||
fn on_market_data(&mut self, data: &crate::MarketData) -> Vec<crate::backtest::strategy::Signal> {
|
||||
// Convert MarketData to MarketUpdate if needed
|
||||
let market_update = data.clone(); // Assuming MarketData is type alias for MarketUpdate
|
||||
|
||||
// Need to block on async call since old trait is sync
|
||||
let signals = tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current().block_on(async {
|
||||
let mut strategy = self.inner.write();
|
||||
strategy.on_data(&market_update, &self.context).await
|
||||
})
|
||||
});
|
||||
|
||||
// Convert new signals to old format
|
||||
signals.into_iter().map(|signal| {
|
||||
match signal {
|
||||
Signal::Buy { symbol, quantity, .. } => {
|
||||
crate::backtest::strategy::Signal {
|
||||
symbol,
|
||||
signal_type: crate::backtest::strategy::SignalType::Buy,
|
||||
strength: 1.0,
|
||||
quantity: Some(quantity),
|
||||
reason: None,
|
||||
metadata: None,
|
||||
}
|
||||
}
|
||||
Signal::Sell { symbol, quantity, .. } => {
|
||||
crate::backtest::strategy::Signal {
|
||||
symbol,
|
||||
signal_type: crate::backtest::strategy::SignalType::Sell,
|
||||
strength: 1.0,
|
||||
quantity: Some(quantity),
|
||||
reason: None,
|
||||
metadata: None,
|
||||
}
|
||||
}
|
||||
Signal::CancelOrder { .. } => {
|
||||
// Old strategy doesn't have cancel concept, skip
|
||||
crate::backtest::strategy::Signal {
|
||||
symbol: String::new(),
|
||||
signal_type: crate::backtest::strategy::SignalType::Close,
|
||||
strength: 0.0,
|
||||
quantity: None,
|
||||
reason: None,
|
||||
metadata: None,
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Skip other signal types
|
||||
crate::backtest::strategy::Signal {
|
||||
symbol: String::new(),
|
||||
signal_type: crate::backtest::strategy::SignalType::Close,
|
||||
strength: 0.0,
|
||||
quantity: None,
|
||||
reason: None,
|
||||
metadata: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}).filter(|s| !s.symbol.is_empty()).collect()
|
||||
}
|
||||
|
||||
fn on_fill(&mut self, symbol: &str, quantity: f64, price: f64, side: &str) {
|
||||
// Create a Fill object from the parameters
|
||||
let fill = Fill {
|
||||
timestamp: chrono::Utc::now(),
|
||||
price,
|
||||
quantity,
|
||||
commission: 0.0,
|
||||
};
|
||||
|
||||
// Block on async call
|
||||
tokio::task::block_in_place(|| {
|
||||
tokio::runtime::Handle::current().block_on(async {
|
||||
let mut strategy = self.inner.write();
|
||||
strategy.on_fill(&format!("order_{}", symbol), &fill, &self.context).await;
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
fn get_name(&self) -> &str {
|
||||
"NewStrategyAdapter"
|
||||
}
|
||||
|
||||
fn get_parameters(&self) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"adapter": "NewToOldStrategyAdapter",
|
||||
"context": {
|
||||
"account_id": self.context.account_id,
|
||||
"starting_capital": self.context.starting_capital,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Adapter to use old strategies with new interface
|
||||
pub struct OldToNewStrategyAdapter {
|
||||
inner: Box<dyn OldStrategy>,
|
||||
}
|
||||
|
||||
impl OldToNewStrategyAdapter {
|
||||
pub fn new(strategy: Box<dyn OldStrategy>) -> Self {
|
||||
Self { inner: strategy }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl NewStrategy for OldToNewStrategyAdapter {
|
||||
async fn init(&mut self, _context: &StrategyContext) -> Result<(), String> {
|
||||
// Old strategy doesn't have init
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn on_data(&mut self, data: &MarketUpdate, _context: &StrategyContext) -> Vec<Signal> {
|
||||
// Call sync method from async context
|
||||
let signals = self.inner.on_market_data(data);
|
||||
|
||||
// Convert old signals to new format
|
||||
signals.into_iter().filter_map(|signal| {
|
||||
match signal.signal_type {
|
||||
crate::backtest::strategy::SignalType::Buy => {
|
||||
Some(Signal::Buy {
|
||||
symbol: signal.symbol,
|
||||
quantity: signal.quantity.unwrap_or(100.0),
|
||||
order_type: OrderType::Market,
|
||||
})
|
||||
}
|
||||
crate::backtest::strategy::SignalType::Sell => {
|
||||
Some(Signal::Sell {
|
||||
symbol: signal.symbol,
|
||||
quantity: signal.quantity.unwrap_or(100.0),
|
||||
order_type: OrderType::Market,
|
||||
})
|
||||
}
|
||||
crate::backtest::strategy::SignalType::Close => {
|
||||
// Could map to cancel, but for now skip
|
||||
None
|
||||
}
|
||||
}
|
||||
}).collect()
|
||||
}
|
||||
|
||||
async fn on_fill(&mut self, _order_id: &str, fill: &Fill, _context: &StrategyContext) {
|
||||
// Extract symbol from order_id if possible, otherwise use placeholder
|
||||
let symbol = "UNKNOWN";
|
||||
let side = "buy"; // Would need to track this
|
||||
self.inner.on_fill(symbol, fill.quantity, fill.price, side);
|
||||
}
|
||||
|
||||
async fn shutdown(&mut self, _context: &StrategyContext) -> Result<(), String> {
|
||||
// Old strategy doesn't have shutdown
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_state(&self) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"adapter": "OldToNewStrategyAdapter",
|
||||
"inner_strategy": self.inner.get_name(),
|
||||
"parameters": self.inner.get_parameters()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
use napi_derive::napi;
|
||||
use napi::bindgen_prelude::*;
|
||||
use std::sync::Arc;
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[napi]
|
||||
pub struct BacktestAPI {
|
||||
core: Arc<crate::TradingCore>,
|
||||
}
|
||||
|
||||
impl BacktestAPI {
|
||||
pub fn new(core: Arc<crate::TradingCore>) -> Self {
|
||||
Self { core }
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl BacktestAPI {
|
||||
#[napi]
|
||||
pub async fn configure(
|
||||
&self,
|
||||
start_date: String,
|
||||
end_date: String,
|
||||
symbols: Vec<String>,
|
||||
initial_capital: f64,
|
||||
commission: f64,
|
||||
slippage: f64,
|
||||
) -> Result<()> {
|
||||
// Parse dates
|
||||
let start = DateTime::parse_from_rfc3339(&start_date)
|
||||
.map_err(|e| Error::from_reason(format!("Invalid start date: {}", e)))?
|
||||
.with_timezone(&Utc);
|
||||
let end = DateTime::parse_from_rfc3339(&end_date)
|
||||
.map_err(|e| Error::from_reason(format!("Invalid end date: {}", e)))?
|
||||
.with_timezone(&Utc);
|
||||
|
||||
// Configure backtest parameters
|
||||
if let crate::TradingMode::Backtest { .. } = self.core.get_mode() {
|
||||
// Update backtest configuration
|
||||
todo!("Update backtest configuration")
|
||||
} else {
|
||||
return Err(Error::from_reason("Not in backtest mode"));
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn load_data(&self, data_source: String) -> Result<()> {
|
||||
// Load historical data for backtest
|
||||
todo!("Load historical data")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn run(&self) -> Result<JsObject> {
|
||||
// Run the backtest
|
||||
if let crate::TradingMode::Backtest { .. } = self.core.get_mode() {
|
||||
// Execute backtest
|
||||
todo!("Execute backtest")
|
||||
} else {
|
||||
return Err(Error::from_reason("Not in backtest mode"));
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_progress(&self) -> Result<f64> {
|
||||
// Get backtest progress (0.0 to 1.0)
|
||||
todo!("Get backtest progress")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn pause(&self) -> Result<()> {
|
||||
// Pause backtest execution
|
||||
todo!("Pause backtest")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn resume(&self) -> Result<()> {
|
||||
// Resume backtest execution
|
||||
todo!("Resume backtest")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_results(&self) -> Result<JsObject> {
|
||||
// Get backtest results
|
||||
todo!("Get backtest results")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
use napi_derive::napi;
|
||||
use napi::bindgen_prelude::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[napi]
|
||||
pub struct MarketDataAPI {
|
||||
core: Arc<crate::TradingCore>,
|
||||
}
|
||||
|
||||
impl MarketDataAPI {
|
||||
pub fn new(core: Arc<crate::TradingCore>) -> Self {
|
||||
Self { core }
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl MarketDataAPI {
|
||||
#[napi]
|
||||
pub async fn subscribe(&self, symbols: Vec<String>) -> Result<()> {
|
||||
// Subscribe to market data for symbols
|
||||
self.core.subscribe_market_data(symbols)
|
||||
.await
|
||||
.map_err(|e| Error::from_reason(e))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn unsubscribe(&self, symbols: Vec<String>) -> Result<()> {
|
||||
// Unsubscribe from market data
|
||||
self.core.unsubscribe_market_data(symbols)
|
||||
.await
|
||||
.map_err(|e| Error::from_reason(e))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_latest_quote(&self, symbol: String) -> Result<JsObject> {
|
||||
// Get latest quote for symbol
|
||||
let quote = self.core.orderbook_manager
|
||||
.get_best_bid_ask(&symbol)
|
||||
.ok_or_else(|| Error::from_reason("No quote available"))?;
|
||||
|
||||
// Convert to JS object
|
||||
// Note: In real implementation, would properly convert Quote to JsObject
|
||||
todo!("Convert quote to JsObject")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_latest_bar(&self, symbol: String) -> Result<JsObject> {
|
||||
// Get latest bar for symbol
|
||||
todo!("Get latest bar implementation")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
use napi_derive::napi;
|
||||
|
||||
pub mod market_data;
|
||||
pub mod orders;
|
||||
pub mod positions;
|
||||
pub mod backtest;
|
||||
pub mod strategies;
|
||||
pub mod system;
|
||||
|
||||
// Main API entry point
|
||||
#[napi]
|
||||
pub struct TradingAPI {
|
||||
inner: std::sync::Arc<crate::TradingCore>,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl TradingAPI {
|
||||
#[napi(constructor)]
|
||||
pub fn new(mode: String) -> napi::Result<Self> {
|
||||
let trading_mode = parse_mode(&mode)?;
|
||||
let core = crate::TradingCore::new(trading_mode)
|
||||
.map_err(|e| napi::Error::from_reason(e))?;
|
||||
|
||||
Ok(Self {
|
||||
inner: std::sync::Arc::new(core),
|
||||
})
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn market_data(&self) -> market_data::MarketDataAPI {
|
||||
market_data::MarketDataAPI::new(self.inner.clone())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn orders(&self) -> orders::OrdersAPI {
|
||||
orders::OrdersAPI::new(self.inner.clone())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn positions(&self) -> positions::PositionsAPI {
|
||||
positions::PositionsAPI::new(self.inner.clone())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn strategies(&self) -> strategies::StrategiesAPI {
|
||||
strategies::StrategiesAPI::new(self.inner.clone())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn system(&self) -> system::SystemAPI {
|
||||
system::SystemAPI::new(self.inner.clone())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn backtest(&self) -> backtest::BacktestAPI {
|
||||
backtest::BacktestAPI::new(self.inner.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_mode(mode: &str) -> napi::Result<crate::TradingMode> {
|
||||
match mode {
|
||||
"backtest" => Ok(crate::TradingMode::Backtest {
|
||||
start_time: chrono::Utc::now(),
|
||||
end_time: chrono::Utc::now(),
|
||||
speed_multiplier: 1.0,
|
||||
}),
|
||||
"paper" => Ok(crate::TradingMode::Paper {
|
||||
starting_capital: 100_000.0,
|
||||
}),
|
||||
"live" => Ok(crate::TradingMode::Live {
|
||||
broker: "default".to_string(),
|
||||
account_id: "default".to_string(),
|
||||
}),
|
||||
_ => Err(napi::Error::from_reason(format!("Unknown mode: {}", mode))),
|
||||
}
|
||||
}
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
use napi_derive::napi;
|
||||
use napi::bindgen_prelude::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[napi]
|
||||
pub struct OrdersAPI {
|
||||
core: Arc<crate::TradingCore>,
|
||||
}
|
||||
|
||||
impl OrdersAPI {
|
||||
pub fn new(core: Arc<crate::TradingCore>) -> Self {
|
||||
Self { core }
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl OrdersAPI {
|
||||
#[napi]
|
||||
pub async fn submit_order(
|
||||
&self,
|
||||
symbol: String,
|
||||
side: String,
|
||||
quantity: f64,
|
||||
order_type: String,
|
||||
limit_price: Option<f64>,
|
||||
stop_price: Option<f64>,
|
||||
) -> Result<String> {
|
||||
let side = match side.as_str() {
|
||||
"buy" => crate::Side::Buy,
|
||||
"sell" => crate::Side::Sell,
|
||||
_ => return Err(Error::from_reason("Invalid side")),
|
||||
};
|
||||
|
||||
let order_type = match order_type.as_str() {
|
||||
"market" => crate::OrderType::Market,
|
||||
"limit" => {
|
||||
let price = limit_price.ok_or_else(|| Error::from_reason("Limit price required"))?;
|
||||
crate::OrderType::Limit { price }
|
||||
}
|
||||
"stop" => {
|
||||
let price = stop_price.ok_or_else(|| Error::from_reason("Stop price required"))?;
|
||||
crate::OrderType::Stop { stop_price: price }
|
||||
}
|
||||
"stop_limit" => {
|
||||
let stop = stop_price.ok_or_else(|| Error::from_reason("Stop price required"))?;
|
||||
let limit = limit_price.ok_or_else(|| Error::from_reason("Limit price required"))?;
|
||||
crate::OrderType::StopLimit { stop_price: stop, limit_price: limit }
|
||||
}
|
||||
_ => return Err(Error::from_reason("Invalid order type")),
|
||||
};
|
||||
|
||||
let order = crate::Order {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
symbol,
|
||||
side,
|
||||
quantity,
|
||||
order_type,
|
||||
time_in_force: crate::TimeInForce::Day,
|
||||
};
|
||||
|
||||
let result = self.core.execution_handler
|
||||
.write()
|
||||
.execute_order(order)
|
||||
.await
|
||||
.map_err(|e| Error::from_reason(e))?;
|
||||
|
||||
Ok(result.order_id)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn cancel_order(&self, order_id: String) -> Result<()> {
|
||||
// Cancel order implementation
|
||||
todo!("Cancel order implementation")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_pending_orders(&self) -> Result<Vec<JsObject>> {
|
||||
// Get pending orders
|
||||
todo!("Get pending orders implementation")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_order_history(&self) -> Result<Vec<JsObject>> {
|
||||
// Get order history
|
||||
todo!("Get order history implementation")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
use napi_derive::napi;
|
||||
use napi::bindgen_prelude::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[napi]
|
||||
pub struct PositionsAPI {
|
||||
core: Arc<crate::TradingCore>,
|
||||
}
|
||||
|
||||
impl PositionsAPI {
|
||||
pub fn new(core: Arc<crate::TradingCore>) -> Self {
|
||||
Self { core }
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl PositionsAPI {
|
||||
#[napi]
|
||||
pub fn get_position(&self, symbol: String) -> Result<JsObject> {
|
||||
let position = self.core.position_tracker
|
||||
.get_position(&symbol)
|
||||
.ok_or_else(|| Error::from_reason("No position found"))?;
|
||||
|
||||
// Convert position to JsObject
|
||||
todo!("Convert position to JsObject")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_all_positions(&self) -> Result<Vec<JsObject>> {
|
||||
let positions = self.core.position_tracker.get_all_positions();
|
||||
|
||||
// Convert positions to JsObjects
|
||||
todo!("Convert positions to JsObjects")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_closed_trades(&self) -> Result<Vec<JsObject>> {
|
||||
let trades = self.core.position_tracker.get_closed_trades();
|
||||
|
||||
// Convert trades to JsObjects
|
||||
todo!("Convert trades to JsObjects")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_pnl(&self, symbol: Option<String>) -> Result<f64> {
|
||||
if let Some(sym) = symbol {
|
||||
// Get P&L for specific symbol
|
||||
let position = self.core.position_tracker
|
||||
.get_position(&sym)
|
||||
.ok_or_else(|| Error::from_reason("No position found"))?;
|
||||
Ok(position.realized_pnl + position.unrealized_pnl)
|
||||
} else {
|
||||
// Get total P&L
|
||||
let positions = self.core.position_tracker.get_all_positions();
|
||||
let total_pnl = positions.into_iter()
|
||||
.map(|p| p.realized_pnl + p.unrealized_pnl)
|
||||
.sum();
|
||||
Ok(total_pnl)
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_portfolio_value(&self) -> Result<f64> {
|
||||
// Calculate total portfolio value
|
||||
todo!("Calculate portfolio value")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
use napi_derive::napi;
|
||||
use napi::bindgen_prelude::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[napi]
|
||||
pub struct StrategiesAPI {
|
||||
core: Arc<crate::TradingCore>,
|
||||
}
|
||||
|
||||
impl StrategiesAPI {
|
||||
pub fn new(core: Arc<crate::TradingCore>) -> Self {
|
||||
Self { core }
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl StrategiesAPI {
|
||||
#[napi]
|
||||
pub async fn add_strategy(
|
||||
&self,
|
||||
name: String,
|
||||
strategy_type: String,
|
||||
parameters: String,
|
||||
) -> Result<String> {
|
||||
// Parse parameters from JSON string
|
||||
let params: serde_json::Value = serde_json::from_str(¶meters)
|
||||
.map_err(|e| Error::from_reason(format!("Invalid parameters: {}", e)))?;
|
||||
|
||||
// Create strategy based on type
|
||||
let strategy = match strategy_type.as_str() {
|
||||
"sma_crossover" => {
|
||||
// Create SMA crossover strategy
|
||||
todo!("Create SMA strategy")
|
||||
}
|
||||
"momentum" => {
|
||||
// Create momentum strategy
|
||||
todo!("Create momentum strategy")
|
||||
}
|
||||
_ => return Err(Error::from_reason("Unknown strategy type")),
|
||||
};
|
||||
|
||||
// Add strategy to core
|
||||
todo!("Add strategy to core")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn remove_strategy(&self, strategy_id: String) -> Result<()> {
|
||||
// Remove strategy
|
||||
todo!("Remove strategy implementation")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_strategies(&self) -> Result<Vec<JsObject>> {
|
||||
// Get all active strategies
|
||||
todo!("Get strategies implementation")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn update_strategy_parameters(
|
||||
&self,
|
||||
strategy_id: String,
|
||||
parameters: String,
|
||||
) -> Result<()> {
|
||||
// Parse and update parameters
|
||||
let params: serde_json::Value = serde_json::from_str(¶meters)
|
||||
.map_err(|e| Error::from_reason(format!("Invalid parameters: {}", e)))?;
|
||||
|
||||
todo!("Update strategy parameters")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_strategy_performance(&self, strategy_id: String) -> Result<JsObject> {
|
||||
// Get performance metrics for strategy
|
||||
todo!("Get strategy performance")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
use napi_derive::napi;
|
||||
use napi::bindgen_prelude::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[napi]
|
||||
pub struct SystemAPI {
|
||||
core: Arc<crate::TradingCore>,
|
||||
}
|
||||
|
||||
impl SystemAPI {
|
||||
pub fn new(core: Arc<crate::TradingCore>) -> Self {
|
||||
Self { core }
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl SystemAPI {
|
||||
#[napi]
|
||||
pub async fn start(&self) -> Result<()> {
|
||||
// Start the trading system
|
||||
match self.core.get_mode() {
|
||||
crate::TradingMode::Backtest { .. } => {
|
||||
// Start backtest processing
|
||||
todo!("Start backtest")
|
||||
}
|
||||
crate::TradingMode::Paper { .. } => {
|
||||
// Start paper trading
|
||||
todo!("Start paper trading")
|
||||
}
|
||||
crate::TradingMode::Live { .. } => {
|
||||
// Start live trading
|
||||
todo!("Start live trading")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
// Stop the trading system
|
||||
todo!("Stop trading system")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_mode(&self) -> String {
|
||||
match self.core.get_mode() {
|
||||
crate::TradingMode::Backtest { .. } => "backtest".to_string(),
|
||||
crate::TradingMode::Paper { .. } => "paper".to_string(),
|
||||
crate::TradingMode::Live { .. } => "live".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_current_time(&self) -> String {
|
||||
self.core.get_time().to_rfc3339()
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn set_risk_limits(&self, limits: String) -> Result<()> {
|
||||
// Parse and set risk limits
|
||||
let limits: serde_json::Value = serde_json::from_str(&limits)
|
||||
.map_err(|e| Error::from_reason(format!("Invalid limits: {}", e)))?;
|
||||
|
||||
todo!("Set risk limits")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_risk_metrics(&self) -> Result<JsObject> {
|
||||
// Get current risk metrics
|
||||
todo!("Get risk metrics")
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn get_analytics(&self) -> Result<JsObject> {
|
||||
// Get trading analytics
|
||||
todo!("Get analytics")
|
||||
}
|
||||
}
|
||||
|
|
@ -1,669 +0,0 @@
|
|||
use chrono::{DateTime, Utc, Datelike};
|
||||
use std::collections::HashMap;
|
||||
use super::results::*;
|
||||
use super::{BacktestConfig, CompletedTrade};
|
||||
use super::trade_tracker::CompletedTrade as TrackedTrade;
|
||||
use crate::{Position, Side};
|
||||
|
||||
pub struct MetricsCalculator {
|
||||
config: BacktestConfig,
|
||||
equity_curve: Vec<(DateTime<Utc>, f64)>,
|
||||
trades: Vec<TrackedTrade>,
|
||||
fills: Vec<CompletedTrade>,
|
||||
positions: HashMap<String, Position>,
|
||||
}
|
||||
|
||||
impl MetricsCalculator {
|
||||
pub fn new(
|
||||
config: BacktestConfig,
|
||||
equity_curve: Vec<(DateTime<Utc>, f64)>,
|
||||
trades: Vec<TrackedTrade>,
|
||||
fills: Vec<CompletedTrade>,
|
||||
positions: HashMap<String, Position>,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
equity_curve,
|
||||
trades,
|
||||
fills,
|
||||
positions,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn calculate_all_metrics(&self) -> BacktestResult {
|
||||
let start_time = Utc::now();
|
||||
let backtest_id = format!("rust-{}", start_time.timestamp_millis());
|
||||
|
||||
// Calculate comprehensive metrics
|
||||
let metrics = self.calculate_metrics();
|
||||
|
||||
// Convert equity curve
|
||||
let equity_points: Vec<EquityPoint> = self.equity_curve.iter()
|
||||
.map(|(dt, value)| EquityPoint {
|
||||
timestamp: dt.timestamp_millis(),
|
||||
value: *value,
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Calculate drawdown curve
|
||||
let drawdown_curve = self.calculate_drawdown_curve();
|
||||
|
||||
// Calculate returns
|
||||
let daily_returns = self.calculate_daily_returns();
|
||||
let cumulative_returns = self.calculate_cumulative_returns();
|
||||
|
||||
// Convert trades to UI format
|
||||
let trades = self.convert_fills_to_trades();
|
||||
let open_trades = self.get_open_trades();
|
||||
|
||||
// Period analysis
|
||||
let monthly_returns = self.calculate_period_returns("monthly");
|
||||
let yearly_returns = self.calculate_period_returns("yearly");
|
||||
|
||||
// Symbol analysis
|
||||
let symbol_analysis = self.calculate_symbol_analysis();
|
||||
|
||||
// Drawdown periods
|
||||
let drawdown_periods = self.analyze_drawdown_periods();
|
||||
|
||||
// Exposure analysis
|
||||
let exposure_analysis = self.calculate_exposure_analysis();
|
||||
|
||||
// Position history
|
||||
let position_history = self.calculate_position_history();
|
||||
|
||||
// Trade signals (extracted from trades)
|
||||
let trade_signals = self.extract_trade_signals();
|
||||
|
||||
BacktestResult {
|
||||
backtest_id,
|
||||
status: "completed".to_string(),
|
||||
started_at: self.config.start_time.to_rfc3339(),
|
||||
completed_at: Utc::now().to_rfc3339(),
|
||||
execution_time_ms: (Utc::now() - start_time).num_milliseconds() as u64,
|
||||
config: self.config.clone(),
|
||||
metrics,
|
||||
equity_curve: equity_points,
|
||||
drawdown_curve,
|
||||
daily_returns,
|
||||
cumulative_returns,
|
||||
trades,
|
||||
open_trades,
|
||||
trade_signals,
|
||||
positions: self.positions.clone(),
|
||||
position_history,
|
||||
monthly_returns,
|
||||
yearly_returns,
|
||||
symbol_analysis,
|
||||
drawdown_periods,
|
||||
exposure_analysis,
|
||||
ohlc_data: HashMap::new(), // Will be filled by orchestrator
|
||||
error: None,
|
||||
warnings: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_metrics(&self) -> BacktestMetrics {
|
||||
let initial_capital = self.config.initial_capital;
|
||||
let final_capital = self.equity_curve.last().map(|(_, v)| *v).unwrap_or(initial_capital);
|
||||
|
||||
// Core performance
|
||||
let total_return = final_capital - initial_capital;
|
||||
let total_return_pct = (total_return / initial_capital) * 100.0;
|
||||
let days = (self.config.end_time - self.config.start_time).num_days() as f64;
|
||||
let years = days / 365.25;
|
||||
let annualized_return = if years > 0.0 {
|
||||
((final_capital / initial_capital).powf(1.0 / years) - 1.0) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Trade statistics
|
||||
let total_trades = self.trades.len();
|
||||
let winning_trades = self.trades.iter().filter(|t| t.pnl > 0.0).count();
|
||||
let losing_trades = self.trades.iter().filter(|t| t.pnl < 0.0).count();
|
||||
let breakeven_trades = self.trades.iter().filter(|t| t.pnl == 0.0).count();
|
||||
|
||||
let win_rate = if total_trades > 0 {
|
||||
(winning_trades as f64 / total_trades as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let loss_rate = if total_trades > 0 {
|
||||
(losing_trades as f64 / total_trades as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// PnL calculations
|
||||
let total_pnl = self.trades.iter().map(|t| t.pnl).sum::<f64>();
|
||||
let total_commission = self.trades.iter().map(|t| t.commission).sum::<f64>();
|
||||
let net_pnl = total_pnl - total_commission;
|
||||
|
||||
let wins: Vec<f64> = self.trades.iter().filter(|t| t.pnl > 0.0).map(|t| t.pnl).collect();
|
||||
let losses: Vec<f64> = self.trades.iter().filter(|t| t.pnl < 0.0).map(|t| t.pnl).collect();
|
||||
|
||||
let avg_win = if !wins.is_empty() {
|
||||
wins.iter().sum::<f64>() / wins.len() as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let avg_loss = if !losses.is_empty() {
|
||||
losses.iter().sum::<f64>() / losses.len() as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let largest_win = wins.iter().cloned().fold(0.0, f64::max);
|
||||
let largest_loss = losses.iter().cloned().fold(0.0, f64::min);
|
||||
|
||||
let avg_trade_pnl = if total_trades > 0 {
|
||||
total_pnl / total_trades as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Risk metrics
|
||||
let returns = self.calculate_returns_series();
|
||||
let volatility = self.calculate_volatility(&returns);
|
||||
let sharpe_ratio = self.calculate_sharpe_ratio(&returns, volatility);
|
||||
let sortino_ratio = self.calculate_sortino_ratio(&returns);
|
||||
let (max_drawdown, max_drawdown_pct, max_dd_duration) = self.calculate_max_drawdown();
|
||||
|
||||
let calmar_ratio = if max_drawdown_pct != 0.0 {
|
||||
annualized_return / max_drawdown_pct.abs()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Value at Risk
|
||||
let (var_95, cvar_95) = self.calculate_var_cvar(&returns, 0.95);
|
||||
|
||||
// Profit factor
|
||||
let gross_profit = wins.iter().sum::<f64>();
|
||||
let gross_loss = losses.iter().map(|l| l.abs()).sum::<f64>();
|
||||
let profit_factor = if gross_loss > 0.0 {
|
||||
gross_profit / gross_loss
|
||||
} else if gross_profit > 0.0 {
|
||||
f64::INFINITY
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Expectancy
|
||||
let expectancy = avg_win * (win_rate / 100.0) - avg_loss.abs() * (loss_rate / 100.0);
|
||||
let expectancy_ratio = if avg_loss != 0.0 {
|
||||
expectancy / avg_loss.abs()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Position statistics
|
||||
let avg_trade_duration_hours = if total_trades > 0 {
|
||||
self.trades.iter()
|
||||
.map(|t| t.duration_seconds as f64 / 3600.0)
|
||||
.sum::<f64>() / total_trades as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let total_long_trades = self.trades.iter().filter(|t| matches!(t.side, Side::Buy)).count();
|
||||
let total_short_trades = self.trades.iter().filter(|t| matches!(t.side, Side::Sell)).count();
|
||||
|
||||
let long_wins = self.trades.iter()
|
||||
.filter(|t| matches!(t.side, Side::Buy) && t.pnl > 0.0)
|
||||
.count();
|
||||
let short_wins = self.trades.iter()
|
||||
.filter(|t| matches!(t.side, Side::Sell) && t.pnl > 0.0)
|
||||
.count();
|
||||
|
||||
let long_win_rate = if total_long_trades > 0 {
|
||||
(long_wins as f64 / total_long_trades as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let short_win_rate = if total_short_trades > 0 {
|
||||
(short_wins as f64 / total_short_trades as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Trading activity
|
||||
let total_volume_traded = self.trades.iter()
|
||||
.map(|t| t.quantity * t.entry_price + t.quantity * t.exit_price)
|
||||
.sum::<f64>();
|
||||
|
||||
let commission_pct_of_pnl = if total_pnl != 0.0 {
|
||||
(total_commission / total_pnl.abs()) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Calculate additional metrics
|
||||
let downside_deviation = self.calculate_downside_deviation(&returns);
|
||||
let win_loss_ratio = if avg_loss != 0.0 {
|
||||
avg_win / avg_loss.abs()
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let kelly_criterion = if win_loss_ratio > 0.0 {
|
||||
(win_rate / 100.0) - ((1.0 - win_rate / 100.0) / win_loss_ratio)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
// Streaks
|
||||
let (max_wins, max_losses, current_streak) = self.calculate_streaks();
|
||||
|
||||
BacktestMetrics {
|
||||
// Core Performance
|
||||
total_return,
|
||||
total_return_pct,
|
||||
annualized_return,
|
||||
total_pnl,
|
||||
net_pnl,
|
||||
|
||||
// Risk Metrics
|
||||
sharpe_ratio,
|
||||
sortino_ratio,
|
||||
calmar_ratio,
|
||||
max_drawdown,
|
||||
max_drawdown_pct,
|
||||
max_drawdown_duration_days: max_dd_duration,
|
||||
volatility,
|
||||
downside_deviation,
|
||||
var_95,
|
||||
cvar_95,
|
||||
|
||||
// Trade Statistics
|
||||
total_trades,
|
||||
winning_trades,
|
||||
losing_trades,
|
||||
breakeven_trades,
|
||||
win_rate,
|
||||
loss_rate,
|
||||
avg_win,
|
||||
avg_loss,
|
||||
largest_win,
|
||||
largest_loss,
|
||||
avg_trade_pnl,
|
||||
avg_trade_duration_hours,
|
||||
profit_factor,
|
||||
expectancy,
|
||||
expectancy_ratio,
|
||||
|
||||
// Position Statistics
|
||||
avg_position_size: 0.0, // TODO: Calculate from position history
|
||||
max_position_size: 0.0,
|
||||
avg_positions_held: 0.0,
|
||||
max_concurrent_positions: 0,
|
||||
total_long_trades,
|
||||
total_short_trades,
|
||||
long_win_rate,
|
||||
short_win_rate,
|
||||
|
||||
// Trading Activity
|
||||
total_volume_traded,
|
||||
total_commission_paid: total_commission,
|
||||
commission_pct_of_pnl,
|
||||
avg_daily_trades: 0.0, // TODO: Calculate
|
||||
max_daily_trades: 0,
|
||||
trading_days: 0,
|
||||
exposure_time_pct: 0.0,
|
||||
|
||||
// Efficiency Metrics
|
||||
return_over_max_dd: if max_drawdown != 0.0 {
|
||||
total_return / max_drawdown.abs()
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
win_loss_ratio,
|
||||
kelly_criterion,
|
||||
ulcer_index: 0.0, // TODO: Calculate
|
||||
serenity_ratio: 0.0,
|
||||
lake_ratio: 0.0,
|
||||
|
||||
// Monthly/Period Analysis
|
||||
best_month_return: 0.0, // TODO: Calculate from monthly returns
|
||||
worst_month_return: 0.0,
|
||||
positive_months: 0,
|
||||
negative_months: 0,
|
||||
monthly_win_rate: 0.0,
|
||||
avg_monthly_return: 0.0,
|
||||
|
||||
// Streak Analysis
|
||||
max_consecutive_wins: max_wins,
|
||||
max_consecutive_losses: max_losses,
|
||||
current_streak,
|
||||
avg_winning_streak: 0.0, // TODO: Calculate
|
||||
avg_losing_streak: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_returns_series(&self) -> Vec<f64> {
|
||||
let mut returns = Vec::new();
|
||||
for i in 1..self.equity_curve.len() {
|
||||
let prev_value = self.equity_curve[i - 1].1;
|
||||
let curr_value = self.equity_curve[i].1;
|
||||
if prev_value > 0.0 {
|
||||
returns.push((curr_value - prev_value) / prev_value);
|
||||
}
|
||||
}
|
||||
returns
|
||||
}
|
||||
|
||||
fn calculate_volatility(&self, returns: &[f64]) -> f64 {
|
||||
if returns.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let mean = returns.iter().sum::<f64>() / returns.len() as f64;
|
||||
let variance = returns.iter()
|
||||
.map(|r| (r - mean).powi(2))
|
||||
.sum::<f64>() / returns.len() as f64;
|
||||
|
||||
// Annualize the volatility
|
||||
variance.sqrt() * (252.0_f64).sqrt()
|
||||
}
|
||||
|
||||
fn calculate_sharpe_ratio(&self, returns: &[f64], volatility: f64) -> f64 {
|
||||
if volatility == 0.0 || returns.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let mean_return = returns.iter().sum::<f64>() / returns.len() as f64;
|
||||
let annualized_return = mean_return * 252.0;
|
||||
let risk_free_rate = 0.02; // 2% annual risk-free rate
|
||||
|
||||
(annualized_return - risk_free_rate) / volatility
|
||||
}
|
||||
|
||||
fn calculate_sortino_ratio(&self, returns: &[f64]) -> f64 {
|
||||
if returns.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let mean_return = returns.iter().sum::<f64>() / returns.len() as f64;
|
||||
let downside_deviation = self.calculate_downside_deviation(returns);
|
||||
|
||||
if downside_deviation == 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let annualized_return = mean_return * 252.0;
|
||||
let risk_free_rate = 0.02;
|
||||
|
||||
(annualized_return - risk_free_rate) / downside_deviation
|
||||
}
|
||||
|
||||
fn calculate_downside_deviation(&self, returns: &[f64]) -> f64 {
|
||||
let negative_returns: Vec<f64> = returns.iter()
|
||||
.filter(|&&r| r < 0.0)
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if negative_returns.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let mean = negative_returns.iter().sum::<f64>() / negative_returns.len() as f64;
|
||||
let variance = negative_returns.iter()
|
||||
.map(|r| (r - mean).powi(2))
|
||||
.sum::<f64>() / negative_returns.len() as f64;
|
||||
|
||||
variance.sqrt() * (252.0_f64).sqrt()
|
||||
}
|
||||
|
||||
fn calculate_max_drawdown(&self) -> (f64, f64, i64) {
|
||||
let mut max_drawdown = 0.0;
|
||||
let mut max_drawdown_pct = 0.0;
|
||||
let mut max_duration = 0i64;
|
||||
let mut peak = self.config.initial_capital;
|
||||
let mut peak_date = self.config.start_time;
|
||||
|
||||
for (date, value) in &self.equity_curve {
|
||||
if *value > peak {
|
||||
peak = *value;
|
||||
peak_date = *date;
|
||||
}
|
||||
|
||||
let drawdown = peak - value;
|
||||
let drawdown_pct = (drawdown / peak) * 100.0;
|
||||
|
||||
if drawdown > max_drawdown {
|
||||
max_drawdown = drawdown;
|
||||
max_drawdown_pct = drawdown_pct;
|
||||
}
|
||||
|
||||
if drawdown > 0.0 {
|
||||
let duration = (*date - peak_date).num_days();
|
||||
if duration > max_duration {
|
||||
max_duration = duration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(max_drawdown, max_drawdown_pct, max_duration)
|
||||
}
|
||||
|
||||
fn calculate_var_cvar(&self, returns: &[f64], confidence: f64) -> (f64, f64) {
|
||||
if returns.is_empty() {
|
||||
return (0.0, 0.0);
|
||||
}
|
||||
|
||||
let mut sorted_returns = returns.to_vec();
|
||||
sorted_returns.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
|
||||
let index = ((1.0 - confidence) * sorted_returns.len() as f64) as usize;
|
||||
let var = sorted_returns[index];
|
||||
|
||||
let cvar = sorted_returns[..=index].iter().sum::<f64>() / (index + 1) as f64;
|
||||
|
||||
(var * 100.0, cvar * 100.0)
|
||||
}
|
||||
|
||||
fn calculate_streaks(&self) -> (usize, usize, i32) {
|
||||
let mut max_wins = 0;
|
||||
let mut max_losses = 0;
|
||||
let mut current_streak = 0;
|
||||
let mut current_wins = 0;
|
||||
let mut current_losses = 0;
|
||||
|
||||
for trade in &self.trades {
|
||||
if trade.pnl > 0.0 {
|
||||
current_wins += 1;
|
||||
current_losses = 0;
|
||||
if current_wins > max_wins {
|
||||
max_wins = current_wins;
|
||||
}
|
||||
current_streak = current_wins as i32;
|
||||
} else if trade.pnl < 0.0 {
|
||||
current_losses += 1;
|
||||
current_wins = 0;
|
||||
if current_losses > max_losses {
|
||||
max_losses = current_losses;
|
||||
}
|
||||
current_streak = -(current_losses as i32);
|
||||
}
|
||||
}
|
||||
|
||||
(max_wins, max_losses, current_streak)
|
||||
}
|
||||
|
||||
fn calculate_drawdown_curve(&self) -> Vec<EquityPoint> {
|
||||
let mut drawdown_curve = Vec::new();
|
||||
let mut peak = self.config.initial_capital;
|
||||
|
||||
for (date, value) in &self.equity_curve {
|
||||
if *value > peak {
|
||||
peak = *value;
|
||||
}
|
||||
let drawdown_pct = ((peak - value) / peak) * 100.0;
|
||||
drawdown_curve.push(EquityPoint {
|
||||
timestamp: date.timestamp_millis(),
|
||||
value: -drawdown_pct, // Negative for visualization
|
||||
});
|
||||
}
|
||||
|
||||
drawdown_curve
|
||||
}
|
||||
|
||||
fn calculate_daily_returns(&self) -> Vec<DailyReturn> {
|
||||
let mut daily_returns = Vec::new();
|
||||
|
||||
for i in 1..self.equity_curve.len() {
|
||||
let prev = &self.equity_curve[i - 1];
|
||||
let curr = &self.equity_curve[i];
|
||||
|
||||
// Only include if it's a new day
|
||||
if prev.0.date() != curr.0.date() {
|
||||
let return_pct = ((curr.1 - prev.1) / prev.1) * 100.0;
|
||||
daily_returns.push(DailyReturn {
|
||||
date: curr.0.format("%Y-%m-%d").to_string(),
|
||||
value: return_pct,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
daily_returns
|
||||
}
|
||||
|
||||
fn calculate_cumulative_returns(&self) -> Vec<EquityPoint> {
|
||||
let initial = self.config.initial_capital;
|
||||
self.equity_curve.iter()
|
||||
.map(|(date, value)| EquityPoint {
|
||||
timestamp: date.timestamp_millis(),
|
||||
value: ((value - initial) / initial) * 100.0,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn convert_fills_to_trades(&self) -> Vec<Trade> {
|
||||
self.fills.iter()
|
||||
.enumerate()
|
||||
.map(|(i, fill)| Trade {
|
||||
id: format!("trade-{}", i),
|
||||
timestamp: fill.timestamp,
|
||||
symbol: fill.symbol.clone(),
|
||||
side: match fill.side {
|
||||
Side::Buy => "buy".to_string(),
|
||||
Side::Sell => "sell".to_string(),
|
||||
},
|
||||
quantity: fill.quantity,
|
||||
price: fill.price,
|
||||
commission: fill.commission,
|
||||
pnl: None, // Individual fills don't have PnL
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn get_open_trades(&self) -> Vec<Trade> {
|
||||
// TODO: Implement based on position tracker
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn calculate_period_returns(&self, period: &str) -> Vec<PeriodReturn> {
|
||||
// TODO: Implement monthly/yearly return calculations
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn calculate_symbol_analysis(&self) -> HashMap<String, SymbolAnalysis> {
|
||||
let mut analysis: HashMap<String, SymbolAnalysis> = HashMap::new();
|
||||
|
||||
// Group trades by symbol
|
||||
for trade in &self.trades {
|
||||
let entry = analysis.entry(trade.symbol.clone()).or_insert(SymbolAnalysis {
|
||||
symbol: trade.symbol.clone(),
|
||||
total_trades: 0,
|
||||
winning_trades: 0,
|
||||
losing_trades: 0,
|
||||
total_pnl: 0.0,
|
||||
win_rate: 0.0,
|
||||
avg_win: 0.0,
|
||||
avg_loss: 0.0,
|
||||
profit_factor: 0.0,
|
||||
total_volume: 0.0,
|
||||
avg_position_size: 0.0,
|
||||
exposure_time_pct: 0.0,
|
||||
});
|
||||
|
||||
entry.total_trades += 1;
|
||||
entry.total_pnl += trade.pnl;
|
||||
entry.total_volume += trade.quantity * (trade.entry_price + trade.exit_price);
|
||||
|
||||
if trade.pnl > 0.0 {
|
||||
entry.winning_trades += 1;
|
||||
} else if trade.pnl < 0.0 {
|
||||
entry.losing_trades += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate derived metrics
|
||||
for (_, entry) in analysis.iter_mut() {
|
||||
if entry.total_trades > 0 {
|
||||
entry.win_rate = (entry.winning_trades as f64 / entry.total_trades as f64) * 100.0;
|
||||
entry.avg_position_size = entry.total_volume / (entry.total_trades as f64 * 2.0);
|
||||
}
|
||||
|
||||
// Calculate avg win/loss
|
||||
let wins: Vec<f64> = self.trades.iter()
|
||||
.filter(|t| t.symbol == entry.symbol && t.pnl > 0.0)
|
||||
.map(|t| t.pnl)
|
||||
.collect();
|
||||
let losses: Vec<f64> = self.trades.iter()
|
||||
.filter(|t| t.symbol == entry.symbol && t.pnl < 0.0)
|
||||
.map(|t| t.pnl)
|
||||
.collect();
|
||||
|
||||
if !wins.is_empty() {
|
||||
entry.avg_win = wins.iter().sum::<f64>() / wins.len() as f64;
|
||||
}
|
||||
if !losses.is_empty() {
|
||||
entry.avg_loss = losses.iter().sum::<f64>() / losses.len() as f64;
|
||||
}
|
||||
|
||||
// Profit factor
|
||||
let gross_profit = wins.iter().sum::<f64>();
|
||||
let gross_loss = losses.iter().map(|l| l.abs()).sum::<f64>();
|
||||
if gross_loss > 0.0 {
|
||||
entry.profit_factor = gross_profit / gross_loss;
|
||||
} else if gross_profit > 0.0 {
|
||||
entry.profit_factor = f64::INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
analysis
|
||||
}
|
||||
|
||||
fn analyze_drawdown_periods(&self) -> Vec<DrawdownPeriod> {
|
||||
// TODO: Implement comprehensive drawdown period analysis
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn calculate_exposure_analysis(&self) -> ExposureAnalysis {
|
||||
// TODO: Implement exposure analysis
|
||||
ExposureAnalysis {
|
||||
avg_gross_exposure: 0.0,
|
||||
avg_net_exposure: 0.0,
|
||||
max_gross_exposure: 0.0,
|
||||
max_net_exposure: 0.0,
|
||||
time_in_market_pct: 0.0,
|
||||
long_exposure_pct: 0.0,
|
||||
short_exposure_pct: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_position_history(&self) -> Vec<PositionSnapshot> {
|
||||
// TODO: Implement position history tracking
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn extract_trade_signals(&self) -> Vec<TradeSignal> {
|
||||
// TODO: Extract signals from strategy execution
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,266 +0,0 @@
|
|||
use chrono::{DateTime, Utc};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::collections::HashMap;
|
||||
use crate::Position;
|
||||
use super::{BacktestConfig, CompletedTrade};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BacktestMetrics {
|
||||
// Core Performance Metrics
|
||||
pub total_return: f64,
|
||||
pub total_return_pct: f64,
|
||||
pub annualized_return: f64,
|
||||
pub total_pnl: f64,
|
||||
pub net_pnl: f64, // After commissions
|
||||
|
||||
// Risk Metrics
|
||||
pub sharpe_ratio: f64,
|
||||
pub sortino_ratio: f64,
|
||||
pub calmar_ratio: f64,
|
||||
pub max_drawdown: f64,
|
||||
pub max_drawdown_pct: f64,
|
||||
pub max_drawdown_duration_days: i64,
|
||||
pub volatility: f64,
|
||||
pub downside_deviation: f64,
|
||||
pub var_95: f64, // Value at Risk 95%
|
||||
pub cvar_95: f64, // Conditional VaR 95%
|
||||
|
||||
// Trade Statistics
|
||||
pub total_trades: usize,
|
||||
pub winning_trades: usize,
|
||||
pub losing_trades: usize,
|
||||
pub breakeven_trades: usize,
|
||||
pub win_rate: f64,
|
||||
pub loss_rate: f64,
|
||||
pub avg_win: f64,
|
||||
pub avg_loss: f64,
|
||||
pub largest_win: f64,
|
||||
pub largest_loss: f64,
|
||||
pub avg_trade_pnl: f64,
|
||||
pub avg_trade_duration_hours: f64,
|
||||
pub profit_factor: f64,
|
||||
pub expectancy: f64,
|
||||
pub expectancy_ratio: f64,
|
||||
|
||||
// Position Statistics
|
||||
pub avg_position_size: f64,
|
||||
pub max_position_size: f64,
|
||||
pub avg_positions_held: f64,
|
||||
pub max_concurrent_positions: usize,
|
||||
pub total_long_trades: usize,
|
||||
pub total_short_trades: usize,
|
||||
pub long_win_rate: f64,
|
||||
pub short_win_rate: f64,
|
||||
|
||||
// Trading Activity
|
||||
pub total_volume_traded: f64,
|
||||
pub total_commission_paid: f64,
|
||||
pub commission_pct_of_pnl: f64,
|
||||
pub avg_daily_trades: f64,
|
||||
pub max_daily_trades: usize,
|
||||
pub trading_days: usize,
|
||||
pub exposure_time_pct: f64,
|
||||
|
||||
// Efficiency Metrics
|
||||
pub return_over_max_dd: f64,
|
||||
pub win_loss_ratio: f64,
|
||||
pub kelly_criterion: f64,
|
||||
pub ulcer_index: f64,
|
||||
pub serenity_ratio: f64,
|
||||
pub lake_ratio: f64,
|
||||
|
||||
// Monthly/Period Analysis
|
||||
pub best_month_return: f64,
|
||||
pub worst_month_return: f64,
|
||||
pub positive_months: usize,
|
||||
pub negative_months: usize,
|
||||
pub monthly_win_rate: f64,
|
||||
pub avg_monthly_return: f64,
|
||||
|
||||
// Streak Analysis
|
||||
pub max_consecutive_wins: usize,
|
||||
pub max_consecutive_losses: usize,
|
||||
pub current_streak: i32, // Positive for wins, negative for losses
|
||||
pub avg_winning_streak: f64,
|
||||
pub avg_losing_streak: f64,
|
||||
}
|
||||
|
||||
// Trade structure that matches web app expectations
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Trade {
|
||||
pub id: String,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub symbol: String,
|
||||
pub side: String, // "buy" or "sell"
|
||||
pub quantity: f64,
|
||||
pub price: f64,
|
||||
pub commission: f64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pnl: Option<f64>,
|
||||
}
|
||||
|
||||
// Equity curve point
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EquityPoint {
|
||||
pub timestamp: i64, // milliseconds since epoch
|
||||
pub value: f64,
|
||||
}
|
||||
|
||||
// Daily return data
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DailyReturn {
|
||||
pub date: String,
|
||||
pub value: f64,
|
||||
}
|
||||
|
||||
// Performance data point for charts
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PerformanceDataPoint {
|
||||
pub timestamp: String,
|
||||
pub portfolio_value: f64,
|
||||
pub pnl: f64,
|
||||
pub drawdown: f64,
|
||||
}
|
||||
|
||||
// Period returns (monthly, weekly, etc)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PeriodReturn {
|
||||
pub period: String, // "2024-01", "2024-W01", etc
|
||||
pub start_date: String,
|
||||
pub end_date: String,
|
||||
pub return_pct: f64,
|
||||
pub pnl: f64,
|
||||
pub trades: usize,
|
||||
pub win_rate: f64,
|
||||
}
|
||||
|
||||
// Trade analysis by symbol
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SymbolAnalysis {
|
||||
pub symbol: String,
|
||||
pub total_trades: usize,
|
||||
pub winning_trades: usize,
|
||||
pub losing_trades: usize,
|
||||
pub total_pnl: f64,
|
||||
pub win_rate: f64,
|
||||
pub avg_win: f64,
|
||||
pub avg_loss: f64,
|
||||
pub profit_factor: f64,
|
||||
pub total_volume: f64,
|
||||
pub avg_position_size: f64,
|
||||
pub exposure_time_pct: f64,
|
||||
}
|
||||
|
||||
// Drawdown period information
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DrawdownPeriod {
|
||||
pub start_date: String,
|
||||
pub end_date: String,
|
||||
pub peak_value: f64,
|
||||
pub trough_value: f64,
|
||||
pub drawdown_pct: f64,
|
||||
pub recovery_date: Option<String>,
|
||||
pub duration_days: i64,
|
||||
pub recovery_days: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BacktestResult {
|
||||
// Metadata
|
||||
pub backtest_id: String,
|
||||
pub status: String,
|
||||
pub started_at: String,
|
||||
pub completed_at: String,
|
||||
pub execution_time_ms: u64,
|
||||
|
||||
// Configuration
|
||||
pub config: BacktestConfig,
|
||||
|
||||
// Core Metrics
|
||||
pub metrics: BacktestMetrics,
|
||||
|
||||
// Time Series Data
|
||||
pub equity_curve: Vec<EquityPoint>,
|
||||
pub drawdown_curve: Vec<EquityPoint>,
|
||||
pub daily_returns: Vec<DailyReturn>,
|
||||
pub cumulative_returns: Vec<EquityPoint>,
|
||||
|
||||
// Trade Data
|
||||
pub trades: Vec<Trade>,
|
||||
pub open_trades: Vec<Trade>,
|
||||
pub trade_signals: Vec<TradeSignal>,
|
||||
|
||||
// Position Data
|
||||
pub positions: HashMap<String, Position>,
|
||||
pub position_history: Vec<PositionSnapshot>,
|
||||
|
||||
// Analytics
|
||||
pub monthly_returns: Vec<PeriodReturn>,
|
||||
pub yearly_returns: Vec<PeriodReturn>,
|
||||
pub symbol_analysis: HashMap<String, SymbolAnalysis>,
|
||||
pub drawdown_periods: Vec<DrawdownPeriod>,
|
||||
pub exposure_analysis: ExposureAnalysis,
|
||||
|
||||
// Market Data
|
||||
pub ohlc_data: HashMap<String, Vec<serde_json::Value>>,
|
||||
|
||||
// Error Handling
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub warnings: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
// Trade signal for visualization
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TradeSignal {
|
||||
pub timestamp: String,
|
||||
pub symbol: String,
|
||||
pub action: String, // "buy", "sell", "hold"
|
||||
pub strength: f64,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
// Position snapshot for tracking
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PositionSnapshot {
|
||||
pub timestamp: String,
|
||||
pub positions: HashMap<String, PositionDetail>,
|
||||
pub total_value: f64,
|
||||
pub cash: f64,
|
||||
pub margin_used: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PositionDetail {
|
||||
pub symbol: String,
|
||||
pub quantity: f64,
|
||||
pub avg_price: f64,
|
||||
pub current_price: f64,
|
||||
pub market_value: f64,
|
||||
pub unrealized_pnl: f64,
|
||||
pub unrealized_pnl_pct: f64,
|
||||
}
|
||||
|
||||
// Exposure analysis
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExposureAnalysis {
|
||||
pub avg_gross_exposure: f64,
|
||||
pub avg_net_exposure: f64,
|
||||
pub max_gross_exposure: f64,
|
||||
pub max_net_exposure: f64,
|
||||
pub time_in_market_pct: f64,
|
||||
pub long_exposure_pct: f64,
|
||||
pub short_exposure_pct: f64,
|
||||
}
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
use chrono::{DateTime, Utc};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use super::{Order, Fill, MarketUpdate, Position};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum EventType {
|
||||
MarketData(MarketUpdate),
|
||||
OrderSubmitted(Order),
|
||||
OrderFilled { order_id: String, fill: Fill },
|
||||
OrderCancelled { order_id: String },
|
||||
OrderRejected { order_id: String, reason: String },
|
||||
PositionUpdate(Position),
|
||||
RiskAlert { message: String, severity: RiskSeverity },
|
||||
SystemStatus { status: SystemStatus },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum RiskSeverity {
|
||||
Info,
|
||||
Warning,
|
||||
Critical,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum SystemStatus {
|
||||
Starting,
|
||||
Running,
|
||||
Paused,
|
||||
Stopping,
|
||||
Error(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Event {
|
||||
pub id: String,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub event_type: EventType,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn new(event_type: EventType) -> Self {
|
||||
Self {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
timestamp: Utc::now(),
|
||||
event_type,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn market_data(data: MarketUpdate) -> Self {
|
||||
Self::new(EventType::MarketData(data))
|
||||
}
|
||||
|
||||
pub fn order_submitted(order: Order) -> Self {
|
||||
Self::new(EventType::OrderSubmitted(order))
|
||||
}
|
||||
|
||||
pub fn order_filled(order_id: String, fill: Fill) -> Self {
|
||||
Self::new(EventType::OrderFilled { order_id, fill })
|
||||
}
|
||||
}
|
||||
|
||||
pub trait EventHandler: Send + Sync {
|
||||
fn handle_event(&self, event: &Event);
|
||||
fn event_types(&self) -> Vec<String>; // Which event types this handler is interested in
|
||||
}
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
use chrono::{DateTime, Utc};
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Quote {
|
||||
pub bid: f64,
|
||||
pub ask: f64,
|
||||
pub bid_size: f64,
|
||||
pub ask_size: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Bar {
|
||||
pub open: f64,
|
||||
pub high: f64,
|
||||
pub low: f64,
|
||||
pub close: f64,
|
||||
pub volume: f64,
|
||||
pub vwap: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Trade {
|
||||
pub price: f64,
|
||||
pub size: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum MarketDataType {
|
||||
Quote(Quote),
|
||||
Bar(Bar),
|
||||
Trade(Trade),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MarketUpdate {
|
||||
pub symbol: String,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub data: MarketDataType,
|
||||
}
|
||||
|
||||
// Type alias for compatibility
|
||||
pub type MarketData = MarketUpdate;
|
||||
|
|
@ -1,10 +0,0 @@
|
|||
pub mod market;
|
||||
pub mod orders;
|
||||
pub mod positions;
|
||||
pub mod events;
|
||||
|
||||
// Re-export commonly used types
|
||||
pub use market::{Quote, Bar, Trade, MarketUpdate, MarketDataType};
|
||||
pub use orders::{Order, OrderType, OrderStatus, TimeInForce, Side, Fill};
|
||||
pub use positions::{Position, PositionUpdate};
|
||||
pub use events::{Event, EventType, EventHandler};
|
||||
|
|
@ -1,104 +0,0 @@
|
|||
use chrono::{DateTime, Utc};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Side {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
impl fmt::Display for Side {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Side::Buy => write!(f, "buy"),
|
||||
Side::Sell => write!(f, "sell"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum OrderType {
|
||||
Market,
|
||||
Limit,
|
||||
Stop,
|
||||
StopLimit,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum OrderStatus {
|
||||
Pending,
|
||||
Submitted,
|
||||
PartiallyFilled,
|
||||
Filled,
|
||||
Cancelled,
|
||||
Rejected,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum TimeInForce {
|
||||
Day,
|
||||
GTC, // Good Till Cancelled
|
||||
IOC, // Immediate or Cancel
|
||||
FOK, // Fill or Kill
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Order {
|
||||
pub id: String,
|
||||
pub symbol: String,
|
||||
pub side: Side,
|
||||
pub quantity: f64,
|
||||
pub order_type: OrderType,
|
||||
pub limit_price: Option<f64>,
|
||||
pub stop_price: Option<f64>,
|
||||
pub time_in_force: TimeInForce,
|
||||
pub status: OrderStatus,
|
||||
pub submitted_at: Option<DateTime<Utc>>,
|
||||
pub filled_quantity: f64,
|
||||
pub average_fill_price: Option<f64>,
|
||||
}
|
||||
|
||||
impl Order {
|
||||
pub fn new_market_order(symbol: String, side: Side, quantity: f64) -> Self {
|
||||
Self {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
symbol,
|
||||
side,
|
||||
quantity,
|
||||
order_type: OrderType::Market,
|
||||
limit_price: None,
|
||||
stop_price: None,
|
||||
time_in_force: TimeInForce::Day,
|
||||
status: OrderStatus::Pending,
|
||||
submitted_at: None,
|
||||
filled_quantity: 0.0,
|
||||
average_fill_price: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_limit_order(symbol: String, side: Side, quantity: f64, limit_price: f64) -> Self {
|
||||
Self {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
symbol,
|
||||
side,
|
||||
quantity,
|
||||
order_type: OrderType::Limit,
|
||||
limit_price: Some(limit_price),
|
||||
stop_price: None,
|
||||
time_in_force: TimeInForce::Day,
|
||||
status: OrderStatus::Pending,
|
||||
submitted_at: None,
|
||||
filled_quantity: 0.0,
|
||||
average_fill_price: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Fill {
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub price: f64,
|
||||
pub quantity: f64,
|
||||
pub commission: f64,
|
||||
}
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
use chrono::{DateTime, Utc};
|
||||
use serde::{Serialize, Deserialize};
|
||||
|
||||
#[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 last_update: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl Position {
|
||||
pub fn new(symbol: String) -> Self {
|
||||
Self {
|
||||
symbol,
|
||||
quantity: 0.0,
|
||||
average_price: 0.0,
|
||||
realized_pnl: 0.0,
|
||||
unrealized_pnl: 0.0,
|
||||
last_update: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_long(&self) -> bool {
|
||||
self.quantity > 0.0
|
||||
}
|
||||
|
||||
pub fn is_short(&self) -> bool {
|
||||
self.quantity < 0.0
|
||||
}
|
||||
|
||||
pub fn is_flat(&self) -> bool {
|
||||
self.quantity.abs() < f64::EPSILON
|
||||
}
|
||||
|
||||
pub fn market_value(&self, current_price: f64) -> f64 {
|
||||
self.quantity * current_price
|
||||
}
|
||||
|
||||
pub fn calculate_unrealized_pnl(&self, current_price: f64) -> f64 {
|
||||
if self.is_flat() {
|
||||
0.0
|
||||
} else if self.is_long() {
|
||||
(current_price - self.average_price) * self.quantity
|
||||
} else {
|
||||
(self.average_price - current_price) * self.quantity.abs()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PositionUpdate {
|
||||
pub symbol: String,
|
||||
pub previous_position: Option<Position>,
|
||||
pub resulting_position: Position,
|
||||
pub realized_pnl: f64,
|
||||
}
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
use std::sync::Arc;
|
||||
use parking_lot::RwLock;
|
||||
use std::collections::HashMap;
|
||||
use crate::domain::{Event, EventHandler};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
pub struct EventBus {
|
||||
handlers: Arc<RwLock<HashMap<String, Vec<Arc<dyn EventHandler>>>>>,
|
||||
sender: mpsc::UnboundedSender<Event>,
|
||||
}
|
||||
|
||||
impl EventBus {
|
||||
pub fn new() -> (Self, mpsc::UnboundedReceiver<Event>) {
|
||||
let (sender, receiver) = mpsc::unbounded_channel();
|
||||
let bus = Self {
|
||||
handlers: Arc::new(RwLock::new(HashMap::new())),
|
||||
sender,
|
||||
};
|
||||
(bus, receiver)
|
||||
}
|
||||
|
||||
pub fn subscribe(&self, event_type: String, handler: Arc<dyn EventHandler>) {
|
||||
let mut handlers = self.handlers.write();
|
||||
handlers.entry(event_type).or_insert_with(Vec::new).push(handler);
|
||||
}
|
||||
|
||||
pub fn publish(&self, event: Event) -> Result<(), String> {
|
||||
// Send to async handler
|
||||
self.sender.send(event.clone())
|
||||
.map_err(|_| "Failed to send event".to_string())?;
|
||||
|
||||
// Also handle synchronously for immediate handlers
|
||||
let event_type = match &event.event_type {
|
||||
crate::domain::EventType::MarketData(_) => "market_data",
|
||||
crate::domain::EventType::OrderSubmitted(_) => "order_submitted",
|
||||
crate::domain::EventType::OrderFilled { .. } => "order_filled",
|
||||
crate::domain::EventType::OrderCancelled { .. } => "order_cancelled",
|
||||
crate::domain::EventType::OrderRejected { .. } => "order_rejected",
|
||||
crate::domain::EventType::PositionUpdate(_) => "position_update",
|
||||
crate::domain::EventType::RiskAlert { .. } => "risk_alert",
|
||||
crate::domain::EventType::SystemStatus { .. } => "system_status",
|
||||
};
|
||||
|
||||
let handlers = self.handlers.read();
|
||||
if let Some(event_handlers) = handlers.get(event_type) {
|
||||
for handler in event_handlers {
|
||||
handler.handle_event(&event);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Simple event processor that runs in the background
|
||||
pub struct EventProcessor {
|
||||
receiver: mpsc::UnboundedReceiver<Event>,
|
||||
handlers: Arc<RwLock<HashMap<String, Vec<Arc<dyn EventHandler>>>>>,
|
||||
}
|
||||
|
||||
impl EventProcessor {
|
||||
pub fn new(
|
||||
receiver: mpsc::UnboundedReceiver<Event>,
|
||||
handlers: Arc<RwLock<HashMap<String, Vec<Arc<dyn EventHandler>>>>>,
|
||||
) -> Self {
|
||||
Self { receiver, handlers }
|
||||
}
|
||||
|
||||
pub async fn run(mut self) {
|
||||
while let Some(event) = self.receiver.recv().await {
|
||||
// Process event asynchronously
|
||||
let event_type = match &event.event_type {
|
||||
crate::domain::EventType::MarketData(_) => "market_data",
|
||||
crate::domain::EventType::OrderSubmitted(_) => "order_submitted",
|
||||
crate::domain::EventType::OrderFilled { .. } => "order_filled",
|
||||
crate::domain::EventType::OrderCancelled { .. } => "order_cancelled",
|
||||
crate::domain::EventType::OrderRejected { .. } => "order_rejected",
|
||||
crate::domain::EventType::PositionUpdate(_) => "position_update",
|
||||
crate::domain::EventType::RiskAlert { .. } => "risk_alert",
|
||||
crate::domain::EventType::SystemStatus { .. } => "system_status",
|
||||
};
|
||||
|
||||
let handlers = self.handlers.read();
|
||||
if let Some(event_handlers) = handlers.get(event_type) {
|
||||
for handler in event_handlers {
|
||||
handler.handle_event(&event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
#![deny(clippy::all)]
|
||||
|
||||
// Existing modules
|
||||
// Canonical financial execution lives in financial/. The other modules retain
|
||||
// reviewed calculations and legacy API compatibility; see ../MIGRATION.md.
|
||||
pub mod core;
|
||||
pub mod adapters;
|
||||
pub mod orderbook;
|
||||
pub mod risk;
|
||||
pub mod positions;
|
||||
|
|
|
|||
|
|
@ -1,67 +0,0 @@
|
|||
#![deny(clippy::all)]
|
||||
|
||||
// Domain modules
|
||||
pub mod domain;
|
||||
pub mod events;
|
||||
pub mod modes;
|
||||
|
||||
// Core functionality modules
|
||||
pub mod core;
|
||||
pub mod orderbook;
|
||||
pub mod risk;
|
||||
pub mod positions;
|
||||
pub mod analytics;
|
||||
pub mod indicators;
|
||||
pub mod backtest;
|
||||
pub mod strategies;
|
||||
|
||||
// API layer
|
||||
pub mod api;
|
||||
|
||||
// Re-export commonly used types from domain
|
||||
pub use domain::{
|
||||
// Market types
|
||||
Quote, Bar, Trade, MarketUpdate, MarketDataType,
|
||||
// Order types
|
||||
Order, OrderType, OrderStatus, TimeInForce, Side, Fill,
|
||||
// Position types
|
||||
Position, PositionUpdate,
|
||||
// Event types
|
||||
Event, EventType, EventHandler,
|
||||
};
|
||||
|
||||
// Re-export mode types
|
||||
pub use modes::{TradingMode, TradingEngine};
|
||||
|
||||
// Re-export other commonly used types
|
||||
pub use positions::{PositionTracker, TradeRecord, ClosedTrade};
|
||||
pub use risk::{RiskLimits, RiskCheckResult, RiskMetrics};
|
||||
|
||||
// Core traits that define the system's abstractions
|
||||
use chrono::{DateTime, Utc};
|
||||
use std::sync::Arc;
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
pub trait MarketDataSource: Send + Sync {
|
||||
async fn get_next_update(&mut self) -> Option<MarketUpdate>;
|
||||
fn seek_to_time(&mut self, timestamp: DateTime<Utc>) -> Result<(), String>;
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ExecutionHandler: Send + Sync {
|
||||
async fn submit_order(&self, order: &Order) -> Result<String, String>;
|
||||
async fn cancel_order(&self, order_id: &str) -> Result<(), String>;
|
||||
async fn get_order_status(&self, order_id: &str) -> Result<OrderStatus, String>;
|
||||
}
|
||||
|
||||
pub trait TimeProvider: Send + Sync {
|
||||
fn now(&self) -> DateTime<Utc>;
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
}
|
||||
|
||||
pub trait FillSimulator: Send + Sync {
|
||||
fn simulate_fill(&self, order: &Order, market_price: f64) -> Option<Fill>;
|
||||
}
|
||||
|
|
@ -1,123 +0,0 @@
|
|||
#![deny(clippy::all)]
|
||||
|
||||
// Domain modules - core types and abstractions
|
||||
pub mod domain;
|
||||
pub mod events;
|
||||
pub mod modes;
|
||||
pub mod strategies;
|
||||
|
||||
// Core functionality modules
|
||||
pub mod core;
|
||||
pub mod orderbook;
|
||||
pub mod risk;
|
||||
pub mod positions;
|
||||
pub mod analytics;
|
||||
pub mod indicators;
|
||||
pub mod backtest;
|
||||
|
||||
// API layer
|
||||
pub mod api;
|
||||
|
||||
// Re-export all domain types
|
||||
pub use domain::*;
|
||||
|
||||
// Re-export event system
|
||||
pub use events::{Event, EventType, EventBus, EventHandler};
|
||||
|
||||
// Re-export mode types and engine trait
|
||||
pub use modes::{TradingMode, TradingEngine};
|
||||
|
||||
// Re-export strategy framework
|
||||
pub use strategies::framework::{Strategy, StrategyContext, Signal, SignalAction};
|
||||
|
||||
// Re-export position tracking
|
||||
pub use positions::{PositionTracker, TradeRecord, ClosedTrade};
|
||||
|
||||
// Re-export risk management
|
||||
pub use risk::{RiskLimits, RiskCheckResult, RiskMetrics, RiskEngine};
|
||||
|
||||
// Re-export analytics
|
||||
pub use analytics::{AnalyticsEngine, PerformanceMetrics};
|
||||
|
||||
// Re-export indicators
|
||||
pub use indicators::{Indicator, IndicatorSet};
|
||||
|
||||
// Re-export backtest types
|
||||
pub use backtest::{BacktestEngine, BacktestResults};
|
||||
|
||||
// Re-export API
|
||||
pub use api::TradingAPI;
|
||||
|
||||
// Core system traits
|
||||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
/// Source of market data - can be historical files, live feed, or simulated
|
||||
#[async_trait]
|
||||
pub trait MarketDataSource: Send + Sync {
|
||||
async fn get_next_update(&mut self) -> Option<MarketUpdate>;
|
||||
fn seek_to_time(&mut self, timestamp: DateTime<Utc>) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// Handles order execution - can be simulated, paper, or live broker
|
||||
#[async_trait]
|
||||
pub trait ExecutionHandler: Send + Sync {
|
||||
async fn submit_order(&self, order: &Order) -> Result<String, String>;
|
||||
async fn cancel_order(&self, order_id: &str) -> Result<(), String>;
|
||||
async fn get_order_status(&self, order_id: &str) -> Result<OrderStatus, String>;
|
||||
}
|
||||
|
||||
/// Provides current time - can be simulated time for backtest or real time
|
||||
pub trait TimeProvider: Send + Sync {
|
||||
fn now(&self) -> DateTime<Utc>;
|
||||
fn sleep_until(&self, target: DateTime<Utc>) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// Simulates order fills for backtest/paper trading
|
||||
pub trait FillSimulator: Send + Sync {
|
||||
fn simulate_fill(&self, order: &Order, market_price: f64, spread: f64) -> Option<Fill>;
|
||||
}
|
||||
|
||||
/// Main trading system that coordinates all components
|
||||
pub struct TradingCore {
|
||||
mode: TradingMode,
|
||||
engine: Box<dyn TradingEngine>,
|
||||
event_bus: EventBus,
|
||||
orderbook_manager: OrderBookManager,
|
||||
position_tracker: PositionTracker,
|
||||
risk_engine: RiskEngine,
|
||||
analytics_engine: AnalyticsEngine,
|
||||
}
|
||||
|
||||
impl TradingCore {
|
||||
/// Create a new trading system for the specified mode
|
||||
pub fn new(mode: TradingMode) -> Result<Self, String> {
|
||||
let engine = modes::create_engine_for_mode(&mode)?;
|
||||
let event_bus = EventBus::new();
|
||||
|
||||
Ok(Self {
|
||||
mode,
|
||||
engine,
|
||||
event_bus,
|
||||
orderbook_manager: OrderBookManager::new(),
|
||||
position_tracker: PositionTracker::new(),
|
||||
risk_engine: RiskEngine::new(),
|
||||
analytics_engine: AnalyticsEngine::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Start the trading system
|
||||
pub async fn start(&mut self) -> Result<(), String> {
|
||||
self.engine.start(&mut self.event_bus).await
|
||||
}
|
||||
|
||||
/// Stop the trading system
|
||||
pub async fn stop(&mut self) -> Result<(), String> {
|
||||
self.engine.stop().await
|
||||
}
|
||||
|
||||
/// Get current trading mode
|
||||
pub fn mode(&self) -> &TradingMode {
|
||||
&self.mode
|
||||
}
|
||||
}
|
||||
|
|
@ -1,291 +0,0 @@
|
|||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Utc};
|
||||
use std::sync::Arc;
|
||||
use parking_lot::RwLock;
|
||||
use crate::{
|
||||
MarketDataSource, ExecutionHandler, TimeProvider, FillSimulator,
|
||||
MarketUpdate, Order, OrderStatus, Fill, OrderBookSnapshot,
|
||||
};
|
||||
use crate::events::EventBus;
|
||||
use crate::domain::{Event, EventType};
|
||||
use super::TradingEngine;
|
||||
|
||||
/// Backtest-specific trading engine
|
||||
pub struct BacktestEngine {
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
current_time: DateTime<Utc>,
|
||||
speed_multiplier: f64,
|
||||
market_data: Box<dyn MarketDataSource>,
|
||||
execution: BacktestExecutor,
|
||||
is_running: Arc<RwLock<bool>>,
|
||||
}
|
||||
|
||||
impl BacktestEngine {
|
||||
pub fn new(
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
speed_multiplier: f64,
|
||||
market_data: Box<dyn MarketDataSource>,
|
||||
) -> Self {
|
||||
Self {
|
||||
start_time,
|
||||
end_time,
|
||||
current_time: start_time,
|
||||
speed_multiplier,
|
||||
market_data,
|
||||
execution: BacktestExecutor::new(),
|
||||
is_running: Arc::new(RwLock::new(false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TradingEngine for BacktestEngine {
|
||||
async fn start(&mut self, event_bus: &mut EventBus) -> Result<(), String> {
|
||||
*self.is_running.write() = true;
|
||||
self.current_time = self.start_time;
|
||||
|
||||
// Seek market data to start time
|
||||
self.market_data.seek_to_time(self.start_time)?;
|
||||
|
||||
// Emit start event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::SystemStart,
|
||||
timestamp: self.current_time,
|
||||
data: serde_json::json!({
|
||||
"mode": "backtest",
|
||||
"start_time": self.start_time,
|
||||
"end_time": self.end_time,
|
||||
}),
|
||||
}).await;
|
||||
|
||||
// Main backtest loop
|
||||
while *self.is_running.read() && self.current_time < self.end_time {
|
||||
// Get next market update
|
||||
if let Some(update) = self.market_data.get_next_update().await {
|
||||
// Update current time
|
||||
self.current_time = update.timestamp;
|
||||
|
||||
// Publish market data event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::MarketData(update.clone()),
|
||||
timestamp: self.current_time,
|
||||
data: serde_json::Value::Null,
|
||||
}).await;
|
||||
|
||||
// Process any pending orders
|
||||
self.execution.process_orders(&update, event_bus).await?;
|
||||
} else {
|
||||
// No more data
|
||||
break;
|
||||
}
|
||||
|
||||
// Simulate time passing (for UI updates, etc.)
|
||||
if self.speed_multiplier > 0.0 {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(
|
||||
(10.0 / self.speed_multiplier) as u64
|
||||
)).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Emit stop event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::SystemStop,
|
||||
timestamp: self.current_time,
|
||||
data: serde_json::json!({
|
||||
"reason": "backtest_complete",
|
||||
"end_time": self.current_time,
|
||||
}),
|
||||
}).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn stop(&mut self) -> Result<(), String> {
|
||||
*self.is_running.write() = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_execution_handler(&self) -> Arc<dyn ExecutionHandler> {
|
||||
Arc::new(self.execution.clone())
|
||||
}
|
||||
|
||||
fn get_time_provider(&self) -> Arc<dyn TimeProvider> {
|
||||
Arc::new(BacktestTimeProvider {
|
||||
current_time: self.current_time,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Backtest order executor
|
||||
#[derive(Clone)]
|
||||
struct BacktestExecutor {
|
||||
pending_orders: Arc<RwLock<Vec<Order>>>,
|
||||
order_history: Arc<RwLock<Vec<(Order, OrderStatus)>>>,
|
||||
fill_simulator: BacktestFillSimulator,
|
||||
}
|
||||
|
||||
impl BacktestExecutor {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
pending_orders: Arc::new(RwLock::new(Vec::new())),
|
||||
order_history: Arc::new(RwLock::new(Vec::new())),
|
||||
fill_simulator: BacktestFillSimulator::new(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn process_orders(
|
||||
&self,
|
||||
market_update: &MarketUpdate,
|
||||
event_bus: &mut EventBus,
|
||||
) -> Result<(), String> {
|
||||
let mut orders = self.pending_orders.write();
|
||||
let mut filled_indices = Vec::new();
|
||||
|
||||
for (idx, order) in orders.iter().enumerate() {
|
||||
if order.symbol != market_update.symbol {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to fill the order
|
||||
if let Some(fill) = self.fill_simulator.try_fill(order, market_update) {
|
||||
// Emit fill event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::OrderFill {
|
||||
order_id: order.id.clone(),
|
||||
fill: fill.clone(),
|
||||
},
|
||||
timestamp: market_update.timestamp,
|
||||
data: serde_json::Value::Null,
|
||||
}).await;
|
||||
|
||||
filled_indices.push(idx);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove filled orders
|
||||
for idx in filled_indices.into_iter().rev() {
|
||||
let order = orders.remove(idx);
|
||||
self.order_history.write().push((order, OrderStatus::Filled));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ExecutionHandler for BacktestExecutor {
|
||||
async fn submit_order(&self, order: &Order) -> Result<String, String> {
|
||||
let order_id = order.id.clone();
|
||||
self.pending_orders.write().push(order.clone());
|
||||
Ok(order_id)
|
||||
}
|
||||
|
||||
async fn cancel_order(&self, order_id: &str) -> Result<(), String> {
|
||||
let mut orders = self.pending_orders.write();
|
||||
if let Some(pos) = orders.iter().position(|o| o.id == order_id) {
|
||||
let order = orders.remove(pos);
|
||||
self.order_history.write().push((order, OrderStatus::Cancelled));
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Order not found".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_order_status(&self, order_id: &str) -> Result<OrderStatus, String> {
|
||||
// Check pending orders
|
||||
if self.pending_orders.read().iter().any(|o| o.id == order_id) {
|
||||
return Ok(OrderStatus::Pending);
|
||||
}
|
||||
|
||||
// Check history
|
||||
if let Some((_, status)) = self.order_history.read()
|
||||
.iter()
|
||||
.find(|(o, _)| o.id == order_id) {
|
||||
return Ok(status.clone());
|
||||
}
|
||||
|
||||
Err("Order not found".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Backtest time provider
|
||||
struct BacktestTimeProvider {
|
||||
current_time: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl TimeProvider for BacktestTimeProvider {
|
||||
fn now(&self) -> DateTime<Utc> {
|
||||
self.current_time
|
||||
}
|
||||
|
||||
fn sleep_until(&self, _target: DateTime<Utc>) -> Result<(), String> {
|
||||
// In backtest, we don't actually sleep
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Backtest fill simulator
|
||||
#[derive(Clone)]
|
||||
struct BacktestFillSimulator {
|
||||
commission_rate: f64,
|
||||
slippage_bps: f64,
|
||||
}
|
||||
|
||||
impl BacktestFillSimulator {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
commission_rate: 0.001, // 0.1%
|
||||
slippage_bps: 5.0, // 5 basis points
|
||||
}
|
||||
}
|
||||
|
||||
fn try_fill(&self, order: &Order, market_update: &MarketUpdate) -> Option<Fill> {
|
||||
match &market_update.data {
|
||||
crate::MarketDataType::Quote(quote) => {
|
||||
self.simulate_fill(order, quote.bid, quote.ask - quote.bid)
|
||||
}
|
||||
crate::MarketDataType::Trade(trade) => {
|
||||
self.simulate_fill(order, trade.price, 0.0001 * trade.price) // 1bp spread estimate
|
||||
}
|
||||
crate::MarketDataType::Bar(bar) => {
|
||||
// Use close price with estimated spread
|
||||
self.simulate_fill(order, bar.close, 0.0002 * bar.close) // 2bp spread estimate
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FillSimulator for BacktestFillSimulator {
|
||||
fn simulate_fill(&self, order: &Order, market_price: f64, spread: f64) -> Option<Fill> {
|
||||
let fill_price = match order.order_type {
|
||||
crate::OrderType::Market => {
|
||||
// Fill at market with slippage
|
||||
let slippage = market_price * self.slippage_bps / 10000.0;
|
||||
match order.side {
|
||||
crate::Side::Buy => market_price + spread/2.0 + slippage,
|
||||
crate::Side::Sell => market_price - spread/2.0 - slippage,
|
||||
}
|
||||
}
|
||||
crate::OrderType::Limit { price } => {
|
||||
// Check if limit price is satisfied
|
||||
match order.side {
|
||||
crate::Side::Buy if price >= market_price + spread/2.0 => price,
|
||||
crate::Side::Sell if price <= market_price - spread/2.0 => price,
|
||||
_ => return None, // Limit not satisfied
|
||||
}
|
||||
}
|
||||
_ => return None, // Other order types not implemented yet
|
||||
};
|
||||
|
||||
let commission = fill_price * order.quantity * self.commission_rate;
|
||||
|
||||
Some(Fill {
|
||||
timestamp: chrono::Utc::now(), // Will be overridden by engine
|
||||
price: fill_price,
|
||||
quantity: order.quantity,
|
||||
commission,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,290 +0,0 @@
|
|||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Utc};
|
||||
use std::sync::Arc;
|
||||
use parking_lot::RwLock;
|
||||
use tokio::sync::mpsc;
|
||||
use crate::{
|
||||
ExecutionHandler, TimeProvider,
|
||||
Order, OrderStatus, Fill,
|
||||
};
|
||||
use crate::events::EventBus;
|
||||
use crate::domain::{Event, EventType};
|
||||
use super::TradingEngine;
|
||||
|
||||
/// Live trading engine - connects to real brokers
|
||||
pub struct LiveEngine {
|
||||
broker: String,
|
||||
account_id: String,
|
||||
broker_connection: Arc<dyn BrokerConnection>,
|
||||
is_running: Arc<RwLock<bool>>,
|
||||
shutdown_tx: Option<mpsc::Sender<()>>,
|
||||
}
|
||||
|
||||
/// Trait for broker connections
|
||||
#[async_trait]
|
||||
pub trait BrokerConnection: Send + Sync {
|
||||
async fn connect(&mut self, account_id: &str) -> Result<(), String>;
|
||||
async fn disconnect(&mut self) -> Result<(), String>;
|
||||
async fn subscribe_market_data(&mut self, symbols: Vec<String>) -> Result<(), String>;
|
||||
async fn submit_order(&self, order: &Order) -> Result<String, String>;
|
||||
async fn cancel_order(&self, order_id: &str) -> Result<(), String>;
|
||||
async fn get_order_status(&self, order_id: &str) -> Result<OrderStatus, String>;
|
||||
async fn get_positions(&self) -> Result<Vec<crate::Position>, String>;
|
||||
async fn get_account_info(&self) -> Result<AccountInfo, String>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AccountInfo {
|
||||
pub cash: f64,
|
||||
pub buying_power: f64,
|
||||
pub portfolio_value: f64,
|
||||
pub day_trades_remaining: Option<u32>,
|
||||
}
|
||||
|
||||
impl LiveEngine {
|
||||
pub fn new(
|
||||
broker: String,
|
||||
account_id: String,
|
||||
broker_connection: Arc<dyn BrokerConnection>,
|
||||
) -> Self {
|
||||
Self {
|
||||
broker,
|
||||
account_id,
|
||||
broker_connection,
|
||||
is_running: Arc::new(RwLock::new(false)),
|
||||
shutdown_tx: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TradingEngine for LiveEngine {
|
||||
async fn start(&mut self, event_bus: &mut EventBus) -> Result<(), String> {
|
||||
*self.is_running.write() = true;
|
||||
|
||||
// Connect to broker
|
||||
self.broker_connection.connect(&self.account_id).await?;
|
||||
|
||||
// Get initial account info
|
||||
let account_info = self.broker_connection.get_account_info().await?;
|
||||
|
||||
let (shutdown_tx, mut shutdown_rx) = mpsc::channel(1);
|
||||
self.shutdown_tx = Some(shutdown_tx);
|
||||
|
||||
// Emit start event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::SystemStart,
|
||||
timestamp: Utc::now(),
|
||||
data: serde_json::json!({
|
||||
"mode": "live",
|
||||
"broker": self.broker,
|
||||
"account_id": self.account_id,
|
||||
"account_info": {
|
||||
"cash": account_info.cash,
|
||||
"buying_power": account_info.buying_power,
|
||||
"portfolio_value": account_info.portfolio_value,
|
||||
},
|
||||
}),
|
||||
}).await;
|
||||
|
||||
// Main live trading loop
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown_rx.recv() => {
|
||||
break;
|
||||
}
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {
|
||||
// Periodic tasks (e.g., check positions, risk)
|
||||
if !*self.is_running.read() {
|
||||
break;
|
||||
}
|
||||
|
||||
// Could emit periodic status updates here
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Disconnect from broker
|
||||
self.broker_connection.disconnect().await?;
|
||||
|
||||
// Emit stop event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::SystemStop,
|
||||
timestamp: Utc::now(),
|
||||
data: serde_json::json!({
|
||||
"reason": "live_trading_stopped",
|
||||
}),
|
||||
}).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn stop(&mut self) -> Result<(), String> {
|
||||
*self.is_running.write() = false;
|
||||
if let Some(tx) = self.shutdown_tx.take() {
|
||||
let _ = tx.send(()).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_execution_handler(&self) -> Arc<dyn ExecutionHandler> {
|
||||
Arc::new(LiveExecutor {
|
||||
broker_connection: self.broker_connection.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn get_time_provider(&self) -> Arc<dyn TimeProvider> {
|
||||
Arc::new(RealTimeProvider)
|
||||
}
|
||||
}
|
||||
|
||||
/// Live order executor - delegates to broker
|
||||
#[derive(Clone)]
|
||||
struct LiveExecutor {
|
||||
broker_connection: Arc<dyn BrokerConnection>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ExecutionHandler for LiveExecutor {
|
||||
async fn submit_order(&self, order: &Order) -> Result<String, String> {
|
||||
// Validate order
|
||||
if order.quantity <= 0.0 {
|
||||
return Err("Invalid order quantity".to_string());
|
||||
}
|
||||
|
||||
// Submit to broker
|
||||
self.broker_connection.submit_order(order).await
|
||||
}
|
||||
|
||||
async fn cancel_order(&self, order_id: &str) -> Result<(), String> {
|
||||
self.broker_connection.cancel_order(order_id).await
|
||||
}
|
||||
|
||||
async fn get_order_status(&self, order_id: &str) -> Result<OrderStatus, String> {
|
||||
self.broker_connection.get_order_status(order_id).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Real-time provider for live trading
|
||||
struct RealTimeProvider;
|
||||
|
||||
impl TimeProvider for RealTimeProvider {
|
||||
fn now(&self) -> DateTime<Utc> {
|
||||
Utc::now()
|
||||
}
|
||||
|
||||
fn sleep_until(&self, target: DateTime<Utc>) -> Result<(), String> {
|
||||
let now = Utc::now();
|
||||
if target > now {
|
||||
let duration = target.signed_duration_since(now);
|
||||
std::thread::sleep(duration.to_std().unwrap_or_default());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Example broker implementations would go here
|
||||
// For now, we'll create a mock broker for testing
|
||||
|
||||
/// Mock broker for testing
|
||||
pub struct MockBroker {
|
||||
is_connected: bool,
|
||||
orders: Arc<RwLock<Vec<(Order, OrderStatus)>>>,
|
||||
}
|
||||
|
||||
impl MockBroker {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
is_connected: false,
|
||||
orders: Arc::new(RwLock::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BrokerConnection for MockBroker {
|
||||
async fn connect(&mut self, _account_id: &str) -> Result<(), String> {
|
||||
self.is_connected = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn disconnect(&mut self) -> Result<(), String> {
|
||||
self.is_connected = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn subscribe_market_data(&mut self, _symbols: Vec<String>) -> Result<(), String> {
|
||||
if !self.is_connected {
|
||||
return Err("Not connected".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn submit_order(&self, order: &Order) -> Result<String, String> {
|
||||
if !self.is_connected {
|
||||
return Err("Not connected".to_string());
|
||||
}
|
||||
|
||||
let order_id = order.id.clone();
|
||||
self.orders.write().push((order.clone(), OrderStatus::Pending));
|
||||
|
||||
// Simulate order being filled after a delay
|
||||
let orders = self.orders.clone();
|
||||
let order_id_clone = order_id.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
let mut orders = orders.write();
|
||||
if let Some(pos) = orders.iter().position(|(o, _)| o.id == order_id_clone) {
|
||||
orders[pos].1 = OrderStatus::Filled;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(order_id)
|
||||
}
|
||||
|
||||
async fn cancel_order(&self, order_id: &str) -> Result<(), String> {
|
||||
if !self.is_connected {
|
||||
return Err("Not connected".to_string());
|
||||
}
|
||||
|
||||
let mut orders = self.orders.write();
|
||||
if let Some(pos) = orders.iter().position(|(o, _)| o.id == order_id) {
|
||||
orders[pos].1 = OrderStatus::Cancelled;
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Order not found".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_order_status(&self, order_id: &str) -> Result<OrderStatus, String> {
|
||||
if !self.is_connected {
|
||||
return Err("Not connected".to_string());
|
||||
}
|
||||
|
||||
let orders = self.orders.read();
|
||||
if let Some((_, status)) = orders.iter().find(|(o, _)| o.id == order_id) {
|
||||
Ok(status.clone())
|
||||
} else {
|
||||
Err("Order not found".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_positions(&self) -> Result<Vec<crate::Position>, String> {
|
||||
if !self.is_connected {
|
||||
return Err("Not connected".to_string());
|
||||
}
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
async fn get_account_info(&self) -> Result<AccountInfo, String> {
|
||||
if !self.is_connected {
|
||||
return Err("Not connected".to_string());
|
||||
}
|
||||
Ok(AccountInfo {
|
||||
cash: 100_000.0,
|
||||
buying_power: 400_000.0,
|
||||
portfolio_value: 100_000.0,
|
||||
day_trades_remaining: Some(3),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
use async_trait::async_trait;
|
||||
use crate::events::EventBus;
|
||||
use crate::{ExecutionHandler, TimeProvider, MarketDataSource};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub mod backtest;
|
||||
pub mod paper;
|
||||
pub mod live;
|
||||
|
||||
pub use backtest::BacktestEngine;
|
||||
pub use paper::PaperEngine;
|
||||
pub use live::{LiveEngine, BrokerConnection};
|
||||
|
||||
/// Trading mode configuration
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TradingMode {
|
||||
Backtest {
|
||||
start_time: chrono::DateTime<chrono::Utc>,
|
||||
end_time: chrono::DateTime<chrono::Utc>,
|
||||
speed_multiplier: f64,
|
||||
},
|
||||
Paper {
|
||||
starting_capital: f64,
|
||||
},
|
||||
Live {
|
||||
broker: String,
|
||||
account_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Common interface for all trading engines
|
||||
#[async_trait]
|
||||
pub trait TradingEngine: Send + Sync {
|
||||
/// Start the trading engine
|
||||
async fn start(&mut self, event_bus: &mut EventBus) -> Result<(), String>;
|
||||
|
||||
/// Stop the trading engine
|
||||
async fn stop(&mut self) -> Result<(), String>;
|
||||
|
||||
/// Get the execution handler for this mode
|
||||
fn get_execution_handler(&self) -> Arc<dyn ExecutionHandler>;
|
||||
|
||||
/// Get the time provider for this mode
|
||||
fn get_time_provider(&self) -> Arc<dyn TimeProvider>;
|
||||
}
|
||||
|
||||
/// Create a trading engine for the specified mode
|
||||
pub fn create_engine_for_mode(
|
||||
mode: &TradingMode,
|
||||
) -> Result<Box<dyn TradingEngine>, String> {
|
||||
match mode {
|
||||
TradingMode::Backtest { start_time, end_time, speed_multiplier } => {
|
||||
// For backtest, we need to create a market data source
|
||||
// This would typically load historical data
|
||||
let market_data = create_backtest_data_source()?;
|
||||
|
||||
Ok(Box::new(BacktestEngine::new(
|
||||
*start_time,
|
||||
*end_time,
|
||||
*speed_multiplier,
|
||||
market_data,
|
||||
)))
|
||||
}
|
||||
TradingMode::Paper { starting_capital } => {
|
||||
// For paper trading, we need a real-time data source
|
||||
let market_data = create_realtime_data_source()?;
|
||||
|
||||
Ok(Box::new(PaperEngine::new(
|
||||
*starting_capital,
|
||||
market_data,
|
||||
)))
|
||||
}
|
||||
TradingMode::Live { broker, account_id } => {
|
||||
// For live trading, we need a broker connection
|
||||
let broker_connection = create_broker_connection(broker)?;
|
||||
|
||||
Ok(Box::new(LiveEngine::new(
|
||||
broker.clone(),
|
||||
account_id.clone(),
|
||||
broker_connection,
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper functions to create data sources and broker connections
|
||||
// These would be implemented based on your specific requirements
|
||||
|
||||
fn create_backtest_data_source() -> Result<Box<dyn MarketDataSource>, String> {
|
||||
// TODO: Implement actual backtest data source
|
||||
// For now, return a placeholder
|
||||
Err("Backtest data source not implemented yet".to_string())
|
||||
}
|
||||
|
||||
fn create_realtime_data_source() -> Result<Box<dyn MarketDataSource>, String> {
|
||||
// TODO: Implement actual real-time data source
|
||||
// For now, return a placeholder
|
||||
Err("Real-time data source not implemented yet".to_string())
|
||||
}
|
||||
|
||||
fn create_broker_connection(broker: &str) -> Result<Arc<dyn BrokerConnection>, String> {
|
||||
match broker {
|
||||
"mock" => Ok(Arc::new(live::MockBroker::new())),
|
||||
_ => Err(format!("Unknown broker: {}", broker)),
|
||||
}
|
||||
}
|
||||
|
|
@ -1,306 +0,0 @@
|
|||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Utc};
|
||||
use std::sync::Arc;
|
||||
use parking_lot::RwLock;
|
||||
use tokio::sync::mpsc;
|
||||
use crate::{
|
||||
MarketDataSource, ExecutionHandler, TimeProvider, FillSimulator,
|
||||
MarketUpdate, Order, OrderStatus, Fill,
|
||||
};
|
||||
use crate::events::EventBus;
|
||||
use crate::domain::{Event, EventType};
|
||||
use super::TradingEngine;
|
||||
|
||||
/// Paper trading engine - simulates live trading without real money
|
||||
pub struct PaperEngine {
|
||||
starting_capital: f64,
|
||||
market_data: Box<dyn MarketDataSource>,
|
||||
execution: PaperExecutor,
|
||||
is_running: Arc<RwLock<bool>>,
|
||||
shutdown_tx: Option<mpsc::Sender<()>>,
|
||||
}
|
||||
|
||||
impl PaperEngine {
|
||||
pub fn new(
|
||||
starting_capital: f64,
|
||||
market_data: Box<dyn MarketDataSource>,
|
||||
) -> Self {
|
||||
Self {
|
||||
starting_capital,
|
||||
market_data,
|
||||
execution: PaperExecutor::new(starting_capital),
|
||||
is_running: Arc::new(RwLock::new(false)),
|
||||
shutdown_tx: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TradingEngine for PaperEngine {
|
||||
async fn start(&mut self, event_bus: &mut EventBus) -> Result<(), String> {
|
||||
*self.is_running.write() = true;
|
||||
|
||||
let (shutdown_tx, mut shutdown_rx) = mpsc::channel(1);
|
||||
self.shutdown_tx = Some(shutdown_tx);
|
||||
|
||||
// Emit start event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::SystemStart,
|
||||
timestamp: Utc::now(),
|
||||
data: serde_json::json!({
|
||||
"mode": "paper",
|
||||
"starting_capital": self.starting_capital,
|
||||
}),
|
||||
}).await;
|
||||
|
||||
// Main paper trading loop
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown_rx.recv() => {
|
||||
break;
|
||||
}
|
||||
update = self.market_data.get_next_update() => {
|
||||
if let Some(market_update) = update {
|
||||
// Publish market data event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::MarketData(market_update.clone()),
|
||||
timestamp: Utc::now(),
|
||||
data: serde_json::Value::Null,
|
||||
}).await;
|
||||
|
||||
// Process pending orders
|
||||
self.execution.process_orders(&market_update, event_bus).await?;
|
||||
}
|
||||
}
|
||||
_ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {
|
||||
// Check if still running
|
||||
if !*self.is_running.read() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Emit stop event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::SystemStop,
|
||||
timestamp: Utc::now(),
|
||||
data: serde_json::json!({
|
||||
"reason": "paper_trading_stopped",
|
||||
}),
|
||||
}).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn stop(&mut self) -> Result<(), String> {
|
||||
*self.is_running.write() = false;
|
||||
if let Some(tx) = self.shutdown_tx.take() {
|
||||
let _ = tx.send(()).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_execution_handler(&self) -> Arc<dyn ExecutionHandler> {
|
||||
Arc::new(self.execution.clone())
|
||||
}
|
||||
|
||||
fn get_time_provider(&self) -> Arc<dyn TimeProvider> {
|
||||
Arc::new(RealTimeProvider)
|
||||
}
|
||||
}
|
||||
|
||||
/// Paper trading order executor
|
||||
#[derive(Clone)]
|
||||
struct PaperExecutor {
|
||||
cash: Arc<RwLock<f64>>,
|
||||
pending_orders: Arc<RwLock<Vec<Order>>>,
|
||||
order_history: Arc<RwLock<Vec<(Order, OrderStatus)>>>,
|
||||
fill_simulator: PaperFillSimulator,
|
||||
}
|
||||
|
||||
impl PaperExecutor {
|
||||
fn new(starting_capital: f64) -> Self {
|
||||
Self {
|
||||
cash: Arc::new(RwLock::new(starting_capital)),
|
||||
pending_orders: Arc::new(RwLock::new(Vec::new())),
|
||||
order_history: Arc::new(RwLock::new(Vec::new())),
|
||||
fill_simulator: PaperFillSimulator::new(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn process_orders(
|
||||
&self,
|
||||
market_update: &MarketUpdate,
|
||||
event_bus: &mut EventBus,
|
||||
) -> Result<(), String> {
|
||||
let mut orders = self.pending_orders.write();
|
||||
let mut filled_indices = Vec::new();
|
||||
|
||||
for (idx, order) in orders.iter().enumerate() {
|
||||
if order.symbol != market_update.symbol {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try to fill the order
|
||||
if let Some(fill) = self.fill_simulator.try_fill(order, market_update) {
|
||||
// Check if we have enough cash for buy orders
|
||||
if order.side == crate::Side::Buy {
|
||||
let required_cash = fill.price * fill.quantity + fill.commission;
|
||||
let mut cash = self.cash.write();
|
||||
if *cash >= required_cash {
|
||||
*cash -= required_cash;
|
||||
} else {
|
||||
continue; // Skip this order
|
||||
}
|
||||
} else {
|
||||
// For sell orders, add cash
|
||||
let proceeds = fill.price * fill.quantity - fill.commission;
|
||||
*self.cash.write() += proceeds;
|
||||
}
|
||||
|
||||
// Emit fill event
|
||||
event_bus.publish(Event {
|
||||
event_type: EventType::OrderFill {
|
||||
order_id: order.id.clone(),
|
||||
fill: fill.clone(),
|
||||
},
|
||||
timestamp: Utc::now(),
|
||||
data: serde_json::json!({
|
||||
"cash_after": *self.cash.read(),
|
||||
}),
|
||||
}).await;
|
||||
|
||||
filled_indices.push(idx);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove filled orders
|
||||
for idx in filled_indices.into_iter().rev() {
|
||||
let order = orders.remove(idx);
|
||||
self.order_history.write().push((order, OrderStatus::Filled));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ExecutionHandler for PaperExecutor {
|
||||
async fn submit_order(&self, order: &Order) -> Result<String, String> {
|
||||
// Basic validation
|
||||
if order.quantity <= 0.0 {
|
||||
return Err("Invalid order quantity".to_string());
|
||||
}
|
||||
|
||||
let order_id = order.id.clone();
|
||||
self.pending_orders.write().push(order.clone());
|
||||
Ok(order_id)
|
||||
}
|
||||
|
||||
async fn cancel_order(&self, order_id: &str) -> Result<(), String> {
|
||||
let mut orders = self.pending_orders.write();
|
||||
if let Some(pos) = orders.iter().position(|o| o.id == order_id) {
|
||||
let order = orders.remove(pos);
|
||||
self.order_history.write().push((order, OrderStatus::Cancelled));
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Order not found".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_order_status(&self, order_id: &str) -> Result<OrderStatus, String> {
|
||||
// Check pending orders
|
||||
if self.pending_orders.read().iter().any(|o| o.id == order_id) {
|
||||
return Ok(OrderStatus::Pending);
|
||||
}
|
||||
|
||||
// Check history
|
||||
if let Some((_, status)) = self.order_history.read()
|
||||
.iter()
|
||||
.find(|(o, _)| o.id == order_id) {
|
||||
return Ok(status.clone());
|
||||
}
|
||||
|
||||
Err("Order not found".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Real-time provider for paper trading
|
||||
struct RealTimeProvider;
|
||||
|
||||
impl TimeProvider for RealTimeProvider {
|
||||
fn now(&self) -> DateTime<Utc> {
|
||||
Utc::now()
|
||||
}
|
||||
|
||||
fn sleep_until(&self, target: DateTime<Utc>) -> Result<(), String> {
|
||||
let now = Utc::now();
|
||||
if target > now {
|
||||
let duration = target.signed_duration_since(now);
|
||||
std::thread::sleep(duration.to_std().unwrap_or_default());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Paper trading fill simulator
|
||||
#[derive(Clone)]
|
||||
struct PaperFillSimulator {
|
||||
commission_rate: f64,
|
||||
slippage_bps: f64,
|
||||
}
|
||||
|
||||
impl PaperFillSimulator {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
commission_rate: 0.001, // 0.1%
|
||||
slippage_bps: 3.0, // 3 basis points (less than backtest)
|
||||
}
|
||||
}
|
||||
|
||||
fn try_fill(&self, order: &Order, market_update: &MarketUpdate) -> Option<Fill> {
|
||||
match &market_update.data {
|
||||
crate::MarketDataType::Quote(quote) => {
|
||||
self.simulate_fill(order, quote.bid, quote.ask - quote.bid)
|
||||
}
|
||||
crate::MarketDataType::Trade(trade) => {
|
||||
self.simulate_fill(order, trade.price, 0.0001 * trade.price)
|
||||
}
|
||||
crate::MarketDataType::Bar(bar) => {
|
||||
self.simulate_fill(order, bar.close, 0.0002 * bar.close)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FillSimulator for PaperFillSimulator {
|
||||
fn simulate_fill(&self, order: &Order, market_price: f64, spread: f64) -> Option<Fill> {
|
||||
let fill_price = match order.order_type {
|
||||
crate::OrderType::Market => {
|
||||
let slippage = market_price * self.slippage_bps / 10000.0;
|
||||
match order.side {
|
||||
crate::Side::Buy => market_price + spread/2.0 + slippage,
|
||||
crate::Side::Sell => market_price - spread/2.0 - slippage,
|
||||
}
|
||||
}
|
||||
crate::OrderType::Limit { price } => {
|
||||
match order.side {
|
||||
crate::Side::Buy if price >= market_price + spread/2.0 => price,
|
||||
crate::Side::Sell if price <= market_price - spread/2.0 => price,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let commission = fill_price * order.quantity * self.commission_rate;
|
||||
|
||||
Some(Fill {
|
||||
timestamp: Utc::now(),
|
||||
price: fill_price,
|
||||
quantity: order.quantity,
|
||||
commission,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1,114 +0,0 @@
|
|||
use async_trait::async_trait;
|
||||
use serde_json::Value;
|
||||
use crate::domain::{MarketUpdate, Fill, Order, Side};
|
||||
use crate::indicators::IndicatorSet;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Context provided to strategies
|
||||
pub struct StrategyContext {
|
||||
pub portfolio_value: f64,
|
||||
pub cash: f64,
|
||||
pub positions: HashMap<String, f64>,
|
||||
pub pending_orders: Vec<Order>,
|
||||
pub indicators: IndicatorSet,
|
||||
}
|
||||
|
||||
/// Signal generated by a strategy
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Signal {
|
||||
pub symbol: String,
|
||||
pub action: SignalAction,
|
||||
pub quantity: Option<f64>,
|
||||
pub confidence: f64, // 0.0 to 1.0
|
||||
pub reason: String,
|
||||
pub metadata: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SignalAction {
|
||||
Buy,
|
||||
Sell,
|
||||
Close,
|
||||
Hold,
|
||||
}
|
||||
|
||||
/// Core strategy trait with lifecycle methods
|
||||
#[async_trait]
|
||||
pub trait Strategy: Send + Sync {
|
||||
/// Called once when strategy is initialized
|
||||
async fn init(&mut self, context: &StrategyContext) -> Result<(), String>;
|
||||
|
||||
/// Called when trading starts
|
||||
async fn on_start(&mut self) -> Result<(), String>;
|
||||
|
||||
/// Called for each market data update
|
||||
async fn on_data(&mut self, data: &MarketUpdate, context: &StrategyContext) -> Vec<Signal>;
|
||||
|
||||
/// Called when an order is filled
|
||||
async fn on_fill(&mut self, order_id: &str, fill: &Fill, context: &StrategyContext);
|
||||
|
||||
/// Called periodically (e.g., every minute)
|
||||
async fn on_timer(&mut self, context: &StrategyContext) -> Vec<Signal> {
|
||||
Vec::new() // Default: no signals on timer
|
||||
}
|
||||
|
||||
/// Called when trading stops
|
||||
async fn on_stop(&mut self) -> Result<(), String>;
|
||||
|
||||
/// Get strategy name
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// Get strategy parameters
|
||||
fn parameters(&self) -> Value;
|
||||
|
||||
/// Update strategy parameters
|
||||
fn update_parameters(&mut self, params: Value) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// Base implementation that strategies can extend
|
||||
pub struct BaseStrategy {
|
||||
name: String,
|
||||
parameters: Value,
|
||||
}
|
||||
|
||||
impl BaseStrategy {
|
||||
pub fn new(name: String, parameters: Value) -> Self {
|
||||
Self { name, parameters }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Strategy for BaseStrategy {
|
||||
async fn init(&mut self, _context: &StrategyContext) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn on_start(&mut self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn on_data(&mut self, _data: &MarketUpdate, _context: &StrategyContext) -> Vec<Signal> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
async fn on_fill(&mut self, _order_id: &str, _fill: &Fill, _context: &StrategyContext) {
|
||||
// Default: no action
|
||||
}
|
||||
|
||||
async fn on_stop(&mut self) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn parameters(&self) -> Value {
|
||||
self.parameters.clone()
|
||||
}
|
||||
|
||||
fn update_parameters(&mut self, params: Value) -> Result<(), String> {
|
||||
self.parameters = params;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -1,192 +0,0 @@
|
|||
// Separate lib for testing without NAPI dependencies
|
||||
#![cfg(test)]
|
||||
|
||||
pub mod core;
|
||||
pub mod adapters;
|
||||
pub mod orderbook;
|
||||
pub mod risk;
|
||||
pub mod positions;
|
||||
pub mod analytics;
|
||||
pub mod indicators;
|
||||
pub mod backtest;
|
||||
pub mod strategies;
|
||||
|
||||
// Re-export commonly used types
|
||||
pub use positions::{Position, PositionUpdate, TradeRecord, ClosedTrade};
|
||||
pub use risk::{RiskLimits, RiskCheckResult, RiskMetrics};
|
||||
|
||||
// Type alias for backtest compatibility
|
||||
pub type MarketData = MarketUpdate;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use parking_lot::RwLock;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum TradingMode {
|
||||
Backtest {
|
||||
start_time: DateTime<Utc>,
|
||||
end_time: DateTime<Utc>,
|
||||
speed_multiplier: f64,
|
||||
},
|
||||
Paper {
|
||||
starting_capital: f64,
|
||||
},
|
||||
Live {
|
||||
broker: String,
|
||||
account_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
// Core traits that allow different implementations based on mode
|
||||
#[async_trait::async_trait]
|
||||
pub trait MarketDataSource: Send + Sync {
|
||||
async fn get_next_update(&mut self) -> Option<MarketUpdate>;
|
||||
fn seek_to_time(&mut self, timestamp: DateTime<Utc>) -> Result<(), String>;
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait ExecutionHandler: Send + Sync {
|
||||
async fn execute_order(&mut self, order: Order) -> Result<ExecutionResult, String>;
|
||||
fn get_fill_simulator(&self) -> Option<&dyn FillSimulator>;
|
||||
}
|
||||
|
||||
pub trait TimeProvider: Send + Sync {
|
||||
fn now(&self) -> DateTime<Utc>;
|
||||
fn sleep_until(&self, target: DateTime<Utc>) -> Result<(), String>;
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
}
|
||||
|
||||
pub trait FillSimulator: Send + Sync {
|
||||
fn simulate_fill(&self, order: &Order, orderbook: &OrderBookSnapshot) -> Option<Fill>;
|
||||
}
|
||||
|
||||
// Main trading core that works across all modes
|
||||
pub struct TradingCore {
|
||||
mode: TradingMode,
|
||||
pub market_data_source: Arc<RwLock<Box<dyn MarketDataSource>>>,
|
||||
pub execution_handler: Arc<RwLock<Box<dyn ExecutionHandler>>>,
|
||||
pub time_provider: Arc<Box<dyn TimeProvider>>,
|
||||
pub orderbooks: Arc<orderbook::OrderBookManager>,
|
||||
pub risk_engine: Arc<risk::RiskEngine>,
|
||||
pub position_tracker: Arc<positions::PositionTracker>,
|
||||
}
|
||||
|
||||
// Market structure definitions
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MarketUpdate {
|
||||
pub symbol: String,
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub data: MarketDataType,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MarketMicrostructure {
|
||||
pub spread: f64,
|
||||
pub volatility: f64,
|
||||
pub tick_size: f64,
|
||||
pub lot_size: f64,
|
||||
pub intraday_volume_profile: Vec<f64>, // 24 hourly buckets
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum MarketDataType {
|
||||
Quote(Quote),
|
||||
Trade(Trade),
|
||||
Bar(Bar),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Quote {
|
||||
pub bid: f64,
|
||||
pub ask: f64,
|
||||
pub bid_size: f64,
|
||||
pub ask_size: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Trade {
|
||||
pub price: f64,
|
||||
pub size: f64,
|
||||
pub side: Side,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Bar {
|
||||
pub open: f64,
|
||||
pub high: f64,
|
||||
pub low: f64,
|
||||
pub close: f64,
|
||||
pub volume: f64,
|
||||
pub vwap: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
pub enum Side {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Order {
|
||||
pub id: String,
|
||||
pub symbol: String,
|
||||
pub side: Side,
|
||||
pub quantity: f64,
|
||||
pub order_type: OrderType,
|
||||
pub time_in_force: TimeInForce,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum OrderType {
|
||||
Market,
|
||||
Limit { price: f64 },
|
||||
Stop { stop_price: f64 },
|
||||
StopLimit { stop_price: f64, limit_price: f64 },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum TimeInForce {
|
||||
Day,
|
||||
GTC,
|
||||
IOC,
|
||||
FOK,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ExecutionResult {
|
||||
pub order_id: String,
|
||||
pub status: OrderStatus,
|
||||
pub fills: Vec<Fill>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum OrderStatus {
|
||||
Pending,
|
||||
Accepted,
|
||||
PartiallyFilled,
|
||||
Filled,
|
||||
Cancelled,
|
||||
Rejected(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Fill {
|
||||
pub timestamp: DateTime<Utc>,
|
||||
pub price: f64,
|
||||
pub quantity: f64,
|
||||
pub commission: f64,
|
||||
}
|
||||
|
||||
// OrderBook types
|
||||
pub type OrderBookSnapshot = orderbook::OrderBookSnapshot;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PriceLevel {
|
||||
pub price: f64,
|
||||
pub size: f64,
|
||||
pub order_count: Option<u32>,
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue