stock-bot/apps/stock/engine/src/financial/risk.rs

914 lines
35 KiB
Rust

//! Financial admission and fill-time gate between matching and the ledger.
//!
//! Orders reserve fee-inclusive cash or owner inventory before execution.
//! Actual fills recheck funding and portfolio constraints; a reservation is not
//! permission to borrow after a price gap. Marks update loss/drawdown latches.
//! The matcher owns price crossing, time-in-force and event eligibility; the
//! host owns the clock and authenticates operator actions. These Rust interfaces
//! separate responsibilities but are not an untrusted-code sandbox.
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 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 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")
}
/// Apply an engine command under the account's clock and identity rules.
/// A policy rejection is a recorded `RiskDisposition::Rejected`, not an
/// infrastructure error. Exact retries return their original receipt and do
/// not charge another fee, reserve more cash or move the clock.
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)
}
/// Buys reserve notional plus fees using fresh marks and any higher limit;
/// pending buys also consume exposure. Sells reserve only this owner's
/// uncommitted inventory, allowing reductions without passing buy-only
/// freshness and loss-halt checks. Both still obey maximum order quantity.
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))
}
/// Loss breaches latch until an explicit reset or applicable risk-session
/// boundary; a subsequent price recovery does not itself lift the halt.
/// 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 {
// Fund this fill AND the still-working remainder without
// spending other orders' reservations. A price gap may
// reject the fill and release the rest of this order.
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))
}
}