Unify simulation order execution and persist paper accounting
This commit is contained in:
parent
7dec0be3b4
commit
63c3856797
37 changed files with 3901 additions and 3043 deletions
|
|
@ -1,20 +1,17 @@
|
|||
use chrono::{DateTime, Utc};
|
||||
use parking_lot::RwLock;
|
||||
use serde::{Deserialize, Serialize};
|
||||
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,
|
||||
orderbook::OrderBookManager, positions::PositionTracker, risk::RiskEngine, ExecutionHandler,
|
||||
Fill, MarketDataSource, MarketDataType, MarketUpdate, Order, Side, TimeProvider, TradingMode,
|
||||
};
|
||||
|
||||
use super::{
|
||||
BacktestConfig, BacktestState, EventQueue, BacktestEvent, EventType,
|
||||
Strategy, Signal, SignalType, BacktestResult, TradeTracker,
|
||||
BacktestConfig, BacktestEvent, BacktestResult, BacktestState, EventQueue, EventType, Signal,
|
||||
SignalType, Strategy, TradeTracker,
|
||||
};
|
||||
|
||||
pub struct BacktestEngine {
|
||||
|
|
@ -22,7 +19,7 @@ pub struct BacktestEngine {
|
|||
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>,
|
||||
|
|
@ -30,22 +27,22 @@ pub struct BacktestEngine {
|
|||
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)>,
|
||||
|
||||
|
||||
// Store latest bar data for each symbol to ensure accurate closing prices
|
||||
latest_bars: HashMap<String, crate::Bar>,
|
||||
|
||||
|
||||
// Store all OHLC data processed by the engine
|
||||
ohlc_history: HashMap<String, Vec<(DateTime<Utc>, crate::Bar)>>,
|
||||
|
||||
|
||||
// Trade tracking
|
||||
trade_tracker: TradeTracker,
|
||||
}
|
||||
|
|
@ -58,10 +55,11 @@ impl BacktestEngine {
|
|||
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)
|
||||
));
|
||||
|
||||
let state = Arc::new(RwLock::new(BacktestState::new(
|
||||
config.initial_capital,
|
||||
config.start_time,
|
||||
)));
|
||||
|
||||
Self {
|
||||
config,
|
||||
state,
|
||||
|
|
@ -82,54 +80,56 @@ impl BacktestEngine {
|
|||
trade_tracker: TradeTracker::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn update_risk_limits(&self, limits: crate::RiskLimits) {
|
||||
self.risk_engine.update_limits(limits);
|
||||
}
|
||||
pub fn add_strategy(&mut self, strategy: Box<dyn Strategy>) {
|
||||
self.strategies.write().push(strategy);
|
||||
}
|
||||
|
||||
|
||||
pub async fn run(&mut self) -> Result<BacktestResult, String> {
|
||||
|
||||
// Initialize start time
|
||||
if let Some(simulated_time) = self.time_provider.as_any()
|
||||
.downcast_ref::<crate::core::time_providers::SimulatedTime>()
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
// Load market data
|
||||
self.load_market_data().await?;
|
||||
|
||||
|
||||
let queue_len = self.event_queue.read().len();
|
||||
|
||||
|
||||
if queue_len == 0 {
|
||||
return Err("No market data loaded".to_string());
|
||||
}
|
||||
|
||||
|
||||
// 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);
|
||||
|
||||
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);
|
||||
|
||||
|
||||
// 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 {
|
||||
|
|
@ -141,31 +141,31 @@ impl BacktestEngine {
|
|||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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> {
|
||||
let mut data_source = self.market_data_source.write();
|
||||
data_source.seek_to_time(self.config.start_time)?;
|
||||
|
||||
|
||||
// Load all data into event queue
|
||||
while let Some(update) = data_source.get_next_update().await {
|
||||
if update.timestamp > self.config.end_time {
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
let event = BacktestEvent::market_data(update.timestamp, update);
|
||||
self.event_queue.write().push(event);
|
||||
}
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
async fn process_event(&mut self, event: BacktestEvent) -> Result<(), String> {
|
||||
match event.event_type {
|
||||
EventType::MarketData(data) => {
|
||||
|
|
@ -186,52 +186,66 @@ impl BacktestEngine {
|
|||
self.advance_time(time);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
async fn process_market_data(&mut self, data: MarketUpdate) -> Result<(), String> {
|
||||
// Update price tracking - single source of truth
|
||||
let price = match &data.data {
|
||||
MarketDataType::Bar(bar) => {
|
||||
// Log OHLCV data for each tick
|
||||
eprintln!("[TICK] {} @ {} - O:{:.2} H:{:.2} L:{:.2} C:{:.2} V:{:.0}",
|
||||
data.symbol,
|
||||
data.timestamp.format("%Y-%m-%d %H:%M:%S"),
|
||||
bar.open, bar.high, bar.low, bar.close, bar.volume);
|
||||
|
||||
eprintln!(
|
||||
"[TICK] {} @ {} - O:{:.2} H:{:.2} L:{:.2} C:{:.2} V:{:.0}",
|
||||
data.symbol,
|
||||
data.timestamp.format("%Y-%m-%d %H:%M:%S"),
|
||||
bar.open,
|
||||
bar.high,
|
||||
bar.low,
|
||||
bar.close,
|
||||
bar.volume
|
||||
);
|
||||
|
||||
// Store the complete bar data for accurate position closing
|
||||
self.latest_bars.insert(data.symbol.clone(), bar.clone());
|
||||
|
||||
|
||||
// Store in OHLC history
|
||||
self.ohlc_history
|
||||
.entry(data.symbol.clone())
|
||||
.or_insert_with(Vec::new)
|
||||
.push((data.timestamp, bar.clone()));
|
||||
|
||||
|
||||
// Debug: Log OHLC history size periodically
|
||||
let history_len = self.ohlc_history.get(&data.symbol).map(|v| v.len()).unwrap_or(0);
|
||||
let history_len = self
|
||||
.ohlc_history
|
||||
.get(&data.symbol)
|
||||
.map(|v| v.len())
|
||||
.unwrap_or(0);
|
||||
if history_len == 1 || history_len % 100 == 0 {
|
||||
eprintln!("[DEBUG] OHLC history for {}: {} bars stored", data.symbol, history_len);
|
||||
eprintln!(
|
||||
"[DEBUG] OHLC history for {}: {} bars stored",
|
||||
data.symbol, history_len
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
bar.close
|
||||
}
|
||||
MarketDataType::Quote(quote) => {
|
||||
// Use mid price for quotes
|
||||
(quote.bid + quote.ask) / 2.0
|
||||
}
|
||||
MarketDataType::Trade(trade) => {
|
||||
trade.price
|
||||
}
|
||||
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));
|
||||
|
||||
self.last_prices
|
||||
.insert(data.symbol.clone(), (data.timestamp, price));
|
||||
self.risk_engine.mark_price(&data.symbol, price);
|
||||
self.risk_engine.roll_day(data.timestamp.date_naive());
|
||||
|
||||
// Convert to simpler MarketData for strategies
|
||||
let market_data = self.convert_to_market_data(&data);
|
||||
|
||||
|
||||
// Send to strategies
|
||||
let mut all_signals = Vec::new();
|
||||
{
|
||||
|
|
@ -241,44 +255,44 @@ impl BacktestEngine {
|
|||
all_signals.extend(signals);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Process signals
|
||||
for signal in all_signals {
|
||||
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> {
|
||||
// Only process strong signals
|
||||
if signal.strength.abs() < 0.7 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
|
||||
// Convert signal to order
|
||||
let order = self.signal_to_order(signal)?;
|
||||
|
||||
|
||||
// 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,
|
||||
|
|
@ -292,7 +306,7 @@ impl BacktestEngine {
|
|||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Ok(crate::Order {
|
||||
id: format!("order_{}", uuid::Uuid::new_v4()),
|
||||
symbol: signal.symbol,
|
||||
|
|
@ -302,69 +316,90 @@ impl BacktestEngine {
|
|||
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
|
||||
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);
|
||||
|
||||
let price = self
|
||||
.last_prices
|
||||
.get(&order.symbol)
|
||||
.map(|(_, price)| *price)
|
||||
.unwrap_or(f64::NAN);
|
||||
let price = if order.side == Side::Buy {
|
||||
price * (1.0 + self.config.slippage)
|
||||
} else {
|
||||
price * (1.0 - self.config.slippage)
|
||||
};
|
||||
let risk_check = self
|
||||
.risk_engine
|
||||
.check_order(&order, current_position, price);
|
||||
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()
|
||||
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
|
||||
let (price_time, base_price) = self.last_prices.get(&order.symbol)
|
||||
let (price_time, base_price) = self
|
||||
.last_prices
|
||||
.get(&order.symbol)
|
||||
.copied()
|
||||
.ok_or_else(|| format!("No price available for symbol: {}", 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),
|
||||
};
|
||||
|
||||
|
||||
// Get the OHLC data that was used
|
||||
let ohlc_info = if let Some(bar) = self.latest_bars.get(&order.symbol) {
|
||||
format!("O:{:.2} H:{:.2} L:{:.2} C:{:.2}", bar.open, bar.high, bar.low, bar.close)
|
||||
format!(
|
||||
"O:{:.2} H:{:.2} L:{:.2} C:{:.2}",
|
||||
bar.open, bar.high, bar.low, bar.close
|
||||
)
|
||||
} else {
|
||||
"No OHLC data".to_string()
|
||||
};
|
||||
|
||||
|
||||
// Log trade execution
|
||||
eprintln!("[TRADE] {} {} {} @ {:.2} | OHLC: {} | Time: {}",
|
||||
eprintln!(
|
||||
"[TRADE] {} {} {} @ {:.2} | OHLC: {} | Time: {}",
|
||||
match order.side {
|
||||
crate::Side::Buy => "BUY",
|
||||
crate::Side::Sell => "SELL",
|
||||
|
|
@ -375,7 +410,7 @@ impl BacktestEngine {
|
|||
ohlc_info,
|
||||
current_time.format("%Y-%m-%d %H:%M:%S")
|
||||
);
|
||||
|
||||
|
||||
// Create fill
|
||||
let fill = crate::Fill {
|
||||
timestamp: current_time,
|
||||
|
|
@ -383,58 +418,74 @@ impl BacktestEngine {
|
|||
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> {
|
||||
|
||||
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
|
||||
let position_before = self
|
||||
.position_tracker
|
||||
.get_position(&order.symbol)
|
||||
.map(|p| p.quantity)
|
||||
.unwrap_or(0.0);
|
||||
|
||||
|
||||
let previous_pnl = self
|
||||
.position_tracker
|
||||
.get_position(&order.symbol)
|
||||
.map(|p| p.realized_pnl)
|
||||
.unwrap_or(0.0);
|
||||
// Update positions
|
||||
let update = self.position_tracker.process_fill(
|
||||
let update = self
|
||||
.position_tracker
|
||||
.process_fill(&order.symbol, &fill, order.side);
|
||||
|
||||
self.risk_engine.update_position(
|
||||
&order.symbol,
|
||||
&fill,
|
||||
order.side,
|
||||
update.resulting_position.quantity,
|
||||
fill.price,
|
||||
);
|
||||
|
||||
self.risk_engine
|
||||
.update_daily_pnl(update.resulting_position.realized_pnl - previous_pnl);
|
||||
// Calculate P&L if position was reduced/closed
|
||||
let pnl = if update.resulting_position.realized_pnl != 0.0 {
|
||||
Some(update.resulting_position.realized_pnl)
|
||||
Some(update.resulting_position.realized_pnl - previous_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,
|
||||
order.symbol.clone(),
|
||||
order.side,
|
||||
fill.clone(),
|
||||
position_after,
|
||||
position_before,
|
||||
pnl
|
||||
pnl,
|
||||
);
|
||||
|
||||
|
||||
// Track trades
|
||||
self.trade_tracker.process_fill(&order.symbol, order.side, &fill);
|
||||
|
||||
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();
|
||||
|
|
@ -446,31 +497,37 @@ impl BacktestEngine {
|
|||
strategy.on_fill(&order.symbol, fill.quantity, fill.price, side_str);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 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;
|
||||
|
||||
self.total_pnl = self
|
||||
.position_tracker
|
||||
.get_all_positions()
|
||||
.iter()
|
||||
.map(|p| p.realized_pnl)
|
||||
.sum();
|
||||
|
||||
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>()
|
||||
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;
|
||||
|
||||
|
||||
// Forward-fill prices: Update timestamps for all symbols to current time
|
||||
// This ensures we don't use stale prices when not all symbols have data at every timestamp
|
||||
let symbols: Vec<String> = self.last_prices.keys().cloned().collect();
|
||||
|
|
@ -483,124 +540,140 @@ impl BacktestEngine {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
|
||||
|
||||
for position in &positions {
|
||||
// Use last known price for the symbol
|
||||
let price = self.last_prices.get(&position.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:
|
||||
// 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;
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
|
||||
let price = self
|
||||
.last_prices
|
||||
.get(symbol)
|
||||
.map(|(_, p)| *p)
|
||||
.unwrap_or(100.0);
|
||||
(position_value / price).floor()
|
||||
}
|
||||
|
||||
|
||||
fn get_next_event_time(&self) -> Option<DateTime<Utc>> {
|
||||
// Get the timestamp of the next event in the queue
|
||||
self.event_queue.read()
|
||||
self.event_queue
|
||||
.read()
|
||||
.peek_next()
|
||||
.map(|event| event.timestamp)
|
||||
}
|
||||
|
||||
|
||||
async fn close_all_positions(&mut self) -> Result<(), String> {
|
||||
// Ensure we have the most recent prices for symbols with positions
|
||||
let current_time = self.time_provider.now();
|
||||
let positions = self.position_tracker.get_all_positions();
|
||||
|
||||
|
||||
// First, ensure all positions have up-to-date prices
|
||||
for position in &positions {
|
||||
if position.quantity.abs() > 0.001 {
|
||||
// Check if we have bar data for this symbol
|
||||
if let Some(latest_bar) = self.latest_bars.get(&position.symbol) {
|
||||
// Use the close price from the latest bar
|
||||
self.last_prices.insert(position.symbol.clone(), (current_time, latest_bar.close));
|
||||
} else if let Some((price_time, price)) = self.last_prices.get(&position.symbol).copied() {
|
||||
self.last_prices
|
||||
.insert(position.symbol.clone(), (current_time, latest_bar.close));
|
||||
} else if let Some((price_time, price)) =
|
||||
self.last_prices.get(&position.symbol).copied()
|
||||
{
|
||||
if price_time < current_time {
|
||||
// Update timestamp to current time for proper fill processing
|
||||
self.last_prices.insert(position.symbol.clone(), (current_time, price));
|
||||
self.last_prices
|
||||
.insert(position.symbol.clone(), (current_time, price));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for position in positions {
|
||||
if position.quantity.abs() > 0.001 {
|
||||
// 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 },
|
||||
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?;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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()
|
||||
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
|
||||
let simple_last_prices: HashMap<String, f64> = self
|
||||
.last_prices
|
||||
.iter()
|
||||
.map(|(symbol, (_, price))| (symbol.clone(), *price))
|
||||
.collect();
|
||||
|
||||
|
||||
// Debug: Log OHLC history size before generating results
|
||||
eprintln!("[DEBUG] Generating results with OHLC history:");
|
||||
for (symbol, bars) in &self.ohlc_history {
|
||||
eprintln!(" {}: {} bars", symbol, bars.len());
|
||||
}
|
||||
|
||||
|
||||
// Use simple results builder with proper trade data
|
||||
BacktestResult::from_engine_data_with_trades(
|
||||
self.config.clone(),
|
||||
|
|
@ -616,4 +689,4 @@ impl BacktestEngine {
|
|||
}
|
||||
|
||||
// Add uuid dependency
|
||||
use uuid::Uuid;
|
||||
use uuid::Uuid;
|
||||
|
|
|
|||
|
|
@ -1,269 +1,311 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
use crate::{Fill, Side};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
#[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 * matched_quantity / fill.quantity,
|
||||
);
|
||||
|
||||
// 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 * matched_quantity / open_pos.quantity
|
||||
+ (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.commission *= 1.0 - matched_quantity / open_pos.quantity;
|
||||
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;
|
||||
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);
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod commission_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn partial_exits_allocate_each_entry_and_exit_commission_once() {
|
||||
let mut tracker = TradeTracker::new();
|
||||
let now = Utc::now();
|
||||
for (side, price, quantity, commission) in [
|
||||
(Side::Buy, 100.0, 10.0, 1.0),
|
||||
(Side::Sell, 110.0, 4.0, 0.4),
|
||||
(Side::Sell, 90.0, 10.0, 1.0),
|
||||
(Side::Buy, 80.0, 4.0, 0.4),
|
||||
] {
|
||||
tracker.process_fill(
|
||||
"A",
|
||||
side,
|
||||
&Fill {
|
||||
timestamp: now,
|
||||
price,
|
||||
quantity,
|
||||
commission,
|
||||
},
|
||||
);
|
||||
}
|
||||
let trades = tracker.get_completed_trades();
|
||||
assert!((trades.iter().map(|t| t.commission).sum::<f64>() - 2.8).abs() < 1e-8);
|
||||
assert!((trades.iter().map(|t| t.pnl).sum::<f64>() - 17.2).abs() < 1e-8);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue