//! Order lifecycle shared by historical replay and quote-driven paper execution. //! //! The host supplies ordered events, liquidity capacity and venue sessions. //! This module reconciles strategy intent, applies latency/price/TIF rules and //! sends candidate fills through [`RiskAccount`]. It never calls strategies or //! invents an intrabar OHLC path. The nested ledger is exposed read-only. use super::{ contract::*, ledger::Ledger, risk::*, scalar::{Posting, ScalarError}, }; use serde::{Deserialize, Serialize}; use std::{ cmp::Ordering, collections::{BTreeMap, BTreeSet}, }; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub enum EventPhase { Observation, Decision, Execution, SessionClose, } /// Scheduler-assigned total order. Instruments are compared lexically after /// phase; source sequence is from the pinned execution series. A quote-driven /// decision may use its observed quote's cursor, but cannot reuse that quote. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct EventKey { pub at: EventTime, pub phase: EventPhase, pub instrument_id: Id, pub source_sequence: Counter, } impl Ord for EventKey { fn cmp(&self, other: &Self) -> Ordering { ( self.at.get(), self.phase, &self.instrument_id, self.source_sequence.get(), ) .cmp(&( other.at.get(), other.phase, &other.instrument_id, other.source_sequence.get(), )) } } impl PartialOrd for EventKey { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum StrategyMode { Target, Orders, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum ExecutionMode { Open, Quote, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct OwnerMode { pub owner_id: Id, pub mode: StrategyMode, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ExecutionSeries { pub instrument_id: Id, pub series_id: Id, pub mode: ExecutionMode, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct MatchingConfig { pub risk: RiskConfig, pub owners: Vec, pub series: Vec, /// Relative fractions, not bps. Both must be <1. Synthetic quotes are /// rounded to eight places BEFORE slippage; actual quotes are not spread again. pub half_spread_rate: NonNegative, pub slippage_rate: NonNegative, pub latency_ms: Counter, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct VenueSession { pub session_id: Id, pub opens_at: EventTime, pub closes_at: EventTime, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde( tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase", deny_unknown_fields )] pub enum ExecutionObservation { /// One shared capacity across owners AND sides. Caller must derive this /// from information available before the open, never current bar volume. Open { /// Physical open time must equal the execution clock; delayed opens /// are skipped by F06, never re-stamped as newly executable prices. opens_at: EventTime, price: Positive, capacity: NonNegative, }, Quote { /// Actual quote observation time, not its later delivery time. observed_at: EventTime, bid: Positive, ask: Positive, bid_size: NonNegative, ask_size: NonNegative, }, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde( tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase", deny_unknown_fields )] pub enum MatchingCommandBody { Submit { decisions: Vec, }, Execute { series_id: Id, observation: ExecutionObservation, }, /// Completed observations from the pinned execution series only. Mark { series_id: Id, price: Positive, observed_at: EventTime, }, OpenSession { session: VenueSession, }, CloseSession { session_id: Id, }, RiskSessionBoundary { risk_session: RiskSessionIdentity, }, Finish, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct MatchingCommand { pub command_id: Id, pub key: EventKey, pub body: MatchingCommandBody, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct MatchingReset { pub key: EventKey, pub reset: OperatorReset, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "source", content = "command", deny_unknown_fields)] pub enum MatchingInput { Engine(MatchingCommand), Operator(MatchingReset), } impl MatchingInput { fn id(&self) -> &Id { match self { Self::Engine(c) => &c.command_id, Self::Operator(c) => &c.reset.command_id, } } fn key(&self) -> &EventKey { match self { Self::Engine(c) => &c.key, Self::Operator(c) => &c.key, } } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum OrderStatus { Open, Filled, Cancelled, Expired, Rejected(RiskRejection), } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ManagedOrder { pub order: RiskOrder, pub time_in_force: TimeInForce, pub submitted_at: EventKey, pub ready_at: EventTime, pub venue_session: Option, pub remaining: NonNegative, pub filled: NonNegative, pub status: OrderStatus, /// Stable within-owner intent order, independent of user-chosen order IDs. pub admission_sequence: Counter, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum MatchingEffect { Risk { command: RiskCommand, outcome: RiskOutcome, }, Operator { command: OperatorReset, outcome: RiskOutcome, }, Order(ManagedOrder), } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum AttemptStatus { Running, Complete, Failed { diagnostic: String }, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct MatchingOutcome { /// Original receipt; never republish its nested effects on retry. pub replayed: bool, pub revision: Counter, pub status: AttemptStatus, /// Exact committed prefix even for Failed. Failed is NOT a usable result. pub effects: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct MatchingReceipt { pub input: MatchingInput, pub outcome: MatchingOutcome, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct MatchingCheckpoint { pub version: Version, pub config: MatchingConfig, pub risk: RiskCheckpoint, pub revision: Counter, pub status: AttemptStatus, pub cursor: Option, pub orders: Vec, pub sessions: Vec<(Id, VenueSession)>, pub receipts: Vec, } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum MatchingError { #[error(transparent)] Risk(#[from] RiskError), #[error(transparent)] Arithmetic(#[from] ScalarError), #[error("invalid matching configuration")] InvalidConfig, #[error("command ID or execution event key conflicts with retained input")] InputConflict, #[error("command/event is backdated or execution phase was already consumed")] IneligibleKey, #[error("wrong execution series, event kind, or instrument")] WrongSeries, #[error("invalid, missing, or closed venue session")] InvalidSession, #[error("owner, mode, session, barrier or revision mismatch")] InvalidDecision, #[error("decision identity/sequence or order identity is reused")] DuplicateIdentity, #[error("cancel is unknown, duplicated, or belongs to another owner")] WrongOwnerCancel, #[error("duplicate target instrument")] DuplicateTarget, #[error("invalid crossed quote")] CrossedQuote, #[error("synthetic execution price rounded to zero")] ZeroPrice, #[error("safe counter or event time exhausted")] CounterOverflow, #[error("attempt is terminal; discard it, do not retry mutations")] Terminal, #[error("checkpoint is inconsistent")] InvalidCheckpoint, } fn nn(p: Posting) -> NonNegative { p.try_into().expect("nonnegative matching invariant") } fn positive(p: Posting) -> Result { p.try_into().map_err(|_| MatchingError::ZeroPrice) } fn next(c: Counter) -> Result { (c.get() + 1) .try_into() .map_err(|_| MatchingError::CounterOverflow) } /// JSON tuple encoding is injective even when user IDs contain delimiters. fn internal_id(value: impl Serialize) -> Id { serde_json::from_value(serde_json::Value::String( serde_json::to_string(&value).expect("serializable identity"), )) .expect("valid generated identity") } /// Pure timing predicate. The replay/paper host separately guarantees that /// the decision used only observations available before this execution event. pub fn eligible(submitted: &EventKey, ready_at: EventTime, event: &EventKey) -> bool { event.phase == EventPhase::Execution && event > submitted && event.at.get() >= ready_at.get() } /// Cross against the pre-slippage quote FIRST; cap only a crossing order. pub fn protected_price( side: Side, limit: Option, bid: Positive, ask: Positive, slippage: NonNegative, ) -> Result, MatchingError> { let quote: Posting = if side == Side::Buy { ask.into() } else { bid.into() }; if let Some(limit) = limit { if (side == Side::Buy && quote > limit.into()) || (side == Side::Sell && quote < limit.into()) { return Ok(None); } } let one: Posting = "1".parse().unwrap(); let rate: Posting = slippage.into(); if rate >= one { return Err(MatchingError::InvalidConfig); } let factor = if side == Side::Buy { one.checked_add(rate)? } else { one.checked_sub(rate)? }; let mut price = Posting::notional(quote, factor)?; if let Some(limit) = limit { price = if side == Side::Buy { price.min(limit.into()) } else { price.max(limit.into()) }; } Ok(Some(positive(price)?)) } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] enum PhysicalExecution { Open(Id, i64), Quote(Id, i64, u64), } impl PhysicalExecution { fn new(key: &EventKey, observation: &ExecutionObservation) -> Self { match observation { ExecutionObservation::Open { opens_at, .. } => { Self::Open(key.instrument_id.clone(), opens_at.get()) } ExecutionObservation::Quote { observed_at, .. } => Self::Quote( key.instrument_id.clone(), observed_at.get(), key.source_sequence.get(), ), } } } /// Only active-order IDs are scanned on an event; journals are never cloned on /// the hot path. Unexpected numeric errors terminally fail the whole attempt. #[derive(Debug)] pub struct MatchingAccount { config: MatchingConfig, risk: RiskAccount, revision: Counter, status: AttemptStatus, cursor: Option, orders: BTreeMap, active: BTreeMap>, sessions: BTreeMap, decisions: BTreeSet<(Id, Id)>, sequences: BTreeMap, admission_sequence: Counter, commands: BTreeMap, events: BTreeMap, physical_events: BTreeSet, barriers: BTreeMap, receipts: Vec, } impl MatchingAccount { pub fn new(mut config: MatchingConfig) -> Result<(Self, OperatorAuthority), MatchingError> { let one: Posting = "1".parse().unwrap(); if Posting::from(config.half_spread_rate) >= one || Posting::from(config.slippage_rate) >= one { return Err(MatchingError::InvalidConfig); } config.owners.sort_by(|a, b| a.owner_id.cmp(&b.owner_id)); config .series .sort_by(|a, b| a.instrument_id.cmp(&b.instrument_id)); config.risk.ledger.owner_ids.sort(); let owners: Vec<_> = config.owners.iter().map(|o| o.owner_id.clone()).collect(); if owners != config.risk.ledger.owner_ids || owners.windows(2).any(|w| w[0] == w[1]) || config.series.is_empty() || config .series .windows(2) .any(|w| w[0].instrument_id == w[1].instrument_id) { return Err(MatchingError::InvalidConfig); } let (risk, authority) = RiskAccount::new(config.risk.clone())?; Ok(( Self { config, risk, revision: 0.try_into().unwrap(), status: AttemptStatus::Running, cursor: None, orders: BTreeMap::new(), active: BTreeMap::new(), sessions: BTreeMap::new(), decisions: BTreeSet::new(), sequences: BTreeMap::new(), admission_sequence: 0.try_into().unwrap(), commands: BTreeMap::new(), events: BTreeMap::new(), physical_events: BTreeSet::new(), barriers: BTreeMap::new(), receipts: Vec::new(), }, authority, )) } pub fn ledger(&self) -> &Ledger { self.risk.ledger() } pub fn risk(&self) -> &RiskAccount { &self.risk } /// Reservation/order-aware barrier token; NOT FinancialSnapshot.revision. /// Every decision in a batch checks this same pre-admission token. pub fn admission_revision(&self) -> Counter { self.revision } pub fn status(&self) -> &AttemptStatus { &self.status } pub fn order(&self, id: &Id) -> Option<&ManagedOrder> { self.orders.get(id) } pub fn orders(&self) -> impl Iterator { self.orders.values() } pub fn receipts(&self) -> &[MatchingReceipt] { &self.receipts } /// Process one host event, checking identity, chronology and ownership first. /// Exact retries return their original receipt with `replayed = true`; /// callers must not publish those effects twice. An unexpected processing /// error can terminally fail the attempt: inspect the returned status too. pub fn apply(&mut self, command: &MatchingCommand) -> Result { self.apply_input(&MatchingInput::Engine(command.clone()), None) } pub fn reset( &mut self, authority: &OperatorAuthority, command: &MatchingReset, ) -> Result { self.apply_input(&MatchingInput::Operator(command.clone()), Some(authority)) } fn series(&self, instrument: &Id) -> Result<&ExecutionSeries, MatchingError> { self.config .series .iter() .find(|s| s.instrument_id == *instrument) .ok_or(MatchingError::WrongSeries) } fn session(&self, instrument: &Id, at: EventTime) -> Result<&VenueSession, MatchingError> { self.sessions .get(instrument) .filter(|s| at.get() >= s.opens_at.get() && at.get() < s.closes_at.get()) .ok_or(MatchingError::InvalidSession) } fn preflight(&self, input: &MatchingInput) -> Result<(), MatchingError> { let key = input.key(); if key.at.get() < self.risk.state().last_event_time.get() || self.cursor.as_ref().is_some_and(|c| key < c) { return Err(MatchingError::IneligibleKey); } if let MatchingInput::Operator(reset) = input { if reset.reset.event_time != key.at { return Err(MatchingError::IneligibleKey); } return Ok(()); } let MatchingInput::Engine(command) = input else { unreachable!() }; match &command.body { MatchingCommandBody::Execute { series_id, observation, } => { // Neither changing a delivery timestamp nor re-numbering an // open may mint another liquidity pool. Quote sequences need // only distinguish quotes at the same physical time; they are // not assumed monotonically increasing across timestamps. if self .physical_events .contains(&PhysicalExecution::new(key, observation)) { return Err(MatchingError::InputConflict); } let series = self.series(&key.instrument_id)?; if key.phase != EventPhase::Execution || self.cursor.as_ref().is_some_and(|c| key <= c) { return Err(MatchingError::IneligibleKey); } if series.series_id != *series_id || !matches!( (series.mode, observation), (ExecutionMode::Open, ExecutionObservation::Open { .. }) | (ExecutionMode::Quote, ExecutionObservation::Quote { .. }) ) { return Err(MatchingError::WrongSeries); } self.session(&key.instrument_id, key.at)?; if let ExecutionObservation::Open { opens_at, .. } = observation { if *opens_at != key.at { return Err(MatchingError::IneligibleKey); } } if let ExecutionObservation::Quote { bid, ask, observed_at, .. } = observation { if Posting::from(*bid) > (*ask).into() { return Err(MatchingError::CrossedQuote); } if observed_at.get() > key.at.get() || self .ledger() .mark(&key.instrument_id) .is_some_and(|m| observed_at.get() < m.event_time.get()) { return Err(MatchingError::IneligibleKey); } } } MatchingCommandBody::Mark { series_id, observed_at, .. } => { if key.phase != EventPhase::Observation { return Err(MatchingError::IneligibleKey); } if self.series(&key.instrument_id)?.series_id != *series_id { return Err(MatchingError::WrongSeries); } if observed_at.get() > key.at.get() || self .ledger() .mark(&key.instrument_id) .is_some_and(|m| observed_at.get() < m.event_time.get()) { return Err(MatchingError::IneligibleKey); } } MatchingCommandBody::OpenSession { session } => { self.series(&key.instrument_id)?; if self.sessions.contains_key(&key.instrument_id) || session.opens_at != key.at || session.closes_at.get() <= session.opens_at.get() { return Err(MatchingError::InvalidSession); } } MatchingCommandBody::CloseSession { session_id } => { let session = self .sessions .get(&key.instrument_id) .ok_or(MatchingError::InvalidSession)?; if session.session_id != *session_id || session.closes_at != key.at { return Err(MatchingError::InvalidSession); } } MatchingCommandBody::Submit { decisions } => { self.preflight_decisions(command, decisions)? } MatchingCommandBody::RiskSessionBoundary { .. } | MatchingCommandBody::Finish => (), } Ok(()) } fn preflight_decisions( &self, command: &MatchingCommand, decisions: &[StrategyDecision], ) -> Result<(), MatchingError> { // A decision cannot be inserted into an earlier bar execution phase. // Quote-driven decisions may use the exact quote cursor, never an open. if command.key.phase != EventPhase::Decision && !(command.key.phase == EventPhase::Execution && self.cursor.as_ref() == Some(&command.key) && self.events.contains_key(&command.key) && self.series(&command.key.instrument_id)?.mode == ExecutionMode::Quote) { return Err(MatchingError::IneligibleKey); } let mut owners = BTreeSet::new(); let mut order_ids = BTreeSet::new(); let mut cancels = BTreeSet::new(); let mut barrier = None; for decision in decisions { let owner = &decision.decision.owner_id; let registered = self .config .owners .iter() .find(|o| o.owner_id == *owner) .ok_or(MatchingError::InvalidDecision)?; if !owners.insert(owner.clone()) || decision.session_id != self.config.risk.ledger.session_id || decision.revision != self.revision || barrier.as_ref().is_some_and(|b| b != &decision.barrier_id) { return Err(MatchingError::InvalidDecision); } barrier = Some(decision.barrier_id.clone()); if self .decisions .contains(&(owner.clone(), decision.decision.decision_id.clone())) || self .sequences .get(owner) .is_some_and(|s| decision.decision.sequence.get() <= s.get()) { return Err(MatchingError::DuplicateIdentity); } match (&decision.intent, registered.mode) { (StrategyIntent::Target { targets }, StrategyMode::Target) => { let mut instruments = BTreeSet::new(); for target in targets { self.series(&target.instrument_id)?; if !instruments.insert(&target.instrument_id) { return Err(MatchingError::DuplicateTarget); } let oid = Self::target_id(decision, &target.instrument_id); if self.orders.contains_key(&oid) || !order_ids.insert(oid) { return Err(MatchingError::DuplicateIdentity); } } } (StrategyIntent::Orders { orders }, StrategyMode::Orders) => { for intent in orders { match intent { OrderIntent::Cancel { order_id } => { if !cancels.insert(order_id) || self .orders .get(order_id) .is_none_or(|o| o.order.decision.owner_id != *owner) { return Err(MatchingError::WrongOwnerCancel); } } OrderIntent::Market { order_id, instrument_id, time_in_force, .. } | OrderIntent::Limit { order_id, instrument_id, time_in_force, .. } => { self.series(instrument_id)?; if self.orders.contains_key(order_id) || !order_ids.insert(order_id.clone()) { return Err(MatchingError::DuplicateIdentity); } if *time_in_force == TimeInForce::DAY { self.session(instrument_id, command.key.at)?; } } } } } _ => return Err(MatchingError::InvalidDecision), } } // Reject timestamp/counter overflow before releasing target orders. command .key .at .get() .checked_add(self.config.latency_ms.get() as i64) .and_then(|t| EventTime::try_from(t).ok()) .ok_or(MatchingError::CounterOverflow)?; let count = u64::try_from(order_ids.len()).map_err(|_| MatchingError::CounterOverflow)?; Counter::try_from(self.admission_sequence.get() + count) .map_err(|_| MatchingError::CounterOverflow)?; Ok(()) } fn apply_input( &mut self, input: &MatchingInput, authority: Option<&OperatorAuthority>, ) -> Result { if let Some(index) = self.commands.get(input.id()) { let receipt = &self.receipts[*index]; if receipt.input != *input { return Err(MatchingError::InputConflict); } // Operator retries still authenticate; they must not leak the reset // receipt through a caller that has no instance capability. if let MatchingInput::Operator(_) = input { self.risk .validate_authority(authority.ok_or(RiskError::UnauthorizedReset)?)?; } let mut outcome = receipt.outcome.clone(); outcome.replayed = true; return Ok(outcome); } if self.status != AttemptStatus::Running { return Err(MatchingError::Terminal); } if let MatchingInput::Engine(MatchingCommand { body: MatchingCommandBody::Submit { decisions }, .. }) = input { if let Some(index) = decisions .first() .and_then(|d| self.barriers.get(&d.barrier_id)) { let MatchingInput::Engine(original) = &self.receipts[*index].input else { unreachable!() }; let MatchingInput::Engine(command) = input else { unreachable!() }; if original.key != command.key || original.body != command.body { return Err(MatchingError::InputConflict); } return Ok(self.record_alias(input, *index)); } } if let MatchingInput::Engine(MatchingCommand { body: MatchingCommandBody::Execute { .. }, .. }) = input { if let Some(index) = self.events.get(input.key()) { let MatchingInput::Engine(original) = &self.receipts[*index].input else { unreachable!() }; let MatchingInput::Engine(command) = input else { unreachable!() }; if original.body != command.body { return Err(MatchingError::InputConflict); } return Ok(self.record_alias(input, *index)); } } self.preflight(input)?; if let MatchingInput::Operator(_) = input { self.risk .validate_authority(authority.ok_or(RiskError::UnauthorizedReset)?)?; } let revision = next(self.revision)?; let mut effects = Vec::new(); let result = self.process(input, authority, &mut effects); if let Err(error) = result { // These single F04 controls validate atomically. Preserve their // ordinary validation errors rather than poisoning a healthy run. if effects.is_empty() && matches!( &error, MatchingError::Risk( RiskError::InvalidBoundaryTime | RiskError::InvalidResetMarks | RiskError::Ledger(super::ledger::LedgerError::InvalidRiskSession) ) ) { return Err(error); } self.status = AttemptStatus::Failed { diagnostic: error.to_string(), }; } self.cursor = Some(input.key().clone()); self.revision = revision; let outcome = MatchingOutcome { replayed: false, revision, status: self.status.clone(), effects, }; if matches!( input, MatchingInput::Engine(MatchingCommand { body: MatchingCommandBody::Execute { .. }, .. }) ) { self.events.insert(input.key().clone(), self.receipts.len()); let MatchingInput::Engine(MatchingCommand { body: MatchingCommandBody::Execute { observation, .. }, .. }) = input else { unreachable!() }; self.physical_events .insert(PhysicalExecution::new(input.key(), observation)); } if let MatchingInput::Engine(MatchingCommand { body: MatchingCommandBody::Submit { decisions }, .. }) = input { if let Some(decision) = decisions.first() { self.barriers .insert(decision.barrier_id.clone(), self.receipts.len()); } } self.commands .insert(input.id().clone(), self.receipts.len()); self.receipts.push(MatchingReceipt { input: input.clone(), outcome: outcome.clone(), }); Ok(outcome) } fn record_alias(&mut self, input: &MatchingInput, index: usize) -> MatchingOutcome { let mut outcome = self.receipts[index].outcome.clone(); outcome.replayed = true; self.commands .insert(input.id().clone(), self.receipts.len()); self.receipts.push(MatchingReceipt { input: input.clone(), outcome: outcome.clone(), }); outcome } fn risk_command( &mut self, input: &MatchingInput, effects: &mut Vec, body: RiskCommandBody, ) -> Result { let command = RiskCommand { command_id: internal_id(("matching", input.id(), effects.len())), event_time: input.key().at, body, }; let outcome = self.risk.apply(&command)?; effects.push(MatchingEffect::Risk { command, outcome: outcome.clone(), }); Ok(outcome) } fn store_order(&mut self, order: ManagedOrder, effects: &mut Vec) { let ids = self .active .entry(order.order.instrument_id.clone()) .or_default(); if order.status == OrderStatus::Open { ids.insert(order.order.order_id.clone()); } else { ids.remove(&order.order.order_id); } effects.push(MatchingEffect::Order(order.clone())); self.orders.insert(order.order.order_id.clone(), order); } fn release( &mut self, input: &MatchingInput, oid: &Id, reason: ReleaseReason, effects: &mut Vec, ) -> Result<(), MatchingError> { let mut order = self .orders .get(oid) .expect("preflight existing order") .clone(); if order.status != OrderStatus::Open { return Ok(()); } self.risk_command( input, effects, RiskCommandBody::Release { owner_id: order.order.decision.owner_id.clone(), order_id: oid.clone(), reason, }, )?; order.status = match reason { ReleaseReason::Cancelled => OrderStatus::Cancelled, ReleaseReason::Expired => OrderStatus::Expired, ReleaseReason::Rejected => unreachable!(), }; self.store_order(order, effects); Ok(()) } fn admit( &mut self, input: &MatchingInput, order: RiskOrder, time_in_force: TimeInForce, effects: &mut Vec, ) -> Result<(), MatchingError> { let admission_sequence = next(self.admission_sequence)?; let ready_at = EventTime::try_from(input.key().at.get() + self.config.latency_ms.get() as i64) .map_err(|_| MatchingError::CounterOverflow)?; let venue_session = if time_in_force == TimeInForce::DAY { Some( self.session(&order.instrument_id, input.key().at)? .session_id .clone(), ) } else { None }; let outcome = self.risk_command( input, effects, RiskCommandBody::Admit { order: order.clone(), }, )?; let status = match outcome.disposition { RiskDisposition::Accepted => OrderStatus::Open, RiskDisposition::Rejected(r) => OrderStatus::Rejected(r), }; let managed = ManagedOrder { remaining: nn(order.quantity.into()), filled: nn(Posting::ZERO), order, time_in_force, submitted_at: input.key().clone(), ready_at, venue_session, status, admission_sequence, }; self.admission_sequence = admission_sequence; self.store_order(managed, effects); Ok(()) } fn target_id(d: &StrategyDecision, instrument: &Id) -> Id { internal_id(( "target", &d.decision.owner_id, &d.decision.decision_id, instrument, )) } fn active_ids(&self, instrument: &Id) -> Vec { let mut ids: Vec<_> = self .active .get(instrument) .into_iter() .flat_map(|s| s.iter().cloned()) .collect(); ids.sort_by(|a, b| { let a = &self.orders[a]; let b = &self.orders[b]; (&a.order.decision.owner_id, a.admission_sequence.get()) .cmp(&(&b.order.decision.owner_id, b.admission_sequence.get())) }); ids } /// Admit owners in stable lexical order against shared account resources. /// Targets are total owner holdings, not buy/sell deltas: pending orders /// count toward the projected holding, so repeating a target preserves an /// already correct working order. Omitted instruments receive no update. fn submit( &mut self, input: &MatchingInput, decisions: &[StrategyDecision], effects: &mut Vec, ) -> Result<(), MatchingError> { let mut decisions: Vec<_> = decisions.iter().collect(); decisions.sort_by(|a, b| a.decision.owner_id.cmp(&b.decision.owner_id)); for decision in decisions { match &decision.intent { StrategyIntent::Orders { orders } => { for intent in orders { match intent { OrderIntent::Cancel { order_id } => { self.release(input, order_id, ReleaseReason::Cancelled, effects)? } OrderIntent::Market { order_id, instrument_id, side, quantity, time_in_force, } => self.admit( input, RiskOrder { order_id: order_id.clone(), decision: decision.decision.clone(), instrument_id: instrument_id.clone(), side: *side, quantity: *quantity, limit_price: None, origin: OrderOrigin::Explicit, }, *time_in_force, effects, )?, OrderIntent::Limit { order_id, instrument_id, side, quantity, price, time_in_force, } => self.admit( input, RiskOrder { order_id: order_id.clone(), decision: decision.decision.clone(), instrument_id: instrument_id.clone(), side: *side, quantity: *quantity, limit_price: Some(*price), origin: OrderOrigin::Explicit, }, *time_in_force, effects, )?, } } } // Sparse updates in declared intent order, NOT an atomic // portfolio rebalance: omitted instruments stay untouched. StrategyIntent::Target { targets } => { for target in targets { let owned = self .ledger() .owner_quantity(&decision.decision.owner_id, &target.instrument_id); let ids: Vec<_> = self .active_ids(&target.instrument_id) .into_iter() .filter(|id| { self.orders[id].order.decision.owner_id == decision.decision.owner_id }) .collect(); let mut projected = owned; for id in &ids { let o = &self.orders[id]; projected = if o.order.side == Side::Buy { projected.checked_add(o.remaining.into())? } else { projected.checked_sub(o.remaining.into())? }; } if projected == target.quantity.into() { continue; } let desired: Posting = target.quantity.into(); let (side, quantity) = if desired >= owned { (Side::Buy, desired.checked_sub(owned)?) } else { (Side::Sell, owned.checked_sub(desired)?) }; for id in ids { self.release(input, &id, ReleaseReason::Cancelled, effects)?; } if !quantity.is_zero() { self.admit( input, RiskOrder { order_id: Self::target_id(decision, &target.instrument_id), decision: decision.decision.clone(), instrument_id: target.instrument_id.clone(), side, quantity: positive(quantity)?, limit_price: None, origin: OrderOrigin::Target, }, TimeInForce::GTC, effects, )?; } } } } self.decisions.insert(( decision.decision.owner_id.clone(), decision.decision.decision_id.clone(), )); self.sequences.insert( decision.decision.owner_id.clone(), decision.decision.sequence, ); } Ok(()) } /// Match only eligible active orders against this event's finite capacity. /// Open events share capacity across both sides; quotes have bid/ask sizes. /// Risk rechecks the proposed quantity and actual price before the order or /// capacity is advanced, so an admitted order can still be rejected here. fn execute( &mut self, input: &MatchingInput, observation: &ExecutionObservation, effects: &mut Vec, ) -> Result<(), MatchingError> { let (bid, ask, mark, mut buy_capacity, mut sell_capacity, shared) = match observation { ExecutionObservation::Open { price, capacity, .. } => { let one: Posting = "1".parse().unwrap(); let bid = positive(Posting::notional( (*price).into(), one.checked_sub(self.config.half_spread_rate.into())?, )?)?; let ask = positive(Posting::notional( (*price).into(), one.checked_add(self.config.half_spread_rate.into())?, )?)?; ( bid, ask, *price, Posting::from(*capacity), Posting::from(*capacity), true, ) } ExecutionObservation::Quote { bid, ask, bid_size, ask_size, .. } => ( *bid, *ask, positive(Posting::midpoint((*bid).into(), (*ask).into())?)?, Posting::from(*ask_size), Posting::from(*bid_size), false, ), }; self.risk_command( input, effects, RiskCommandBody::Mark { instrument_id: input.key().instrument_id.clone(), price: mark, observed_at: match observation { ExecutionObservation::Quote { observed_at, .. } => *observed_at, ExecutionObservation::Open { .. } => input.key().at, }, }, )?; for id in self.active_ids(&input.key().instrument_id) { let mut order = self.orders[&id].clone(); if !eligible(&order.submitted_at, order.ready_at, input.key()) { continue; } if matches!(observation, ExecutionObservation::Quote { observed_at, .. } if observed_at.get() < order.ready_at.get()) { continue; } let capacity = if order.order.side == Side::Buy { buy_capacity } else { sell_capacity }; let price = protected_price( order.order.side, order.order.limit_price, bid, ask, self.config.slippage_rate, )?; let remainder: Posting = order.remaining.into(); let can_fill = price.is_some() && !capacity.is_zero() && (order.time_in_force != TimeInForce::FOK || capacity >= remainder); if can_fill { let quantity = remainder.min(capacity); // Complete all fallible arithmetic before committing the risk fill. let remaining = nn(remainder.checked_sub(quantity)?); let filled = nn(Posting::from(order.filled).checked_add(quantity)?); let remaining_capacity = capacity.checked_sub(quantity)?; let fill_id = internal_id(("fill", input.key(), &id)); let fee_id = internal_id(("fee", input.key(), &id)); let outcome = self.risk_command( input, effects, RiskCommandBody::Fill { order_id: id.clone(), fill_id, fee_id, quantity: positive(quantity)?, price: price.expect("crossing checked"), }, )?; match outcome.disposition { RiskDisposition::Accepted => { order.remaining = remaining; order.filled = filled; if Posting::from(remaining).is_zero() { order.status = OrderStatus::Filled; } if shared { buy_capacity = remaining_capacity; sell_capacity = remaining_capacity; } else if order.order.side == Side::Buy { buy_capacity = remaining_capacity; } else { sell_capacity = remaining_capacity; } } RiskDisposition::Rejected(reason) => { order.status = OrderStatus::Rejected(reason) } } self.store_order(order.clone(), effects); } if order.status == OrderStatus::Open && matches!(order.time_in_force, TimeInForce::IOC | TimeInForce::FOK) { self.release(input, &id, ReleaseReason::Cancelled, effects)?; } } Ok(()) } fn process( &mut self, input: &MatchingInput, authority: Option<&OperatorAuthority>, effects: &mut Vec, ) -> Result<(), MatchingError> { let MatchingInput::Engine(command) = input else { let MatchingInput::Operator(reset) = input else { unreachable!() }; let mut command = reset.reset.clone(); command.command_id = internal_id(("operator", input.id())); let outcome = self .risk .reset(authority.expect("preflight authority"), &command)?; effects.push(MatchingEffect::Operator { command, outcome }); return Ok(()); }; match &command.body { MatchingCommandBody::Submit { decisions } => self.submit(input, decisions, effects)?, MatchingCommandBody::Execute { observation, .. } => { self.execute(input, observation, effects)? } MatchingCommandBody::Mark { price, observed_at, .. } => { self.risk_command( input, effects, RiskCommandBody::Mark { instrument_id: command.key.instrument_id.clone(), price: *price, observed_at: *observed_at, }, )?; } MatchingCommandBody::RiskSessionBoundary { risk_session } => { self.risk_command( input, effects, RiskCommandBody::RiskSessionBoundary { risk_session: risk_session.clone(), }, )?; } MatchingCommandBody::OpenSession { session } => { self.sessions .insert(command.key.instrument_id.clone(), session.clone()); } MatchingCommandBody::CloseSession { .. } => { for id in self.active_ids(&command.key.instrument_id) { if self.orders[&id].time_in_force == TimeInForce::DAY { self.release(input, &id, ReleaseReason::Expired, effects)?; } } self.sessions.remove(&command.key.instrument_id); } MatchingCommandBody::Finish => { // End of research cancels working orders, not holdings. Terminal // equity therefore marks inventory without a fabricated sale/fee. let instruments: Vec<_> = self.active.keys().cloned().collect(); for instrument in instruments { for id in self.active_ids(&instrument) { self.release(input, &id, ReleaseReason::Cancelled, effects)?; } } self.status = AttemptStatus::Complete; } } Ok(()) } pub fn checkpoint(&self) -> MatchingCheckpoint { MatchingCheckpoint { version: Version, config: self.config.clone(), risk: self.risk.checkpoint(), revision: self.revision, status: self.status.clone(), cursor: self.cursor.clone(), orders: self.orders.values().cloned().collect(), sessions: self .sessions .iter() .map(|(i, s)| (i.clone(), s.clone())) .collect(), receipts: self.receipts.clone(), } } /// Full journal replay checks consistency, not authenticity. Recovery does /// not resurrect a failed attempt or issue a strategy reset capability. pub fn restore( checkpoint: MatchingCheckpoint, ) -> Result<(Self, OperatorAuthority), MatchingError> { let (mut account, authority) = Self::new(checkpoint.config.clone()).map_err(|_| MatchingError::InvalidCheckpoint)?; for receipt in &checkpoint.receipts { let outcome = account .apply_input(&receipt.input, Some(&authority)) .map_err(|_| MatchingError::InvalidCheckpoint)?; if outcome != receipt.outcome { return Err(MatchingError::InvalidCheckpoint); } } if account.checkpoint() != checkpoint { return Err(MatchingError::InvalidCheckpoint); } Ok((account, authority)) } }