feat(research): add canonical session reporting and analytics
This commit is contained in:
parent
1e164450c3
commit
3838295eec
28 changed files with 2402 additions and 47 deletions
|
|
@ -5,6 +5,7 @@ use crate::financial::{
|
|||
contract::*,
|
||||
matching::OrderStatus,
|
||||
replay::*,
|
||||
reporting::ReportingFacts,
|
||||
result::{project, FinancialProjection},
|
||||
};
|
||||
use napi::{Error, Result};
|
||||
|
|
@ -60,6 +61,15 @@ struct ProjectionResult<'a> {
|
|||
projection: FinancialProjection<'a>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ReportResult<'a> {
|
||||
#[serde(flatten)]
|
||||
financial: ProjectionResult<'a>,
|
||||
reporting_version: Version,
|
||||
reporting: &'a ReportingFacts,
|
||||
}
|
||||
|
||||
fn error(error: impl std::fmt::Display) -> Error {
|
||||
Error::from_reason(error.to_string())
|
||||
}
|
||||
|
|
@ -204,6 +214,31 @@ impl ReplayHost {
|
|||
})
|
||||
.map_err(error)
|
||||
}
|
||||
|
||||
pub fn report(&self, input: String) -> Result<String> {
|
||||
let identity: Identity = parse(&input)?;
|
||||
self.check(&identity)?;
|
||||
let replay = self.replay.as_ref().unwrap();
|
||||
let reporting = replay.reporting().map_err(error)?;
|
||||
serde_json::to_string(&ReportResult {
|
||||
financial: ProjectionResult {
|
||||
format: "report",
|
||||
projection_version: Version,
|
||||
financial_version: Version,
|
||||
identity: &self.identity,
|
||||
status: "complete",
|
||||
manifest: &self.manifest,
|
||||
policy: &self.config,
|
||||
view: view(replay)?,
|
||||
limitations: replay.limitations(),
|
||||
model_limitations: replay.model_limitations(),
|
||||
projection: project(replay.financial().ledger()).map_err(error)?,
|
||||
},
|
||||
reporting_version: Version,
|
||||
reporting,
|
||||
})
|
||||
.map_err(error)
|
||||
}
|
||||
}
|
||||
|
||||
// NAPI's impl macro requires literal method annotations. Keep this tiny
|
||||
|
|
@ -236,6 +271,10 @@ impl FinancialReplaySession {
|
|||
self.0.project(input)
|
||||
}
|
||||
#[napi]
|
||||
pub fn report(&self, input: String) -> Result<String> {
|
||||
self.0.report(input)
|
||||
}
|
||||
#[napi]
|
||||
pub fn dispose(&mut self) {
|
||||
self.0.dispose();
|
||||
}
|
||||
|
|
@ -333,6 +372,13 @@ mod tests {
|
|||
final_result
|
||||
);
|
||||
let projected: Value = serde_json::from_str(&compact).unwrap();
|
||||
let report = native.report(identity.to_string()).unwrap();
|
||||
assert_eq!(native.report(identity.to_string()).unwrap(), report);
|
||||
assert_eq!(native.project(identity.to_string()).unwrap(), compact);
|
||||
assert_eq!(native.replay.as_ref().unwrap().checkpoint(), before);
|
||||
let reported: Value = serde_json::from_str(&report).unwrap();
|
||||
assert_eq!(reported["projection"], projected["projection"]);
|
||||
assert_eq!(reported["reporting"]["occupiedMs"], "120000");
|
||||
assert_eq!(projected["view"], final_result["view"]);
|
||||
assert!(projected.get("receipts").is_none());
|
||||
let load: Load = parse(fixture).unwrap();
|
||||
|
|
@ -341,8 +387,13 @@ mod tests {
|
|||
projected["projection"],
|
||||
serde_json::to_value(project(restored.financial().ledger()).unwrap()).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
reported["reporting"],
|
||||
serde_json::to_value(restored.reporting().unwrap()).unwrap()
|
||||
);
|
||||
native.dispose();
|
||||
assert!(native.finalize(identity.to_string()).is_err());
|
||||
assert!(native.project(identity.to_string()).is_err());
|
||||
assert!(native.report(identity.to_string()).is_err());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ pub mod contract;
|
|||
pub mod ledger;
|
||||
pub mod matching;
|
||||
pub mod replay;
|
||||
pub mod reporting;
|
||||
pub mod result;
|
||||
pub mod risk;
|
||||
pub mod scalar;
|
||||
|
|
@ -28,6 +29,9 @@ mod replay_tests;
|
|||
#[cfg(test)]
|
||||
mod result_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod reporting_tests;
|
||||
|
||||
// Exercise the pure host adapter without linking every legacy NAPI export.
|
||||
#[cfg(test)]
|
||||
#[path = "../api/replay.rs"]
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
use super::{
|
||||
contract::*,
|
||||
matching::*,
|
||||
reporting::{Reporting, ReportingFacts},
|
||||
scalar::{Posting, ScalarError},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
|
@ -214,6 +215,7 @@ pub struct Replay {
|
|||
status: ReplayStatus,
|
||||
submissions: Vec<DecisionSubmission>,
|
||||
matching: MatchingAccount,
|
||||
reporting: Reporting,
|
||||
}
|
||||
|
||||
impl Replay {
|
||||
|
|
@ -230,6 +232,12 @@ impl Replay {
|
|||
.iter()
|
||||
.map(|s| s.series_id.clone())
|
||||
.collect();
|
||||
let reporting = Reporting::new(
|
||||
&config.matching.risk.ledger.risk_session,
|
||||
&config.risk_boundaries,
|
||||
&input.bounds,
|
||||
matching.ledger().cash(),
|
||||
);
|
||||
Ok(Self {
|
||||
input,
|
||||
config,
|
||||
|
|
@ -243,6 +251,7 @@ impl Replay {
|
|||
status: ReplayStatus::Running,
|
||||
submissions: Vec::new(),
|
||||
matching,
|
||||
reporting,
|
||||
})
|
||||
}
|
||||
fn canonicalize(input: &mut PreparedReplay, config: &mut ReplayConfig) {
|
||||
|
|
@ -652,6 +661,12 @@ impl Replay {
|
|||
pub fn model_limitations(&self) -> &'static [&'static str] {
|
||||
MODEL_LIMITATIONS
|
||||
}
|
||||
pub fn reporting(&self) -> Result<&ReportingFacts, &str> {
|
||||
if self.status != ReplayStatus::Complete {
|
||||
return Err("only a complete replay can report successfully");
|
||||
}
|
||||
self.reporting.facts()
|
||||
}
|
||||
|
||||
fn command(
|
||||
&mut self,
|
||||
|
|
@ -659,11 +674,13 @@ impl Replay {
|
|||
key: EventKey,
|
||||
body: MatchingCommandBody,
|
||||
) -> Result<(), ReplayError> {
|
||||
let at = key.at;
|
||||
let out = self.matching.apply(&MatchingCommand {
|
||||
command_id: id(("replay", index)),
|
||||
key,
|
||||
body,
|
||||
})?;
|
||||
self.reporting.committed(at, &out, self.matching.ledger());
|
||||
if let AttemptStatus::Failed { diagnostic } = out.status {
|
||||
self.status = ReplayStatus::Failed { diagnostic };
|
||||
}
|
||||
|
|
@ -766,6 +783,7 @@ impl Replay {
|
|||
self.command(index, key, MatchingCommandBody::Finish)?;
|
||||
if self.status == ReplayStatus::Running {
|
||||
self.status = ReplayStatus::Complete;
|
||||
self.reporting.finish(self.matching.ledger());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -782,6 +800,8 @@ impl Replay {
|
|||
while self.status == ReplayStatus::Running && processed < budget {
|
||||
let index = self.next_event;
|
||||
let event = self.events[index].clone();
|
||||
let at = event.key.at;
|
||||
let observation = event.key.phase == EventPhase::Observation;
|
||||
self.next_event += 1;
|
||||
processed += 1;
|
||||
if let Err(error) = self.process(index, event) {
|
||||
|
|
@ -789,6 +809,15 @@ impl Replay {
|
|||
diagnostic: error.to_string(),
|
||||
};
|
||||
}
|
||||
if observation
|
||||
&& self.status == ReplayStatus::Running
|
||||
&& self.events.get(self.next_event).is_none_or(|next| {
|
||||
next.key.at != at || next.key.phase != EventPhase::Observation
|
||||
})
|
||||
{
|
||||
self.reporting
|
||||
.after_observations(at, self.matching.ledger());
|
||||
}
|
||||
if let Some(barrier) = &self.pending {
|
||||
return Ok(ReplayStep::Decision(barrier.clone()));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -570,6 +570,158 @@ fn restore_before_and_after_every_decision_and_at_complete() {
|
|||
target(&mut uninterrupted, &b, "2");
|
||||
}
|
||||
assert_eq!(r.checkpoint(), uninterrupted.checkpoint());
|
||||
assert_eq!(r.reporting().unwrap(), uninterrupted.reporting().unwrap());
|
||||
}
|
||||
|
||||
fn reporting_boundary(name: &str, at: i64) -> RiskSessionIdentity {
|
||||
RiskSessionIdentity {
|
||||
calendar_id: id("account"),
|
||||
calendar_revision: id("1"),
|
||||
session_id: id(name),
|
||||
starts_at: t(at),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_session_marks_follow_observations_without_changing_earlier_risk_reset() {
|
||||
let (mut input, mut config) = fixture();
|
||||
input.bounds.trade_start = t(0);
|
||||
config.risk_boundaries = vec![
|
||||
reporting_boundary("risk2", 20),
|
||||
reporting_boundary("risk3", 30),
|
||||
];
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
assert!(r.reporting().is_err());
|
||||
let b = next(&mut r).unwrap();
|
||||
target(&mut r, &b, "2");
|
||||
let b = next(&mut r).unwrap();
|
||||
assert_eq!(b.at, t(20));
|
||||
// Existing reset runs before the completed observation's13 mark.
|
||||
assert_eq!(
|
||||
Posting::from(r.financial().risk().state().daily_baseline),
|
||||
p("9999.76")
|
||||
);
|
||||
no_change(&mut r, &b);
|
||||
complete(&mut r);
|
||||
let facts = r.reporting().unwrap();
|
||||
assert_eq!(facts.initial_equity, p("10000"));
|
||||
assert_eq!(facts.sessions.len(), 2);
|
||||
assert_eq!(facts.sessions[0].session.session_id, id("risk1"));
|
||||
assert_eq!(facts.sessions[0].period_start, t(0));
|
||||
assert_eq!(facts.sessions[0].period_end, t(20));
|
||||
assert_eq!(facts.sessions[0].equity, p("10001.76"));
|
||||
assert_eq!(facts.sessions[1].equity, p("10005.76"));
|
||||
assert!(!facts
|
||||
.sessions
|
||||
.iter()
|
||||
.any(|s| s.partial_start || s.partial_end));
|
||||
assert_eq!(facts.occupied_ms, "20");
|
||||
assert_eq!(facts.elapsed_ms, "30");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reporting_clips_warmup_initial_and_final_periods_and_deduplicates_exact_end() {
|
||||
for exact_start in [false, true] {
|
||||
for exact_end in [false, true] {
|
||||
let (input, mut config) = fixture();
|
||||
config.risk_boundaries = vec![
|
||||
reporting_boundary("warmup", 5),
|
||||
reporting_boundary("risk2", 20),
|
||||
];
|
||||
if exact_start {
|
||||
config.risk_boundaries.push(reporting_boundary("start", 10));
|
||||
}
|
||||
if exact_end {
|
||||
config.risk_boundaries.push(reporting_boundary("end", 30));
|
||||
}
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
complete(&mut r);
|
||||
let facts = r.reporting().unwrap();
|
||||
assert_eq!(facts.sessions.len(), 2);
|
||||
assert_eq!(
|
||||
facts.sessions[0].session.session_id,
|
||||
id(if exact_start { "start" } else { "warmup" })
|
||||
);
|
||||
assert_eq!(facts.sessions[0].period_start, t(10));
|
||||
assert_eq!(facts.sessions[0].partial_start, !exact_start);
|
||||
assert!(!facts.sessions[0].partial_end);
|
||||
assert_eq!(facts.sessions[1].partial_end, !exact_end);
|
||||
assert_eq!(facts.sessions[1].period_end, t(30));
|
||||
assert!(facts.sessions.iter().all(|s| s.equity == p("10000")));
|
||||
assert_eq!(facts.occupied_ms, "0");
|
||||
assert!(facts.occupied_intervals.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reporting_boundary_without_decision_and_terminal_stale_mark_use_only_available_facts() {
|
||||
let (mut input, mut config) = fixture();
|
||||
config.risk_boundaries = vec![reporting_boundary("risk2", 15)];
|
||||
input.bars[2].available_at = t(31); // Final close15 is not available by end30.
|
||||
let mut r = Replay::new(input, config).unwrap();
|
||||
let b = next(&mut r).unwrap();
|
||||
target(&mut r, &b, "2");
|
||||
complete(&mut r);
|
||||
let facts = r.reporting().unwrap();
|
||||
assert_eq!(facts.sessions[0].period_end, t(15));
|
||||
assert_eq!(facts.sessions[0].equity, p("9999.76"));
|
||||
// Last available authoritative mark is the open14, not the future close15.
|
||||
assert_eq!(facts.sessions[1].equity, p("10003.76"));
|
||||
assert_eq!(
|
||||
facts.sessions[1].equity,
|
||||
r.financial().ledger().equity().unwrap()
|
||||
);
|
||||
assert_eq!(r.observations().count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reporting_restore_every_event_including_partial_observation_groups() {
|
||||
let (mut input, mut config) = fixture();
|
||||
input.series.push(series("Y-bars", "Y"));
|
||||
input
|
||||
.bars
|
||||
.extend(input.bars.clone().into_iter().map(|mut bar| {
|
||||
bar.series_id = id("Y-bars");
|
||||
bar.instrument_id = id("Y");
|
||||
bar
|
||||
}));
|
||||
config.matching.series.push(ExecutionSeries {
|
||||
instrument_id: id("Y"),
|
||||
series_id: id("Y-bars"),
|
||||
mode: ExecutionMode::Open,
|
||||
});
|
||||
config.risk_boundaries = vec![
|
||||
reporting_boundary("risk2", 20),
|
||||
reporting_boundary("risk3", 30),
|
||||
];
|
||||
let mut uninterrupted = Replay::new(input.clone(), config.clone()).unwrap();
|
||||
while let Some(b) = next(&mut uninterrupted) {
|
||||
target(&mut uninterrupted, &b, "2");
|
||||
}
|
||||
let mut resumed = Replay::new(input.clone(), config.clone()).unwrap();
|
||||
loop {
|
||||
let step = resumed.advance(1).unwrap();
|
||||
let cp = resumed.checkpoint();
|
||||
resumed = Replay::restore(input.clone(), config.clone(), &cp).unwrap();
|
||||
assert_eq!(resumed.checkpoint(), cp);
|
||||
match step {
|
||||
ReplayStep::Decision(b) => {
|
||||
target(&mut resumed, &b, "2");
|
||||
resumed =
|
||||
Replay::restore(input.clone(), config.clone(), &resumed.checkpoint()).unwrap();
|
||||
}
|
||||
ReplayStep::Complete => break,
|
||||
ReplayStep::Progress { .. } => {}
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
}
|
||||
assert_eq!(uninterrupted.checkpoint(), resumed.checkpoint());
|
||||
assert_eq!(
|
||||
uninterrupted.reporting().unwrap(),
|
||||
resumed.reporting().unwrap()
|
||||
);
|
||||
assert_eq!(resumed.reporting().unwrap().sessions.len(), 2);
|
||||
}
|
||||
#[test]
|
||||
fn altered_input_config_and_checkpoint_rejected() {
|
||||
|
|
@ -808,6 +960,9 @@ fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() {
|
|||
config.matching.risk.fee_rate = nn("0");
|
||||
config.matching.risk.max_daily_loss = pos("10");
|
||||
config.matching.risk.max_drawdown_amount = pos("10");
|
||||
// A reporting sample uses the final observation-group equity without
|
||||
// changing the existing sequential risk latch.
|
||||
config.risk_boundaries.push(reporting_boundary("risk2", 20));
|
||||
let mut permuted = input.clone();
|
||||
permuted.bars.reverse();
|
||||
let mut checkpoints = vec![];
|
||||
|
|
@ -847,6 +1002,11 @@ fn sequential_equal_time_marks_can_latch_risk_before_synchronized_barrier() {
|
|||
assert!(r.financial().risk().state().daily_halted);
|
||||
assert!(r.financial().risk().state().drawdown_halted);
|
||||
checkpoints.push(r.checkpoint());
|
||||
no_change(&mut r, &b);
|
||||
complete(&mut r);
|
||||
assert_eq!(r.reporting().unwrap().sessions[0].equity, p("10000"));
|
||||
assert!(r.financial().risk().state().daily_halted);
|
||||
assert!(r.financial().risk().state().drawdown_halted);
|
||||
}
|
||||
assert_eq!(checkpoints[0], checkpoints[1]);
|
||||
assert!(MODEL_LIMITATIONS
|
||||
|
|
|
|||
238
apps/stock/engine/src/financial/reporting.rs
Normal file
238
apps/stock/engine/src/financial/reporting.rs
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
//! Reporting-only facts sampled during the existing replay. This state cannot
|
||||
//! submit financial commands and is rebuilt by the normal checkpoint restore.
|
||||
use super::{
|
||||
contract::*,
|
||||
ledger::Ledger,
|
||||
matching::{MatchingEffect, MatchingOutcome},
|
||||
replay::ReplayBounds,
|
||||
scalar::Posting,
|
||||
};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SessionEquity {
|
||||
pub session: RiskSessionIdentity,
|
||||
pub period_start: EventTime,
|
||||
pub period_end: EventTime,
|
||||
pub partial_start: bool,
|
||||
pub partial_end: bool,
|
||||
pub equity: Posting,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OccupiedInterval {
|
||||
pub start: EventTime,
|
||||
pub end: EventTime,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReportingFacts {
|
||||
pub calendar_id: Id,
|
||||
pub calendar_revision: Id,
|
||||
pub trade_start: EventTime,
|
||||
pub trade_end: EventTime,
|
||||
pub initial_equity: Posting,
|
||||
pub sampling: &'static str,
|
||||
pub exposure_basis: &'static str,
|
||||
pub sessions: Vec<SessionEquity>,
|
||||
pub occupied_intervals: Vec<OccupiedInterval>,
|
||||
pub occupied_ms: String,
|
||||
pub elapsed_ms: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Reporting {
|
||||
facts: ReportingFacts,
|
||||
session: RiskSessionIdentity,
|
||||
period_start: EventTime,
|
||||
boundaries: Vec<RiskSessionIdentity>,
|
||||
next_boundary: usize,
|
||||
occupied_since: Option<EventTime>,
|
||||
failure: Option<String>,
|
||||
complete: bool,
|
||||
}
|
||||
|
||||
impl Reporting {
|
||||
pub fn new(
|
||||
initial: &RiskSessionIdentity,
|
||||
boundaries: &[RiskSessionIdentity],
|
||||
bounds: &ReplayBounds,
|
||||
initial_equity: Posting,
|
||||
) -> Self {
|
||||
// Replay has already validated/canonicalized this account calendar.
|
||||
let session = boundaries
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|b| b.starts_at.get() <= bounds.trade_start.get())
|
||||
.unwrap_or(initial)
|
||||
.clone();
|
||||
Self {
|
||||
facts: ReportingFacts {
|
||||
calendar_id: initial.calendar_id.clone(),
|
||||
calendar_revision: initial.calendar_revision.clone(),
|
||||
trade_start: bounds.trade_start,
|
||||
trade_end: bounds.trade_end,
|
||||
initial_equity,
|
||||
sampling: "account-boundary-after-observations-v1",
|
||||
exposure_basis: "elapsed-calendar-time",
|
||||
sessions: Vec::new(),
|
||||
occupied_intervals: Vec::new(),
|
||||
occupied_ms: "0".into(),
|
||||
// Both endpoints are safe i64 timestamps; their difference may
|
||||
// exceed JS's safe integer domain but cannot overflow i64.
|
||||
elapsed_ms: (bounds.trade_end.get() - bounds.trade_start.get()).to_string(),
|
||||
},
|
||||
session,
|
||||
period_start: bounds.trade_start,
|
||||
boundaries: boundaries
|
||||
.iter()
|
||||
.filter(|b| b.starts_at.get() > bounds.trade_start.get())
|
||||
.cloned()
|
||||
.collect(),
|
||||
next_boundary: 0,
|
||||
occupied_since: None,
|
||||
failure: None,
|
||||
complete: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Called only after the complete equal-time Observation group. No extra
|
||||
/// event enters Replay.events, and the earlier risk reset is untouched.
|
||||
pub fn after_observations(&mut self, at: EventTime, ledger: &Ledger) {
|
||||
if self.failure.is_some() || self.complete {
|
||||
return;
|
||||
}
|
||||
let Some(boundary) = self.boundaries.get(self.next_boundary) else {
|
||||
return;
|
||||
};
|
||||
if boundary.starts_at != at {
|
||||
return;
|
||||
}
|
||||
let next_session = boundary.clone();
|
||||
if self.sample(at, false, ledger) {
|
||||
self.session = next_session;
|
||||
self.period_start = at;
|
||||
self.next_boundary += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn sample(&mut self, at: EventTime, partial_end: bool, ledger: &Ledger) -> bool {
|
||||
match ledger.equity() {
|
||||
Ok(equity) => {
|
||||
self.facts.sessions.push(SessionEquity {
|
||||
session: self.session.clone(),
|
||||
period_start: self.period_start,
|
||||
period_end: at,
|
||||
partial_start: self.period_start != self.session.starts_at,
|
||||
partial_end,
|
||||
equity,
|
||||
});
|
||||
true
|
||||
}
|
||||
Err(error) => {
|
||||
self.failure = Some(format!("reporting equity unavailable: {error}"));
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Only a committed fill can change occupancy. Query authoritative current
|
||||
/// holdings once per matching outcome; never reconstruct quantities/deltas.
|
||||
pub fn committed(&mut self, at: EventTime, outcome: &MatchingOutcome, ledger: &Ledger) {
|
||||
if self.failure.is_some() || self.complete || outcome.replayed {
|
||||
return;
|
||||
}
|
||||
let filled = outcome.effects.iter().any(|effect| match effect {
|
||||
MatchingEffect::Risk { outcome, .. } if !outcome.replayed => outcome
|
||||
.financial
|
||||
.as_ref()
|
||||
.filter(|financial| !financial.replayed)
|
||||
.is_some_and(|financial| {
|
||||
financial
|
||||
.effects
|
||||
.effects
|
||||
.iter()
|
||||
.any(|effect| matches!(effect, FinancialEffect::FillApplied { .. }))
|
||||
}),
|
||||
_ => false,
|
||||
});
|
||||
if !filled {
|
||||
return;
|
||||
}
|
||||
let occupied = ledger.owned_quantities().next().is_some();
|
||||
match (self.occupied_since, occupied) {
|
||||
(None, true) => self.occupied_since = Some(at),
|
||||
(Some(start), false) => {
|
||||
self.interval(start, at);
|
||||
self.occupied_since = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn interval(&mut self, start: EventTime, end: EventTime) {
|
||||
let start = if start.get() < self.facts.trade_start.get() {
|
||||
self.facts.trade_start
|
||||
} else {
|
||||
start
|
||||
};
|
||||
let end = if end.get() > self.facts.trade_end.get() {
|
||||
self.facts.trade_end
|
||||
} else {
|
||||
end
|
||||
};
|
||||
if start.get() >= end.get() {
|
||||
return;
|
||||
}
|
||||
if let Some(last) = self.facts.occupied_intervals.last_mut() {
|
||||
if last.end.get() >= start.get() {
|
||||
if end.get() > last.end.get() {
|
||||
last.end = end;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.facts
|
||||
.occupied_intervals
|
||||
.push(OccupiedInterval { start, end });
|
||||
}
|
||||
|
||||
pub fn finish(&mut self, ledger: &Ledger) {
|
||||
if self.failure.is_some() || self.complete {
|
||||
return;
|
||||
}
|
||||
if self.next_boundary != self.boundaries.len() {
|
||||
self.failure = Some("reporting boundary was not sampled".into());
|
||||
return;
|
||||
}
|
||||
if self.period_start.get() < self.facts.trade_end.get()
|
||||
&& !self.sample(self.facts.trade_end, true, ledger)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(start) = self.occupied_since.take() {
|
||||
self.interval(start, self.facts.trade_end);
|
||||
}
|
||||
let occupied: i64 = self
|
||||
.facts
|
||||
.occupied_intervals
|
||||
.iter()
|
||||
.map(|interval| interval.end.get() - interval.start.get())
|
||||
.sum();
|
||||
self.facts.occupied_ms = occupied.to_string();
|
||||
self.complete = true;
|
||||
}
|
||||
|
||||
pub fn facts(&self) -> Result<&ReportingFacts, &str> {
|
||||
if let Some(failure) = &self.failure {
|
||||
Err(failure)
|
||||
} else if !self.complete {
|
||||
Err("reporting is incomplete")
|
||||
} else {
|
||||
Ok(&self.facts)
|
||||
}
|
||||
}
|
||||
}
|
||||
159
apps/stock/engine/src/financial/reporting_tests.rs
Normal file
159
apps/stock/engine/src/financial/reporting_tests.rs
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
use super::{contract::*, ledger::Ledger, matching::*, replay::ReplayBounds, reporting::Reporting};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn time(at: i64) -> EventTime {
|
||||
at.try_into().unwrap()
|
||||
}
|
||||
fn ledger() -> Ledger {
|
||||
Ledger::new(
|
||||
serde_json::from_value(json!({
|
||||
"version":1,"sessionId":"s","accountId":"a","baseCurrency":"USD",
|
||||
"reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":"10000",
|
||||
"riskSession":{"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0}
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn initial() -> RiskSessionIdentity {
|
||||
serde_json::from_value(
|
||||
json!({"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0}),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn reporting(ledger: &Ledger, start: i64, end: i64) -> Reporting {
|
||||
let mut initial = initial();
|
||||
initial.starts_at = time(start.min(0));
|
||||
Reporting::new(
|
||||
&initial,
|
||||
&[],
|
||||
&ReplayBounds {
|
||||
warmup_start: time(start),
|
||||
trade_start: time(start),
|
||||
trade_end: time(end),
|
||||
},
|
||||
ledger.cash(),
|
||||
)
|
||||
}
|
||||
fn apply(ledger: &mut Ledger, at: i64, name: &str, body: Value) -> MatchingOutcome {
|
||||
let command: EngineFinancialCommand = serde_json::from_value(json!({
|
||||
"version":1,"sessionId":"s","accountId":"a","commandId":name,"eventTime":at,"body":body,
|
||||
}))
|
||||
.unwrap();
|
||||
let financial = ledger.apply(&command).unwrap();
|
||||
// A reporting unit fixture wraps an actual ledger receipt, not invented deltas.
|
||||
serde_json::from_value(json!({"replayed":false,"revision":1,"status":"Running","effects":[{
|
||||
"Risk":{"command":{"commandId":name,"eventTime":at,"body":{"kind":"mark","instrumentId":"X","price":"10","observedAt":at}},
|
||||
"outcome":{"replayed":false,"revision":1,"disposition":"Accepted","financial":financial,
|
||||
"remaining":null,"releasedOrder":null,"resetBaseline":null}}
|
||||
}]})).unwrap()
|
||||
}
|
||||
fn fill(ledger: &mut Ledger, at: i64, owner: &str, side: &str) -> MatchingOutcome {
|
||||
let name = format!("{owner}-{side}-{at}");
|
||||
apply(
|
||||
ledger,
|
||||
at,
|
||||
&name,
|
||||
json!({"kind":"applyFill","decision":{"ownerId":owner,"decisionId":name,"sequence":0},
|
||||
"orderId":name,"fillId":name,"instrumentId":"X","side":side,"quantity":"1","price":"10",
|
||||
"fee":{"feeId":name,"amount":"0"}}),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_positions_open_position_exposure_and_same_time_handoff() {
|
||||
let mut ledger = ledger();
|
||||
apply(
|
||||
&mut ledger,
|
||||
0,
|
||||
"mark",
|
||||
json!({"kind":"mark","instrumentId":"X","price":"10"}),
|
||||
);
|
||||
let mut report = reporting(&ledger, 0, 50);
|
||||
for (at, owner, side) in [
|
||||
(10, "A", "buy"),
|
||||
(20, "B", "buy"),
|
||||
(25, "A", "sell"),
|
||||
(30, "B", "sell"),
|
||||
(30, "A", "buy"),
|
||||
(40, "A", "sell"),
|
||||
(40, "B", "buy"),
|
||||
] {
|
||||
let outcome = fill(&mut ledger, at, owner, side);
|
||||
report.committed(time(at), &outcome, &ledger);
|
||||
}
|
||||
report.finish(&ledger);
|
||||
let facts = report.facts().unwrap();
|
||||
assert_eq!(facts.occupied_ms, "40");
|
||||
assert_eq!(facts.elapsed_ms, "50");
|
||||
assert_eq!(facts.occupied_intervals.len(), 1);
|
||||
assert_eq!(facts.occupied_intervals[0].start, time(10));
|
||||
assert_eq!(facts.occupied_intervals[0].end, time(50));
|
||||
assert!(ledger.owned_quantities().next().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reporting_skips_each_nested_replayed_alias_and_zero_length_occupancy() {
|
||||
for level in 0..3 {
|
||||
let mut ledger = ledger();
|
||||
apply(
|
||||
&mut ledger,
|
||||
0,
|
||||
"mark",
|
||||
json!({"kind":"mark","instrumentId":"X","price":"10"}),
|
||||
);
|
||||
let mut report = reporting(&ledger, 0, 30);
|
||||
let outcome = fill(&mut ledger, 10, "A", "buy");
|
||||
let mut alias = outcome.clone();
|
||||
if level == 0 {
|
||||
alias.replayed = true;
|
||||
}
|
||||
let MatchingEffect::Risk { outcome: risk, .. } = &mut alias.effects[0] else {
|
||||
panic!()
|
||||
};
|
||||
if level == 1 {
|
||||
risk.replayed = true;
|
||||
}
|
||||
if level == 2 {
|
||||
risk.financial.as_mut().unwrap().replayed = true;
|
||||
}
|
||||
report.committed(time(0), &alias, &ledger);
|
||||
report.committed(time(10), &outcome, &ledger);
|
||||
let sell = fill(&mut ledger, 10, "A", "sell");
|
||||
report.committed(time(10), &sell, &ledger);
|
||||
report.finish(&ledger);
|
||||
assert!(report.facts().unwrap().occupied_intervals.is_empty());
|
||||
assert_eq!(report.facts().unwrap().occupied_ms, "0");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reporting_failure_retains_financial_state_and_cannot_return_success() {
|
||||
let mut ledger = ledger();
|
||||
let mut report = reporting(&ledger, 0, 20);
|
||||
fill(&mut ledger, 10, "A", "buy"); // No mark: ledger equity is explicitly unavailable.
|
||||
let checkpoint = ledger.checkpoint();
|
||||
report.finish(&ledger);
|
||||
assert!(report.facts().unwrap_err().contains("equity unavailable"));
|
||||
assert_eq!(ledger.checkpoint(), checkpoint);
|
||||
apply(
|
||||
&mut ledger,
|
||||
15,
|
||||
"mark",
|
||||
json!({"kind":"mark","instrumentId":"X","price":"10"}),
|
||||
);
|
||||
report.finish(&ledger); // A failed report cannot silently become successful later.
|
||||
assert!(report.facts().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duration_strings_cover_the_entire_safe_timestamp_domain_without_rounding() {
|
||||
let ledger = ledger();
|
||||
let mut report = reporting(&ledger, -9_007_199_254_740_991, 9_007_199_254_740_990);
|
||||
assert!(report.facts().is_err());
|
||||
report.finish(&ledger);
|
||||
let facts = report.facts().unwrap();
|
||||
assert_eq!(facts.elapsed_ms, "18014398509481981");
|
||||
assert_eq!(facts.occupied_ms, "0");
|
||||
assert!(!facts.sessions[0].partial_start && facts.sessions[0].partial_end);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue