feat(engine): add deterministic historical replay
This commit is contained in:
parent
ccf333cc0a
commit
417a7bd21e
10 changed files with 2055 additions and 28 deletions
|
|
@ -5,6 +5,7 @@
|
|||
pub mod contract;
|
||||
pub mod ledger;
|
||||
pub mod matching;
|
||||
pub mod replay;
|
||||
pub mod risk;
|
||||
pub mod scalar;
|
||||
|
||||
|
|
@ -19,3 +20,6 @@ mod risk_tests;
|
|||
|
||||
#[cfg(test)]
|
||||
mod matching_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod replay_tests;
|
||||
|
|
|
|||
888
apps/stock/engine/src/financial/replay.rs
Normal file
888
apps/stock/engine/src/financial/replay.rs
Normal file
|
|
@ -0,0 +1,888 @@
|
|||
//! Internal F06 bar replay, not a public/native session or a legacy cutover.
|
||||
//!
|
||||
//! F07 must verify the frozen D01 snapshot, retain its eligibility/limitations,
|
||||
//! and adapt prices to canonical decimals before calling this trusted host API.
|
||||
//! This module does not authenticate provenance or repeat D01 normalization.
|
||||
//! Exact canonical prepared input/config bytes bind checkpoints independently
|
||||
//! of the caller's dataset label. They are not a replacement dataset hash.
|
||||
//!
|
||||
//! Bars are stored once; published history is an index prefix, never a clone on
|
||||
//! advance. Only explicit checkpoints copy retained history. Matching remains
|
||||
//! the sole financial authority. No strategy can access the future event vector
|
||||
//! through the context API. This is API separation, not a security sandbox.
|
||||
use super::{
|
||||
contract::*,
|
||||
matching::*,
|
||||
scalar::{Posting, ScalarError},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// Always disclose these in addition to retained dataset limitations. Changing
|
||||
/// mark batching is a financial-policy decision, not a replay optimization.
|
||||
pub const MODEL_LIMITATIONS: &[&str] = &[
|
||||
"Open-only matching uses previously available completed-bar volume, not contemporaneous liquidity.",
|
||||
"Equal-time asset marks apply in lexical instrument order; intermediate equity may latch portfolio risk before the synchronized decision barrier.",
|
||||
"Quote replay and abutting same-series venue sessions are not supported.",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum DatasetEligibility {
|
||||
Eligible,
|
||||
Exploratory,
|
||||
Ineligible,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum PriceAdjustment {
|
||||
Raw,
|
||||
ProviderAdjusted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ReplaySeries {
|
||||
pub series_id: Id,
|
||||
pub instrument_id: Id,
|
||||
pub adjustment: PriceAdjustment,
|
||||
/// Exact retained venue boundaries, including the actual preceding open
|
||||
/// for a mid-session warmup. Abutting sessions are unsupported in v1.
|
||||
pub sessions: Vec<VenueSession>,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PreparedBar {
|
||||
pub series_id: Id,
|
||||
pub instrument_id: Id,
|
||||
pub interval_start: EventTime,
|
||||
pub interval_end: EventTime,
|
||||
pub event_time: EventTime,
|
||||
pub available_at: EventTime,
|
||||
pub source_sequence: Counter,
|
||||
pub open: Positive,
|
||||
pub high: Positive,
|
||||
pub low: Positive,
|
||||
pub close: Positive,
|
||||
pub volume: NonNegative,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ReplayBounds {
|
||||
pub warmup_start: EventTime,
|
||||
pub trade_start: EventTime,
|
||||
pub trade_end: EventTime,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PreparedReplay {
|
||||
pub dataset_id: Id,
|
||||
pub eligibility: DatasetEligibility,
|
||||
pub limitations: Vec<String>,
|
||||
pub bounds: ReplayBounds,
|
||||
pub series: Vec<ReplaySeries>,
|
||||
pub bars: Vec<PreparedBar>,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DecisionCadence {
|
||||
pub owner_id: Id,
|
||||
/// Union of completed observation arrivals; one decision per timestamp.
|
||||
pub series_ids: Vec<Id>,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ReplayConfig {
|
||||
pub matching: MatchingConfig,
|
||||
pub participation_rate: NonNegative,
|
||||
pub cadence: Vec<DecisionCadence>,
|
||||
pub allow_exploratory: bool,
|
||||
/// Separate account clock, never inferred from an instrument's sessions.
|
||||
pub risk_boundaries: Vec<RiskSessionIdentity>,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum InputAvailability {
|
||||
Missing,
|
||||
Fresh {
|
||||
event_time: EventTime,
|
||||
available_at: EventTime,
|
||||
},
|
||||
Stale {
|
||||
event_time: EventTime,
|
||||
available_at: EventTime,
|
||||
},
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct SeriesAvailability {
|
||||
pub series_id: Id,
|
||||
pub availability: InputAvailability,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DecisionBarrier {
|
||||
pub barrier_id: Id,
|
||||
pub at: EventTime,
|
||||
/// Reservation/order-aware matching revision, not ledger revision.
|
||||
pub revision: Counter,
|
||||
pub owner_ids: Vec<Id>,
|
||||
pub observation_count: usize,
|
||||
/// Feature freshness uses the same declared age budget as financial marks.
|
||||
pub inputs: Vec<SeriesAvailability>,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ReplayStatus {
|
||||
Running,
|
||||
Complete,
|
||||
Failed { diagnostic: String },
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ReplayStep {
|
||||
Progress { processed: usize },
|
||||
Decision(DecisionBarrier),
|
||||
Complete,
|
||||
Failed { diagnostic: String },
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DecisionSubmission {
|
||||
pub barrier_id: Id,
|
||||
pub decisions: Vec<StrategyDecision>,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ReplayCheckpoint {
|
||||
pub version: Version,
|
||||
pub binding: String,
|
||||
pub next_event: usize,
|
||||
pub observation_count: usize,
|
||||
pub pending: Option<DecisionBarrier>,
|
||||
pub status: ReplayStatus,
|
||||
pub submissions: Vec<DecisionSubmission>,
|
||||
pub matching: MatchingCheckpoint,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ReplayError {
|
||||
#[error("invalid prepared replay input: {0}")]
|
||||
InvalidInput(&'static str),
|
||||
#[error("advance requires a positive event budget")]
|
||||
InvalidBudget,
|
||||
#[error("submission does not match the pending barrier and exact due owners")]
|
||||
InvalidSubmission,
|
||||
#[error("replay is terminal")]
|
||||
Terminal,
|
||||
#[error("checkpoint input/config or retained replay state does not match")]
|
||||
InvalidCheckpoint,
|
||||
#[error(transparent)]
|
||||
Matching(#[from] MatchingError),
|
||||
#[error(transparent)]
|
||||
Arithmetic(#[from] ScalarError),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum EventBody {
|
||||
OpenSession(VenueSession),
|
||||
RiskBoundary(RiskSessionIdentity),
|
||||
Observe(usize),
|
||||
Decision(Vec<Id>),
|
||||
Open(usize),
|
||||
CloseSession(Id),
|
||||
Finish,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
struct Event {
|
||||
key: EventKey,
|
||||
// Session/account controls precede observations; series ID breaks feature
|
||||
// source-sequence ties. Matcher observation keys receive canonical ranks.
|
||||
control_rank: u8,
|
||||
series_id: Id,
|
||||
body: EventBody,
|
||||
}
|
||||
fn id(value: impl Serialize) -> Id {
|
||||
serde_json::from_value(serde_json::Value::String(
|
||||
serde_json::to_string(&value).unwrap(),
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
fn time_order(bar: &PreparedBar) -> (i64, u64) {
|
||||
(bar.event_time.get(), bar.source_sequence.get())
|
||||
}
|
||||
fn invalid(reason: &'static str) -> ReplayError {
|
||||
ReplayError::InvalidInput(reason)
|
||||
}
|
||||
|
||||
/// No mutable matcher/ledger accessor or strategy-facing future-data accessor.
|
||||
#[derive(Debug)]
|
||||
pub struct Replay {
|
||||
input: PreparedReplay,
|
||||
config: ReplayConfig,
|
||||
binding: String,
|
||||
events: Vec<Event>,
|
||||
next_event: usize,
|
||||
published: Vec<usize>,
|
||||
latest: BTreeMap<Id, usize>,
|
||||
execution_series: BTreeSet<Id>,
|
||||
pending: Option<DecisionBarrier>,
|
||||
status: ReplayStatus,
|
||||
submissions: Vec<DecisionSubmission>,
|
||||
matching: MatchingAccount,
|
||||
}
|
||||
|
||||
impl Replay {
|
||||
pub fn new(mut input: PreparedReplay, mut config: ReplayConfig) -> Result<Self, ReplayError> {
|
||||
Self::canonicalize(&mut input, &mut config);
|
||||
Self::validate(&input, &config)?;
|
||||
let matching = MatchingAccount::new(config.matching.clone())?.0;
|
||||
let events = Self::events(&input, &config)?;
|
||||
let binding =
|
||||
serde_json::to_string(&(&input, &config)).expect("serializable prepared input");
|
||||
let execution_series = config
|
||||
.matching
|
||||
.series
|
||||
.iter()
|
||||
.map(|s| s.series_id.clone())
|
||||
.collect();
|
||||
Ok(Self {
|
||||
input,
|
||||
config,
|
||||
binding,
|
||||
events,
|
||||
next_event: 0,
|
||||
published: Vec::new(),
|
||||
latest: BTreeMap::new(),
|
||||
execution_series,
|
||||
pending: None,
|
||||
status: ReplayStatus::Running,
|
||||
submissions: Vec::new(),
|
||||
matching,
|
||||
})
|
||||
}
|
||||
fn canonicalize(input: &mut PreparedReplay, config: &mut ReplayConfig) {
|
||||
input.series.sort_by(|a, b| a.series_id.cmp(&b.series_id));
|
||||
for series in &mut input.series {
|
||||
series.sessions.sort_by_key(|s| s.opens_at.get());
|
||||
}
|
||||
input.bars.sort_by(|a, b| {
|
||||
(
|
||||
&a.series_id,
|
||||
a.interval_start.get(),
|
||||
a.source_sequence.get(),
|
||||
)
|
||||
.cmp(&(
|
||||
&b.series_id,
|
||||
b.interval_start.get(),
|
||||
b.source_sequence.get(),
|
||||
))
|
||||
});
|
||||
input.limitations.sort();
|
||||
config
|
||||
.matching
|
||||
.owners
|
||||
.sort_by(|a, b| a.owner_id.cmp(&b.owner_id));
|
||||
config.matching.risk.ledger.owner_ids.sort();
|
||||
config
|
||||
.matching
|
||||
.series
|
||||
.sort_by(|a, b| a.instrument_id.cmp(&b.instrument_id));
|
||||
config.cadence.sort_by(|a, b| a.owner_id.cmp(&b.owner_id));
|
||||
for cadence in &mut config.cadence {
|
||||
cadence.series_ids.sort();
|
||||
}
|
||||
config.risk_boundaries.sort_by_key(|s| s.starts_at.get());
|
||||
}
|
||||
fn validate(input: &PreparedReplay, config: &ReplayConfig) -> Result<(), ReplayError> {
|
||||
let b = &input.bounds;
|
||||
if b.warmup_start.get() > b.trade_start.get() || b.trade_start.get() >= b.trade_end.get() {
|
||||
return Err(invalid(
|
||||
"bounds must satisfy warmupStart <= tradeStart < tradeEnd",
|
||||
));
|
||||
}
|
||||
if input.eligibility == DatasetEligibility::Ineligible
|
||||
|| (input.eligibility == DatasetEligibility::Exploratory
|
||||
&& (!config.allow_exploratory || input.limitations.is_empty()))
|
||||
{
|
||||
return Err(invalid(
|
||||
"dataset eligibility/limitations do not permit this run",
|
||||
));
|
||||
}
|
||||
if Posting::from(config.participation_rate) > "1".parse::<Posting>().unwrap() {
|
||||
return Err(invalid("participation must be between zero and one"));
|
||||
}
|
||||
if input.series.is_empty()
|
||||
|| input
|
||||
.series
|
||||
.windows(2)
|
||||
.any(|w| w[0].series_id == w[1].series_id)
|
||||
{
|
||||
return Err(invalid("series IDs must be unique and nonempty"));
|
||||
}
|
||||
let series: BTreeMap<_, _> = input.series.iter().map(|s| (&s.series_id, s)).collect();
|
||||
for s in &input.series {
|
||||
let mut ids = BTreeSet::new();
|
||||
for session in &s.sessions {
|
||||
if session.opens_at.get() >= session.closes_at.get()
|
||||
|| !ids.insert(&session.session_id)
|
||||
{
|
||||
return Err(invalid("invalid or duplicate retained session"));
|
||||
}
|
||||
}
|
||||
if s.sessions
|
||||
.windows(2)
|
||||
.any(|w| w[0].closes_at.get() >= w[1].opens_at.get())
|
||||
{
|
||||
return Err(invalid(
|
||||
"overlapping or abutting retained sessions are unsupported",
|
||||
));
|
||||
}
|
||||
}
|
||||
let instruments: BTreeSet<_> = input.series.iter().map(|s| &s.instrument_id).collect();
|
||||
let execution: BTreeSet<_> = config
|
||||
.matching
|
||||
.series
|
||||
.iter()
|
||||
.map(|s| &s.instrument_id)
|
||||
.collect();
|
||||
if instruments != execution {
|
||||
return Err(invalid(
|
||||
"each instrument needs exactly one execution series",
|
||||
));
|
||||
}
|
||||
let initial = config.matching.risk.ledger.risk_session.starts_at.get();
|
||||
if initial > b.warmup_start.get() {
|
||||
return Err(invalid("initial account clock follows warmup"));
|
||||
}
|
||||
for e in &config.matching.series {
|
||||
let s = series
|
||||
.get(&e.series_id)
|
||||
.ok_or_else(|| invalid("unknown execution series"))?;
|
||||
if e.mode != ExecutionMode::Open {
|
||||
return Err(invalid("quote replay has no D01 dataset contract yet"));
|
||||
}
|
||||
if e.instrument_id != s.instrument_id || s.adjustment != PriceAdjustment::Raw {
|
||||
return Err(invalid(
|
||||
"execution series must agree with instrument and contain raw prices",
|
||||
));
|
||||
}
|
||||
for session in &s.sessions {
|
||||
if session.closes_at.get() > b.warmup_start.get()
|
||||
&& session.opens_at.get() < b.trade_end.get()
|
||||
&& session.opens_at.get() < initial
|
||||
{
|
||||
return Err(invalid(
|
||||
"initial account clock follows true preceding venue open",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sequences = BTreeSet::new();
|
||||
let mut intervals = BTreeMap::new();
|
||||
for bar in &input.bars {
|
||||
let s = series
|
||||
.get(&bar.series_id)
|
||||
.ok_or_else(|| invalid("bar references unknown series"))?;
|
||||
if bar.instrument_id != s.instrument_id
|
||||
|| bar.interval_start.get() < b.warmup_start.get()
|
||||
|| bar.interval_start.get() >= b.trade_end.get()
|
||||
|| bar.interval_end.get() > b.trade_end.get()
|
||||
|| bar.interval_start.get() >= bar.interval_end.get()
|
||||
|| bar.event_time != bar.interval_end
|
||||
|| bar.available_at.get() < bar.interval_end.get()
|
||||
{
|
||||
return Err(invalid("invalid bar identity, timing or bounds"));
|
||||
}
|
||||
if !sequences.insert((&bar.series_id, bar.source_sequence.get())) {
|
||||
return Err(invalid("source sequence must be unique within its series"));
|
||||
}
|
||||
if intervals
|
||||
.insert(&bar.series_id, bar.interval_end.get())
|
||||
.is_some_and(|end| end > bar.interval_start.get())
|
||||
{
|
||||
return Err(invalid("overlapping or duplicate bar intervals"));
|
||||
}
|
||||
let low: Posting = bar.low.into();
|
||||
let high: Posting = bar.high.into();
|
||||
if low > high
|
||||
|| Posting::from(bar.open) < low
|
||||
|| Posting::from(bar.open) > high
|
||||
|| Posting::from(bar.close) < low
|
||||
|| Posting::from(bar.close) > high
|
||||
{
|
||||
return Err(invalid("inconsistent OHLC prices"));
|
||||
}
|
||||
// Session lookup is logarithmic, not a full calendar scan per bar.
|
||||
let session = s
|
||||
.sessions
|
||||
.partition_point(|v| v.opens_at.get() <= bar.interval_start.get());
|
||||
if session == 0 || s.sessions[session - 1].closes_at.get() < bar.interval_end.get() {
|
||||
return Err(invalid("bar is not contained in a retained venue session"));
|
||||
}
|
||||
}
|
||||
if intervals.len() != input.series.len() {
|
||||
return Err(invalid(
|
||||
"every declared series requires at least one prepared bar",
|
||||
));
|
||||
}
|
||||
let owners: Vec<_> = config.matching.owners.iter().map(|o| &o.owner_id).collect();
|
||||
if owners
|
||||
!= config
|
||||
.cadence
|
||||
.iter()
|
||||
.map(|c| &c.owner_id)
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
return Err(invalid("each owner requires exactly one declared cadence"));
|
||||
}
|
||||
for c in &config.cadence {
|
||||
if c.series_ids.is_empty()
|
||||
|| c.series_ids.windows(2).any(|w| w[0] == w[1])
|
||||
|| c.series_ids.iter().any(|s| !series.contains_key(s))
|
||||
{
|
||||
return Err(invalid("cadence series must be known and distinct"));
|
||||
}
|
||||
}
|
||||
let risk = &config.matching.risk.ledger.risk_session;
|
||||
let mut prior = initial;
|
||||
let mut risk_ids = BTreeSet::from([&risk.session_id]);
|
||||
for boundary in &config.risk_boundaries {
|
||||
if boundary.calendar_id != risk.calendar_id
|
||||
|| boundary.calendar_revision != risk.calendar_revision
|
||||
|| boundary.starts_at.get() <= prior
|
||||
|| boundary.starts_at.get() > b.trade_end.get()
|
||||
|| !risk_ids.insert(&boundary.session_id)
|
||||
{
|
||||
return Err(invalid("invalid account risk boundary"));
|
||||
}
|
||||
prior = boundary.starts_at.get();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn events(input: &PreparedReplay, config: &ReplayConfig) -> Result<Vec<Event>, ReplayError> {
|
||||
let mut events = Vec::with_capacity(input.bars.len().saturating_mul(2));
|
||||
let first = config
|
||||
.matching
|
||||
.series
|
||||
.first()
|
||||
.ok_or_else(|| invalid("missing execution series"))?
|
||||
.instrument_id
|
||||
.clone();
|
||||
let last = config.matching.series.last().unwrap().instrument_id.clone();
|
||||
let mut push = |at, phase, instrument_id: Id, sequence: Counter, rank, series_id, body| {
|
||||
events.push(Event {
|
||||
key: EventKey {
|
||||
at,
|
||||
phase,
|
||||
instrument_id,
|
||||
source_sequence: sequence,
|
||||
},
|
||||
control_rank: rank,
|
||||
series_id,
|
||||
body,
|
||||
});
|
||||
};
|
||||
let zero: Counter = 0.try_into().unwrap();
|
||||
let mut execution = BTreeMap::new();
|
||||
for e in &config.matching.series {
|
||||
execution.insert(&e.series_id, &e.instrument_id);
|
||||
let s = input
|
||||
.series
|
||||
.iter()
|
||||
.find(|s| s.series_id == e.series_id)
|
||||
.unwrap();
|
||||
for session in &s.sessions {
|
||||
if session.closes_at.get() <= input.bounds.warmup_start.get()
|
||||
|| session.opens_at.get() >= input.bounds.trade_end.get()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
push(
|
||||
session.opens_at,
|
||||
EventPhase::Observation,
|
||||
e.instrument_id.clone(),
|
||||
zero,
|
||||
0,
|
||||
s.series_id.clone(),
|
||||
EventBody::OpenSession(session.clone()),
|
||||
);
|
||||
if session.closes_at.get() <= input.bounds.trade_end.get() {
|
||||
push(
|
||||
session.closes_at,
|
||||
EventPhase::SessionClose,
|
||||
e.instrument_id.clone(),
|
||||
zero,
|
||||
0,
|
||||
s.series_id.clone(),
|
||||
EventBody::CloseSession(session.session_id.clone()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for boundary in &config.risk_boundaries {
|
||||
push(
|
||||
boundary.starts_at,
|
||||
EventPhase::Observation,
|
||||
first.clone(),
|
||||
zero,
|
||||
1,
|
||||
first.clone(),
|
||||
EventBody::RiskBoundary(boundary.clone()),
|
||||
);
|
||||
}
|
||||
let mut cadence: BTreeMap<&Id, Vec<&Id>> = BTreeMap::new();
|
||||
for c in &config.cadence {
|
||||
for series in &c.series_ids {
|
||||
cadence.entry(series).or_default().push(&c.owner_id);
|
||||
}
|
||||
}
|
||||
let mut decisions: BTreeMap<i64, BTreeSet<Id>> = BTreeMap::new();
|
||||
for (index, bar) in input.bars.iter().enumerate() {
|
||||
if bar.available_at.get() <= input.bounds.trade_end.get() {
|
||||
push(
|
||||
bar.available_at,
|
||||
EventPhase::Observation,
|
||||
bar.instrument_id.clone(),
|
||||
bar.source_sequence,
|
||||
2,
|
||||
bar.series_id.clone(),
|
||||
EventBody::Observe(index),
|
||||
);
|
||||
if bar.available_at.get() >= input.bounds.trade_start.get()
|
||||
&& bar.available_at.get() < input.bounds.trade_end.get()
|
||||
{
|
||||
for owner in cadence.get(&bar.series_id).into_iter().flatten() {
|
||||
decisions
|
||||
.entry(bar.available_at.get())
|
||||
.or_default()
|
||||
.insert((*owner).clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if execution.contains_key(&bar.series_id)
|
||||
&& bar.interval_start.get() >= input.bounds.trade_start.get()
|
||||
{
|
||||
push(
|
||||
bar.interval_start,
|
||||
EventPhase::Execution,
|
||||
bar.instrument_id.clone(),
|
||||
bar.source_sequence,
|
||||
0,
|
||||
bar.series_id.clone(),
|
||||
EventBody::Open(index),
|
||||
);
|
||||
}
|
||||
}
|
||||
for (at, owners) in decisions {
|
||||
push(
|
||||
at.try_into().unwrap(),
|
||||
EventPhase::Decision,
|
||||
first.clone(),
|
||||
zero,
|
||||
0,
|
||||
first.clone(),
|
||||
EventBody::Decision(owners.into_iter().collect()),
|
||||
);
|
||||
}
|
||||
push(
|
||||
input.bounds.trade_end,
|
||||
EventPhase::SessionClose,
|
||||
last.clone(),
|
||||
zero,
|
||||
3,
|
||||
last,
|
||||
EventBody::Finish,
|
||||
);
|
||||
events.sort_by(|a, b| {
|
||||
(
|
||||
a.key.at.get(),
|
||||
a.key.phase,
|
||||
&a.key.instrument_id,
|
||||
a.control_rank,
|
||||
a.key.source_sequence.get(),
|
||||
&a.series_id,
|
||||
)
|
||||
.cmp(&(
|
||||
b.key.at.get(),
|
||||
b.key.phase,
|
||||
&b.key.instrument_id,
|
||||
b.control_rank,
|
||||
b.key.source_sequence.get(),
|
||||
&b.series_id,
|
||||
))
|
||||
});
|
||||
// Matcher has no series field in its key. Give same-phase observations
|
||||
// canonical ranks after sorting by source sequence + stable series ID;
|
||||
// execution keys retain the actual pinned-series source sequence.
|
||||
let mut previous = None;
|
||||
let mut rank = 0_u64;
|
||||
for event in &mut events {
|
||||
let group = (
|
||||
event.key.at.get(),
|
||||
event.key.phase,
|
||||
event.key.instrument_id.clone(),
|
||||
);
|
||||
if previous.as_ref() == Some(&group) {
|
||||
rank += 1;
|
||||
} else {
|
||||
rank = 0;
|
||||
}
|
||||
if event.key.phase != EventPhase::Execution {
|
||||
event.key.source_sequence = rank
|
||||
.try_into()
|
||||
.map_err(|_| invalid("event rank overflow"))?;
|
||||
}
|
||||
previous = Some(group);
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
pub fn status(&self) -> &ReplayStatus {
|
||||
&self.status
|
||||
}
|
||||
pub fn barrier(&self) -> Option<&DecisionBarrier> {
|
||||
self.pending.as_ref()
|
||||
}
|
||||
pub fn financial(&self) -> &MatchingAccount {
|
||||
&self.matching
|
||||
}
|
||||
/// Only already published bars, in canonical arrival order.
|
||||
pub fn observations(&self) -> impl Iterator<Item = &PreparedBar> {
|
||||
self.published.iter().map(|i| &self.input.bars[*i])
|
||||
}
|
||||
pub fn latest_observation(&self, series: &Id) -> Option<&PreparedBar> {
|
||||
self.latest.get(series).map(|i| &self.input.bars[*i])
|
||||
}
|
||||
pub fn limitations(&self) -> &[String] {
|
||||
&self.input.limitations
|
||||
}
|
||||
pub fn model_limitations(&self) -> &'static [&'static str] {
|
||||
MODEL_LIMITATIONS
|
||||
}
|
||||
|
||||
fn command(
|
||||
&mut self,
|
||||
index: usize,
|
||||
key: EventKey,
|
||||
body: MatchingCommandBody,
|
||||
) -> Result<(), ReplayError> {
|
||||
let out = self.matching.apply(&MatchingCommand {
|
||||
command_id: id(("replay", index)),
|
||||
key,
|
||||
body,
|
||||
})?;
|
||||
if let AttemptStatus::Failed { diagnostic } = out.status {
|
||||
self.status = ReplayStatus::Failed { diagnostic };
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn process(&mut self, index: usize, event: Event) -> Result<(), ReplayError> {
|
||||
let key = event.key;
|
||||
match event.body {
|
||||
EventBody::OpenSession(session) => {
|
||||
self.command(index, key, MatchingCommandBody::OpenSession { session })?
|
||||
}
|
||||
EventBody::RiskBoundary(risk_session) => self.command(
|
||||
index,
|
||||
key,
|
||||
MatchingCommandBody::RiskSessionBoundary { risk_session },
|
||||
)?,
|
||||
EventBody::CloseSession(session_id) => {
|
||||
self.command(index, key, MatchingCommandBody::CloseSession { session_id })?
|
||||
}
|
||||
EventBody::Observe(bar_index) => {
|
||||
let bar = &self.input.bars[bar_index];
|
||||
self.published.push(bar_index);
|
||||
if self
|
||||
.latest
|
||||
.get(&bar.series_id)
|
||||
.is_none_or(|old| time_order(bar) > time_order(&self.input.bars[*old]))
|
||||
{
|
||||
self.latest.insert(bar.series_id.clone(), bar_index);
|
||||
}
|
||||
if self.execution_series.contains(&bar.series_id)
|
||||
&& self.latest.get(&bar.series_id) == Some(&bar_index)
|
||||
// A delayed close at t must not replace the next interval's
|
||||
// already processed open at t (Execution follows Observation).
|
||||
&& self.matching.ledger().mark(&bar.instrument_id).is_none_or(|m| bar.event_time.get() > m.event_time.get())
|
||||
{
|
||||
let body = MatchingCommandBody::Mark {
|
||||
series_id: bar.series_id.clone(),
|
||||
price: bar.close,
|
||||
observed_at: bar.event_time,
|
||||
};
|
||||
self.command(index, key, body)?;
|
||||
}
|
||||
}
|
||||
EventBody::Decision(owner_ids) => {
|
||||
let max_age = self.config.matching.risk.max_mark_age_ms.get();
|
||||
let inputs = self
|
||||
.input
|
||||
.series
|
||||
.iter()
|
||||
.map(|series| {
|
||||
let availability = match self.latest_observation(&series.series_id) {
|
||||
None => InputAvailability::Missing,
|
||||
Some(b) if (key.at.get() - b.event_time.get()) as u64 > max_age => {
|
||||
InputAvailability::Stale {
|
||||
event_time: b.event_time,
|
||||
available_at: b.available_at,
|
||||
}
|
||||
}
|
||||
Some(b) => InputAvailability::Fresh {
|
||||
event_time: b.event_time,
|
||||
available_at: b.available_at,
|
||||
},
|
||||
};
|
||||
SeriesAvailability {
|
||||
series_id: series.series_id.clone(),
|
||||
availability,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
self.pending = Some(DecisionBarrier {
|
||||
barrier_id: id(("barrier", index, key.at.get())),
|
||||
at: key.at,
|
||||
revision: self.matching.admission_revision(),
|
||||
owner_ids,
|
||||
observation_count: self.published.len(),
|
||||
inputs,
|
||||
});
|
||||
}
|
||||
EventBody::Open(bar_index) => {
|
||||
let bar = &self.input.bars[bar_index];
|
||||
let volume = self
|
||||
.latest_observation(&bar.series_id)
|
||||
.map(|b| b.volume)
|
||||
.unwrap_or_else(|| Posting::ZERO.try_into().unwrap());
|
||||
let capacity =
|
||||
Posting::notional(volume.into(), self.config.participation_rate.into())?
|
||||
.try_into()
|
||||
.expect("nonnegative participation");
|
||||
let body = MatchingCommandBody::Execute {
|
||||
series_id: bar.series_id.clone(),
|
||||
observation: ExecutionObservation::Open {
|
||||
opens_at: bar.interval_start,
|
||||
price: bar.open,
|
||||
capacity,
|
||||
},
|
||||
};
|
||||
self.command(index, key, body)?;
|
||||
}
|
||||
EventBody::Finish => {
|
||||
self.command(index, key, MatchingCommandBody::Finish)?;
|
||||
if self.status == ReplayStatus::Running {
|
||||
self.status = ReplayStatus::Complete;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn advance(&mut self, budget: usize) -> Result<ReplayStep, ReplayError> {
|
||||
if budget == 0 {
|
||||
return Err(ReplayError::InvalidBudget);
|
||||
}
|
||||
if let Some(barrier) = &self.pending {
|
||||
return Ok(ReplayStep::Decision(barrier.clone()));
|
||||
}
|
||||
let mut processed = 0;
|
||||
while self.status == ReplayStatus::Running && processed < budget {
|
||||
let index = self.next_event;
|
||||
let event = self.events[index].clone();
|
||||
self.next_event += 1;
|
||||
processed += 1;
|
||||
if let Err(error) = self.process(index, event) {
|
||||
self.status = ReplayStatus::Failed {
|
||||
diagnostic: error.to_string(),
|
||||
};
|
||||
}
|
||||
if let Some(barrier) = &self.pending {
|
||||
return Ok(ReplayStep::Decision(barrier.clone()));
|
||||
}
|
||||
}
|
||||
Ok(match &self.status {
|
||||
ReplayStatus::Running => ReplayStep::Progress { processed },
|
||||
ReplayStatus::Complete => ReplayStep::Complete,
|
||||
ReplayStatus::Failed { diagnostic } => ReplayStep::Failed {
|
||||
diagnostic: diagnostic.clone(),
|
||||
},
|
||||
})
|
||||
}
|
||||
pub fn submit(
|
||||
&mut self,
|
||||
mut submission: DecisionSubmission,
|
||||
) -> Result<MatchingOutcome, ReplayError> {
|
||||
if self.status != ReplayStatus::Running {
|
||||
return Err(ReplayError::Terminal);
|
||||
}
|
||||
let barrier = self
|
||||
.pending
|
||||
.as_ref()
|
||||
.ok_or(ReplayError::InvalidSubmission)?;
|
||||
submission
|
||||
.decisions
|
||||
.sort_by(|a, b| a.decision.owner_id.cmp(&b.decision.owner_id));
|
||||
let owners: Vec<_> = submission
|
||||
.decisions
|
||||
.iter()
|
||||
.map(|d| &d.decision.owner_id)
|
||||
.collect();
|
||||
if submission.barrier_id != barrier.barrier_id
|
||||
|| owners != barrier.owner_ids.iter().collect::<Vec<_>>()
|
||||
|| submission
|
||||
.decisions
|
||||
.iter()
|
||||
.any(|d| d.barrier_id != barrier.barrier_id || d.revision != barrier.revision)
|
||||
{
|
||||
return Err(ReplayError::InvalidSubmission);
|
||||
}
|
||||
let index = self.next_event - 1;
|
||||
let out = self.matching.apply(&MatchingCommand {
|
||||
command_id: id(("replay", index)),
|
||||
key: self.events[index].key.clone(),
|
||||
body: MatchingCommandBody::Submit {
|
||||
decisions: submission.decisions.clone(),
|
||||
},
|
||||
})?;
|
||||
self.submissions.push(submission);
|
||||
self.pending = None;
|
||||
if let AttemptStatus::Failed { diagnostic } = &out.status {
|
||||
self.status = ReplayStatus::Failed {
|
||||
diagnostic: diagnostic.clone(),
|
||||
};
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
pub fn checkpoint(&self) -> ReplayCheckpoint {
|
||||
ReplayCheckpoint {
|
||||
version: Version,
|
||||
binding: self.binding.clone(),
|
||||
next_event: self.next_event,
|
||||
observation_count: self.published.len(),
|
||||
pending: self.pending.clone(),
|
||||
status: self.status.clone(),
|
||||
submissions: self.submissions.clone(),
|
||||
matching: self.matching.checkpoint(),
|
||||
}
|
||||
}
|
||||
/// Deterministic fixed-decision-trace recovery. Strategy state/RNG and
|
||||
/// strategy recomputation are separately owned by F07/S01.
|
||||
pub fn restore(
|
||||
input: PreparedReplay,
|
||||
config: ReplayConfig,
|
||||
checkpoint: &ReplayCheckpoint,
|
||||
) -> Result<Self, ReplayError> {
|
||||
let mut replay = Self::new(input, config)?;
|
||||
if replay.binding != checkpoint.binding || checkpoint.next_event > replay.events.len() {
|
||||
return Err(ReplayError::InvalidCheckpoint);
|
||||
}
|
||||
let mut submissions = checkpoint.submissions.iter();
|
||||
while replay.next_event < checkpoint.next_event {
|
||||
if replay.status != ReplayStatus::Running {
|
||||
return Err(ReplayError::InvalidCheckpoint);
|
||||
}
|
||||
replay.advance(1)?;
|
||||
if replay.pending.is_some() {
|
||||
if replay.next_event == checkpoint.next_event && checkpoint.pending.is_some() {
|
||||
break;
|
||||
}
|
||||
replay
|
||||
.submit(
|
||||
submissions
|
||||
.next()
|
||||
.ok_or(ReplayError::InvalidCheckpoint)?
|
||||
.clone(),
|
||||
)
|
||||
.map_err(|_| ReplayError::InvalidCheckpoint)?;
|
||||
}
|
||||
}
|
||||
if submissions.next().is_some() || replay.checkpoint() != *checkpoint {
|
||||
return Err(ReplayError::InvalidCheckpoint);
|
||||
}
|
||||
Ok(replay)
|
||||
}
|
||||
}
|
||||
967
apps/stock/engine/src/financial/replay_tests.rs
Normal file
967
apps/stock/engine/src/financial/replay_tests.rs
Normal file
|
|
@ -0,0 +1,967 @@
|
|||
use super::{contract::*, matching::*, replay::*, scalar::Posting};
|
||||
use serde_json::json;
|
||||
use std::time::Instant;
|
||||
|
||||
fn id(s: &str) -> Id {
|
||||
serde_json::from_value(json!(s)).unwrap()
|
||||
}
|
||||
fn t(n: i64) -> EventTime {
|
||||
n.try_into().unwrap()
|
||||
}
|
||||
fn p(s: &str) -> Posting {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
fn pos(s: &str) -> Positive {
|
||||
p(s).try_into().unwrap()
|
||||
}
|
||||
fn nn(s: &str) -> NonNegative {
|
||||
p(s).try_into().unwrap()
|
||||
}
|
||||
fn venue(name: &str, start: i64, end: i64) -> VenueSession {
|
||||
VenueSession {
|
||||
session_id: id(name),
|
||||
opens_at: t(start),
|
||||
closes_at: t(end),
|
||||
}
|
||||
}
|
||||
fn series(name: &str, symbol: &str) -> ReplaySeries {
|
||||
ReplaySeries {
|
||||
series_id: id(name),
|
||||
instrument_id: id(symbol),
|
||||
adjustment: PriceAdjustment::Raw,
|
||||
sessions: vec![venue("day1", 0, 10000000)],
|
||||
}
|
||||
}
|
||||
fn bar(
|
||||
series: &str,
|
||||
symbol: &str,
|
||||
start: i64,
|
||||
end: i64,
|
||||
available: i64,
|
||||
seq: u64,
|
||||
open: &str,
|
||||
close: &str,
|
||||
volume: &str,
|
||||
) -> PreparedBar {
|
||||
PreparedBar {
|
||||
series_id: id(series),
|
||||
instrument_id: id(symbol),
|
||||
interval_start: t(start),
|
||||
interval_end: t(end),
|
||||
event_time: t(end),
|
||||
available_at: t(available),
|
||||
source_sequence: seq.try_into().unwrap(),
|
||||
open: pos(open),
|
||||
high: p(open).max(p(close)).try_into().unwrap(),
|
||||
low: p(open).min(p(close)).try_into().unwrap(),
|
||||
close: pos(close),
|
||||
volume: nn(volume),
|
||||
}
|
||||
}
|
||||
fn fixture() -> (PreparedReplay, ReplayConfig) {
|
||||
let matching:MatchingConfig=serde_json::from_value(json!({
|
||||
"risk":{"ledger":{"version":1,"sessionId":"run","accountId":"account","baseCurrency":"USD","reserveOwnerId":"reserve","ownerIds":["A"],"initialCapital":"10000","riskSession":{"calendarId":"account","calendarRevision":"1","sessionId":"risk1","startsAt":0}},
|
||||
"feeRate":"0.01","maxOrderQuantity":"1000000","maxPositionQuantity":"1000000","maxSymbolExposure":"1000000","maxGrossExposure":"1000000","maxDailyLoss":"1000000","maxDrawdownAmount":"1000000","maxMarkAgeMs":10000000},
|
||||
"owners":[{"ownerId":"A","mode":"Target"}],"series":[{"instrumentId":"X","seriesId":"X-bars","mode":"Open"}],"halfSpreadRate":"0","slippageRate":"0","latencyMs":0
|
||||
})).unwrap();
|
||||
(
|
||||
PreparedReplay {
|
||||
dataset_id: id("frozen-fixture"),
|
||||
eligibility: DatasetEligibility::Eligible,
|
||||
limitations: vec!["previous completed volume capacity; zero modeled latency".into()],
|
||||
bounds: ReplayBounds {
|
||||
warmup_start: t(0),
|
||||
trade_start: t(10),
|
||||
trade_end: t(30),
|
||||
},
|
||||
series: vec![series("X-bars", "X")],
|
||||
bars: vec![
|
||||
bar("X-bars", "X", 0, 10, 10, 7, "10", "11", "100"),
|
||||
bar("X-bars", "X", 10, 20, 20, 3, "12", "13", "100"),
|
||||
bar("X-bars", "X", 20, 30, 30, 9, "14", "15", "100"),
|
||||
],
|
||||
},
|
||||
ReplayConfig {
|
||||
matching,
|
||||
participation_rate: nn("1"),
|
||||
cadence: vec![DecisionCadence {
|
||||
owner_id: id("A"),
|
||||
series_ids: vec![id("X-bars")],
|
||||
}],
|
||||
allow_exploratory: false,
|
||||
risk_boundaries: vec![],
|
||||
},
|
||||
)
|
||||
}
|
||||
fn next(r: &mut Replay) -> Option<DecisionBarrier> {
|
||||
loop {
|
||||
match r.advance(100).unwrap() {
|
||||
ReplayStep::Decision(b) => return Some(b),
|
||||
ReplayStep::Complete => return None,
|
||||
ReplayStep::Failed { diagnostic } => panic!("replay failed: {diagnostic}"),
|
||||
ReplayStep::Progress { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn target(r: &mut Replay, b: &DecisionBarrier, quantity: &str) -> MatchingOutcome {
|
||||
let decisions = b
|
||||
.owner_ids
|
||||
.iter()
|
||||
.map(|owner| StrategyDecision {
|
||||
version: Version,
|
||||
session_id: id("run"),
|
||||
barrier_id: b.barrier_id.clone(),
|
||||
revision: b.revision,
|
||||
decision: DecisionIdentity {
|
||||
owner_id: owner.clone(),
|
||||
decision_id: id(&format!("{}-{owner:?}", b.at.get())),
|
||||
sequence: (b.at.get() as u64).try_into().unwrap(),
|
||||
},
|
||||
intent: StrategyIntent::Target {
|
||||
targets: vec![Target {
|
||||
instrument_id: id("X"),
|
||||
quantity: nn(quantity),
|
||||
}],
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
r.submit(DecisionSubmission {
|
||||
barrier_id: b.barrier_id.clone(),
|
||||
decisions,
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
fn no_change(r: &mut Replay, b: &DecisionBarrier) -> MatchingOutcome {
|
||||
let decisions = b
|
||||
.owner_ids
|
||||
.iter()
|
||||
.map(|owner| StrategyDecision {
|
||||
version: Version,
|
||||
session_id: id("run"),
|
||||
barrier_id: b.barrier_id.clone(),
|
||||
revision: b.revision,
|
||||
decision: DecisionIdentity {
|
||||
owner_id: owner.clone(),
|
||||
decision_id: id(&format!("{}-{owner:?}", b.at.get())),
|
||||
sequence: (b.at.get() as u64).try_into().unwrap(),
|
||||
},
|
||||
intent: StrategyIntent::Target { targets: vec![] },
|
||||
})
|
||||
.collect();
|
||||
r.submit(DecisionSubmission {
|
||||
barrier_id: b.barrier_id.clone(),
|
||||
decisions,
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
fn complete(r: &mut Replay) {
|
||||
while let Some(b) = next(r) {
|
||||
no_change(r, &b);
|
||||
}
|
||||
}
|
||||
fn fill_prices(r: &Replay) -> Vec<Posting> {
|
||||
r.financial()
|
||||
.receipts()
|
||||
.iter()
|
||||
.flat_map(|r| &r.outcome.effects)
|
||||
.filter_map(|effect| {
|
||||
if let MatchingEffect::Risk { command, outcome } = effect {
|
||||
if let super::risk::RiskCommandBody::Fill { price, .. } = command.body {
|
||||
if outcome.financial.is_some()
|
||||
&& outcome.disposition == super::risk::RiskDisposition::Accepted
|
||||
{
|
||||
return Some(price.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
#[test]
|
||||
fn adjacent_open_zero_latency() {
|
||||
let (input, config) = fixture();
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(10));
|
||||
assert_eq!(b.observation_count, 1);
|
||||
assert_eq!(r.observations().next().unwrap().close, pos("11"));
|
||||
target(&mut r, &b, "2");
|
||||
complete(&mut r);
|
||||
assert_eq!(fill_prices(&r), vec![p("12")]);
|
||||
assert_eq!(r.financial().ledger().cash(), p("9975.76"));
|
||||
assert_eq!(r.financial().ledger().equity().unwrap(), p("10005.76"));
|
||||
}
|
||||
#[test]
|
||||
fn positive_latency_skips_open() {
|
||||
let (input, mut config) = fixture();
|
||||
config.matching.latency_ms = 1.try_into().unwrap();
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
target(&mut r, &b, "2");
|
||||
complete(&mut r);
|
||||
assert_eq!(fill_prices(&r), vec![p("14")]);
|
||||
}
|
||||
#[test]
|
||||
fn future_ohlcv_does_not_change_open_fill() {
|
||||
let (input, config) = fixture();
|
||||
let mut changed = input.clone();
|
||||
changed.bars[1].high = pos("999");
|
||||
changed.bars[1].low = pos("1");
|
||||
changed.bars[1].close = pos("888");
|
||||
changed.bars[1].volume = nn("0");
|
||||
let mut traces = vec![];
|
||||
for data in [input, changed] {
|
||||
let mut r = Replay::new(data, config.clone()).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
target(&mut r, &b, "2");
|
||||
let _ = next(&mut r).unwrap();
|
||||
traces.push((fill_prices(&r), r.financial().ledger().cash()));
|
||||
}
|
||||
assert_eq!(traces[0], traces[1]);
|
||||
assert_eq!(traces[0].0, vec![p("12")]);
|
||||
}
|
||||
#[test]
|
||||
fn future_suffix_mutation() {
|
||||
let (input, config) = fixture();
|
||||
let mut changed = input.clone();
|
||||
changed.bars[2].open = pos("999");
|
||||
changed.bars[2].high = pos("999");
|
||||
let mut prefix = vec![];
|
||||
for data in [input, changed] {
|
||||
let mut r = Replay::new(data, config.clone()).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
target(&mut r, &b, "2");
|
||||
let b = next(&mut r).unwrap();
|
||||
prefix.push((
|
||||
b,
|
||||
r.observations().cloned().collect::<Vec<_>>(),
|
||||
r.financial().checkpoint(),
|
||||
));
|
||||
}
|
||||
assert_eq!(prefix[0], prefix[1]);
|
||||
}
|
||||
#[test]
|
||||
fn daily_close_target_survives_to_open() {
|
||||
let (mut input, config) = fixture();
|
||||
input.bounds.trade_start = t(0);
|
||||
input.bounds.trade_end = t(40);
|
||||
input.series[0].sessions = vec![
|
||||
venue("day1", 0, 10),
|
||||
venue("day2", 20, 30),
|
||||
venue("day3", 35, 40),
|
||||
];
|
||||
input.bars = vec![
|
||||
bar("X-bars", "X", 0, 10, 10, 0, "10", "11", "100"),
|
||||
bar("X-bars", "X", 20, 30, 30, 1, "12", "13", "100"),
|
||||
bar("X-bars", "X", 35, 40, 40, 2, "14", "15", "100"),
|
||||
];
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(10));
|
||||
target(&mut r, &b, "2");
|
||||
complete(&mut r);
|
||||
assert_eq!(fill_prices(&r), vec![p("12")]);
|
||||
let fill = r
|
||||
.financial()
|
||||
.receipts()
|
||||
.iter()
|
||||
.find(|r| {
|
||||
r.outcome.effects.iter().any(|e| {
|
||||
matches!(
|
||||
e,
|
||||
MatchingEffect::Risk {
|
||||
command: super::risk::RiskCommand {
|
||||
body: super::risk::RiskCommandBody::Fill { .. },
|
||||
..
|
||||
},
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
let MatchingInput::Engine(c) = &fill.input else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(c.key.at, t(20));
|
||||
}
|
||||
#[test]
|
||||
fn feature_timeframe_does_not_duplicate_liquidity() {
|
||||
let (input, config) = fixture();
|
||||
let mut extra = input.clone();
|
||||
extra.series.push(series("feature", "X"));
|
||||
extra.bars.extend([
|
||||
bar("feature", "X", 0, 5, 5, 0, "10", "99", "9999"),
|
||||
bar("feature", "X", 5, 15, 15, 1, "99", "999", "9999"),
|
||||
]);
|
||||
let mut traces = vec![];
|
||||
for data in [input, extra] {
|
||||
let mut r = Replay::new(data, config.clone()).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
target(&mut r, &b, "150");
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(20));
|
||||
no_change(&mut r, &b);
|
||||
complete(&mut r);
|
||||
traces.push((fill_prices(&r), r.financial().ledger().economic_snapshot()));
|
||||
}
|
||||
assert_eq!(traces[0], traces[1]);
|
||||
assert_eq!(traces[0].0.len(), 2);
|
||||
}
|
||||
#[test]
|
||||
fn equal_timestamp_symbol_permutation() {
|
||||
let (mut input, mut config) = fixture();
|
||||
input.series.push(series("Y-bars", "Y"));
|
||||
input
|
||||
.bars
|
||||
.extend(input.bars.clone().into_iter().map(|mut b| {
|
||||
b.series_id = id("Y-bars");
|
||||
b.instrument_id = id("Y");
|
||||
b
|
||||
}));
|
||||
config.matching.series.push(ExecutionSeries {
|
||||
instrument_id: id("Y"),
|
||||
series_id: id("Y-bars"),
|
||||
mode: ExecutionMode::Open,
|
||||
});
|
||||
config.matching.owners.push(OwnerMode {
|
||||
owner_id: id("B"),
|
||||
mode: StrategyMode::Target,
|
||||
});
|
||||
config.matching.risk.ledger.owner_ids.push(id("B"));
|
||||
config.cadence.push(DecisionCadence {
|
||||
owner_id: id("B"),
|
||||
series_ids: vec![id("Y-bars")],
|
||||
});
|
||||
config.risk_boundaries.push(RiskSessionIdentity {
|
||||
calendar_id: id("account"),
|
||||
calendar_revision: id("1"),
|
||||
session_id: id("risk2"),
|
||||
starts_at: t(10),
|
||||
});
|
||||
let mut changed = input.clone();
|
||||
changed.bars.reverse();
|
||||
changed.series.reverse();
|
||||
let mut reversed = config.clone();
|
||||
reversed.cadence.reverse();
|
||||
reversed.matching.series.reverse();
|
||||
reversed.matching.owners.reverse();
|
||||
reversed.matching.risk.ledger.owner_ids.reverse();
|
||||
let mut traces = vec![];
|
||||
for (data, cfg) in [(input, config), (changed, reversed)] {
|
||||
let mut r = Replay::new(data, cfg).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.owner_ids, vec![id("A"), id("B")]);
|
||||
assert_eq!(b.observation_count, 2);
|
||||
assert_eq!(b.revision, r.financial().admission_revision());
|
||||
assert_ne!(
|
||||
b.revision,
|
||||
r.financial().ledger().economic_snapshot().revision
|
||||
);
|
||||
target(&mut r, &b, "2");
|
||||
complete(&mut r);
|
||||
traces.push(r.checkpoint());
|
||||
}
|
||||
assert_eq!(traces[0], traces[1]);
|
||||
}
|
||||
#[test]
|
||||
fn warmup_cannot_trade() {
|
||||
let (mut input, config) = fixture();
|
||||
input.bounds.trade_start = t(20);
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
assert!(matches!(
|
||||
r.submit(DecisionSubmission {
|
||||
barrier_id: id("invented"),
|
||||
decisions: vec![]
|
||||
}),
|
||||
Err(ReplayError::InvalidSubmission)
|
||||
));
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(20));
|
||||
assert_eq!(b.observation_count, 2);
|
||||
assert!(fill_prices(&r).is_empty());
|
||||
assert!(!r.financial().receipts().iter().any(|r| matches!(
|
||||
&r.input,
|
||||
MatchingInput::Engine(MatchingCommand {
|
||||
body: MatchingCommandBody::Execute { .. },
|
||||
..
|
||||
})
|
||||
)));
|
||||
target(&mut r, &b, "2");
|
||||
complete(&mut r);
|
||||
assert_eq!(fill_prices(&r), vec![p("14")]);
|
||||
}
|
||||
#[test]
|
||||
fn stale_mark_timestamp_preserved() {
|
||||
let (mut input, mut config) = fixture();
|
||||
input.bars[0].available_at = t(15);
|
||||
config.matching.risk.max_mark_age_ms = 2.try_into().unwrap();
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(15));
|
||||
assert_eq!(
|
||||
r.financial().ledger().mark(&id("X")).unwrap().event_time,
|
||||
t(10)
|
||||
);
|
||||
assert!(
|
||||
matches!(b.inputs[0].availability,InputAvailability::Stale {event_time,available_at} if event_time==t(10)&&available_at==t(15))
|
||||
);
|
||||
target(&mut r, &b, "2");
|
||||
complete(&mut r);
|
||||
assert!(fill_prices(&r).is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn delayed_older_observation_preserves_mark_and_capacity() {
|
||||
let (mut input, config) = fixture();
|
||||
input.bounds.trade_end = t(40);
|
||||
input.bars[0].available_at = t(25);
|
||||
input.bars[0].volume = nn("999");
|
||||
input.bars[1].volume = nn("2");
|
||||
input
|
||||
.bars
|
||||
.push(bar("X-bars", "X", 30, 40, 40, 15, "16", "17", "100"));
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(20));
|
||||
target(&mut r, &b, "10");
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(25));
|
||||
assert_eq!(
|
||||
r.financial().ledger().mark(&id("X")).unwrap().price,
|
||||
pos("14")
|
||||
);
|
||||
assert_eq!(r.latest_observation(&id("X-bars")).unwrap().volume, nn("2"));
|
||||
no_change(&mut r, &b);
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(
|
||||
r.financial().ledger().owner_quantity(&id("A"), &id("X")),
|
||||
p("2")
|
||||
);
|
||||
no_change(&mut r, &b);
|
||||
complete(&mut r);
|
||||
assert_eq!(fill_prices(&r), vec![p("14"), p("16")]);
|
||||
}
|
||||
#[test]
|
||||
fn delayed_close_at_prior_open_timestamp_cannot_regress_mark() {
|
||||
let (mut input, config) = fixture();
|
||||
input.bars[1].available_at = t(25);
|
||||
input.bars[2].open = pos("30");
|
||||
input.bars[2].high = pos("30");
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
no_change(&mut r, &b);
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(25));
|
||||
let mark = r.financial().ledger().mark(&id("X")).unwrap();
|
||||
assert_eq!(mark.event_time, t(20));
|
||||
assert_eq!(mark.price, pos("30"));
|
||||
}
|
||||
#[test]
|
||||
fn mid_session_start_retains_true_session_open() {
|
||||
let (mut input, config) = fixture();
|
||||
input.bounds.warmup_start = t(5);
|
||||
input.bars[0].interval_start = t(5);
|
||||
let mut r = Replay::new(input.clone(), config.clone()).unwrap();
|
||||
let _ = next(&mut r).unwrap();
|
||||
let MatchingInput::Engine(c) = &r.financial().receipts()[0].input else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(c.key.at, t(0));
|
||||
let mut bad = config;
|
||||
bad.matching.risk.ledger.risk_session.starts_at = t(5);
|
||||
assert!(matches!(
|
||||
Replay::new(input, bad),
|
||||
Err(ReplayError::InvalidInput(
|
||||
"initial account clock follows true preceding venue open"
|
||||
))
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn terminal_observations_mark_only_and_later_rows_unavailable() {
|
||||
let (mut input, config) = fixture();
|
||||
input.series.push(series("feature", "X"));
|
||||
input
|
||||
.bars
|
||||
.push(bar("feature", "X", 0, 30, 31, 0, "99", "999", "10"));
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
target(&mut r, &b, "2");
|
||||
complete(&mut r);
|
||||
assert_eq!(r.observations().count(), 3);
|
||||
assert_eq!(
|
||||
r.financial().ledger().mark(&id("X")).unwrap().price,
|
||||
pos("15")
|
||||
);
|
||||
assert_eq!(r.checkpoint().submissions.len(), 2);
|
||||
assert!(r.latest_observation(&id("feature")).is_none());
|
||||
}
|
||||
#[test]
|
||||
fn equal_time_feature_series_sequence_ties_stable_and_missing_explicit() {
|
||||
let (mut input, config) = fixture();
|
||||
input.series.extend([
|
||||
series("feature-z", "X"),
|
||||
series("feature-a", "X"),
|
||||
series("missing", "X"),
|
||||
]);
|
||||
input.bars.extend([
|
||||
bar("feature-z", "X", 0, 10, 10, 7, "10", "99", "1"),
|
||||
bar("feature-a", "X", 0, 10, 10, 7, "10", "88", "1"),
|
||||
bar("missing", "X", 0, 20, 20, 7, "10", "88", "1"),
|
||||
]);
|
||||
let mut changed = input.clone();
|
||||
changed.bars.reverse();
|
||||
let mut results = vec![];
|
||||
for data in [input, changed] {
|
||||
let mut r = Replay::new(data, config.clone()).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
assert!(b
|
||||
.inputs
|
||||
.iter()
|
||||
.any(|i| i.series_id == id("missing") && i.availability == InputAvailability::Missing));
|
||||
results.push((
|
||||
b,
|
||||
r.observations()
|
||||
.map(|b| b.series_id.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
r.checkpoint(),
|
||||
));
|
||||
}
|
||||
assert_eq!(results[0], results[1]);
|
||||
assert_eq!(
|
||||
results[0].1,
|
||||
vec![id("X-bars"), id("feature-a"), id("feature-z")]
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn restore_before_and_after_every_decision_and_at_complete() {
|
||||
let (input, config) = fixture();
|
||||
let mut r = Replay::new(input.clone(), config.clone()).unwrap();
|
||||
loop {
|
||||
let step = r.advance(1).unwrap();
|
||||
let checkpoint = r.checkpoint();
|
||||
r = Replay::restore(input.clone(), config.clone(), &checkpoint).unwrap();
|
||||
assert_eq!(checkpoint, r.checkpoint());
|
||||
match step {
|
||||
ReplayStep::Decision(b) => {
|
||||
target(&mut r, &b, "2");
|
||||
let cp = r.checkpoint();
|
||||
r = Replay::restore(input.clone(), config.clone(), &cp).unwrap();
|
||||
}
|
||||
ReplayStep::Complete => break,
|
||||
ReplayStep::Progress { .. } => {}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
let mut uninterrupted = Replay::new(input, config).unwrap();
|
||||
while let Some(b) = next(&mut uninterrupted) {
|
||||
target(&mut uninterrupted, &b, "2");
|
||||
}
|
||||
assert_eq!(r.checkpoint(), uninterrupted.checkpoint());
|
||||
}
|
||||
#[test]
|
||||
fn altered_input_config_and_checkpoint_rejected() {
|
||||
let (input, config) = fixture();
|
||||
let mut r = Replay::new(input.clone(), config.clone()).unwrap();
|
||||
let _ = next(&mut r);
|
||||
let cp = r.checkpoint();
|
||||
let mut changed = input.clone();
|
||||
changed.bars[2].volume = nn("101");
|
||||
assert!(matches!(
|
||||
Replay::restore(changed, config.clone(), &cp),
|
||||
Err(ReplayError::InvalidCheckpoint)
|
||||
));
|
||||
let mut changed = config.clone();
|
||||
changed.matching.latency_ms = 1.try_into().unwrap();
|
||||
assert!(matches!(
|
||||
Replay::restore(input.clone(), changed, &cp),
|
||||
Err(ReplayError::InvalidCheckpoint)
|
||||
));
|
||||
let mut bad = cp.clone();
|
||||
bad.pending.as_mut().unwrap().revision = 999.try_into().unwrap();
|
||||
assert!(matches!(
|
||||
Replay::restore(input.clone(), config.clone(), &bad),
|
||||
Err(ReplayError::InvalidCheckpoint)
|
||||
));
|
||||
let mut bad = cp;
|
||||
bad.observation_count += 1;
|
||||
assert!(matches!(
|
||||
Replay::restore(input, config, &bad),
|
||||
Err(ReplayError::InvalidCheckpoint)
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn bounded_advance_and_atomic_due_owner_validation() {
|
||||
let (input, config) = fixture();
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
assert_eq!(r.advance(0), Err(ReplayError::InvalidBudget));
|
||||
assert!(matches!(
|
||||
r.advance(1).unwrap(),
|
||||
ReplayStep::Progress { processed: 1 }
|
||||
));
|
||||
assert_eq!(r.observations().count(), 0);
|
||||
let b = next(&mut r).unwrap();
|
||||
let cp = r.checkpoint();
|
||||
assert_eq!(r.advance(1000).unwrap(), ReplayStep::Decision(b.clone()));
|
||||
assert!(matches!(
|
||||
r.submit(DecisionSubmission {
|
||||
barrier_id: b.barrier_id.clone(),
|
||||
decisions: vec![]
|
||||
}),
|
||||
Err(ReplayError::InvalidSubmission)
|
||||
));
|
||||
assert_eq!(cp, r.checkpoint());
|
||||
target(&mut r, &b, "2");
|
||||
assert!(matches!(
|
||||
r.submit(DecisionSubmission {
|
||||
barrier_id: b.barrier_id,
|
||||
decisions: vec![]
|
||||
}),
|
||||
Err(ReplayError::InvalidSubmission)
|
||||
));
|
||||
}
|
||||
#[test]
|
||||
fn explicit_input_contract_rejections() {
|
||||
let (input, config) = fixture();
|
||||
let mut bad = input.clone();
|
||||
bad.bars.clear();
|
||||
assert!(Replay::new(bad, config.clone()).is_err());
|
||||
let mut bad = input.clone();
|
||||
bad.eligibility = DatasetEligibility::Ineligible;
|
||||
assert!(Replay::new(bad, config.clone()).is_err());
|
||||
let mut bad = input.clone();
|
||||
bad.eligibility = DatasetEligibility::Exploratory;
|
||||
assert!(Replay::new(bad.clone(), config.clone()).is_err());
|
||||
let mut allowed = config.clone();
|
||||
allowed.allow_exploratory = true;
|
||||
assert!(Replay::new(bad, allowed).is_ok());
|
||||
let mut bad = input.clone();
|
||||
bad.series[0].adjustment = PriceAdjustment::ProviderAdjusted;
|
||||
assert!(Replay::new(bad, config.clone()).is_err());
|
||||
let mut bad = config.clone();
|
||||
bad.matching.series[0].mode = ExecutionMode::Quote;
|
||||
assert!(Replay::new(input.clone(), bad).is_err());
|
||||
let mut bad = input.clone();
|
||||
bad.series[0].sessions = vec![venue("a", 0, 10), venue("b", 10, 30)];
|
||||
assert!(matches!(
|
||||
Replay::new(bad, config.clone()),
|
||||
Err(ReplayError::InvalidInput(
|
||||
"overlapping or abutting retained sessions are unsupported"
|
||||
))
|
||||
));
|
||||
let mut bad = input.clone();
|
||||
bad.bars[1].source_sequence = bad.bars[0].source_sequence;
|
||||
assert!(Replay::new(bad, config.clone()).is_err());
|
||||
let mut bad = input.clone();
|
||||
bad.bars[1].available_at = t(19);
|
||||
assert!(Replay::new(bad, config.clone()).is_err());
|
||||
let mut bad = config.clone();
|
||||
bad.participation_rate = nn("1.1");
|
||||
assert!(Replay::new(input, bad).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn financial_failure_is_terminal_with_reproducible_diagnostic_prefix() {
|
||||
let (mut input, config) = fixture();
|
||||
let maximum = super::scalar::MAX_POSTING;
|
||||
input.bars[0].high = pos(maximum);
|
||||
input.bars[0].close = pos(maximum);
|
||||
let mut r = Replay::new(input.clone(), config.clone()).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
let outcome = target(&mut r, &b, "2");
|
||||
assert!(matches!(outcome.status, AttemptStatus::Failed { .. }));
|
||||
assert!(matches!(r.advance(100).unwrap(), ReplayStep::Failed { .. }));
|
||||
let checkpoint = r.checkpoint();
|
||||
let restored = Replay::restore(input, config, &checkpoint).unwrap();
|
||||
assert_eq!(restored.checkpoint(), checkpoint);
|
||||
assert!(matches!(
|
||||
r.submit(DecisionSubmission {
|
||||
barrier_id: b.barrier_id,
|
||||
decisions: vec![]
|
||||
}),
|
||||
Err(ReplayError::Terminal)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn irrelevant_old_sessions_do_not_backdate_initialization() {
|
||||
let (mut input, config) = fixture();
|
||||
input.series[0].sessions.insert(0, venue("old", -20, -10));
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
complete(&mut r);
|
||||
let MatchingInput::Engine(first) = &r.financial().receipts()[0].input else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(first.key.at, t(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_execution_failure_preserves_committed_prefix_and_restores() {
|
||||
let (mut input, mut config) = fixture();
|
||||
config.matching.slippage_rate = nn("0.9");
|
||||
input.bars[1].open = pos(super::scalar::MAX_POSTING);
|
||||
input.bars[1].high = pos(super::scalar::MAX_POSTING);
|
||||
let mut r = Replay::new(input.clone(), config.clone()).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
target(&mut r, &b, "2");
|
||||
assert!(matches!(r.advance(100).unwrap(), ReplayStep::Failed { .. }));
|
||||
let receipt = r.financial().receipts().last().unwrap();
|
||||
assert!(matches!(
|
||||
receipt.outcome.status,
|
||||
AttemptStatus::Failed { .. }
|
||||
));
|
||||
assert!(!receipt.outcome.effects.is_empty());
|
||||
assert!(fill_prices(&r).is_empty());
|
||||
let checkpoint = r.checkpoint();
|
||||
let mut restored = Replay::restore(input, config, &checkpoint).unwrap();
|
||||
assert_eq!(restored.checkpoint(), checkpoint);
|
||||
assert!(matches!(
|
||||
restored.advance(100).unwrap(),
|
||||
ReplayStep::Failed { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_time_risk_boundary_venue_opens_and_marks_have_monotone_keys() {
|
||||
let (mut input, mut config) = fixture();
|
||||
input.series.push(ReplaySeries {
|
||||
sessions: vec![venue("Y-day", 10, 30)],
|
||||
..series("Y-bars", "Y")
|
||||
});
|
||||
input
|
||||
.bars
|
||||
.push(bar("Y-bars", "Y", 10, 20, 20, 7, "20", "21", "100"));
|
||||
config.matching.series.push(ExecutionSeries {
|
||||
instrument_id: id("Y"),
|
||||
series_id: id("Y-bars"),
|
||||
mode: ExecutionMode::Open,
|
||||
});
|
||||
config.risk_boundaries.push(RiskSessionIdentity {
|
||||
calendar_id: id("account"),
|
||||
calendar_revision: id("1"),
|
||||
session_id: id("risk2"),
|
||||
starts_at: t(10),
|
||||
});
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(10));
|
||||
assert_eq!(
|
||||
r.financial().risk().state().risk_session.session_id,
|
||||
id("risk2")
|
||||
);
|
||||
let at10 = r
|
||||
.financial()
|
||||
.receipts()
|
||||
.iter()
|
||||
.filter_map(|r| match &r.input {
|
||||
MatchingInput::Engine(c) if c.key.at == t(10) => Some(c),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert!(at10.windows(2).all(|w| w[0].key < w[1].key));
|
||||
assert!(at10.iter().any(
|
||||
|c| matches!(c.body, MatchingCommandBody::OpenSession { .. })
|
||||
&& c.key.instrument_id == id("Y")
|
||||
));
|
||||
no_change(&mut r, &b);
|
||||
complete(&mut r);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() {
|
||||
let (mut input, mut config) = fixture();
|
||||
for b in &mut input.bars {
|
||||
b.open = pos("100");
|
||||
b.high = pos("100");
|
||||
b.low = pos("100");
|
||||
b.close = pos("100");
|
||||
}
|
||||
input.series.push(series("Y-bars", "Y"));
|
||||
input
|
||||
.bars
|
||||
.extend(input.bars.clone().into_iter().map(|mut b| {
|
||||
b.series_id = id("Y-bars");
|
||||
b.instrument_id = id("Y");
|
||||
b
|
||||
}));
|
||||
input.bars[1].close = pos("50");
|
||||
input.bars[1].low = pos("50");
|
||||
input.bars[4].close = pos("150");
|
||||
input.bars[4].high = pos("150");
|
||||
config.matching.series.push(ExecutionSeries {
|
||||
instrument_id: id("Y"),
|
||||
series_id: id("Y-bars"),
|
||||
mode: ExecutionMode::Open,
|
||||
});
|
||||
config.matching.risk.fee_rate = nn("0");
|
||||
config.matching.risk.max_daily_loss = pos("10");
|
||||
config.matching.risk.max_drawdown_amount = pos("10");
|
||||
let mut permuted = input.clone();
|
||||
permuted.bars.reverse();
|
||||
let mut checkpoints = vec![];
|
||||
for data in [input, permuted] {
|
||||
let mut r = Replay::new(data, config.clone()).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
r.submit(DecisionSubmission {
|
||||
barrier_id: b.barrier_id.clone(),
|
||||
decisions: vec![StrategyDecision {
|
||||
version: Version,
|
||||
session_id: id("run"),
|
||||
barrier_id: b.barrier_id,
|
||||
revision: b.revision,
|
||||
decision: DecisionIdentity {
|
||||
owner_id: id("A"),
|
||||
decision_id: id("pair"),
|
||||
sequence: 1.try_into().unwrap(),
|
||||
},
|
||||
intent: StrategyIntent::Target {
|
||||
targets: vec![
|
||||
Target {
|
||||
instrument_id: id("X"),
|
||||
quantity: nn("1"),
|
||||
},
|
||||
Target {
|
||||
instrument_id: id("Y"),
|
||||
quantity: nn("1"),
|
||||
},
|
||||
],
|
||||
},
|
||||
}],
|
||||
})
|
||||
.unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(20));
|
||||
assert_eq!(r.financial().ledger().equity().unwrap(), p("10000"));
|
||||
assert!(r.financial().risk().state().daily_halted);
|
||||
assert!(r.financial().risk().state().drawdown_halted);
|
||||
checkpoints.push(r.checkpoint());
|
||||
}
|
||||
assert_eq!(checkpoints[0], checkpoints[1]);
|
||||
assert!(MODEL_LIMITATIONS
|
||||
.iter()
|
||||
.any(|s| s.contains("intermediate equity")));
|
||||
}
|
||||
#[test]
|
||||
fn no_known_volume_and_zero_capacity_cannot_fill() {
|
||||
let (mut input, config) = fixture();
|
||||
input.bars[0].volume = nn("0");
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
target(&mut r, &b, "2");
|
||||
let b = next(&mut r).unwrap();
|
||||
assert!(fill_prices(&r).is_empty());
|
||||
no_change(&mut r, &b);
|
||||
complete(&mut r);
|
||||
assert_eq!(fill_prices(&r), vec![p("14")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_completed_volume_does_not_fill_a_live_order() {
|
||||
let (mut input, mut config) = fixture();
|
||||
input.bounds.trade_start = t(0);
|
||||
input.bars[0].available_at = t(25);
|
||||
input.bars[1].available_at = t(25);
|
||||
input.series.push(series("feature", "X"));
|
||||
input
|
||||
.bars
|
||||
.push(bar("feature", "X", 0, 11, 11, 0, "10", "10", "9999"));
|
||||
config.cadence[0].series_ids = vec![id("feature")];
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(11));
|
||||
assert!(r.latest_observation(&id("X-bars")).is_none());
|
||||
target(&mut r, &b, "2");
|
||||
assert!(r
|
||||
.financial()
|
||||
.orders()
|
||||
.any(|o| o.status == OrderStatus::Open));
|
||||
complete(&mut r);
|
||||
assert!(fill_prices(&r).is_empty());
|
||||
assert_eq!(r.financial().ledger().cash(), p("10000"));
|
||||
assert!(r
|
||||
.financial()
|
||||
.orders()
|
||||
.all(|o| o.status == OrderStatus::Cancelled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual release component measurement; no timing CI assertion"]
|
||||
fn replay_scaling_measurement() {
|
||||
for instruments in [1, 2] {
|
||||
for count in [1000, 10000, 100000] {
|
||||
let (mut input, mut config) = fixture();
|
||||
let per_instrument = count / instruments;
|
||||
if instruments == 2 {
|
||||
input.series.push(series("Y-bars", "Y"));
|
||||
config.matching.series.push(ExecutionSeries {
|
||||
instrument_id: id("Y"),
|
||||
series_id: id("Y-bars"),
|
||||
mode: ExecutionMode::Open,
|
||||
});
|
||||
}
|
||||
input.bounds.trade_start = t(10);
|
||||
input.bounds.trade_end = t((per_instrument * 10) as i64);
|
||||
input.bars = (0..count)
|
||||
.map(|i| {
|
||||
let (series, symbol) = if i < per_instrument {
|
||||
("X-bars", "X")
|
||||
} else {
|
||||
("Y-bars", "Y")
|
||||
};
|
||||
let index = i % per_instrument;
|
||||
bar(
|
||||
series,
|
||||
symbol,
|
||||
(index * 10) as i64,
|
||||
((index + 1) * 10) as i64,
|
||||
((index + 1) * 10) as i64,
|
||||
index as u64,
|
||||
"10",
|
||||
"10",
|
||||
"100",
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
// One barrier/buy, then mark-only traversal measures the cursor rather
|
||||
// than pretending 100k orders have no F05 journal/memory cost.
|
||||
input.series.push(series("cadence", "X"));
|
||||
input
|
||||
.bars
|
||||
.push(bar("cadence", "X", 0, 10, 10, 0, "10", "10", "100"));
|
||||
config.cadence[0].series_ids = vec![id("cadence")];
|
||||
let mut expected = None;
|
||||
for repeat in 0..3 {
|
||||
let data = input.clone();
|
||||
let cfg = config.clone();
|
||||
let started = Instant::now();
|
||||
let mut r = Replay::new(data, cfg).unwrap();
|
||||
let load = started.elapsed();
|
||||
let started = Instant::now();
|
||||
while let Some(b) = next(&mut r) {
|
||||
target(&mut r, &b, "1");
|
||||
}
|
||||
let traverse = started.elapsed();
|
||||
assert_eq!(fill_prices(&r), vec![p("10")]);
|
||||
assert_eq!(r.financial().ledger().cash(), p("9989.9"));
|
||||
assert_eq!(r.financial().ledger().equity().unwrap(), p("9999.9"));
|
||||
let started = Instant::now();
|
||||
let checkpoint = r.checkpoint();
|
||||
let checkpoint_time = started.elapsed();
|
||||
let bytes = serde_json::to_vec(&checkpoint).unwrap();
|
||||
if let Some(expected) = &expected {
|
||||
assert_eq!(&bytes, expected);
|
||||
} else {
|
||||
expected = Some(bytes.clone());
|
||||
}
|
||||
drop(r);
|
||||
let data = input.clone();
|
||||
let cfg = config.clone();
|
||||
let started = Instant::now();
|
||||
let restored = Replay::restore(data, cfg, &checkpoint).unwrap();
|
||||
let restore = started.elapsed();
|
||||
assert_eq!(restored.checkpoint(), checkpoint);
|
||||
println!("replay instruments={instruments} execution_bars={count} total_bars={} repeat={repeat} load_us={} replay_us={} checkpoint_us={} restore_us={} checkpoint_bytes={} fills=1",count+1,load.as_micros(),traverse.as_micros(),checkpoint_time.as_micros(),restore.as_micros(),bytes.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue