finished initial backtest / engine

This commit is contained in:
Boki 2025-07-03 12:49:22 -04:00
parent 55b4ca78c9
commit c106a719e8
18 changed files with 1571 additions and 180 deletions

View file

@ -159,6 +159,20 @@ impl TradingEngine {
#[napi]
pub fn process_fill(&self, symbol: String, price: f64, quantity: f64, side: String, commission: f64) -> Result<String> {
self.process_fill_with_metadata(symbol, price, quantity, side, commission, None, None)
}
#[napi]
pub fn process_fill_with_metadata(
&self,
symbol: String,
price: f64,
quantity: f64,
side: String,
commission: f64,
order_id: Option<String>,
strategy_id: Option<String>
) -> Result<String> {
let side = match side.as_str() {
"buy" | "Buy" => Side::Buy,
"sell" | "Sell" => Side::Sell,
@ -175,7 +189,7 @@ impl TradingEngine {
commission,
};
let update = core.position_tracker.process_fill(&symbol, &fill, side);
let update = core.position_tracker.process_fill_with_tracking(&symbol, &fill, side, order_id, strategy_id);
// Update risk engine with new position
core.risk_engine.update_position(&symbol, update.resulting_position.quantity);
@ -212,12 +226,18 @@ impl TradingEngine {
// Backtest-specific methods
#[napi]
pub fn advance_time(&self, _to_timestamp: i64) -> Result<()> {
pub fn advance_time(&self, to_timestamp: i64) -> Result<()> {
let core = self.core.lock();
if let TradingMode::Backtest { .. } = core.get_mode() {
// In real implementation, would downcast and advance time
// For now, return success in backtest mode
Ok(())
// Downcast time provider to SimulatedTime and advance it
if let Some(simulated_time) = core.time_provider.as_any().downcast_ref::<crate::core::time_providers::SimulatedTime>() {
let new_time = DateTime::<Utc>::from_timestamp_millis(to_timestamp)
.ok_or_else(|| Error::from_reason("Invalid timestamp"))?;
simulated_time.advance_to(new_time);
Ok(())
} else {
Err(Error::from_reason("Failed to access simulated time provider"))
}
} else {
Err(Error::from_reason("Can only advance time in backtest mode"))
}
@ -274,6 +294,39 @@ impl TradingEngine {
Ok(())
}
#[napi]
pub fn get_trade_history(&self) -> Result<String> {
let core = self.core.lock();
let trades = core.position_tracker.get_trade_history();
Ok(serde_json::to_string(&trades).unwrap())
}
#[napi]
pub fn get_closed_trades(&self) -> Result<String> {
let core = self.core.lock();
let trades = core.position_tracker.get_closed_trades();
Ok(serde_json::to_string(&trades).unwrap())
}
#[napi]
pub fn get_open_trades(&self) -> Result<String> {
let core = self.core.lock();
let trades = core.position_tracker.get_open_trades();
Ok(serde_json::to_string(&trades).unwrap())
}
#[napi]
pub fn get_trade_count(&self) -> Result<u32> {
let core = self.core.lock();
Ok(core.position_tracker.get_trade_count() as u32)
}
#[napi]
pub fn get_closed_trade_count(&self) -> Result<u32> {
let core = self.core.lock();
Ok(core.position_tracker.get_closed_trade_count() as u32)
}
}
// Helper functions to parse JavaScript objects