work on new engine

This commit is contained in:
Boki 2025-07-04 11:24:27 -04:00
parent 44476da13f
commit a1e5a21847
126 changed files with 3425 additions and 6695 deletions

View file

@ -0,0 +1,715 @@
use std::collections::HashMap;
use std::sync::Arc;
use parking_lot::RwLock;
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};
use crate::{
TradingMode, MarketDataSource, ExecutionHandler, TimeProvider,
MarketUpdate, MarketDataType, Order, Fill, Side,
positions::PositionTracker,
risk::RiskEngine,
orderbook::OrderBookManager,
};
use super::{
BacktestConfig, BacktestState, EventQueue, BacktestEvent, EventType,
Strategy, Signal, SignalType, BacktestResult, TradeTracker,
};
pub struct BacktestEngine {
config: BacktestConfig,
state: Arc<RwLock<BacktestState>>,
event_queue: Arc<RwLock<EventQueue>>,
strategies: Arc<RwLock<Vec<Box<dyn Strategy>>>>,
// Core components
position_tracker: Arc<PositionTracker>,
risk_engine: Arc<RiskEngine>,
orderbook_manager: Arc<OrderBookManager>,
time_provider: Arc<Box<dyn TimeProvider>>,
pub market_data_source: Arc<RwLock<Box<dyn MarketDataSource>>>,
execution_handler: Arc<RwLock<Box<dyn ExecutionHandler>>>,
// Metrics
total_trades: usize,
profitable_trades: usize,
total_pnl: f64,
// Price tracking - single source of truth
// Maps symbol -> (timestamp, price)
last_prices: HashMap<String, (DateTime<Utc>, f64)>,
// Trade tracking
trade_tracker: TradeTracker,
}
impl BacktestEngine {
pub fn new(
config: BacktestConfig,
mode: TradingMode,
time_provider: Box<dyn TimeProvider>,
market_data_source: Box<dyn MarketDataSource>,
execution_handler: Box<dyn ExecutionHandler>,
) -> Self {
let state = Arc::new(RwLock::new(
BacktestState::new(config.initial_capital, config.start_time)
));
Self {
config,
state,
event_queue: Arc::new(RwLock::new(EventQueue::new())),
strategies: Arc::new(RwLock::new(Vec::new())),
position_tracker: Arc::new(PositionTracker::new()),
risk_engine: Arc::new(RiskEngine::new()),
orderbook_manager: Arc::new(OrderBookManager::new()),
time_provider: Arc::new(time_provider),
market_data_source: Arc::new(RwLock::new(market_data_source)),
execution_handler: Arc::new(RwLock::new(execution_handler)),
total_trades: 0,
profitable_trades: 0,
total_pnl: 0.0,
last_prices: HashMap::new(),
trade_tracker: TradeTracker::new(),
}
}
pub fn add_strategy(&mut self, strategy: Box<dyn Strategy>) {
self.strategies.write().push(strategy);
}
pub async fn run(&mut self) -> Result<BacktestResult, String> {
eprintln!("=== BacktestEngine::run() START ===");
eprintln!("Config: start={}, end={}, symbols={:?}",
self.config.start_time, self.config.end_time, self.config.symbols);
eprintln!("Number of strategies loaded: {}", self.strategies.read().len());
// Initialize start time
if let Some(simulated_time) = self.time_provider.as_any()
.downcast_ref::<crate::core::time_providers::SimulatedTime>()
{
simulated_time.advance_to(self.config.start_time);
eprintln!("Time initialized to: {}", self.config.start_time);
}
// Load market data
eprintln!("Loading market data from data source...");
self.load_market_data().await?;
let queue_len = self.event_queue.read().len();
eprintln!("Event queue length after loading: {}", queue_len);
if queue_len == 0 {
eprintln!("WARNING: No events loaded! Check data source.");
}
// Main event loop - process events grouped by timestamp
let mut iteration = 0;
let mut last_update_time = self.config.start_time;
while !self.event_queue.read().is_empty() {
iteration += 1;
// Get the next event's timestamp
let next_event_time = self.event_queue.read()
.peek_next()
.map(|e| e.timestamp);
if let Some(event_time) = next_event_time {
// Advance time to the next event
self.advance_time(event_time);
// Get all events at this timestamp
let current_time = self.time_provider.now();
let events = self.event_queue.write().pop_until(current_time);
if iteration <= 5 || iteration % 100 == 0 {
eprintln!("Processing iteration {} at time {} with {} events",
iteration, current_time, events.len());
}
// Process all events at this timestamp
for event in events {
self.process_event(event).await?;
}
// Only update portfolio value if time has actually advanced
// This ensures we have prices for all symbols at this timestamp
if current_time > last_update_time {
self.update_portfolio_value();
last_update_time = current_time;
}
} else {
// No more events
break;
}
}
eprintln!("Backtest complete. Total trades: {}", self.total_trades);
// Close all open positions at market prices
self.close_all_positions().await?;
// Generate results
Ok(self.generate_results())
}
async fn load_market_data(&mut self) -> Result<(), String> {
eprintln!("=== load_market_data START ===");
let mut data_source = self.market_data_source.write();
// Check if it's a HistoricalDataSource
if let Some(historical) = data_source.as_any()
.downcast_ref::<crate::core::market_data_sources::HistoricalDataSource>() {
eprintln!("Data source is HistoricalDataSource");
eprintln!("Historical data points available: {}", historical.data_len());
} else {
eprintln!("WARNING: Data source is NOT HistoricalDataSource!");
}
eprintln!("Seeking to start time: {}", self.config.start_time);
data_source.seek_to_time(self.config.start_time)?;
let mut count = 0;
let mut first_few = 0;
// Load all data into event queue
while let Some(update) = data_source.get_next_update().await {
if update.timestamp > self.config.end_time {
eprintln!("Reached end time at {} data points", count);
break;
}
count += 1;
// Log first few data points
if first_few < 3 {
eprintln!("Data point {}: symbol={}, time={}, type={:?}",
count, update.symbol, update.timestamp,
match &update.data {
MarketDataType::Bar(b) => format!("Bar(close={})", b.close),
MarketDataType::Quote(q) => format!("Quote(bid={}, ask={})", q.bid, q.ask),
MarketDataType::Trade(t) => format!("Trade(price={})", t.price),
}
);
first_few += 1;
}
if count % 100 == 0 {
eprintln!("Loaded {} data points so far...", count);
}
let event = BacktestEvent::market_data(update.timestamp, update);
self.event_queue.write().push(event);
}
eprintln!("=== load_market_data COMPLETE ===");
eprintln!("Total data points loaded: {}", count);
Ok(())
}
async fn process_event(&mut self, event: BacktestEvent) -> Result<(), String> {
match event.event_type {
EventType::MarketData(data) => {
self.process_market_data(data).await?;
}
EventType::OrderSubmitted(order) => {
self.process_order_submission(order).await?;
}
EventType::OrderFilled(_fill) => {
// Fills are already processed when orders are executed
// This event is just for recording
// Note: We now record fills in process_fill with symbol info
}
EventType::OrderCancelled(order_id) => {
self.process_order_cancellation(&order_id)?;
}
EventType::TimeUpdate(time) => {
self.advance_time(time);
}
}
Ok(())
}
async fn process_market_data(&mut self, data: MarketUpdate) -> Result<(), String> {
static mut MARKET_DATA_COUNT: usize = 0;
unsafe {
MARKET_DATA_COUNT += 1;
if MARKET_DATA_COUNT <= 3 || MARKET_DATA_COUNT % 100 == 0 {
eprintln!("process_market_data #{}: symbol={}, time={}",
MARKET_DATA_COUNT, data.symbol, data.timestamp);
}
}
// Update price tracking - single source of truth
let price = match &data.data {
MarketDataType::Bar(bar) => {
let old_entry = self.last_prices.get(&data.symbol);
let old_price = old_entry.map(|(_, p)| *p);
eprintln!("📊 PRICE UPDATE: {} @ {} - close: ${:.2} (was: ${:?})",
data.symbol, data.timestamp.format("%Y-%m-%d"), bar.close, old_price);
bar.close
}
MarketDataType::Quote(quote) => {
// Use mid price for quotes
(quote.bid + quote.ask) / 2.0
}
MarketDataType::Trade(trade) => {
trade.price
}
};
// Store price with timestamp - this is our source of truth
self.last_prices.insert(data.symbol.clone(), (data.timestamp, price));
// Convert to simpler MarketData for strategies
let market_data = self.convert_to_market_data(&data);
// Send to strategies
let mut all_signals = Vec::new();
{
let mut strategies = self.strategies.write();
for (i, strategy) in strategies.iter_mut().enumerate() {
let signals = strategy.on_market_data(&market_data);
if !signals.is_empty() {
eprintln!("Strategy {} generated {} signals!", i, signals.len());
}
all_signals.extend(signals);
}
}
// Process signals
for signal in all_signals {
eprintln!("Processing signal: {:?}", signal);
self.process_signal(signal).await?;
}
// Check pending orders for fills
self.check_pending_orders(&data).await?;
// Don't update portfolio value here - wait until all events at this timestamp are processed
Ok(())
}
fn convert_to_market_data(&self, update: &MarketUpdate) -> MarketUpdate {
// MarketData is a type alias for MarketUpdate
update.clone()
}
async fn process_signal(&mut self, signal: Signal) -> Result<(), String> {
let current_time = self.time_provider.now();
eprintln!("📡 SIGNAL at {}: {:?} {} (strength: {}, reason: {:?})",
current_time.format("%Y-%m-%d"),
signal.signal_type,
signal.symbol,
signal.strength,
signal.reason);
// Only process strong signals
if signal.strength.abs() < 0.7 {
eprintln!(" Signal ignored (strength < 0.7)");
return Ok(());
}
// Check current price before creating order
if let Some((price_time, price)) = self.last_prices.get(&signal.symbol) {
eprintln!(" Current price for {}: ${:.2} (from {})",
signal.symbol, price, price_time.format("%Y-%m-%d"));
}
// Convert signal to order
let order = self.signal_to_order(signal)?;
eprintln!(" Creating {:?} order for {} shares", order.side, order.quantity);
// Submit order
self.process_order_submission(order).await
}
fn signal_to_order(&self, signal: Signal) -> Result<Order, String> {
let quantity = signal.quantity.unwrap_or_else(|| {
// Calculate position size based on portfolio
self.calculate_position_size(&signal.symbol, signal.strength)
});
let side = match signal.signal_type {
SignalType::Buy => Side::Buy,
SignalType::Sell => Side::Sell,
SignalType::Close => {
// Determine side based on current position
let position = self.position_tracker.get_position(&signal.symbol);
if position.as_ref().map(|p| p.quantity > 0.0).unwrap_or(false) {
Side::Sell
} else {
Side::Buy
}
}
};
Ok(crate::Order {
id: format!("order_{}", uuid::Uuid::new_v4()),
symbol: signal.symbol,
side,
quantity,
order_type: crate::OrderType::Market,
time_in_force: crate::TimeInForce::Day,
})
}
async fn process_order_submission(&mut self, order: Order) -> Result<(), String> {
// Risk checks
// Get current position for the symbol
let current_position = self.position_tracker
.get_position(&order.symbol)
.map(|p| p.quantity);
let risk_check = self.risk_engine.check_order(&order, current_position);
if !risk_check.passed {
return Err(format!("Risk check failed: {:?}", risk_check.violations));
}
// Add to pending orders
self.state.write().add_pending_order(order.clone());
// For market orders in backtesting, fill immediately
if matches!(order.order_type, crate::OrderType::Market) {
self.check_order_fill(&order).await?;
}
Ok(())
}
async fn check_pending_orders(&mut self, market_data: &MarketUpdate) -> Result<(), String> {
let orders_to_check: Vec<Order> = {
let state = self.state.read();
state.pending_orders.values()
.filter(|o| o.symbol == market_data.symbol)
.cloned()
.collect()
};
for order in orders_to_check {
self.check_order_fill(&order).await?;
}
Ok(())
}
async fn check_order_fill(&mut self, order: &Order) -> Result<(), String> {
let current_time = self.time_provider.now();
// Get current market price - only use if it's from the current time
let (price_time, base_price) = self.last_prices.get(&order.symbol)
.copied()
.ok_or_else(|| format!("No price available for symbol: {}", order.symbol))?;
// CRITICAL: Verify the price is from the current time
if price_time != current_time {
eprintln!("⚠️ WARNING: Price timestamp mismatch! Current: {}, Price from: {}",
current_time.format("%Y-%m-%d %H:%M:%S"),
price_time.format("%Y-%m-%d %H:%M:%S"));
// In a real system, we would reject this fill or fetch current price
// For now, log the issue
}
eprintln!("🔍 CHECK_ORDER_FILL: {:?} {} @ time {} - price: ${:.2} (from {})",
order.side, order.symbol, current_time.format("%Y-%m-%d"),
base_price, price_time.format("%Y-%m-%d"));
// DEBUG: Check what's in last_prices for this symbol
eprintln!(" DEBUG: All prices for {}: {:?}",
order.symbol,
self.last_prices.get(&order.symbol));
// Apply slippage
let fill_price = match order.side {
crate::Side::Buy => base_price * (1.0 + self.config.slippage),
crate::Side::Sell => base_price * (1.0 - self.config.slippage),
};
eprintln!(" Fill price after slippage ({}): ${:.2}", self.config.slippage, fill_price);
// Create fill
let fill = crate::Fill {
timestamp: current_time,
price: fill_price,
quantity: order.quantity,
commission: order.quantity * fill_price * self.config.commission,
};
// Process the fill
self.process_fill(&order, fill).await
}
async fn process_fill(&mut self, order: &crate::Order, fill: crate::Fill) -> Result<(), String> {
// Remove from pending orders
self.state.write().remove_pending_order(&order.id);
// Get position before the fill
let position_before = self.position_tracker
.get_position(&order.symbol)
.map(|p| p.quantity)
.unwrap_or(0.0);
// Update positions
let update = self.position_tracker.process_fill(
&order.symbol,
&fill,
order.side,
);
// Calculate P&L if position was reduced/closed
let pnl = if update.resulting_position.realized_pnl != 0.0 {
Some(update.resulting_position.realized_pnl)
} else {
None
};
// Get position after this fill
let position_after = update.resulting_position.quantity;
// Record the fill with position and P&L information
self.state.write().record_fill(
order.symbol.clone(),
order.side,
fill.clone(),
position_after,
position_before,
pnl
);
// Track trades
self.trade_tracker.process_fill(&order.symbol, order.side, &fill);
// Update cash
let cash_change = match order.side {
crate::Side::Buy => -(fill.quantity * fill.price + fill.commission),
crate::Side::Sell => fill.quantity * fill.price - fill.commission,
};
self.state.write().cash += cash_change;
// Notify strategies
{
let mut strategies = self.strategies.write();
for strategy in strategies.iter_mut() {
let side_str = match order.side {
crate::Side::Buy => "buy",
crate::Side::Sell => "sell",
};
strategy.on_fill(&order.symbol, fill.quantity, fill.price, side_str);
}
}
let fill_date = fill.timestamp.format("%Y-%m-%d").to_string();
let is_feb_mar_2024 = fill_date >= "2024-02-28".to_string() && fill_date <= "2024-03-05".to_string();
if is_feb_mar_2024 {
eprintln!("
🔴 CRITICAL FILL on {}: {} {} @ {} (side: {:?})",
fill_date, fill.quantity, order.symbol, fill.price, order.side);
eprintln!("Cash before: ${:.2}, Cash after: ${:.2}, Cash change: ${:.2}",
self.state.read().cash - cash_change, self.state.read().cash, cash_change);
}
eprintln!("Fill processed: {} {} @ {} (side: {:?})",
fill.quantity, order.symbol, fill.price, order.side);
eprintln!("Current position after fill: {}",
self.position_tracker.get_position(&order.symbol)
.map(|p| p.quantity)
.unwrap_or(0.0));
// Update metrics
self.total_trades += 1;
if update.resulting_position.realized_pnl > 0.0 {
self.profitable_trades += 1;
}
self.total_pnl = update.resulting_position.realized_pnl;
Ok(())
}
fn process_order_cancellation(&mut self, order_id: &str) -> Result<(), String> {
self.state.write().remove_pending_order(order_id);
Ok(())
}
fn advance_time(&mut self, time: DateTime<Utc>) {
if let Some(simulated_time) = self.time_provider.as_any()
.downcast_ref::<crate::core::time_providers::SimulatedTime>()
{
simulated_time.advance_to(time);
}
self.state.write().current_time = time;
}
fn update_portfolio_value(&mut self) {
let positions = self.position_tracker.get_all_positions();
let cash = self.state.read().cash;
let mut portfolio_value = cash;
let current_time = self.time_provider.now();
// Debug logging for first few updates
static mut UPDATE_COUNT: usize = 0;
unsafe {
UPDATE_COUNT += 1;
if UPDATE_COUNT <= 5 || UPDATE_COUNT % 100 == 0 ||
// Log around Feb 28 - Mar 5, 2024
(current_time.format("%Y-%m-%d").to_string() >= "2024-02-28".to_string() &&
current_time.format("%Y-%m-%d").to_string() <= "2024-03-05".to_string()) {
eprintln!("=== Portfolio Update #{} at {} ===", UPDATE_COUNT, current_time);
eprintln!("Cash: ${:.2}", cash);
}
}
for position in &positions {
// Use last known price for the symbol
let price = self.last_prices.get(&position.symbol)
.map(|(_, p)| *p)
.unwrap_or(position.average_price);
// Calculate market value correctly for long and short positions
let market_value = if position.quantity > 0.0 {
// Long position: value = quantity * current_price
position.quantity * price
} else {
// Short position:
// We have a liability to buy back shares at current market price
// This is a negative value that reduces portfolio value
// Value = quantity * price (quantity is already negative)
position.quantity * price
};
portfolio_value += market_value;
unsafe {
if UPDATE_COUNT <= 5 || UPDATE_COUNT % 100 == 0 ||
// Log around Feb 28 - Mar 5, 2024
(current_time.format("%Y-%m-%d").to_string() >= "2024-02-28".to_string() &&
current_time.format("%Y-%m-%d").to_string() <= "2024-03-05".to_string()) {
let pnl = if position.quantity > 0.0 {
(price - position.average_price) * position.quantity
} else {
(position.average_price - price) * position.quantity.abs()
};
let position_type = if position.quantity > 0.0 { "LONG" } else { "SHORT" };
eprintln!(" {} {} position: {} shares @ avg ${:.2}, current ${:.2} = ${:.2} (P&L: ${:.2})",
position_type, position.symbol, position.quantity, position.average_price, price, market_value, pnl);
}
}
}
unsafe {
if UPDATE_COUNT <= 5 || UPDATE_COUNT % 100 == 0 ||
// Log around Feb 28 - Mar 5, 2024
(current_time.format("%Y-%m-%d").to_string() >= "2024-02-28".to_string() &&
current_time.format("%Y-%m-%d").to_string() <= "2024-03-05".to_string()) {
eprintln!("Total Portfolio Value: ${:.2}", portfolio_value);
eprintln!("===================================");
}
}
self.state.write().update_portfolio_value(portfolio_value);
}
fn calculate_position_size(&self, symbol: &str, signal_strength: f64) -> f64 {
let state = self.state.read();
let portfolio_value = state.portfolio_value;
let cash = state.cash;
// Use available cash, not total portfolio value for position sizing
let allocation = 0.2; // 20% of available cash per position
let position_value = cash.min(portfolio_value * allocation) * signal_strength.abs();
let price = self.last_prices.get(symbol)
.map(|(_, p)| *p)
.unwrap_or(100.0);
let shares = (position_value / price).floor();
eprintln!("Position sizing for {}: portfolio=${:.2}, cash=${:.2}, price=${:.2}, shares={}",
symbol, portfolio_value, cash, price, shares);
shares
}
fn get_next_event_time(&self) -> Option<DateTime<Utc>> {
// Get the timestamp of the next event in the queue
self.event_queue.read()
.peek_next()
.map(|event| event.timestamp)
}
async fn close_all_positions(&mut self) -> Result<(), String> {
eprintln!("=== Closing all open positions at end of backtest ===");
eprintln!("Current time: {}", self.time_provider.now());
eprintln!("Last prices:");
for (symbol, (time, price)) in &self.last_prices {
eprintln!(" {}: ${:.2} (from {})", symbol, price, time.format("%Y-%m-%d %H:%M:%S"));
}
let positions = self.position_tracker.get_all_positions();
for position in positions {
if position.quantity.abs() > 0.001 {
let last_price = self.last_prices.get(&position.symbol).map(|(_, p)| *p);
eprintln!("Closing position: {} {} shares of {} at last price: {:?}",
if position.quantity > 0.0 { "Selling" } else { "Buying" },
position.quantity.abs(),
position.symbol,
last_price
);
// Create market order to close position
let order = crate::Order {
id: format!("close_{}", uuid::Uuid::new_v4()),
symbol: position.symbol.clone(),
side: if position.quantity > 0.0 { Side::Sell } else { Side::Buy },
quantity: position.quantity.abs(),
order_type: crate::OrderType::Market,
time_in_force: crate::TimeInForce::Day,
};
// Process the closing order
self.check_order_fill(&order).await?;
}
}
eprintln!("All positions closed. Final cash: {}", self.state.read().cash);
Ok(())
}
fn generate_results(&self) -> BacktestResult {
let state = self.state.read();
let start_time = self.config.start_time;
// Get final positions
let final_positions = self.position_tracker.get_all_positions()
.into_iter()
.map(|p| (p.symbol.clone(), p))
.collect();
// Get completed trades from tracker
let completed_trades = self.trade_tracker.get_completed_trades();
// Convert last_prices to simple HashMap for results
let simple_last_prices: HashMap<String, f64> = self.last_prices
.iter()
.map(|(symbol, (_, price))| (symbol.clone(), *price))
.collect();
// Use simple results builder with proper trade data
BacktestResult::from_engine_data_with_trades(
self.config.clone(),
state.equity_curve.clone(),
state.completed_trades.clone(),
completed_trades,
final_positions,
start_time,
&simple_last_prices,
)
}
}
// Add uuid dependency
use uuid::Uuid;

View file

@ -0,0 +1,55 @@
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};
use crate::{MarketUpdate, Order, Fill};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EventType {
MarketData(MarketUpdate),
OrderSubmitted(Order),
OrderFilled(Fill),
OrderCancelled(String), // order_id
TimeUpdate(DateTime<Utc>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacktestEvent {
pub timestamp: DateTime<Utc>,
pub event_type: EventType,
}
impl BacktestEvent {
pub fn market_data(timestamp: DateTime<Utc>, data: MarketUpdate) -> Self {
Self {
timestamp,
event_type: EventType::MarketData(data),
}
}
pub fn order_submitted(timestamp: DateTime<Utc>, order: Order) -> Self {
Self {
timestamp,
event_type: EventType::OrderSubmitted(order),
}
}
pub fn order_filled(timestamp: DateTime<Utc>, fill: Fill) -> Self {
Self {
timestamp,
event_type: EventType::OrderFilled(fill),
}
}
pub fn order_cancelled(timestamp: DateTime<Utc>, order_id: String) -> Self {
Self {
timestamp,
event_type: EventType::OrderCancelled(order_id),
}
}
pub fn time_update(timestamp: DateTime<Utc>) -> Self {
Self {
timestamp,
event_type: EventType::TimeUpdate(timestamp),
}
}
}

View file

@ -0,0 +1,669 @@
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()
}
}

