moving engine to rust
This commit is contained in:
parent
d14380d740
commit
16ac28a565
16 changed files with 1598 additions and 3 deletions
206
apps/stock/core/src/api/backtest.rs
Normal file
206
apps/stock/core/src/api/backtest.rs
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
use napi::bindgen_prelude::*;
|
||||
use napi::{threadsafe_function::ThreadsafeFunction, JsObject};
|
||||
use napi_derive::napi;
|
||||
use std::sync::Arc;
|
||||
use parking_lot::Mutex;
|
||||
use crate::backtest::{
|
||||
BacktestEngine as RustBacktestEngine,
|
||||
BacktestConfig,
|
||||
Strategy, Signal,
|
||||
strategy::{TypeScriptStrategy, StrategyCall, StrategyResponse},
|
||||
};
|
||||
use crate::{TradingMode, MarketUpdate};
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[napi]
|
||||
pub struct BacktestEngine {
|
||||
inner: Arc<Mutex<Option<RustBacktestEngine>>>,
|
||||
strategies: Arc<Mutex<Vec<Arc<Mutex<TypeScriptStrategy>>>>>,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl BacktestEngine {
|
||||
#[napi(constructor)]
|
||||
pub fn new(config: napi::JsObject, env: Env) -> Result<Self> {
|
||||
let config = parse_backtest_config(config)?;
|
||||
|
||||
// Create mode
|
||||
let mode = TradingMode::Backtest {
|
||||
start_time: config.start_time,
|
||||
end_time: config.end_time,
|
||||
speed_multiplier: 0.0, // Max speed
|
||||
};
|
||||
|
||||
// Create components
|
||||
let time_provider = crate::core::create_time_provider(&mode);
|
||||
let market_data_source = crate::core::create_market_data_source(&mode);
|
||||
let execution_handler = crate::core::create_execution_handler(&mode);
|
||||
|
||||
let engine = RustBacktestEngine::new(
|
||||
config,
|
||||
mode,
|
||||
time_provider,
|
||||
market_data_source,
|
||||
execution_handler,
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
inner: Arc::new(Mutex::new(Some(engine))),
|
||||
strategies: Arc::new(Mutex::new(Vec::new())),
|
||||
})
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn add_typescript_strategy(
|
||||
&mut self,
|
||||
name: String,
|
||||
id: String,
|
||||
parameters: napi::JsObject,
|
||||
callback: napi::JsFunction,
|
||||
) -> Result<()> {
|
||||
// Convert JsObject to serde_json::Value
|
||||
let params = serde_json::Value::Object(serde_json::Map::new());
|
||||
|
||||
let mut strategy = TypeScriptStrategy::new(name, id, params);
|
||||
|
||||
// Create a thread-safe callback wrapper
|
||||
let tsfn: ThreadsafeFunction<String> = callback
|
||||
.create_threadsafe_function(0, |ctx| {
|
||||
ctx.env.create_string_from_std(ctx.value)
|
||||
.map(|v| vec![v])
|
||||
})?;
|
||||
|
||||
// Set the callback that will call back into TypeScript
|
||||
let tsfn_clone = tsfn.clone();
|
||||
strategy.callback = Some(Box::new(move |call| {
|
||||
let call_json = serde_json::to_string(&call).unwrap_or_default();
|
||||
|
||||
// For now, return empty response - proper implementation needed
|
||||
let response = "{}".to_string();
|
||||
|
||||
serde_json::from_str(&response)
|
||||
.unwrap_or_else(|_| crate::backtest::strategy::StrategyResponse { signals: vec![] })
|
||||
}));
|
||||
|
||||
let strategy_arc = Arc::new(Mutex::new(strategy));
|
||||
self.strategies.lock().push(strategy_arc.clone());
|
||||
|
||||
// Add to engine
|
||||
if let Some(engine) = self.inner.lock().as_mut() {
|
||||
engine.add_strategy(Box::new(StrategyWrapper(strategy_arc)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn run(&mut self) -> Result<String> {
|
||||
let mut engine = self.inner.lock().take()
|
||||
.ok_or_else(|| Error::from_reason("Engine already consumed"))?;
|
||||
|
||||
// Run the backtest synchronously for now
|
||||
let runtime = tokio::runtime::Runtime::new()
|
||||
.map_err(|e| Error::from_reason(e.to_string()))?;
|
||||
|
||||
let result = runtime.block_on(engine.run())
|
||||
.map_err(|e| Error::from_reason(e))?;
|
||||
|
||||
// Return result as JSON
|
||||
serde_json::to_string(&result)
|
||||
.map_err(|e| Error::from_reason(e.to_string()))
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn load_market_data(&self, data: Vec<napi::JsObject>) -> Result<()> {
|
||||
// Convert JS objects to MarketData
|
||||
let market_data: Vec<MarketUpdate> = data.into_iter()
|
||||
.filter_map(|obj| parse_market_data(obj).ok())
|
||||
.collect();
|
||||
|
||||
// In real implementation, this would load into the market data source
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Wrapper to make TypeScriptStrategy implement Strategy trait
|
||||
struct StrategyWrapper(Arc<Mutex<TypeScriptStrategy>>);
|
||||
|
||||
impl Strategy for StrategyWrapper {
|
||||
fn on_market_data(&mut self, data: &MarketUpdate) -> Vec<Signal> {
|
||||
self.0.lock().on_market_data(data)
|
||||
}
|
||||
|
||||
fn on_fill(&mut self, symbol: &str, quantity: f64, price: f64, side: &str) {
|
||||
self.0.lock().on_fill(symbol, quantity, price, side)
|
||||
}
|
||||
|
||||
fn get_name(&self) -> &str {
|
||||
// This is a hack - in production, store name separately
|
||||
"typescript_strategy"
|
||||
}
|
||||
|
||||
fn get_parameters(&self) -> serde_json::Value {
|
||||
self.0.lock().parameters.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_backtest_config(obj: napi::JsObject) -> Result<BacktestConfig> {
|
||||
let name: String = obj.get_named_property("name")?;
|
||||
let symbols: Vec<String> = obj.get_named_property("symbols")?;
|
||||
let start_date: String = obj.get_named_property("startDate")?;
|
||||
let end_date: String = obj.get_named_property("endDate")?;
|
||||
let initial_capital: f64 = obj.get_named_property("initialCapital")?;
|
||||
let commission: f64 = obj.get_named_property("commission")?;
|
||||
let slippage: f64 = obj.get_named_property("slippage")?;
|
||||
let data_frequency: String = obj.get_named_property("dataFrequency")?;
|
||||
|
||||
Ok(BacktestConfig {
|
||||
name,
|
||||
symbols,
|
||||
start_time: DateTime::parse_from_rfc3339(&start_date)
|
||||
.map_err(|e| Error::from_reason(e.to_string()))?
|
||||
.with_timezone(&Utc),
|
||||
end_time: DateTime::parse_from_rfc3339(&end_date)
|
||||
.map_err(|e| Error::from_reason(e.to_string()))?
|
||||
.with_timezone(&Utc),
|
||||
initial_capital,
|
||||
commission,
|
||||
slippage,
|
||||
data_frequency,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_market_data(obj: napi::JsObject) -> Result<crate::MarketUpdate> {
|
||||
let symbol: String = obj.get_named_property("symbol")?;
|
||||
let timestamp: i64 = obj.get_named_property("timestamp")?;
|
||||
let data_type: String = obj.get_named_property("type")?;
|
||||
|
||||
let data = if data_type == "bar" {
|
||||
crate::MarketDataType::Bar(crate::Bar {
|
||||
open: obj.get_named_property("open")?,
|
||||
high: obj.get_named_property("high")?,
|
||||
low: obj.get_named_property("low")?,
|
||||
close: obj.get_named_property("close")?,
|
||||
volume: obj.get_named_property("volume")?,
|
||||
vwap: obj.get_named_property("vwap").ok(),
|
||||
})
|
||||
} else {
|
||||
return Err(Error::from_reason("Unsupported market data type"));
|
||||
};
|
||||
|
||||
Ok(crate::MarketUpdate {
|
||||
symbol,
|
||||
timestamp: DateTime::<Utc>::from_timestamp(timestamp / 1000, 0)
|
||||
.ok_or_else(|| Error::from_reason("Invalid timestamp"))?,
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
// Error handling for threadsafe functions
|
||||
struct ErrorStrategy;
|
||||
|
||||
impl From<napi::Error> for ErrorStrategy {
|
||||
fn from(e: napi::Error) -> Self {
|
||||
ErrorStrategy
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue