feat(engine): add canonical risk and order matching

This commit is contained in:
Boki 2026-10-22 22:15:34 -04:00
parent b65acccd91
commit ccf333cc0a
13 changed files with 5129 additions and 36 deletions

View file

@ -589,6 +589,37 @@ impl Ledger {
.and_then(|i| i.mark.as_ref())
}
/// Small immutable views for the risk gate; no economic snapshot/history
/// allocation is necessary for an ordinary transition.
pub fn cash(&self) -> Posting {
self.cash
}
pub fn equity(&self) -> Result<Posting, LedgerError> {
if self.totals.unmarked != 0 {
return Err(LedgerError::MissingMark);
}
Ok(self.cash.checked_add(self.totals.marked)?)
}
pub fn owner_quantity(&self, owner_id: &Id, instrument_id: &Id) -> Posting {
self.instruments
.get(instrument_id)
.and_then(|i| i.books.get(owner_id))
.map(|b| b.quantity)
.unwrap_or(Posting::ZERO)
}
pub fn owned_quantities(&self) -> impl Iterator<Item = (&Id, &Id, Posting)> {
self.instruments.iter().flat_map(|(id, instrument)| {
instrument
.books
.iter()
.filter(|(_, book)| !book.quantity.is_zero())
.map(move |(owner, book)| (id, owner, book.quantity))
})
}
pub fn aggregate_positions(&self) -> Vec<AggregatePosition> {
self.instruments
.iter()

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -4,6 +4,8 @@
//! transitions/idempotency; F04 owns risk; F06/F07 own replay/session state.
pub mod contract;
pub mod ledger;
pub mod matching;
pub mod risk;
pub mod scalar;
#[cfg(test)]
@ -11,3 +13,9 @@ mod tests;
#[cfg(test)]
mod ledger_tests;
#[cfg(test)]
mod risk_tests;
#[cfg(test)]
mod matching_tests;

View file

@ -0,0 +1,897 @@
//! Additive authoritative cash/risk gate. Not connected to legacy execution.
//! F05 supplies normalized orders/matching; F06 supplies the engine clock.
//! Limit crossing, TIF and execution-event eligibility are not certified here.
//! This host API is not a sandbox for arbitrary in-process Rust code.
use super::{
contract::*,
ledger::*,
scalar::{Posting, ScalarError},
};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, sync::Arc};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskConfig {
pub ledger: LedgerConfig,
pub fee_rate: NonNegative,
pub max_order_quantity: Positive,
pub max_position_quantity: Positive,
pub max_symbol_exposure: Positive,
pub max_gross_exposure: Positive,
pub max_daily_loss: Positive,
pub max_drawdown_amount: Positive,
pub max_mark_age_ms: Counter,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OrderOrigin {
Explicit,
Target,
}
/// Already normalized by the future order coordinator. Origin is provenance,
/// never an alternate risk path. No target expansion, TIF or matching here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskOrder {
pub order_id: Id,
pub decision: DecisionIdentity,
pub instrument_id: Id,
pub side: Side,
pub quantity: Positive,
pub limit_price: Option<Positive>,
pub origin: OrderOrigin,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReleaseReason {
Cancelled,
Rejected,
Expired,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
tag = "kind",
rename_all = "camelCase",
rename_all_fields = "camelCase",
deny_unknown_fields
)]
pub enum RiskCommandBody {
Admit {
order: RiskOrder,
},
Fill {
order_id: Id,
fill_id: Id,
fee_id: Id,
quantity: Positive,
price: Positive,
},
Mark {
instrument_id: Id,
price: Positive,
observed_at: EventTime,
},
Release {
owner_id: Id,
order_id: Id,
reason: ReleaseReason,
},
RiskSessionBoundary {
risk_session: RiskSessionIdentity,
},
}
/// Commands are scoped to this account instance. Time comes from the engine,
/// not a strategy-supplied timestamp. There is intentionally no reset variant.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskCommand {
pub command_id: Id,
pub event_time: EventTime,
pub body: RiskCommandBody,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Reservation {
pub order: RiskOrder,
pub remaining: Positive,
pub cash: NonNegative,
/// Buy reservation price, never a synthetic ledger mark. Sells reserve
/// inventory, require no fresh mark and have no reservation price.
pub price: Option<Positive>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RiskRejection {
OrderSize,
PositionSize,
SymbolExposure,
GrossExposure,
InsufficientCash,
InsufficientInventory,
MissingMark,
StaleMark,
DailyLoss,
Drawdown,
InactiveOrder,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RiskDisposition {
Accepted,
Rejected(RiskRejection),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskOutcome {
/// Returns the ORIGINAL receipt. When true, do not publish/apply any of
/// its effects again, even if nested financial.replayed is originally false.
/// A retry does not update risk state, reservations or the current clock.
pub replayed: bool,
pub revision: Counter,
pub disposition: RiskDisposition,
pub financial: Option<ApplyOutcome>,
pub remaining: Option<Reservation>,
pub released_order: Option<Id>,
pub reset_baseline: Option<NonNegative>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskState {
pub daily_baseline: NonNegative,
pub peak_equity: NonNegative,
pub daily_halted: bool,
pub drawdown_halted: bool,
pub risk_session: RiskSessionIdentity,
pub last_event_time: EventTime,
}
/// Host-issued instance capability. No Deserialize/Clone or public constructor;
/// do not give it to strategy code. This is API separation, not authentication.
#[derive(Debug)]
pub struct OperatorAuthority(Arc<()>);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct OperatorReset {
pub command_id: Id,
pub event_time: EventTime,
pub actor_id: Id,
pub reason: Id,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "source", content = "command", deny_unknown_fields)]
pub enum RiskInput {
Engine(RiskCommand),
Operator(OperatorReset),
}
impl RiskInput {
fn id(&self) -> &Id {
match self {
Self::Engine(c) => &c.command_id,
Self::Operator(c) => &c.command_id,
}
}
fn time(&self) -> EventTime {
match self {
Self::Engine(c) => c.event_time,
Self::Operator(c) => c.event_time,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskReceipt {
pub input: RiskInput,
pub outcome: RiskOutcome,
}
/// Journal replay validates consistency, not authenticity of genesis/history.
/// Durable provenance and operator authentication belong to the host. This is
/// risk+ledger recovery only, not F07 replay/strategy/RNG recovery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RiskCheckpoint {
pub version: Version,
pub config: RiskConfig,
pub ledger: LedgerCheckpoint,
pub revision: Counter,
pub state: RiskState,
pub reservations: Vec<Reservation>,
pub receipts: Vec<RiskReceipt>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RiskError {
#[error(transparent)]
Ledger(#[from] LedgerError),
#[error(transparent)]
Arithmetic(#[from] ScalarError),
#[error("fee rate must be in [0, 1]")]
InvalidFeeRate,
#[error("command ID reused with a conflicting payload")]
CommandConflict,
#[error("order ID is unknown or reused")]
OrderConflict,
#[error("fill ID reused with conflicting payload/time")]
FillConflict,
#[error("fee ID reused by another fill")]
FeeConflict,
#[error("owner is unregistered or does not own this order")]
WrongOwner,
#[error("fill quantity exceeds remaining reserved quantity")]
ExcessFill,
#[error("engine command time is backdated")]
BackdatedCommand,
#[error("mark is future-dated or older than the retained mark")]
InvalidMarkTime,
#[error("new risk boundary must occur at its declared start")]
InvalidBoundaryTime,
#[error("operator capability does not belong to this account instance")]
UnauthorizedReset,
#[error("cannot reset against stale or missing marks")]
InvalidResetMarks,
#[error("risk revision exhausted safe integer range")]
RevisionOverflow,
#[error("checkpoint is inconsistent with its genesis and receipts")]
InvalidCheckpoint,
}
/// No Clone, mutable ledger access, or unrestricted fill entry point. Ordinary
/// transitions touch scalar state and active reservations, never copy history.
#[derive(Debug)]
pub struct RiskAccount {
config: RiskConfig,
ledger: Ledger,
revision: Counter,
state: RiskState,
pending: BTreeMap<Id, Reservation>,
orders: BTreeMap<Id, RiskOrder>,
reserved_cash: Posting,
receipts: Vec<RiskReceipt>,
commands: BTreeMap<Id, usize>,
fills: BTreeMap<Id, usize>,
fees: BTreeMap<Id, Id>,
authority: Arc<()>,
}
fn nn(p: Posting) -> NonNegative {
p.try_into().expect("nonnegative risk invariant")
}
fn pos(p: Posting) -> Positive {
p.try_into().expect("positive remaining quantity")
}
impl RiskAccount {
pub fn new(mut config: RiskConfig) -> Result<(Self, OperatorAuthority), RiskError> {
if Posting::from(config.fee_rate) > "1".parse::<Posting>()? {
return Err(RiskError::InvalidFeeRate);
}
config.ledger.owner_ids.sort();
let ledger = Ledger::new(config.ledger.clone())?;
let authority = Arc::new(());
let capability = OperatorAuthority(authority.clone());
let state = RiskState {
daily_baseline: config.ledger.initial_capital,
peak_equity: config.ledger.initial_capital,
daily_halted: false,
drawdown_halted: false,
risk_session: config.ledger.risk_session.clone(),
last_event_time: config.ledger.risk_session.starts_at,
};
Ok((
Self {
config,
ledger,
state,
revision: Counter::try_from(0).unwrap(),
pending: BTreeMap::new(),
orders: BTreeMap::new(),
reserved_cash: Posting::ZERO,
receipts: Vec::new(),
commands: BTreeMap::new(),
fills: BTreeMap::new(),
fees: BTreeMap::new(),
authority,
},
capability,
))
}
pub fn ledger(&self) -> &Ledger {
&self.ledger
}
pub fn state(&self) -> &RiskState {
&self.state
}
pub fn reservations(&self) -> impl Iterator<Item = &Reservation> {
self.pending.values()
}
pub fn available_cash(&self) -> Posting {
self.ledger
.cash()
.checked_sub(self.reserved_cash)
.expect("cash reservations are funded")
}
pub fn apply(&mut self, command: &RiskCommand) -> Result<RiskOutcome, RiskError> {
self.apply_input(&RiskInput::Engine(command.clone()))
}
pub fn reset(
&mut self,
authority: &OperatorAuthority,
reset: &OperatorReset,
) -> Result<RiskOutcome, RiskError> {
self.validate_authority(authority)?;
self.apply_input(&RiskInput::Operator(reset.clone()))
}
pub(super) fn validate_authority(
&self,
authority: &OperatorAuthority,
) -> Result<(), RiskError> {
if Arc::ptr_eq(&self.authority, &authority.0) {
Ok(())
} else {
Err(RiskError::UnauthorizedReset)
}
}
fn financial(
&self,
id: &Id,
time: EventTime,
body: EngineCommandBody,
) -> EngineFinancialCommand {
EngineFinancialCommand {
version: Version,
session_id: self.config.ledger.session_id.clone(),
account_id: self.config.ledger.account_id.clone(),
command_id: id.clone(),
event_time: time,
body,
}
}
fn fee(&self, quantity: Posting, price: Posting) -> Result<Posting, RiskError> {
Ok(Posting::rate_fee(
quantity,
price,
self.config.fee_rate.into(),
)?)
}
fn cash_for(&self, quantity: Posting, price: Posting) -> Result<Posting, RiskError> {
Ok(Posting::notional(quantity, price)?.checked_add(self.fee(quantity, price)?)?)
}
fn fresh(&self, instrument: &Id, time: EventTime) -> Result<Positive, RiskRejection> {
let mark = self
.ledger
.mark(instrument)
.ok_or(RiskRejection::MissingMark)?;
let age = i128::from(time.get()) - i128::from(mark.event_time.get());
if age < 0 || age > i128::from(self.config.max_mark_age_ms.get()) {
return Err(RiskRejection::StaleMark);
}
Ok(mark.price)
}
fn fresh_all(&self, time: EventTime) -> Result<(), RiskRejection> {
for (id, _, _) in self.ledger.owned_quantities() {
self.fresh(id, time)?;
}
for r in self.pending.values() {
self.fresh(&r.order.instrument_id, time)?;
}
Ok(())
}
/// Scan current owned books + live buy commitments, not historical orders.
/// Per-owner rounding matches the canonical marked holdings identity.
fn increase_check(
&self,
candidate: &Reservation,
time: EventTime,
replacing: bool,
) -> Result<Option<RiskRejection>, RiskError> {
if let Err(reason) = self.fresh_all(time) {
return Ok(Some(reason));
}
if self.state.daily_halted {
return Ok(Some(RiskRejection::DailyLoss));
}
if self.state.drawdown_halted {
return Ok(Some(RiskRejection::Drawdown));
}
let mut books = BTreeMap::<(Id, Id), (Posting, Posting)>::new();
let candidate_price: Posting = candidate.price.expect("buy reservation price").into();
let mut add =
|id: &Id, owner: &Id, quantity: Posting, price: Posting| -> Result<(), RiskError> {
let entry = books
.entry((id.clone(), owner.clone()))
.or_insert((Posting::ZERO, Posting::ZERO));
entry.0 = entry.0.checked_add(quantity)?;
entry.1 = entry.1.max(price);
Ok(())
};
for (id, owner, quantity) in self.ledger.owned_quantities() {
let mark: Posting = self.ledger.mark(id).expect("fresh owned mark").price.into();
add(
id,
owner,
quantity,
if *id == candidate.order.instrument_id {
mark.max(candidate_price)
} else {
mark
},
)?;
}
for r in self.pending.values() {
if r.order.side != Side::Buy
|| (replacing && r.order.order_id == candidate.order.order_id)
{
continue;
}
let mark: Posting = self
.ledger
.mark(&r.order.instrument_id)
.expect("fresh pending mark")
.price
.into();
let mut price = mark.max(r.price.expect("buy price").into());
if r.order.instrument_id == candidate.order.instrument_id {
price = price.max(candidate_price);
}
add(
&r.order.instrument_id,
&r.order.decision.owner_id,
r.remaining.into(),
price,
)?;
}
add(
&candidate.order.instrument_id,
&candidate.order.decision.owner_id,
candidate.remaining.into(),
candidate_price,
)?;
// Sum prospective quantity per owner/book BEFORE rounding its value.
// Separately rounding tiny existing/pending lots can understate the
// value after those lots join one canonical owner book. Conservatively
// value each prospective book at its greatest committed/market price.
let mut quantities = BTreeMap::<Id, Posting>::new();
let mut exposure = BTreeMap::<Id, Posting>::new();
for ((id, _), (quantity, price)) in books {
let q = quantities
.get(&id)
.copied()
.unwrap_or(Posting::ZERO)
.checked_add(quantity)?;
let e = exposure
.get(&id)
.copied()
.unwrap_or(Posting::ZERO)
.checked_add(Posting::notional(quantity, price)?)?;
quantities.insert(id.clone(), q);
exposure.insert(id, e);
}
if quantities
.values()
.any(|q| *q > self.config.max_position_quantity.into())
{
return Ok(Some(RiskRejection::PositionSize));
}
if exposure
.values()
.any(|e| *e > self.config.max_symbol_exposure.into())
{
return Ok(Some(RiskRejection::SymbolExposure));
}
if Posting::sum(exposure.values().copied())? > self.config.max_gross_exposure.into() {
return Ok(Some(RiskRejection::GrossExposure));
}
Ok(None)
}
fn reservation(
&self,
order: &RiskOrder,
time: EventTime,
) -> Result<Result<Reservation, RiskRejection>, RiskError> {
let quantity: Posting = order.quantity.into();
if quantity > self.config.max_order_quantity.into() {
return Ok(Err(RiskRejection::OrderSize));
}
if order.side == Side::Sell {
let committed = Posting::sum(
self.pending
.values()
.filter(|r| {
r.order.side == Side::Sell
&& r.order.decision.owner_id == order.decision.owner_id
&& r.order.instrument_id == order.instrument_id
})
.map(|r| r.remaining.into()),
)?;
if quantity.checked_add(committed)?
> self
.ledger
.owner_quantity(&order.decision.owner_id, &order.instrument_id)
{
return Ok(Err(RiskRejection::InsufficientInventory));
}
return Ok(Ok(Reservation {
order: order.clone(),
remaining: order.quantity,
cash: nn(Posting::ZERO),
price: None,
}));
}
let mark = match self.fresh(&order.instrument_id, time) {
Ok(p) => p,
Err(r) => return Ok(Err(r)),
};
let price = pos(Posting::from(mark).max(
order
.limit_price
.map(Posting::from)
.unwrap_or(Posting::ZERO),
));
let cash = self.cash_for(quantity, price.into())?;
let reservation = Reservation {
order: order.clone(),
remaining: order.quantity,
cash: nn(cash),
price: Some(price),
};
if cash > self.available_cash() {
return Ok(Err(RiskRejection::InsufficientCash));
}
if let Some(reason) = self.increase_check(&reservation, time, false)? {
return Ok(Err(reason));
}
Ok(Ok(reservation))
}
/// All operands are nonnegative representable ledger equity values, so
/// their ordered differences cannot overflow. No fallible state arithmetic
/// occurs after a ledger commit.
fn observe_equity(&mut self) {
let equity = self
.ledger
.equity()
.expect("risk permits only explicitly marked inventory");
let peak = Posting::from(self.state.peak_equity).max(equity);
self.state.peak_equity = nn(peak);
let baseline: Posting = self.state.daily_baseline.into();
if baseline >= equity
&& baseline
.checked_sub(equity)
.expect("nonnegative bounded difference")
>= self.config.max_daily_loss.into()
{
self.state.daily_halted = true;
}
if peak
.checked_sub(equity)
.expect("nonnegative bounded difference")
>= self.config.max_drawdown_amount.into()
{
self.state.drawdown_halted = true;
}
}
fn record(&mut self, input: &RiskInput, outcome: &RiskOutcome) {
self.commands
.insert(input.id().clone(), self.receipts.len());
self.receipts.push(RiskReceipt {
input: input.clone(),
outcome: outcome.clone(),
});
}
fn apply_input(&mut self, input: &RiskInput) -> Result<RiskOutcome, RiskError> {
if let Some(index) = self.commands.get(input.id()) {
let receipt = &self.receipts[*index];
if receipt.input != *input {
return Err(RiskError::CommandConflict);
}
let mut outcome = receipt.outcome.clone();
outcome.replayed = true;
return Ok(outcome);
}
if let RiskInput::Engine(RiskCommand {
body: RiskCommandBody::Fill { fill_id, .. },
..
}) = input
{
if let Some(index) = self.fills.get(fill_id) {
let receipt = &self.receipts[*index];
let RiskInput::Engine(original) = &receipt.input else {
unreachable!()
};
let RiskInput::Engine(command) = input else {
unreachable!()
};
if original.body != command.body || original.event_time != command.event_time {
return Err(RiskError::FillConflict);
}
let mut outcome = receipt.outcome.clone();
outcome.replayed = true;
self.record(input, &outcome);
return Ok(outcome);
}
}
if input.time().get() < self.state.last_event_time.get() {
return Err(RiskError::BackdatedCommand);
}
let revision =
Counter::try_from(self.revision.get() + 1).map_err(|_| RiskError::RevisionOverflow)?;
let mut outcome = RiskOutcome {
replayed: false,
revision,
disposition: RiskDisposition::Accepted,
financial: None,
remaining: None,
released_order: None,
reset_baseline: None,
};
match input {
RiskInput::Operator(_) => {
self.fresh_all(input.time())
.map_err(|_| RiskError::InvalidResetMarks)?;
let equity = self.ledger.equity()?;
self.state.daily_baseline = nn(equity);
self.state.peak_equity = nn(equity);
self.state.daily_halted = false;
self.state.drawdown_halted = false;
outcome.reset_baseline = Some(nn(equity));
}
RiskInput::Engine(command) => match &command.body {
RiskCommandBody::Admit { order } => {
if !self
.config
.ledger
.owner_ids
.contains(&order.decision.owner_id)
{
return Err(RiskError::WrongOwner);
}
if self.orders.contains_key(&order.order_id) {
return Err(RiskError::OrderConflict);
}
match self.reservation(order, command.event_time)? {
Ok(reservation) => {
let cash = self.reserved_cash.checked_add(reservation.cash.into())?;
outcome.remaining = Some(reservation.clone());
self.pending.insert(order.order_id.clone(), reservation);
self.reserved_cash = cash;
}
Err(reason) => outcome.disposition = RiskDisposition::Rejected(reason),
}
self.orders.insert(order.order_id.clone(), order.clone());
}
RiskCommandBody::Release {
owner_id, order_id, ..
} => {
let order = self.orders.get(order_id).ok_or(RiskError::OrderConflict)?;
if order.decision.owner_id != *owner_id {
return Err(RiskError::WrongOwner);
}
if let Some(r) = self.pending.get(order_id) {
let cash = self.reserved_cash.checked_sub(r.cash.into())?;
self.pending.remove(order_id);
self.reserved_cash = cash;
outcome.released_order = Some(order_id.clone());
}
}
RiskCommandBody::Mark {
instrument_id,
price,
observed_at,
} => {
if observed_at.get() > command.event_time.get()
|| self
.ledger
.mark(instrument_id)
.is_some_and(|m| observed_at.get() < m.event_time.get())
{
return Err(RiskError::InvalidMarkTime);
}
outcome.financial = Some(self.ledger.apply(&self.financial(
&command.command_id,
*observed_at,
EngineCommandBody::Mark {
instrument_id: instrument_id.clone(),
price: *price,
},
))?);
self.observe_equity();
}
RiskCommandBody::RiskSessionBoundary { risk_session } => {
if *risk_session != self.state.risk_session
&& risk_session.starts_at != command.event_time
{
return Err(RiskError::InvalidBoundaryTime);
}
let equity = self.ledger.equity()?;
let changed = *risk_session != self.state.risk_session;
outcome.financial = Some(self.ledger.apply(&self.financial(
&command.command_id,
command.event_time,
EngineCommandBody::RiskSessionBoundary {
risk_session: risk_session.clone(),
},
))?);
if changed {
self.state.risk_session = risk_session.clone();
self.state.daily_baseline = nn(equity);
self.state.daily_halted = false;
}
}
RiskCommandBody::Fill {
order_id,
fill_id,
fee_id,
quantity,
price,
} => {
if !self.orders.contains_key(order_id) {
return Err(RiskError::OrderConflict);
}
if self.fees.contains_key(fee_id) {
return Err(RiskError::FeeConflict);
}
let Some(reservation) = self.pending.get(order_id).cloned() else {
outcome.disposition =
RiskDisposition::Rejected(RiskRejection::InactiveOrder);
self.finish_fill(input, &outcome, fill_id, fee_id);
return Ok(outcome);
};
if Posting::from(*quantity) > reservation.remaining.into() {
return Err(RiskError::ExcessFill);
}
let remainder =
Posting::from(reservation.remaining).checked_sub((*quantity).into())?;
let other_cash = self.reserved_cash.checked_sub(reservation.cash.into())?;
let fee = self.fee((*quantity).into(), (*price).into())?;
let mut next = None;
let mut rejected = None;
if reservation.order.side == Side::Buy {
let mark = match self
.fresh(&reservation.order.instrument_id, command.event_time)
{
Ok(mark) => Posting::from(mark),
Err(reason) => {
rejected = Some(reason);
Posting::ZERO
}
};
let reserve_price = pos(Posting::from(*price)
.max(mark)
.max(reservation.price.expect("buy price").into()));
if !remainder.is_zero() {
next = Some(Reservation {
remaining: pos(remainder),
cash: nn(self.cash_for(remainder, reserve_price.into())?),
price: Some(reserve_price),
..reservation.clone()
});
}
let cost = self.cash_for((*quantity).into(), (*price).into())?;
let needed = Posting::sum([
other_cash,
cost,
next.as_ref()
.map(|r| r.cash.into())
.unwrap_or(Posting::ZERO),
])?;
if needed > self.ledger.cash() {
rejected = Some(RiskRejection::InsufficientCash);
}
if rejected.is_none() {
let all_remaining = Reservation {
price: Some(reserve_price),
..reservation.clone()
};
rejected =
self.increase_check(&all_remaining, command.event_time, true)?;
}
} else if !remainder.is_zero() {
next = Some(Reservation {
remaining: pos(remainder),
..reservation.clone()
});
}
let reserved_cash = if rejected.is_some() {
other_cash
} else {
other_cash.checked_add(
next.as_ref()
.map(|r| r.cash.into())
.unwrap_or(Posting::ZERO),
)?
};
if let Some(reason) = rejected {
outcome.disposition = RiskDisposition::Rejected(reason);
outcome.released_order = Some(order_id.clone());
} else {
outcome.financial = Some(self.ledger.apply(&self.financial(
&command.command_id,
command.event_time,
EngineCommandBody::ApplyFill {
decision: reservation.order.decision.clone(),
order_id: order_id.clone(),
fill_id: fill_id.clone(),
instrument_id: reservation.order.instrument_id.clone(),
side: reservation.order.side,
quantity: *quantity,
price: *price,
fee: Fee {
fee_id: fee_id.clone(),
amount: nn(fee),
},
},
))?);
outcome.remaining = next.clone();
self.observe_equity();
}
self.pending.remove(order_id);
if rejected.is_none() {
if let Some(r) = next {
self.pending.insert(order_id.clone(), r);
}
}
self.reserved_cash = reserved_cash;
self.finish_fill(input, &outcome, fill_id, fee_id);
return Ok(outcome);
}
},
}
self.revision = revision;
self.state.last_event_time = input.time();
self.record(input, &outcome);
Ok(outcome)
}
fn finish_fill(&mut self, input: &RiskInput, outcome: &RiskOutcome, fill_id: &Id, fee_id: &Id) {
self.fills.insert(fill_id.clone(), self.receipts.len());
self.fees.insert(fee_id.clone(), fill_id.clone());
self.revision = outcome.revision;
self.state.last_event_time = input.time();
self.record(input, outcome);
}
pub fn checkpoint(&self) -> RiskCheckpoint {
RiskCheckpoint {
version: Version,
config: self.config.clone(),
ledger: self.ledger.checkpoint(),
revision: self.revision,
state: self.state.clone(),
reservations: self.pending.values().cloned().collect(),
receipts: self.receipts.clone(),
}
}
/// Restoring issues a new instance capability; the previous account's
/// capability cannot authorize operations on this restored instance.
pub fn restore(checkpoint: RiskCheckpoint) -> Result<(Self, OperatorAuthority), RiskError> {
let (mut account, authority) =
Self::new(checkpoint.config.clone()).map_err(|_| RiskError::InvalidCheckpoint)?;
for receipt in &checkpoint.receipts {
let outcome = account
.apply_input(&receipt.input)
.map_err(|_| RiskError::InvalidCheckpoint)?;
if outcome != receipt.outcome {
return Err(RiskError::InvalidCheckpoint);
}
}
if account.checkpoint() != checkpoint {
return Err(RiskError::InvalidCheckpoint);
}
Ok((account, authority))
}
}

View file

@ -0,0 +1,884 @@
use super::{
contract::*,
ledger::LedgerError,
risk::*,
scalar::{Posting, ScalarError, MAX_POSTING},
};
use serde_json::json;
use std::time::Instant;
fn p(v: &str) -> Posting {
v.parse().unwrap()
}
fn id(v: &str) -> Id {
serde_json::from_value(json!(v)).unwrap()
}
fn positive(v: &str) -> Positive {
p(v).try_into().unwrap()
}
fn time(v: i64) -> EventTime {
v.try_into().unwrap()
}
fn config(capital: &str) -> RiskConfig {
serde_json::from_value(json!({
"ledger":{"version":1,"sessionId":"run","accountId":"account","baseCurrency":"USD",
"reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":capital,
"riskSession":{"calendarId":"account-calendar","calendarRevision":"v1","sessionId":"day1","startsAt":0}},
"feeRate":"0","maxOrderQuantity":"1000000","maxPositionQuantity":"1000000",
"maxSymbolExposure":"1000000","maxGrossExposure":"1000000","maxDailyLoss":"1000000",
"maxDrawdownAmount":"1000000","maxMarkAgeMs":100
})).unwrap()
}
fn account(capital: &str) -> RiskAccount {
RiskAccount::new(config(capital)).unwrap().0
}
fn cmd(key: &str, t: i64, body: RiskCommandBody) -> RiskCommand {
RiskCommand {
command_id: id(key),
event_time: time(t),
body,
}
}
fn mark_command(key: &str, instrument: &str, price: &str, t: i64, observed: i64) -> RiskCommand {
cmd(
key,
t,
RiskCommandBody::Mark {
instrument_id: id(instrument),
price: positive(price),
observed_at: time(observed),
},
)
}
fn mark(a: &mut RiskAccount, key: &str, instrument: &str, price: &str, t: i64) {
accepted(
a.apply(&mark_command(key, instrument, price, t, t))
.unwrap(),
);
}
fn order(key: &str, owner: &str, instrument: &str, side: Side, quantity: &str) -> RiskOrder {
RiskOrder {
order_id: id(key),
decision: DecisionIdentity {
owner_id: id(owner),
decision_id: id(&format!("decision-{key}")),
sequence: 0.try_into().unwrap(),
},
instrument_id: id(instrument),
side,
quantity: positive(quantity),
limit_price: None,
origin: OrderOrigin::Explicit,
}
}
fn admit_command(o: RiskOrder, t: i64) -> RiskCommand {
cmd(
&format!("admit-{}", serde_json::to_string(&o.order_id).unwrap()),
t,
RiskCommandBody::Admit { order: o },
)
}
fn admit(a: &mut RiskAccount, o: RiskOrder, t: i64) -> RiskOutcome {
a.apply(&admit_command(o, t)).unwrap()
}
fn fill_command(order: &str, fill: &str, quantity: &str, price: &str, t: i64) -> RiskCommand {
cmd(
fill,
t,
RiskCommandBody::Fill {
order_id: id(order),
fill_id: id(fill),
fee_id: id(&format!("fee-{fill}")),
quantity: positive(quantity),
price: positive(price),
},
)
}
fn fill(
a: &mut RiskAccount,
order: &str,
key: &str,
quantity: &str,
price: &str,
t: i64,
) -> RiskOutcome {
a.apply(&fill_command(order, key, quantity, price, t))
.unwrap()
}
fn release(
a: &mut RiskAccount,
key: &str,
order: &str,
owner: &str,
reason: ReleaseReason,
t: i64,
) -> RiskOutcome {
a.apply(&cmd(
key,
t,
RiskCommandBody::Release {
owner_id: id(owner),
order_id: id(order),
reason,
},
))
.unwrap()
}
fn accepted(out: RiskOutcome) {
assert_eq!(out.disposition, RiskDisposition::Accepted);
}
fn rejected(out: RiskOutcome, reason: RiskRejection) {
assert_eq!(out.disposition, RiskDisposition::Rejected(reason));
}
fn unchanged(a: &mut RiskAccount, c: &RiskCommand, error: RiskError) {
let before = a.checkpoint();
assert_eq!(a.apply(c), Err(error));
assert_eq!(a.checkpoint(), before);
}
fn buy(
a: &mut RiskAccount,
key: &str,
owner: &str,
instrument: &str,
quantity: &str,
price: &str,
t: i64,
) {
accepted(admit(
a,
order(key, owner, instrument, Side::Buy, quantity),
t,
));
accepted(fill(a, key, &format!("fill-{key}"), quantity, price, t));
}
fn boundary(key: &str, session: &str, starts: i64, t: i64) -> RiskCommand {
cmd(
key,
t,
RiskCommandBody::RiskSessionBoundary {
risk_session: RiskSessionIdentity {
calendar_id: id("account-calendar"),
calendar_revision: id("v1"),
session_id: id(session),
starts_at: time(starts),
},
},
)
}
fn reset(key: &str, t: i64) -> OperatorReset {
OperatorReset {
command_id: id(key),
event_time: time(t),
actor_id: id("operator"),
reason: id("reviewed incident"),
}
}
fn reconcile(a: &RiskAccount) {
let value = a.ledger().valuation().unwrap();
assert_eq!(
value.equity,
value.cash.checked_add(value.marked_holdings).unwrap()
);
let reserved = Posting::sum(a.reservations().map(|r| r.cash.into())).unwrap();
assert_eq!(
a.available_cash().checked_add(reserved).unwrap(),
value.cash
);
assert!(!a.available_cash().is_negative());
assert_eq!(
value.equity,
Posting::sum(value.owners.iter().map(|o| o.equity_contribution)).unwrap()
);
}
#[test]
fn competing_reservations_and_all_release_reasons() {
let mut c = config("100");
c.fee_rate = p("0.01").try_into().unwrap();
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "10", 0);
accepted(admit(&mut a, order("one", "A", "X", Side::Buy, "6"), 0));
assert_eq!(a.available_cash(), p("39.4"));
rejected(
admit(&mut a, order("two", "B", "X", Side::Buy, "4"), 0),
RiskRejection::InsufficientCash,
);
assert_eq!(a.reservations().count(), 1);
accepted(fill(&mut a, "one", "part", "2", "10", 1));
assert_eq!(
a.reservations().next().unwrap().cash,
p("40.4").try_into().unwrap()
);
assert_eq!(a.available_cash(), p("39.4"));
accepted(release(
&mut a,
"cancel",
"one",
"A",
ReleaseReason::Cancelled,
1,
));
assert_eq!(a.available_cash(), p("79.8"));
for (i, reason) in [ReleaseReason::Rejected, ReleaseReason::Expired]
.into_iter()
.enumerate()
{
let oid = format!("later-{i}");
accepted(admit(&mut a, order(&oid, "A", "X", Side::Buy, "1"), 1));
accepted(release(
&mut a,
&format!("release-{i}"),
&oid,
"A",
reason,
1,
));
}
assert_eq!(a.reservations().count(), 0);
reconcile(&a);
}
#[test]
fn adverse_gap_reject_remainder_preserves_prior_fills_and_receipts() {
let mut a = account("100");
mark(&mut a, "m", "X", "10", 0);
accepted(admit(&mut a, order("o", "A", "X", Side::Buy, "10"), 0));
accepted(fill(&mut a, "o", "first", "2", "10", 1));
let command = fill_command("o", "gap", "2", "11", 2);
let outcome = a.apply(&command).unwrap();
rejected(outcome.clone(), RiskRejection::InsufficientCash);
assert_eq!(outcome.released_order, Some(id("o")));
assert!(outcome.financial.is_none());
assert_eq!(a.ledger().cash(), p("80"));
assert_eq!(a.ledger().owner_quantity(&id("A"), &id("X")), p("2"));
assert_eq!(a.reservations().count(), 0);
let checkpoint = a.checkpoint();
let mut retry = outcome.clone();
retry.replayed = true;
assert_eq!(a.apply(&command).unwrap(), retry);
assert_eq!(a.checkpoint(), checkpoint);
let mut alias = command.clone();
alias.command_id = id("gap-alias");
assert_eq!(a.apply(&alias).unwrap(), retry);
assert_eq!(a.ledger().cash(), p("80"));
let mut restored = RiskAccount::restore(a.checkpoint()).unwrap().0;
assert_eq!(restored.apply(&alias).unwrap(), retry);
reconcile(&restored);
}
#[test]
fn stale_other_symbol_and_other_pending_symbol_block_increases_not_reductions() {
for pending_only in [false, true] {
let mut a = account("1000");
mark(&mut a, "mx", "X", "10", 0);
accepted(admit(&mut a, order("old", "A", "X", Side::Buy, "1"), 0));
if !pending_only {
accepted(fill(&mut a, "old", "old-fill", "1", "10", 0));
}
mark(&mut a, "my", "Y", "10", 101);
rejected(
admit(&mut a, order("new", "B", "Y", Side::Buy, "1"), 101),
RiskRejection::StaleMark,
);
if !pending_only {
accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "1"), 101));
accepted(fill(&mut a, "sell", "sell-fill", "1", "9", 101));
}
reconcile(&a);
}
}
#[test]
fn delayed_mark_is_not_freshened_and_future_or_backdated_time_is_atomic() {
let mut a = account("100");
accepted(
a.apply(&mark_command("delayed", "X", "10", 101, 0))
.unwrap(),
);
assert_eq!(a.ledger().mark(&id("X")).unwrap().event_time, time(0));
rejected(
admit(&mut a, order("o", "A", "X", Side::Buy, "1"), 101),
RiskRejection::StaleMark,
);
unchanged(
&mut a,
&mark_command("future", "Y", "10", 101, 102),
RiskError::InvalidMarkTime,
);
unchanged(
&mut a,
&mark_command("backdated", "Y", "10", 100, 100),
RiskError::BackdatedCommand,
);
unchanged(
&mut a,
&mark_command("older", "X", "10", 101, -1),
RiskError::InvalidMarkTime,
);
}
#[test]
fn marked_loss_halt_and_explicit_risk_session_boundary() {
let mut c = config("100");
c.max_daily_loss = positive("10");
c.max_drawdown_amount = positive("50");
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "10", 0);
buy(&mut a, "buy", "A", "X", "5", "10", 0);
mark(&mut a, "loss", "X", "8", 1);
assert_eq!(a.ledger().valuation().unwrap().realized_gross_pnl, p("0"));
assert!(a.state().daily_halted);
rejected(
admit(&mut a, order("halted", "A", "X", Side::Buy, "1"), 1),
RiskRejection::DailyLoss,
);
accepted(a.apply(&boundary("same", "day1", 0, 1)).unwrap());
assert!(a.state().daily_halted);
mark(&mut a, "recover", "X", "10", 2);
assert!(a.state().daily_halted);
accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "1"), 2));
accepted(fill(&mut a, "sell", "sell-fill", "1", "10", 2));
accepted(a.apply(&boundary("next", "day2", 3, 3)).unwrap());
assert!(!a.state().daily_halted);
assert_eq!(a.state().daily_baseline, p("100").try_into().unwrap());
accepted(admit(&mut a, order("after", "A", "X", Side::Buy, "1"), 3));
reconcile(&a);
}
#[test]
fn drawdown_halt_survives_rollover_restore_and_requires_authorized_reset() {
let mut c = config("100");
c.max_drawdown_amount = positive("10");
let (mut a, authority) = RiskAccount::new(c).unwrap();
mark(&mut a, "m", "X", "10", 0);
buy(&mut a, "buy", "A", "X", "5", "10", 0);
mark(&mut a, "peak", "X", "12", 1);
mark(&mut a, "loss", "X", "10", 2);
assert!(a.state().drawdown_halted);
accepted(a.apply(&boundary("next", "day2", 3, 3)).unwrap());
assert_eq!(a.state().peak_equity, p("110").try_into().unwrap());
let (mut restored, restored_authority) = RiskAccount::restore(a.checkpoint()).unwrap();
assert!(restored.state().drawdown_halted);
rejected(
admit(&mut restored, order("halted", "A", "X", Side::Buy, "1"), 3),
RiskRejection::Drawdown,
);
let before = restored.checkpoint();
assert_eq!(
restored.reset(&authority, &reset("bad", 3)),
Err(RiskError::UnauthorizedReset)
);
assert_eq!(restored.checkpoint(), before);
let outcome = restored
.reset(&restored_authority, &reset("reset", 3))
.unwrap();
assert_eq!(outcome.reset_baseline, Some(p("100").try_into().unwrap()));
assert!(!restored.state().drawdown_halted);
assert!(!restored.state().daily_halted);
assert_eq!(restored.state().peak_equity, p("100").try_into().unwrap());
assert_eq!(
RiskAccount::restore(restored.checkpoint())
.unwrap()
.0
.checkpoint(),
restored.checkpoint()
);
}
#[test]
fn unauthorized_reset_denied_and_not_deserializable_as_engine_command() {
let (mut a, _) = RiskAccount::new(config("100")).unwrap();
let (_, wrong_authority) = RiskAccount::new(config("100")).unwrap();
let before = a.checkpoint();
assert_eq!(
a.reset(&wrong_authority, &reset("unauthorized", 0)),
Err(RiskError::UnauthorizedReset)
);
assert_eq!(a.checkpoint(), before);
assert!(serde_json::from_value::<RiskCommandBody>(
json!({"kind":"reset","actorId":"operator"})
)
.is_err());
}
#[test]
fn alternate_venue_does_not_reset_account_day_and_invalid_boundaries_are_atomic() {
let mut a = account("100");
mark(&mut a, "m", "X", "10", 10);
let mut venue = boundary("venue", "day2", 10, 10);
if let RiskCommandBody::RiskSessionBoundary { risk_session } = &mut venue.body {
risk_session.calendar_id = id("another-venue");
}
unchanged(
&mut a,
&venue,
RiskError::Ledger(LedgerError::InvalidRiskSession),
);
unchanged(
&mut a,
&boundary("future", "day2", 11, 10),
RiskError::InvalidBoundaryTime,
);
unchanged(
&mut a,
&boundary("past", "day2", 9, 10),
RiskError::InvalidBoundaryTime,
);
unchanged(
&mut a,
&boundary("changed-start", "day1", 10, 10),
RiskError::Ledger(LedgerError::InvalidRiskSession),
);
}
#[test]
fn inventory_reservations_wrong_owner_and_zero_cash_sell() {
let mut c = config("110");
c.fee_rate = p("0.1").try_into().unwrap();
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "10", 0);
buy(&mut a, "buy", "A", "X", "10", "10", 0);
assert_eq!(a.ledger().cash(), p("0"));
rejected(
admit(&mut a, order("steal", "B", "X", Side::Sell, "1"), 0),
RiskRejection::InsufficientInventory,
);
accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "6"), 101));
rejected(
admit(&mut a, order("oversell", "A", "X", Side::Sell, "5"), 101),
RiskRejection::InsufficientInventory,
);
unchanged(
&mut a,
&cmd(
"steal-cancel",
101,
RiskCommandBody::Release {
owner_id: id("B"),
order_id: id("sell"),
reason: ReleaseReason::Cancelled,
},
),
RiskError::WrongOwner,
);
accepted(fill(&mut a, "sell", "sell-fill", "2", "10", 101));
assert_eq!(a.ledger().cash(), p("18"));
accepted(release(
&mut a,
"release",
"sell",
"A",
ReleaseReason::Expired,
101,
));
accepted(admit(&mut a, order("rest", "A", "X", Side::Sell, "8"), 101));
accepted(fill(&mut a, "rest", "rest-fill", "8", "10", 101));
assert_eq!(a.ledger().cash(), p("90"));
reconcile(&a);
}
#[test]
fn pending_sells_never_fund_buys_or_reduce_exposure_and_fill_price_is_checked() {
let mut c = config("200");
c.max_gross_exposure = positive("100");
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "mx", "X", "10", 0);
mark(&mut a, "my", "Y", "10", 0);
buy(&mut a, "buy", "A", "X", "10", "10", 0);
accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "10"), 0));
rejected(
admit(&mut a, order("new", "B", "Y", Side::Buy, "1"), 0),
RiskRejection::GrossExposure,
);
let mut b = account("100");
mark(&mut b, "m", "X", "10", 0);
buy(&mut b, "buy", "A", "X", "10", "10", 0);
accepted(admit(&mut b, order("sell", "A", "X", Side::Sell, "10"), 0));
rejected(
admit(&mut b, order("fund", "B", "X", Side::Buy, "1"), 0),
RiskRejection::InsufficientCash,
);
let mut c = config("1000");
c.max_symbol_exposure = positive("100");
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "10", 0);
accepted(admit(&mut a, order("o", "A", "X", Side::Buy, "10"), 0));
rejected(
fill(&mut a, "o", "gap", "1", "11", 1),
RiskRejection::SymbolExposure,
);
assert_eq!(a.ledger().cash(), p("1000"));
assert_eq!(a.reservations().count(), 0);
}
#[test]
fn fee_is_rounded_once_and_quantum_partial_fill_cannot_leave_unfunded_remainder() {
let mut c = config("0.00000001");
c.fee_rate = p("0.5").try_into().unwrap();
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "0.5", 0);
buy(&mut a, "buy", "A", "X", "0.00000001", "0.5", 0);
assert_eq!(a.ledger().cash(), p("0"));
assert_eq!(a.ledger().valuation().unwrap().fees, p("0"));
let mut a = account("0.00000001");
mark(&mut a, "m", "X", "0.5", 0);
accepted(admit(
&mut a,
order("o", "A", "X", Side::Buy, "0.00000002"),
0,
));
rejected(
fill(&mut a, "o", "split", "0.00000001", "0.5", 0),
RiskRejection::InsufficientCash,
);
assert_eq!(a.ledger().cash(), p("0.00000001"));
assert_eq!(a.reservations().count(), 0);
reconcile(&a);
}
#[test]
fn exposure_respects_owner_rounding_and_combined_pending_quantities() {
let mut c = config("1");
c.max_gross_exposure = positive("0.00000002");
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "0.5", 0);
buy(&mut a, "a", "A", "X", "0.00000001", "0.5", 0);
buy(&mut a, "b", "B", "X", "0.00000001", "0.5", 0);
assert_eq!(
a.ledger().valuation().unwrap().marked_holdings,
p("0.00000002")
);
rejected(
admit(&mut a, order("c", "A", "X", Side::Buy, "0.00000002"), 0),
RiskRejection::GrossExposure,
);
let mut c = config("1");
c.max_symbol_exposure = positive("0.00000001");
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "0.49", 0);
buy(&mut a, "existing", "A", "X", "0.00000003", "0.49", 0);
rejected(
admit(
&mut a,
order("candidate", "A", "X", Side::Buy, "0.00000001"),
0,
),
RiskRejection::SymbolExposure,
);
let mut c = config("1");
c.max_symbol_exposure = positive("0.00000001");
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "0.49", 0);
accepted(admit(
&mut a,
order("pending", "A", "X", Side::Buy, "0.00000003"),
0,
));
rejected(
admit(
&mut a,
order("candidate", "A", "X", Side::Buy, "0.00000001"),
0,
),
RiskRejection::SymbolExposure,
);
}
#[test]
fn duplicate_accepted_rejected_and_conflicting_ids_preserve_state() {
let mut a = account("100");
mark(&mut a, "m", "X", "10", 0);
for (key, quantity) in [("good", "1"), ("bad", "100")] {
let command = admit_command(order(key, "A", "X", Side::Buy, quantity), 0);
let mut expected = a.apply(&command).unwrap();
expected.replayed = true;
let checkpoint = a.checkpoint();
assert_eq!(a.apply(&command).unwrap(), expected);
assert_eq!(a.checkpoint(), checkpoint);
let mut conflicting = command.clone();
conflicting.event_time = time(1);
unchanged(&mut a, &conflicting, RiskError::CommandConflict);
conflicting.command_id = id(&format!("new-{key}"));
unchanged(&mut a, &conflicting, RiskError::OrderConflict);
}
let fill = fill_command("good", "fill", "1", "10", 0);
let mut expected = a.apply(&fill).unwrap();
expected.replayed = true;
let mut alias = fill.clone();
alias.command_id = id("alias");
assert_eq!(a.apply(&alias).unwrap(), expected);
let mut conflict = alias.clone();
conflict.command_id = id("conflict");
conflict.event_time = time(1);
unchanged(&mut a, &conflict, RiskError::FillConflict);
accepted(admit(&mut a, order("later", "A", "X", Side::Buy, "1"), 0));
let mut fee_conflict = fill_command("later", "later-fill", "1", "10", 0);
if let RiskCommandBody::Fill { fee_id, .. } = &mut fee_conflict.body {
*fee_id = id("fee-fill");
}
unchanged(&mut a, &fee_conflict, RiskError::FeeConflict);
unchanged(
&mut a,
&fill_command("unreserved", "bypass", "1", "10", 0),
RiskError::OrderConflict,
);
unchanged(
&mut a,
&fill_command("later", "too-big", "2", "10", 0),
RiskError::ExcessFill,
);
reconcile(&a);
}
#[test]
fn replay_after_clock_advance_returns_original_receipt_without_republishing() {
let mut a = account("100");
mark(&mut a, "m", "X", "10", 0);
let rejected_command = admit_command(order("bad", "A", "X", Side::Buy, "100"), 0);
let mut rejected_outcome = a.apply(&rejected_command).unwrap();
rejected_outcome.replayed = true;
accepted(admit(&mut a, order("good", "A", "X", Side::Buy, "1"), 0));
let fill = fill_command("good", "filled", "1", "10", 0);
let mut outcome = a.apply(&fill).unwrap();
outcome.replayed = true;
assert!(!outcome.financial.as_ref().unwrap().replayed);
mark(&mut a, "later-mark", "X", "11", 10);
let before = a.checkpoint();
assert_eq!(a.apply(&rejected_command).unwrap(), rejected_outcome);
assert_eq!(a.apply(&fill).unwrap(), outcome);
assert_eq!(a.checkpoint(), before);
let mut alias = fill.clone();
alias.command_id = id("later-alias");
assert_eq!(a.apply(&alias).unwrap(), outcome);
assert_eq!(a.state().last_event_time, time(10));
assert_eq!(a.checkpoint().revision, before.revision);
assert_eq!(a.ledger().checkpoint(), before.ledger);
let mut restored = RiskAccount::restore(a.checkpoint()).unwrap().0;
let checkpoint = restored.checkpoint();
assert_eq!(restored.apply(&alias).unwrap(), outcome);
assert_eq!(restored.checkpoint(), checkpoint);
}
#[test]
fn quantity_limits_limit_reservations_and_pending_mark_repricing() {
let mut c = config("1000");
c.max_order_quantity = positive("2");
c.max_position_quantity = positive("3");
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "10", 0);
rejected(
admit(&mut a, order("large", "A", "X", Side::Buy, "3"), 0),
RiskRejection::OrderSize,
);
accepted(admit(&mut a, order("a", "A", "X", Side::Buy, "2"), 0));
rejected(
admit(&mut a, order("b", "B", "X", Side::Buy, "2"), 0),
RiskRejection::PositionSize,
);
accepted(fill(&mut a, "a", "fill-a", "2", "10", 0));
rejected(
admit(&mut a, order("sell-large", "A", "X", Side::Sell, "3"), 0),
RiskRejection::OrderSize,
);
let mut c = config("1000");
c.max_gross_exposure = positive("100");
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "mx", "X", "10", 0);
mark(&mut a, "my", "Y", "10", 0);
let mut limit = order("limit", "A", "X", Side::Buy, "5");
limit.limit_price = Some(positive("11"));
accepted(admit(&mut a, limit, 0));
assert_eq!(a.available_cash(), p("945"));
mark(&mut a, "up", "X", "20", 1);
// The pending reservation remains funded at its admitted price, but risk
// exposure revalues the open commitment at the new canonical mark.
assert_eq!(a.available_cash(), p("945"));
rejected(
admit(&mut a, order("new", "B", "Y", Side::Buy, "1"), 1),
RiskRejection::GrossExposure,
);
// Limit crossing remains F05's job; F04's fill rejection here is freshness.
rejected(
fill(&mut a, "limit", "stale", "1", "10", 102),
RiskRejection::StaleMark,
);
assert_eq!(a.reservations().count(), 0);
reconcile(&a);
}
#[test]
fn checkpoint_tamper_is_rejected_and_replay_is_byte_identical() {
let (mut a, authority) = RiskAccount::new(config("100")).unwrap();
mark(&mut a, "m", "X", "10", 0);
accepted(admit(&mut a, order("o", "A", "X", Side::Buy, "5"), 0));
accepted(fill(&mut a, "o", "part", "2", "10", 1));
accepted(a.reset(&authority, &reset("reset", 1)).unwrap());
let checkpoint = a.checkpoint();
let encoded = serde_json::to_vec(&checkpoint).unwrap();
let restored = RiskAccount::restore(serde_json::from_slice(&encoded).unwrap())
.unwrap()
.0;
assert_eq!(serde_json::to_vec(&restored.checkpoint()).unwrap(), encoded);
for variant in 0..8 {
let mut changed = checkpoint.clone();
match variant {
0 => changed.state.drawdown_halted = true,
1 => changed.reservations[0].cash = p("1").try_into().unwrap(),
2 => changed.state.last_event_time = time(999),
3 => {
changed.receipts[1].outcome.disposition =
RiskDisposition::Rejected(RiskRejection::DailyLoss)
}
4 => changed.receipts.swap(0, 1),
5 => changed.state.daily_baseline = p("99").try_into().unwrap(),
6 => changed.ledger.economic.cash = p("99").try_into().unwrap(),
_ => {
changed.receipts.last_mut().unwrap().outcome.reset_baseline =
Some(p("99").try_into().unwrap())
}
}
assert!(matches!(
RiskAccount::restore(changed),
Err(RiskError::InvalidCheckpoint)
));
}
}
#[test]
fn malformed_limits_overflow_and_failed_marks_are_atomic() {
let mut invalid = config("100");
invalid.fee_rate = p("1.00000001").try_into().unwrap();
assert!(matches!(
RiskAccount::new(invalid),
Err(RiskError::InvalidFeeRate)
));
let mut a = account("100");
mark(&mut a, "m", "X", "1", 0);
buy(&mut a, "a", "A", "X", "1", "1", 0);
buy(&mut a, "b", "B", "X", "2", "1", 0);
unchanged(
&mut a,
&mark_command("overflow", "X", MAX_POSTING, 1, 1),
RiskError::Ledger(LedgerError::Arithmetic(ScalarError::Overflow)),
);
let mut c = config(MAX_POSTING);
c.max_order_quantity = positive(MAX_POSTING);
c.max_position_quantity = positive(MAX_POSTING);
c.max_symbol_exposure = positive(MAX_POSTING);
c.max_gross_exposure = positive(MAX_POSTING);
let mut a = RiskAccount::new(c).unwrap().0;
mark(&mut a, "m", "X", "0.00000001", 0);
accepted(admit(
&mut a,
order("large", "A", "X", Side::Buy, MAX_POSTING),
0,
));
unchanged(
&mut a,
&admit_command(order("more", "A", "X", Side::Buy, "1"), 0),
RiskError::Arithmetic(ScalarError::Overflow),
);
// Unrepresentable arithmetic is an atomic command error, not an ordinary
// affordable-range risk rejection. The host must fail the unsupported
// attempt rather than silently borrowing, resizing or retrying forever.
unchanged(
&mut a,
&fill_command("large", "overflow-fill", MAX_POSTING, "2", 1),
RiskError::Arithmetic(ScalarError::Overflow),
);
}
#[test]
fn raw_order_and_target_normalization_cannot_bypass_identical_policy() {
// Exhaustive bounded parameter property, including fee/cash rejection and
// fill gaps. The actual target expansion/mode coordinator belongs to F05.
for capital in 1..=12 {
for quantity in 1..=15 {
let mut c = config(&capital.to_string());
c.fee_rate = p("0.1").try_into().unwrap();
let mut explicit = RiskAccount::new(c.clone()).unwrap().0;
let mut target = RiskAccount::new(c).unwrap().0;
for a in [&mut explicit, &mut target] {
mark(a, "m", "X", "1", 0);
}
let original = order("o", "A", "X", Side::Buy, &quantity.to_string());
let mut normalized = original.clone();
normalized.origin = OrderOrigin::Target;
let raw = admit(&mut explicit, original, 0);
let target_out = admit(&mut target, normalized, 0);
assert_eq!(raw.disposition, target_out.disposition);
assert_eq!(explicit.available_cash(), target.available_cash());
if raw.disposition == RiskDisposition::Accepted {
let raw_fill = fill(&mut explicit, "o", "fill", &quantity.to_string(), "1.1", 1);
let target_fill = fill(&mut target, "o", "fill", &quantity.to_string(), "1.1", 1);
assert_eq!(raw_fill.disposition, target_fill.disposition);
assert_eq!(raw_fill.financial, target_fill.financial);
}
assert_eq!(explicit.ledger().checkpoint(), target.ledger().checkpoint());
reconcile(&explicit);
reconcile(&target);
}
}
}
#[test]
#[ignore = "manual release workload; no unstable timing assertion"]
fn risk_transition_measurement() {
for multi in [false, true] {
for count in [1000, 10000] {
let mut inputs = Vec::new();
for n in 0..count / 4 {
let symbol = if multi {
format!("asset-{}", n % 4)
} else {
"asset".into()
};
let owner = if multi && n % 2 == 1 { "B" } else { "A" };
let oid = format!("order-{n}");
let t = n as i64;
inputs.push(mark_command(&format!("mark-{n}"), &symbol, "10", t, t));
inputs.push(admit_command(
order(&oid, owner, &symbol, Side::Buy, "2"),
t,
));
inputs.push(fill_command(&oid, &format!("fill-{n}"), "1", "10", t));
inputs.push(cmd(
&format!("release-{n}"),
t,
RiskCommandBody::Release {
owner_id: id(owner),
order_id: id(&oid),
reason: ReleaseReason::Cancelled,
},
));
}
let mut expected = None;
for repeat in 0..3 {
let mut c = config("1000000");
c.fee_rate = p("0.01").try_into().unwrap();
let mut a = RiskAccount::new(c).unwrap().0;
let started = Instant::now();
let outcomes: Vec<_> = inputs.iter().map(|c| a.apply(c).unwrap()).collect();
let elapsed = started.elapsed();
let snap_start = Instant::now();
let checkpoint = a.checkpoint();
let snapshot_elapsed = snap_start.elapsed();
let bytes = serde_json::to_vec(&checkpoint).unwrap();
let economic_and_receipts =
serde_json::to_vec(&(checkpoint.clone(), outcomes)).unwrap();
if let Some(expected) = &expected {
assert_eq!(&economic_and_receipts, expected);
} else {
expected = Some(economic_and_receipts);
}
let restore_start = Instant::now();
let restored = RiskAccount::restore(checkpoint).unwrap().0;
let restore_elapsed = restore_start.elapsed();
assert_eq!(serde_json::to_vec(&restored.checkpoint()).unwrap(), bytes);
reconcile(&restored);
println!("risk multi={multi} commands={count} repeat={repeat} apply_us={} checkpoint_us={} restore_us={} checkpoint_bytes={} open_orders={} owners={} assets={}",
elapsed.as_micros(), snapshot_elapsed.as_micros(), restore_elapsed.as_micros(), bytes.len(), a.reservations().count(), if multi {2} else {1}, if multi {4} else {1});
}
}
}
}

View file

@ -67,6 +67,20 @@ impl Posting {
Self::rounded_units(units)
}
/// Rate-only execution fee: multiply all three exact values before the
/// single posting boundary (never charge a percentage of rounded notional).
pub(super) fn rate_fee(quantity: Self, price: Self, rate: Self) -> Result<Self, ScalarError> {
Self::rounded_units(BigRational::new(
quantity.units() * price.units() * rate.units(),
BigInt::from(10u32).pow(POSTING_SCALE * 2),
))
}
/// Quote midpoint, with one rounding boundary and no overflowing a+b.
pub(super) fn midpoint(a: Self, b: Self) -> Result<Self, ScalarError> {
Self::rounded_units(BigRational::new(a.units() + b.units(), BigInt::from(2)))
}
/// Partial disposal only: quantity is positive and <= owned quantity.
/// A final disposal deliberately bypasses division and releases residue.
pub(super) fn released_basis(