View file

@ -0,0 +1,155 @@
use crate::{MarketUpdate, Order, Fill, TradingMode, MarketDataSource, ExecutionHandler, TimeProvider, Side};
use crate::positions::PositionTracker;
use crate::risk::RiskEngine;
use crate::orderbook::OrderBookManager;
use chrono::{DateTime, Utc};
use std::collections::{BTreeMap, VecDeque};
use std::sync::Arc;
use parking_lot::RwLock;
use serde::{Serialize, Deserialize};
pub mod engine;
pub mod event;
pub mod strategy;
pub mod simple_results;
pub mod trade_tracker;
pub use engine::BacktestEngine;
pub use event::{BacktestEvent, EventType};
pub use strategy::{Strategy, Signal, SignalType};
pub use simple_results::{BacktestResult, BacktestMetrics};
pub use trade_tracker::{TradeTracker, CompletedTrade as TrackedTrade};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletedTrade {
pub symbol: String,
pub side: Side,
pub timestamp: DateTime<Utc>,
pub price: f64,
pub quantity: f64,
pub commission: f64,
pub position_after: f64, // Position size after this trade
pub pnl: Option<f64>, // P&L if position was reduced/closed
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BacktestConfig {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub strategy: Option<String>,
pub symbols: Vec<String>,
#[serde(rename = "startDate")]
pub start_time: DateTime<Utc>,
#[serde(rename = "endDate")]
pub end_time: DateTime<Utc>,
pub initial_capital: f64,
pub commission: f64,
pub slippage: f64,
pub data_frequency: String,
}
#[derive(Debug, Clone)]
pub struct BacktestState {
pub current_time: DateTime<Utc>,
pub portfolio_value: f64,
pub cash: f64,
pub equity_curve: Vec<(DateTime<Utc>, f64)>,
pub pending_orders: BTreeMap<String, Order>,
pub completed_trades: Vec<CompletedTrade>,
}
impl BacktestState {
pub fn new(initial_capital: f64, start_time: DateTime<Utc>) -> Self {
Self {
current_time: start_time,
portfolio_value: initial_capital,
cash: initial_capital,
equity_curve: vec![(start_time, initial_capital)],
pending_orders: BTreeMap::new(),
completed_trades: Vec::new(),
}
}
pub fn update_portfolio_value(&mut self, value: f64) {
self.portfolio_value = value;
// Only add a new equity curve point if the timestamp has changed
// or if it's the first point
if self.equity_curve.is_empty() ||
self.equity_curve.last().map(|(t, _)| *t != self.current_time).unwrap_or(true) {
self.equity_curve.push((self.current_time, value));
} else {
// Update the last point with the new value
if let Some(last) = self.equity_curve.last_mut() {
last.1 = value;
}
}
}
pub fn add_pending_order(&mut self, order: Order) {
self.pending_orders.insert(order.id.clone(), order);
}
pub fn remove_pending_order(&mut self, order_id: &str) -> Option<Order> {
self.pending_orders.remove(order_id)
}
pub fn record_fill(&mut self, symbol: String, side: Side, fill: Fill, position_after: f64, position_before: f64, pnl: Option<f64>) {
self.completed_trades.push(CompletedTrade {
symbol,
side,
timestamp: fill.timestamp,
price: fill.price,
quantity: fill.quantity,
commission: fill.commission,
position_after,
pnl,
});
}
}
// Event queue for deterministic replay
#[derive(Debug)]
pub struct EventQueue {
events: VecDeque<BacktestEvent>,
}
impl EventQueue {
pub fn new() -> Self {
Self {
events: VecDeque::new(),
}
}
pub fn push(&mut self, event: BacktestEvent) {
// Insert in time order
let pos = self.events.iter().position(|e| e.timestamp > event.timestamp)
.unwrap_or(self.events.len());
self.events.insert(pos, event);
}
pub fn pop_until(&mut self, timestamp: DateTime<Utc>) -> Vec<BacktestEvent> {
let mut events = Vec::new();
while let Some(event) = self.events.front() {
if event.timestamp <= timestamp {
events.push(self.events.pop_front().unwrap());
} else {
break;
}
}
events
}
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn len(&self) -> usize {
self.events.len()
}
pub fn peek_next(&self) -> Option<&BacktestEvent> {
self.events.front()
}
}

View file

@ -0,0 +1,266 @@
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,
}

View file

@ -0,0 +1,565 @@
use chrono::{DateTime, Utc, Datelike};
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use crate::Position;
use super::{BacktestConfig, CompletedTrade};
use super::trade_tracker::CompletedTrade as TrackedTrade;
// Simplified metrics that match what the web app expects
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BacktestMetrics {
pub total_return: f64,
pub sharpe_ratio: f64,
pub max_drawdown: f64,
pub win_rate: f64,
pub total_trades: usize,
pub profitable_trades: usize,
// Additional fields for compatibility
pub profit_factor: f64,
pub total_pnl: f64,
pub avg_win: f64,
pub avg_loss: f64,
pub expectancy: f64,
pub calmar_ratio: f64,
pub sortino_ratio: f64,
// Missing fields required by web app
pub final_value: f64,
pub winning_trades: usize,
pub losing_trades: usize,
pub largest_win: f64,
pub largest_loss: f64,
pub annual_return: f64,
}
// Individual trade (fill) structure for UI
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Trade {
pub id: String,
pub timestamp: String,
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>,
pub position_after: f64, // Position size after this trade
}
// Analytics data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Analytics {
pub drawdown_series: Vec<EquityPoint>,
pub daily_returns: Vec<f64>,
pub monthly_returns: HashMap<String, f64>,
pub exposure_time: f64,
pub risk_metrics: HashMap<String, f64>,
}
// Position structure for web app
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionInfo {
pub symbol: String,
pub quantity: f64,
pub average_price: f64,
pub current_price: f64,
pub unrealized_pnl: f64,
pub realized_pnl: f64,
}
// Equity data point for charts
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EquityDataPoint {
pub date: String,
pub value: f64,
}
// Simplified backtest result
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BacktestResult {
pub backtest_id: String,
pub status: String,
pub completed_at: String,
pub config: BacktestConfig,
pub metrics: BacktestMetrics,
pub equity: Vec<EquityDataPoint>,
pub trades: Vec<Trade>, // Now shows all individual fills
pub positions: Vec<PositionInfo>,
pub analytics: Analytics,
pub execution_time: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
pub ohlc_data: HashMap<String, Vec<serde_json::Value>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EquityPoint {
pub timestamp: i64,
pub value: f64,
}
impl BacktestResult {
pub fn from_engine_data(
config: BacktestConfig,
equity_curve: Vec<(DateTime<Utc>, f64)>,
fills: Vec<CompletedTrade>,
final_positions: HashMap<String, Position>,
start_time: DateTime<Utc>,
) -> Self {
let initial_capital = config.initial_capital;
let final_value = equity_curve.last().map(|(_, v)| *v).unwrap_or(initial_capital);
// Convert fills to trades
let trades: Vec<Trade> = fills.iter()
.enumerate()
.map(|(i, fill)| Trade {
id: format!("trade-{}", i),
timestamp: fill.timestamp.to_rfc3339(),
symbol: fill.symbol.clone(),
side: match fill.side {
crate::Side::Buy => "buy".to_string(),
crate::Side::Sell => "sell".to_string(),
},
quantity: fill.quantity,
price: fill.price,
commission: fill.commission,
pnl: fill.pnl,
position_after: fill.position_after,
})
.collect();
// Calculate metrics
let total_trades = trades.len();
let total_return = ((final_value - initial_capital) / initial_capital) * 100.0;
let total_pnl = final_value - initial_capital;
// Basic win rate calculation - this is simplified
let profitable_trades = 0; // TODO: Calculate from paired trades
let win_rate = 0.0; // TODO: Calculate properly
// Calculate daily returns
let mut daily_returns_vec = Vec::new();
let mut prev_date = equity_curve.first().map(|(d, _)| d.date_naive()).unwrap_or_default();
let mut prev_value = initial_capital;
for (dt, value) in &equity_curve {
if dt.date_naive() != prev_date {
let daily_return = (value - prev_value) / prev_value;
daily_returns_vec.push(daily_return);
prev_date = dt.date_naive();
prev_value = *value;
}
}
// Calculate volatility (annualized)
let volatility = if daily_returns_vec.len() > 1 {
let mean = daily_returns_vec.iter().sum::<f64>() / daily_returns_vec.len() as f64;
let variance = daily_returns_vec.iter()
.map(|r| (r - mean).powi(2))
.sum::<f64>() / daily_returns_vec.len() as f64;
variance.sqrt() * (252.0_f64).sqrt()
} else {
0.0
};
// Calculate Sharpe ratio
let risk_free_rate = 0.02; // 2% annual
let days = (config.end_time - config.start_time).num_days() as f64;
let years = days / 365.25;
let annualized_return = if years > 0.0 {
(final_value / initial_capital).powf(1.0 / years) - 1.0
} else {
0.0
};
let sharpe_ratio = if volatility > 0.0 {
(annualized_return - risk_free_rate) / volatility
} else {
0.0
};
// Calculate max drawdown
let (max_drawdown, drawdown_series) = Self::calculate_drawdown(&equity_curve, initial_capital);
// Calculate Calmar ratio
let calmar_ratio = if max_drawdown > 0.0 {
annualized_return / max_drawdown
} else {
0.0
};
// Convert positions
let positions: Vec<PositionInfo> = final_positions.iter()
.map(|(symbol, pos)| {
let current_price = pos.average_price; // TODO: Get actual current price
let unrealized_pnl = (current_price - pos.average_price) * pos.quantity;
PositionInfo {
symbol: symbol.clone(),
quantity: pos.quantity,
average_price: pos.average_price,
current_price,
unrealized_pnl,
realized_pnl: pos.realized_pnl,
}
})
.collect();
// Convert equity curve to the format expected by web app
let equity: Vec<EquityDataPoint> = equity_curve.iter()
.map(|(dt, val)| EquityDataPoint {
date: dt.to_rfc3339(),
value: *val,
})
.collect();
let metrics = BacktestMetrics {
total_return,
sharpe_ratio,
max_drawdown,
win_rate,
total_trades,
profitable_trades,
profit_factor: 0.0,
total_pnl,
avg_win: 0.0,
avg_loss: 0.0,
expectancy: 0.0,
calmar_ratio,
sortino_ratio: 0.0, // TODO: Calculate
final_value,
winning_trades: profitable_trades,
losing_trades: 0,
largest_win: 0.0,
largest_loss: 0.0,
annual_return: annualized_return * 100.0,
};
// Create analytics
let analytics = Analytics {
drawdown_series,
daily_returns: daily_returns_vec,
monthly_returns: HashMap::new(), // TODO: Calculate
exposure_time: 0.0, // TODO: Calculate
risk_metrics: HashMap::new(), // TODO: Add risk metrics
};
BacktestResult {
backtest_id: format!("rust-{}", Utc::now().timestamp_millis()),
status: "completed".to_string(),
completed_at: Utc::now().to_rfc3339(),
config,
metrics,
equity,
trades: Vec::new(), // No completed trades in simple version
positions,
analytics,
execution_time: (Utc::now() - start_time).num_milliseconds() as u64,
error: None,
ohlc_data: HashMap::new(),
}
}
fn calculate_drawdown(equity_curve: &[(DateTime<Utc>, f64)], initial_capital: f64) -> (f64, Vec<EquityPoint>) {
let mut max_drawdown = 0.0;
let mut peak = initial_capital;
let mut drawdown_series = Vec::new();
for (dt, value) in equity_curve {
if *value > peak {
peak = *value;
}
let drawdown_pct = if peak > 0.0 {
((peak - value) / peak) * 100.0
} else {
0.0
};
if drawdown_pct > max_drawdown {
max_drawdown = drawdown_pct;
}
drawdown_series.push(EquityPoint {
timestamp: dt.timestamp_millis(),
value: -drawdown_pct, // Negative for visualization
});
}
(max_drawdown / 100.0, drawdown_series) // Return as decimal
}
pub fn from_engine_data_with_trades(
config: BacktestConfig,
equity_curve: Vec<(DateTime<Utc>, f64)>,
fills: Vec<CompletedTrade>,
completed_trades: Vec<TrackedTrade>,
final_positions: HashMap<String, Position>,
start_time: DateTime<Utc>,
last_prices: &HashMap<String, f64>,
) -> Self {
let initial_capital = config.initial_capital;
let final_value = equity_curve.last().map(|(_, v)| *v).unwrap_or(initial_capital);
// Convert fills to web app format (all individual trades)
let trades: Vec<Trade> = fills.iter()
.enumerate()
.map(|(i, fill)| Trade {
id: format!("trade-{}", i + 1),
timestamp: fill.timestamp.to_rfc3339(),
symbol: fill.symbol.clone(),
side: match fill.side {
crate::Side::Buy => "buy".to_string(),
crate::Side::Sell => "sell".to_string(),
},
quantity: fill.quantity,
price: fill.price,
commission: fill.commission,
pnl: fill.pnl,
position_after: fill.position_after,
})
.collect();
// Calculate metrics from completed trades
let total_trades = completed_trades.len();
let total_return = ((final_value - initial_capital) / initial_capital) * 100.0;
let total_pnl = final_value - initial_capital;
// Calculate win rate and profit metrics
let winning_trades: Vec<&TrackedTrade> = completed_trades.iter()
.filter(|t| t.pnl > 0.0)
.collect();
let losing_trades: Vec<&TrackedTrade> = completed_trades.iter()
.filter(|t| t.pnl < 0.0)
.collect();
let profitable_trades = winning_trades.len();
let win_rate = if total_trades > 0 {
(profitable_trades as f64 / total_trades as f64) * 100.0
} else {
0.0
};
let avg_win = if !winning_trades.is_empty() {
winning_trades.iter().map(|t| t.pnl).sum::<f64>() / winning_trades.len() as f64
} else {
0.0
};
let avg_loss = if !losing_trades.is_empty() {
losing_trades.iter().map(|t| t.pnl).sum::<f64>() / losing_trades.len() as f64
} else {
0.0
};
let gross_profit = winning_trades.iter().map(|t| t.pnl).sum::<f64>();
let gross_loss = losing_trades.iter().map(|t| t.pnl.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
};
let expectancy = avg_win * (win_rate / 100.0) - avg_loss.abs() * ((100.0 - win_rate) / 100.0);
// Calculate daily returns
let mut daily_returns_vec = Vec::new();
let mut prev_date = equity_curve.first().map(|(d, _)| d.date_naive()).unwrap_or_default();
let mut prev_value = initial_capital;
for (dt, value) in &equity_curve {
if dt.date_naive() != prev_date {
let daily_return = (value - prev_value) / prev_value;
daily_returns_vec.push(daily_return);
prev_date = dt.date_naive();
prev_value = *value;
}
}
// Calculate volatility (annualized)
let volatility = if daily_returns_vec.len() > 1 {
let mean = daily_returns_vec.iter().sum::<f64>() / daily_returns_vec.len() as f64;
let variance = daily_returns_vec.iter()
.map(|r| (r - mean).powi(2))
.sum::<f64>() / daily_returns_vec.len() as f64;
variance.sqrt() * (252.0_f64).sqrt()
} else {
0.0
};
// Calculate Sharpe ratio
let risk_free_rate = 0.02; // 2% annual
let days = (config.end_time - config.start_time).num_days() as f64;
let years = days / 365.25;
let annualized_return = if years > 0.0 {
(final_value / initial_capital).powf(1.0 / years) - 1.0
} else {
0.0
};
let sharpe_ratio = if volatility > 0.0 {
(annualized_return - risk_free_rate) / volatility
} else {
0.0
};
// Calculate Sortino ratio (using downside deviation)
let negative_returns: Vec<f64> = daily_returns_vec.iter()
.filter(|&&r| r < 0.0)
.cloned()
.collect();
let downside_deviation = if !negative_returns.is_empty() {
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()
} else {
0.0
};
let sortino_ratio = if downside_deviation > 0.0 {
(annualized_return - risk_free_rate) / downside_deviation
} else {
0.0
};
// Calculate max drawdown
let (max_drawdown, drawdown_series) = Self::calculate_drawdown(&equity_curve, initial_capital);
// Calculate Calmar ratio
let calmar_ratio = if max_drawdown > 0.0 {
annualized_return / max_drawdown
} else {
0.0
};
// Convert positions with actual last prices
let positions: Vec<PositionInfo> = final_positions.iter()
.map(|(symbol, pos)| {
let current_price = last_prices.get(symbol).copied()
.unwrap_or(pos.average_price);
let unrealized_pnl = (current_price - pos.average_price) * pos.quantity;
PositionInfo {
symbol: symbol.clone(),
quantity: pos.quantity,
average_price: pos.average_price,
current_price,
unrealized_pnl,
realized_pnl: pos.realized_pnl,
}
})
.collect();
// Convert equity curve to the format expected by web app
let equity: Vec<EquityDataPoint> = equity_curve.iter()
.map(|(dt, val)| EquityDataPoint {
date: dt.to_rfc3339(),
value: *val,
})
.collect();
// Convert individual fills to UI format (for backward compatibility)
let _fill_trades: Vec<Trade> = fills.iter()
.enumerate()
.map(|(i, fill)| Trade {
id: format!("fill-{}", i),
timestamp: fill.timestamp.to_rfc3339(),
symbol: fill.symbol.clone(),
side: match fill.side {
crate::Side::Buy => "buy".to_string(),
crate::Side::Sell => "sell".to_string(),
},
quantity: fill.quantity,
price: fill.price,
commission: fill.commission,
pnl: fill.pnl,
position_after: fill.position_after,
})
.collect();
// Find largest win/loss
let largest_win = winning_trades.iter()
.map(|t| t.pnl)
.max_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap_or(0.0);
let largest_loss = losing_trades.iter()
.map(|t| t.pnl)
.min_by(|a, b| a.partial_cmp(b).unwrap())
.unwrap_or(0.0);
let metrics = BacktestMetrics {
total_return,
sharpe_ratio,
max_drawdown,
win_rate,
total_trades,
profitable_trades,
profit_factor,
total_pnl,
avg_win,
avg_loss,
expectancy,
calmar_ratio,
sortino_ratio,
final_value,
winning_trades: profitable_trades,
losing_trades: losing_trades.len(),
largest_win,
largest_loss,
annual_return: annualized_return * 100.0, // Convert to percentage
};
// Calculate monthly returns
let mut monthly_returns = HashMap::new();
let mut monthly_values: HashMap<String, Vec<f64>> = HashMap::new();
for (dt, value) in &equity_curve {
let month_key = format!("{}-{:02}", dt.year(), dt.month());
monthly_values.entry(month_key).or_insert_with(Vec::new).push(*value);
}
for (month, values) in monthly_values {
if values.len() >= 2 {
let start = values.first().unwrap();
let end = values.last().unwrap();
let monthly_return = ((end - start) / start) * 100.0;
monthly_returns.insert(month, monthly_return);
}
}
// Create analytics
let analytics = Analytics {
drawdown_series,
daily_returns: daily_returns_vec,
monthly_returns,
exposure_time: 0.0, // TODO: Calculate based on position history
risk_metrics: {
let mut metrics = HashMap::new();
metrics.insert("volatility".to_string(), volatility);
metrics.insert("downside_deviation".to_string(), downside_deviation);
metrics.insert("value_at_risk_95".to_string(), 0.0); // TODO: Calculate VaR
metrics
},
};
BacktestResult {
backtest_id: format!("rust-{}", Utc::now().timestamp_millis()),
status: "completed".to_string(),
completed_at: Utc::now().to_rfc3339(),
config,
metrics,
equity,
trades, // Return the completed trades
positions,
analytics,
execution_time: (Utc::now() - start_time).num_milliseconds() as u64,
error: None,
ohlc_data: HashMap::new(),
}
}
}

View file

@ -0,0 +1,100 @@
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};
use crate::MarketData;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SignalType {
Buy,
Sell,
Close,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Signal {
pub symbol: String,
pub signal_type: SignalType,
pub strength: f64, // -1.0 to 1.0
pub quantity: Option<f64>,
pub reason: Option<String>,
pub metadata: Option<serde_json::Value>,
}
// This trait will be implemented by Rust strategies
// TypeScript strategies will communicate through FFI
pub trait Strategy: Send + Sync {
fn on_market_data(&mut self, data: &MarketData) -> Vec<Signal>;
fn on_fill(&mut self, symbol: &str, quantity: f64, price: f64, side: &str);
fn get_name(&self) -> &str;
fn get_parameters(&self) -> serde_json::Value;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StrategyCall {
pub method: String,
pub data: serde_json::Value,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StrategyResponse {
pub signals: Vec<Signal>,
}
// Bridge for TypeScript strategies
// This will be used to wrap TypeScript strategies
pub struct TypeScriptStrategy {
pub name: String,
pub id: String,
pub parameters: serde_json::Value,
// Callback function will be injected from TypeScript
pub callback: Option<Box<dyn Fn(StrategyCall) -> StrategyResponse + Send + Sync>>,
}
impl TypeScriptStrategy {
pub fn new(name: String, id: String, parameters: serde_json::Value) -> Self {
Self {
name,
id,
parameters,
callback: None,
}
}
}
impl Strategy for TypeScriptStrategy {
fn on_market_data(&mut self, data: &MarketData) -> Vec<Signal> {
if let Some(callback) = &self.callback {
let call = StrategyCall {
method: "on_market_data".to_string(),
data: serde_json::to_value(data).unwrap_or_default(),
};
let response = callback(call);
response.signals
} else {
Vec::new()
}
}
fn on_fill(&mut self, symbol: &str, quantity: f64, price: f64, side: &str) {
if let Some(callback) = &self.callback {
let call = StrategyCall {
method: "on_fill".to_string(),
data: serde_json::json!({
"symbol": symbol,
"quantity": quantity,
"price": price,
"side": side
}),
};
callback(call);
}
}
fn get_name(&self) -> &str {
&self.name
}
fn get_parameters(&self) -> serde_json::Value {
self.parameters.clone()
}
}

View file

@ -0,0 +1,269 @@
use std::collections::{HashMap, VecDeque};
use chrono::{DateTime, Utc};
use serde::{Serialize, Deserialize};
use crate::{Fill, Side};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletedTrade {
pub id: String,
pub symbol: String,
pub entry_time: DateTime<Utc>,
pub exit_time: DateTime<Utc>,
pub entry_price: f64,
pub exit_price: f64,
pub quantity: f64,
pub side: Side, // Side of the opening trade
pub pnl: f64,
pub pnl_percent: f64,
pub commission: f64,
pub duration_seconds: i64,
}
#[derive(Debug, Clone)]
struct OpenPosition {
symbol: String,
side: Side,
quantity: f64,
entry_price: f64,
entry_time: DateTime<Utc>,
commission: f64,
}
/// Tracks fills and matches them into completed trades
pub struct TradeTracker {
open_positions: HashMap<String, VecDeque<OpenPosition>>,
completed_trades: Vec<CompletedTrade>,
trade_counter: u64,
}
impl TradeTracker {
pub fn new() -> Self {
Self {
open_positions: HashMap::new(),
completed_trades: Vec::new(),
trade_counter: 0,
}
}
pub fn get_completed_trades(&self) -> Vec<CompletedTrade> {
self.completed_trades.clone()
}
pub fn process_fill(&mut self, symbol: &str, side: Side, fill: &Fill) {
let positions = self.open_positions.entry(symbol.to_string()).or_insert_with(VecDeque::new);
// Check if this fill closes existing positions
let mut remaining_quantity = fill.quantity;
let mut fills_to_remove = Vec::new();
for (idx, open_pos) in positions.iter_mut().enumerate() {
// Only match against opposite side positions
if open_pos.side == side {
continue;
}
if remaining_quantity <= 0.0 {
break;
}
let matched_quantity = remaining_quantity.min(open_pos.quantity);
// Calculate PnL
let (pnl, pnl_percent) = Self::calculate_pnl(
&open_pos,
fill.price,
matched_quantity,
fill.commission,
);
// Create completed trade
self.trade_counter += 1;
let completed_trade = CompletedTrade {
id: format!("trade-{}", self.trade_counter),
symbol: symbol.to_string(),
entry_time: open_pos.entry_time,
exit_time: fill.timestamp,
entry_price: open_pos.entry_price,
exit_price: fill.price,
quantity: matched_quantity,
side: open_pos.side.clone(),
pnl,
pnl_percent,
commission: open_pos.commission + (fill.commission * matched_quantity / fill.quantity),
duration_seconds: (fill.timestamp - open_pos.entry_time).num_seconds(),
};
eprintln!("📈 TRADE CLOSED: {} {} @ entry: ${:.2} ({}), exit: ${:.2} ({}) = P&L: ${:.2}",
symbol,
match open_pos.side { Side::Buy => "LONG", Side::Sell => "SHORT" },
open_pos.entry_price,
open_pos.entry_time.format("%Y-%m-%d"),
fill.price,
fill.timestamp.format("%Y-%m-%d"),
pnl
);
self.completed_trades.push(completed_trade);
// Update open position
open_pos.quantity -= matched_quantity;
remaining_quantity -= matched_quantity;
if open_pos.quantity <= 0.0 {
fills_to_remove.push(idx);
}
}
// Remove fully closed positions
for idx in fills_to_remove.iter().rev() {
positions.remove(*idx);
}
// If there's remaining quantity, it opens a new position
if remaining_quantity > 0.0 {
let new_position = OpenPosition {
symbol: symbol.to_string(),
side,
quantity: remaining_quantity,
entry_price: fill.price,
entry_time: fill.timestamp,
commission: fill.commission * remaining_quantity / fill.quantity,
};
positions.push_back(new_position);
}
}
fn calculate_pnl(open_pos: &OpenPosition, exit_price: f64, quantity: f64, exit_commission: f64) -> (f64, f64) {
let entry_value = open_pos.entry_price * quantity;
let exit_value = exit_price * quantity;
let gross_pnl = match open_pos.side {
Side::Buy => exit_value - entry_value,
Side::Sell => entry_value - exit_value,
};
let commission = open_pos.commission * (quantity / open_pos.quantity) + exit_commission * (quantity / open_pos.quantity);
let net_pnl = gross_pnl - commission;
let pnl_percent = (net_pnl / entry_value) * 100.0;
(net_pnl, pnl_percent)
}
pub fn get_open_positions(&self) -> HashMap<String, Vec<(Side, f64, f64)>> {
let mut result = HashMap::new();
for (symbol, positions) in &self.open_positions {
let pos_info: Vec<(Side, f64, f64)> = positions
.iter()
.map(|p| (p.side.clone(), p.quantity, p.entry_price))
.collect();
if !pos_info.is_empty() {
result.insert(symbol.clone(), pos_info);
}
}
result
}
pub fn get_net_position(&self, symbol: &str) -> f64 {
let positions = match self.open_positions.get(symbol) {
Some(pos) => pos,
None => return 0.0,
};
let mut net = 0.0;
for pos in positions {
match pos.side {
Side::Buy => net += pos.quantity,
Side::Sell => net -= pos.quantity,
}
}
net
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple_round_trip() {
let mut tracker = TradeTracker::new();
// Buy 100 shares at $50
let buy_fill = Fill {
timestamp: Utc::now(),
price: 50.0,
quantity: 100.0,
commission: 1.0,
};
tracker.process_fill("AAPL", Side::Buy, &buy_fill);
// Sell 100 shares at $55
let sell_fill = Fill {
timestamp: Utc::now(),
price: 55.0,
quantity: 100.0,
commission: 1.0,
};
tracker.process_fill("AAPL", Side::Sell, &sell_fill);
let trades = tracker.get_completed_trades();
assert_eq!(trades.len(), 1);
let trade = &trades[0];
assert_eq!(trade.symbol, "AAPL");
assert_eq!(trade.quantity, 100.0);
assert_eq!(trade.entry_price, 50.0);
assert_eq!(trade.exit_price, 55.0);
assert_eq!(trade.pnl, 498.0); // (55-50)*100 - 2 commission
assert_eq!(trade.side, Side::Buy);
}
#[test]
fn test_partial_fills() {
let mut tracker = TradeTracker::new();
// Buy 100 shares at $50
let buy_fill = Fill {
timestamp: Utc::now(),
price: 50.0,
quantity: 100.0,
commission: 1.0,
};
tracker.process_fill("AAPL", Side::Buy, &buy_fill);
// Sell 60 shares at $55
let sell_fill1 = Fill {
timestamp: Utc::now(),
price: 55.0,
quantity: 60.0,
commission: 0.6,
};
tracker.process_fill("AAPL", Side::Sell, &sell_fill1);
// Check we have one completed trade and remaining position
let trades = tracker.get_completed_trades();
assert_eq!(trades.len(), 1);
assert_eq!(trades[0].quantity, 60.0);
assert_eq!(tracker.get_net_position("AAPL"), 40.0);
// Sell remaining 40 shares at $52
let sell_fill2 = Fill {
timestamp: Utc::now(),
price: 52.0,
quantity: 40.0,
commission: 0.4,
};
tracker.process_fill("AAPL", Side::Sell, &sell_fill2);
// Now we should have 2 completed trades and no position
let trades = tracker.get_completed_trades();
assert_eq!(trades.len(), 2);
assert_eq!(tracker.get_net_position("AAPL"), 0.0);
}
}