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),
|
||||
})
|
||||
}
|
||||
|
|
|
|||
172
test/integration/native-market-data.test.ts
Normal file
172
test/integration/native-market-data.test.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { BacktestEngine } from '@stock-bot/engine';
|
||||
import { nativeResultSchema } from '../../apps/stock/orchestrator/src/backtest/native-result';
|
||||
|
||||
function engine() {
|
||||
return new BacktestEngine({
|
||||
name: 'Native data admission',
|
||||
symbols: ['A.US', 'B.US'],
|
||||
startDate: new Date(0).toISOString(),
|
||||
endDate: new Date(4_000).toISOString(),
|
||||
initialCapital: 100,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1m',
|
||||
});
|
||||
}
|
||||
|
||||
function bar(timestamp = 1_001, price = 10): Record<string, unknown> {
|
||||
return {
|
||||
symbol: 'A.US',
|
||||
timestamp,
|
||||
type: 'bar',
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 1_000,
|
||||
vwap: price,
|
||||
};
|
||||
}
|
||||
|
||||
describe('native market-data admission', () => {
|
||||
test('retains distinct millisecond timestamps in replay order', () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar(1_001, 10), bar(1_999, 11)]);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']?.map(row => [row.timestamp, row.close])).toEqual([
|
||||
[1_001, 10],
|
||||
[1_999, 11],
|
||||
]);
|
||||
expect(result.equity.map(row => Date.parse(row.date))).toEqual([0, 1_001, 1_999]);
|
||||
});
|
||||
|
||||
const invalidFields: Array<[string, unknown]> = [
|
||||
['open', Number.NaN],
|
||||
['open', 0],
|
||||
['open', -1],
|
||||
['high', Number.POSITIVE_INFINITY],
|
||||
['high', 9],
|
||||
['low', Number.NEGATIVE_INFINITY],
|
||||
['low', 11],
|
||||
['close', Number.NaN],
|
||||
['close', '10'],
|
||||
['volume', -1],
|
||||
['volume', Number.NaN],
|
||||
['volume', Number.POSITIVE_INFINITY],
|
||||
['vwap', Number.NaN],
|
||||
['vwap', Number.POSITIVE_INFINITY],
|
||||
['vwap', 0],
|
||||
['vwap', -1],
|
||||
['vwap', '10'],
|
||||
['timestamp', Number.NaN],
|
||||
['timestamp', Number.POSITIVE_INFINITY],
|
||||
['timestamp', 1_500.5],
|
||||
['timestamp', Number.MAX_SAFE_INTEGER + 1],
|
||||
['timestamp', Number.MAX_SAFE_INTEGER],
|
||||
['timestamp', '1500'],
|
||||
['type', 'quote'],
|
||||
['symbol', ' '],
|
||||
];
|
||||
for (const [field, value] of invalidFields) {
|
||||
test(`rejects invalid ${field}=${String(value)} with the zero-based row index`, () => {
|
||||
const subject = engine();
|
||||
expect(() =>
|
||||
subject.loadMarketData([bar(500), { ...bar(1_500), [field]: value }, bar(2_500)])
|
||||
).toThrow(/Market data row 1:/);
|
||||
});
|
||||
}
|
||||
|
||||
for (const field of ['symbol', 'timestamp', 'type', 'open', 'high', 'low', 'close', 'volume']) {
|
||||
test(`rejects missing ${field} with the zero-based row index`, () => {
|
||||
const subject = engine();
|
||||
const incomplete = bar(1_500);
|
||||
delete incomplete[field];
|
||||
expect(() => subject.loadMarketData([bar(500), incomplete, bar(2_500)])).toThrow(
|
||||
/Market data row 1:/
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
for (const value of [null, undefined, 1, 'bar', []]) {
|
||||
test(`rejects a non-record row (${String(value)}) with its index`, () => {
|
||||
const subject = engine();
|
||||
expect(() => subject.loadMarketData([bar(500), value as object, bar(2_500)])).toThrow(
|
||||
/Market data row 1:/
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test('a malformed replacement preserves all previously admitted data', () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar(1_001, 10), bar(1_999, 11)]);
|
||||
expect(() =>
|
||||
subject.loadMarketData([bar(500, 20), { ...bar(1_500, 30), low: 31 }, bar(2_500, 40)])
|
||||
).toThrow(/Market data row 1:/);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']?.map(row => [row.timestamp, row.close])).toEqual([
|
||||
[1_001, 10],
|
||||
[1_999, 11],
|
||||
]);
|
||||
});
|
||||
|
||||
test('an invalid first load does not admit its valid neighboring rows', () => {
|
||||
const subject = engine();
|
||||
expect(() =>
|
||||
subject.loadMarketData([bar(500), { ...bar(1_500), close: Number.NaN }, bar(2_500)])
|
||||
).toThrow(/Market data row 1:/);
|
||||
expect(() => subject.run()).toThrow('No market data loaded');
|
||||
});
|
||||
|
||||
test('a valid replacement after a rejected load succeeds without stale rows', () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar(500)]);
|
||||
expect(() => subject.loadMarketData([{ ...bar(1_001), type: 'quote' }])).toThrow(
|
||||
/Market data row 0: Unsupported market data type: quote/
|
||||
);
|
||||
subject.loadMarketData([bar(1_999, 11)]);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']?.map(row => [row.timestamp, row.close])).toEqual([[1_999, 11]]);
|
||||
});
|
||||
|
||||
for (const conflicting of [false, true]) {
|
||||
test(`rejects ${conflicting ? 'conflicting' : 'identical'} duplicates without replacing good data`, () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar(1_001)]);
|
||||
expect(() => subject.loadMarketData([bar(1_500), bar(1_500, conflicting ? 11 : 10)])).toThrow(
|
||||
/Market data row 1: Duplicate bar identity A\.US at 1500ms \(first at row 0\)/
|
||||
);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']?.map(row => row.timestamp)).toEqual([1_001]);
|
||||
});
|
||||
}
|
||||
|
||||
test('rejects decreasing timestamps instead of relying on an invalid historical seek order', () => {
|
||||
const subject = engine();
|
||||
expect(() => subject.loadMarketData([bar(1_999), bar(1_001)])).toThrow(
|
||||
/Market data row 1: Timestamps must be nondecreasing/
|
||||
);
|
||||
});
|
||||
|
||||
test('accepts distinct same-time symbols, zero volume and optional absent VWAP', () => {
|
||||
const subject = engine();
|
||||
const withoutVwap = { ...bar(1_001), volume: 0 };
|
||||
delete withoutVwap.vwap;
|
||||
subject.loadMarketData([
|
||||
{ ...bar(1_001), symbol: 'B.US', vwap: null },
|
||||
withoutVwap,
|
||||
{ ...bar(1_999), vwap: undefined },
|
||||
]);
|
||||
const result = nativeResultSchema.parse(JSON.parse(subject.run()));
|
||||
expect(result.ohlcData['A.US']).toHaveLength(2);
|
||||
expect(result.ohlcData['B.US']).toHaveLength(1);
|
||||
expect(result.ohlcData['A.US']?.[0]?.volume).toBe(0);
|
||||
});
|
||||
|
||||
test('rejects loading into a consumed engine explicitly', () => {
|
||||
const subject = engine();
|
||||
subject.loadMarketData([bar()]);
|
||||
subject.run();
|
||||
expect(() => subject.loadMarketData([bar()])).toThrow('Engine already consumed');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue