fix(engine): validate native market data atomically
This commit is contained in:
parent
6d357af983
commit
ee670a3bd1
2 changed files with 266 additions and 35 deletions
|
|
@ -6,6 +6,7 @@ use chrono::{DateTime, Utc};
|
|||
use napi::bindgen_prelude::*;
|
||||
use napi_derive::napi;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[napi]
|
||||
|
|
@ -213,28 +214,47 @@ impl BacktestEngine {
|
|||
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();
|
||||
|
||||
// Load data into the historical data source
|
||||
if let Some(engine) = self.inner.lock().as_ref() {
|
||||
// Access the market data source through the engine
|
||||
let mut data_source = engine.market_data_source.write();
|
||||
if let Some(historical_source) = data_source
|
||||
.as_any_mut()
|
||||
.downcast_mut::<crate::core::market_data_sources::HistoricalDataSource>(
|
||||
) {
|
||||
historical_source.load_data(market_data);
|
||||
} else {
|
||||
#[napi(ts_args_type = "data: Array<object>")]
|
||||
pub fn load_market_data(&self, data: Vec<napi::JsUnknown>) -> Result<()> {
|
||||
// Validate the complete replacement before touching the historical source.
|
||||
let mut market_data: Vec<MarketUpdate> = Vec::with_capacity(data.len());
|
||||
let mut previous_time = None;
|
||||
let mut identities_at_time = HashMap::new();
|
||||
for (index, obj) in data.into_iter().enumerate() {
|
||||
let row_error =
|
||||
|reason| Error::from_reason(format!("Market data row {index}: {reason}"));
|
||||
let update = napi::JsObject::try_from(obj)
|
||||
.and_then(parse_market_data)
|
||||
.map_err(|error| row_error(error.reason))?;
|
||||
if previous_time.is_some_and(|previous| update.timestamp < previous) {
|
||||
return Err(row_error("Timestamps must be nondecreasing".to_string()));
|
||||
}
|
||||
} else {
|
||||
if previous_time != Some(update.timestamp) {
|
||||
identities_at_time.clear();
|
||||
}
|
||||
// Identical duplicates also replay a strategy twice, so reject them too.
|
||||
if let Some(first_index) = identities_at_time.insert(update.symbol.clone(), index) {
|
||||
return Err(row_error(format!(
|
||||
"Duplicate bar identity {} at {}ms (first at row {})",
|
||||
update.symbol,
|
||||
update.timestamp.timestamp_millis(),
|
||||
first_index
|
||||
)));
|
||||
}
|
||||
previous_time = Some(update.timestamp);
|
||||
market_data.push(update);
|
||||
}
|
||||
|
||||
let guard = self.inner.lock();
|
||||
let engine = guard
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::from_reason("Engine already consumed"))?;
|
||||
let mut data_source = engine.market_data_source.write();
|
||||
let historical_source = data_source
|
||||
.as_any_mut()
|
||||
.downcast_mut::<crate::core::market_data_sources::HistoricalDataSource>()
|
||||
.ok_or_else(|| Error::from_reason("Historical market data source unavailable"))?;
|
||||
historical_source.load_data(market_data);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -269,26 +289,65 @@ fn parse_backtest_config(obj: napi::JsObject) -> Result<BacktestConfig> {
|
|||
|
||||
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")?;
|
||||
if symbol.trim().is_empty() {
|
||||
return Err(Error::from_reason("Symbol must be nonempty"));
|
||||
}
|
||||
let timestamp: f64 = obj.get_named_property("timestamp")?;
|
||||
// Reading as i64 first would silently truncate fractional JS timestamps.
|
||||
if !timestamp.is_finite()
|
||||
|| timestamp.fract() != 0.0
|
||||
|| timestamp.abs() > 9_007_199_254_740_991.0
|
||||
{
|
||||
return Err(Error::from_reason(
|
||||
"Timestamp must be a safe integer epoch millisecond",
|
||||
));
|
||||
}
|
||||
let timestamp = DateTime::<Utc>::from_timestamp_millis(timestamp as i64)
|
||||
.ok_or_else(|| Error::from_reason("Invalid 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"));
|
||||
if data_type != "bar" {
|
||||
return Err(Error::from_reason(format!(
|
||||
"Unsupported market data type: {data_type}"
|
||||
)));
|
||||
}
|
||||
let 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")?,
|
||||
};
|
||||
for (field, price) in [
|
||||
("open", bar.open),
|
||||
("high", bar.high),
|
||||
("low", bar.low),
|
||||
("close", bar.close),
|
||||
] {
|
||||
if !price.is_finite() || price <= 0.0 {
|
||||
return Err(Error::from_reason(format!(
|
||||
"{field} must be positive and finite"
|
||||
)));
|
||||
}
|
||||
}
|
||||
if bar.high < bar.open.max(bar.close) || bar.low > bar.open.min(bar.close) {
|
||||
return Err(Error::from_reason("Invalid OHLC range"));
|
||||
}
|
||||
if !bar.volume.is_finite() || bar.volume < 0.0 {
|
||||
return Err(Error::from_reason("Volume must be nonnegative and finite"));
|
||||
}
|
||||
if bar
|
||||
.vwap
|
||||
.is_some_and(|price| !price.is_finite() || price <= 0.0)
|
||||
{
|
||||
return Err(Error::from_reason(
|
||||
"VWAP must be positive and finite when provided",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(crate::MarketUpdate {
|
||||
symbol,
|
||||
timestamp: DateTime::<Utc>::from_timestamp(timestamp / 1000, 0)
|
||||
.ok_or_else(|| Error::from_reason("Invalid timestamp"))?,
|
||||
data,
|
||||
timestamp,
|
||||
data: crate::MarketDataType::Bar(bar),
|
||||
})
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue