fixed test strat

This commit is contained in:
Boki 2025-07-03 18:33:15 -04:00
parent 6cf3179092
commit 8a9a4bc336
12 changed files with 1301 additions and 8 deletions

Binary file not shown.

View file

@ -110,10 +110,65 @@ impl PositionTracker {
// Handle trade matching for closed trades
match side {
Side::Buy => {
// For buy orders, just add to open trades
self.open_trades.entry(symbol.to_string())
.or_insert_with(Vec::new)
.push(trade_record);
// For buy orders, try to match with open sell trades (closing shorts)
if let Some(mut open_trades) = self.open_trades.get_mut(symbol) {
let mut remaining_quantity = fill.quantity;
let mut trades_to_remove = Vec::new();
// FIFO matching against short positions
for (idx, open_trade) in open_trades.iter_mut().enumerate() {
if open_trade.side == Side::Sell && remaining_quantity > 0.0 {
let close_quantity = remaining_quantity.min(open_trade.quantity);
// Create closed trade record for short position
let closed_trade = ClosedTrade {
id: format!("CT{}", self.generate_trade_id()),
symbol: symbol.to_string(),
entry_time: open_trade.timestamp,
exit_time: fill.timestamp,
entry_price: open_trade.price,
exit_price: fill.price,
quantity: close_quantity,
side: Side::Sell, // Opening side (short)
pnl: close_quantity * (open_trade.price - fill.price) - (open_trade.commission + fill.commission * close_quantity / fill.quantity),
pnl_percent: ((open_trade.price - fill.price) / open_trade.price) * 100.0,
commission: open_trade.commission + fill.commission * close_quantity / fill.quantity,
duration_ms: (fill.timestamp - open_trade.timestamp).num_milliseconds(),
entry_fill_id: open_trade.id.clone(),
exit_fill_id: trade_record.id.clone(),
};
self.closed_trades.write().push(closed_trade);
// Update quantities
remaining_quantity -= close_quantity;
open_trade.quantity -= close_quantity;
if open_trade.quantity <= 0.0 {
trades_to_remove.push(idx);
}
}
}
// Remove fully closed trades
for idx in trades_to_remove.into_iter().rev() {
open_trades.remove(idx);
}
// If we still have quantity left, it's a new long position
if remaining_quantity > 0.0 {
let long_trade = TradeRecord {
quantity: remaining_quantity,
..trade_record.clone()
};
open_trades.push(long_trade);
}
} else {
// No open trades, start a new long position
self.open_trades.entry(symbol.to_string())
.or_insert_with(Vec::new)
.push(trade_record);
}
}
Side::Sell => {
// For sell orders, try to match with open buy trades
@ -169,6 +224,11 @@ impl PositionTracker {
};
open_trades.push(short_trade);
}
} else {
// No open trades, start a new short position
self.open_trades.entry(symbol.to_string())
.or_insert_with(Vec::new)
.push(trade_record);
}
}
}