238 lines
7.8 KiB
Rust
238 lines
7.8 KiB
Rust
//! 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)
|
|
}
|
|
}
|
|
}
|