fixed up rust system

This commit is contained in:
Boki 2025-07-03 21:45:08 -04:00
parent 063f4c8e27
commit a58072cf93
7 changed files with 255 additions and 44 deletions

View file

@ -61,11 +61,15 @@ impl BacktestEngine {
parameters: napi::JsObject,
callback: napi::JsFunction,
) -> Result<()> {
// For now, let's use a simple SMA crossover strategy directly in Rust
// This bypasses the TypeScript callback complexity
// Use shorter periods for testing with low volatility mock data
let fast_period = 5;
let slow_period = 15;
eprintln!("WARNING: TypeScript strategy callbacks not yet implemented");
eprintln!("Using fallback SimpleSMAStrategy for: {}", name);
// For now, let's use a simple SMA strategy as a fallback
// TODO: Implement proper TypeScript callback handling
let fast_period: usize = parameters.get_named_property::<f64>("fastPeriod")
.unwrap_or(5.0) as usize;
let slow_period: usize = parameters.get_named_property::<f64>("slowPeriod")
.unwrap_or(15.0) as usize;
if let Some(engine) = self.inner.lock().as_mut() {
engine.add_strategy(Box::new(SimpleSMAStrategy::new(
@ -81,23 +85,26 @@ impl BacktestEngine {
#[napi]
pub fn run(&mut self) -> Result<String> {
eprintln!("Starting backtest run");
eprintln!("=== BACKTEST RUN START ===");
let mut engine = self.inner.lock().take()
.ok_or_else(|| Error::from_reason("Engine already consumed"))?;
eprintln!("Creating tokio runtime");
// Config and strategies are private, skip detailed logging
// Run the backtest synchronously for now
let runtime = tokio::runtime::Runtime::new()
.map_err(|e| Error::from_reason(e.to_string()))?;
eprintln!("Running backtest engine");
let result = runtime.block_on(engine.run())
.map_err(|e| {
eprintln!("Backtest engine error: {}", e);
eprintln!("ERROR: Backtest engine failed: {}", e);
Error::from_reason(e)
})?;
eprintln!("Serializing result");
eprintln!("=== BACKTEST RUN COMPLETE ===");
eprintln!("Total trades: {}", result.trades.len());
eprintln!("Equity curve length: {}", result.equity_curve.len());
// Return result as JSON
serde_json::to_string(&result)
.map_err(|e| Error::from_reason(e.to_string()))
@ -232,6 +239,7 @@ struct SimpleSMAStrategy {
impl SimpleSMAStrategy {
fn new(name: String, id: String, fast_period: usize, slow_period: usize) -> Self {
eprintln!("Creating SimpleSMAStrategy: name={}, fast={}, slow={}", name, fast_period, slow_period);
Self {
name,
id,
@ -245,6 +253,15 @@ impl SimpleSMAStrategy {
impl Strategy for SimpleSMAStrategy {
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
// Count calls
static mut CALL_COUNT: usize = 0;
unsafe {
CALL_COUNT += 1;
if CALL_COUNT % 100 == 1 {
eprintln!("SimpleSMAStrategy.on_market_data called {} times", CALL_COUNT);
}
}
let mut signals = Vec::new();
// Check if it's bar data
@ -259,26 +276,44 @@ impl Strategy for SimpleSMAStrategy {
// Debug: Log first few prices
if history.len() <= 3 {
eprintln!("Price history for {}: {:?}", symbol, history);
} else if history.len() == 10 || history.len() == 15 {
eprintln!("Price history length for {}: {} bars", symbol, history.len());
}
// Keep only necessary history
if history.len() > self.slow_period {
// Keep only necessary history (need one extra for previous SMA calculation)
if history.len() > self.slow_period + 1 {
history.remove(0);
}
// Need enough data
if history.len() >= self.slow_period {
// Debug when we first have enough data
if history.len() == self.slow_period {
eprintln!("Now have enough data for {}: {} bars", symbol, history.len());
}
// Calculate SMAs
let fast_sma = history[history.len() - self.fast_period..].iter().sum::<f64>() / self.fast_period as f64;
let slow_sma = history.iter().sum::<f64>() / history.len() as f64;
// Debug: Log SMAs periodically
if history.len() % 10 == 0 {
eprintln!("SMAs for {}: fast={:.2}, slow={:.2}, price={:.2}", symbol, fast_sma, slow_sma, price);
if history.len() % 10 == 0 || (history.len() > self.slow_period && history.len() < self.slow_period + 5) {
eprintln!("SMAs for {}: fast={:.2}, slow={:.2}, price={:.2}, history_len={}",
symbol, fast_sma, slow_sma, price, history.len());
// Also log if they're close to crossing
let diff = (fast_sma - slow_sma).abs();
let pct_diff = diff / slow_sma * 100.0;
if pct_diff < 1.0 {
eprintln!(" -> SMAs are close! Difference: {:.4} ({:.2}%)", diff, pct_diff);
}
}
// Previous SMAs (if we have enough history)
if history.len() > self.slow_period {
// Debug: First time checking for crossovers
if history.len() == self.slow_period + 1 {
eprintln!("Starting crossover checks for {}", symbol);
}
let prev_history = &history[..history.len() - 1];
let prev_fast_sma = prev_history[prev_history.len() - self.fast_period..].iter().sum::<f64>() / self.fast_period as f64;
let prev_slow_sma = prev_history.iter().sum::<f64>() / prev_history.len() as f64;