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

752 lines
27 KiB
Rust

//! Cash-funded, long-only accounting beneath the matcher and risk gate.
//!
//! One account shares cash, while each instrument holds separate owner books.
//! Fills change quantity/cost/cash; marks change valuation; fees are explicit
//! postings. No order eligibility, strategy sizing or exposure policy lives here.
//!
//! apply() stages only the affected book/owner/instrument scalars before its
//! infallible commit. Marks touch owners of that instrument, not other books.
//! Checkpoint copying and history replay occur only at explicit boundaries.
//! Invalid internal commands return errors without receipts or state changes;
//! risk-policy rejections are different, accepted/recorded outcomes upstream.
use super::{
contract::*,
scalar::{Posting, ScalarError},
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LedgerConfig {
pub version: Version,
pub session_id: Id,
pub account_id: Id,
pub base_currency: Id,
pub reserve_owner_id: Id,
pub owner_ids: Vec<Id>,
pub initial_capital: NonNegative,
pub risk_session: RiskSessionIdentity,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LedgerMark {
pub instrument_id: Id,
pub price: Positive,
pub event_time: EventTime,
pub command_id: Id,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ApplyOutcome {
/// A replay returns the ORIGINAL receipt, including original command ID,
/// event time and revision. Its deltas MUST NOT be published/applied again.
pub replayed: bool,
pub effects: FinancialEffects,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LedgerReceipt {
pub command: EngineFinancialCommand,
pub outcome: ApplyOutcome,
}
/// A restorable LEDGER checkpoint, not a complete engine/session checkpoint.
/// It contains no orders, reservations, risk limits/peaks, replay cursors,
/// strategy states or RNG. Identity indexes are reconstructed from receipts in
/// acceptance order (never lexical ID order). History is retained without
/// compaction in v1. Restore validates internal consistency, not authenticity
/// of the supplied genesis/history; durable provenance remains a caller duty.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct LedgerCheckpoint {
pub version: Version,
pub config: LedgerConfig,
pub economic: FinancialSnapshot,
pub marks: Vec<LedgerMark>,
pub receipts: Vec<LedgerReceipt>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OwnerValuation {
pub owner_id: Id,
pub initial_capital: Posting,
pub marked_holdings: Posting,
pub remaining_cost: Posting,
pub realized_gross_pnl: Posting,
pub unrealized_pnl: Posting,
pub fees: Posting,
/// Reserve capital + realized + unrealized - fees. Not a separate cash
/// wallet or allocation limit; owner contributions may be negative.
pub equity_contribution: Posting,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LedgerValuation {
pub cash: Posting,
pub marked_holdings: Posting,
pub equity: Posting,
pub remaining_cost: Posting,
pub realized_gross_pnl: Posting,
pub unrealized_pnl: Posting,
pub fees: Posting,
pub owners: Vec<OwnerValuation>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AggregatePosition {
pub instrument_id: Id,
pub quantity: Posting,
pub remaining_cost: Posting,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum LedgerError {
#[error(transparent)]
Arithmetic(#[from] ScalarError),
#[error("duplicate or reserve strategy owner in configuration")]
InvalidOwners,
#[error("command belongs to a different session/account")]
WrongScope,
#[error("command ID reused with a different payload")]
CommandConflict,
#[error("fill ID reused with a different payload or event time")]
FillConflict,
#[error("fee ID already belongs to another fill")]
FeeConflict,
#[error("order ID reused with different decision, instrument or side")]
OrderConflict,
#[error("owner is not registered or is the reserve owner")]
UnknownOwner,
#[error("owner does not have the requested inventory")]
InsufficientInventory,
#[error("cash cannot cover the fill and fee")]
InsufficientCash,
#[error("open inventory has no explicit market mark")]
MissingMark,
#[error("ledger revision exhausted safe integer range")]
RevisionOverflow,
#[error("risk session changes calendar or has an inconsistent/backward boundary")]
InvalidRiskSession,
#[error("checkpoint is inconsistent with its genesis and accepted receipts")]
InvalidCheckpoint,
}
#[derive(Debug, Clone, Copy)]
struct Book {
quantity: Posting,
cost: Posting,
realized: Posting,
}
impl Default for Book {
fn default() -> Self {
Self {
quantity: Posting::ZERO,
cost: Posting::ZERO,
realized: Posting::ZERO,
}
}
}
/// Cached aggregates are private and only changed by an accepted staged plan.
#[derive(Debug, Clone, Copy)]
struct Totals {
cost: Posting,
realized: Posting,
fees: Posting,
marked: Posting,
unmarked: usize,
}
impl Default for Totals {
fn default() -> Self {
Self {
cost: Posting::ZERO,
realized: Posting::ZERO,
fees: Posting::ZERO,
marked: Posting::ZERO,
unmarked: 0,
}
}
}
impl Totals {
fn owner_valuation(
self,
owner_id: Id,
capital: Posting,
) -> Result<OwnerValuation, LedgerError> {
if self.unmarked != 0 {
return Err(LedgerError::MissingMark);
}
let unrealized = self.marked.checked_sub(self.cost)?;
Ok(OwnerValuation {
owner_id,
initial_capital: capital,
marked_holdings: self.marked,
remaining_cost: self.cost,
realized_gross_pnl: self.realized,
unrealized_pnl: unrealized,
fees: self.fees,
equity_contribution: Posting::sum([
capital,
self.realized,
unrealized,
negative(self.fees)?,
])?,
})
}
}
#[derive(Debug)]
struct Instrument {
books: BTreeMap<Id, Book>,
mark: Option<LedgerMark>,
quantity: Posting,
cost: Posting,
marked: Posting,
}
impl Default for Instrument {
fn default() -> Self {
Self {
books: BTreeMap::new(),
mark: None,
quantity: Posting::ZERO,
cost: Posting::ZERO,
marked: Posting::ZERO,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct OrderBinding {
decision: DecisionIdentity,
instrument_id: Id,
side: Side,
}
/// Deliberately not Clone/Serialize: ordinary transitions cannot accidentally
/// copy or serialize the entire resident account/history.
#[derive(Debug)]
pub struct Ledger {
config: LedgerConfig,
cash: Posting,
revision: Counter,
risk_session: RiskSessionIdentity,
instruments: BTreeMap<Id, Instrument>,
owners: BTreeMap<Id, Totals>,
totals: Totals,
receipts: Vec<LedgerReceipt>,
commands: BTreeMap<Id, usize>,
fills: BTreeMap<Id, usize>,
fees: BTreeMap<Id, Id>,
orders: BTreeMap<Id, OrderBinding>,
}
fn negative(value: Posting) -> Result<Posting, ScalarError> {
Posting::ZERO.checked_sub(value)
}
fn nonnegative(value: Posting) -> NonNegative {
NonNegative::try_from(value)
.expect("kernel preserves nonnegative quantities, costs, cash and fees")
}
fn replace(total: Posting, old: Posting, new: Posting) -> Result<Posting, ScalarError> {
Posting::sum([total, negative(old)?, new])
}
impl Ledger {
pub fn new(mut config: LedgerConfig) -> Result<Self, LedgerError> {
config.owner_ids.sort();
if config.owner_ids.windows(2).any(|w| w[0] == w[1])
|| config.owner_ids.contains(&config.reserve_owner_id)
{
return Err(LedgerError::InvalidOwners);
}
let owners = config
.owner_ids
.iter()
.cloned()
.map(|id| (id, Totals::default()))
.collect();
Ok(Self {
cash: config.initial_capital.into(),
revision: Counter::try_from(0).expect("zero"),
risk_session: config.risk_session.clone(),
config,
owners,
instruments: BTreeMap::new(),
totals: Totals::default(),
receipts: Vec::new(),
commands: BTreeMap::new(),
fills: BTreeMap::new(),
fees: BTreeMap::new(),
orders: BTreeMap::new(),
})
}
/// Post a scoped command once. Reused command/fill IDs must retain their
/// original economic payload; exact retries return the original effects.
/// Fallible arithmetic and ownership/funding checks finish before mutation,
/// so an error leaves cash, books, revisions and receipts unchanged.
pub fn apply(&mut self, command: &EngineFinancialCommand) -> Result<ApplyOutcome, LedgerError> {
if command.session_id != self.config.session_id
|| command.account_id != self.config.account_id
{
return Err(LedgerError::WrongScope);
}
if let Some(index) = self.commands.get(&command.command_id) {
let receipt = &self.receipts[*index];
if receipt.command != *command {
return Err(LedgerError::CommandConflict);
}
let mut outcome = receipt.outcome.clone();
outcome.replayed = true;
return Ok(outcome);
}
if let EngineCommandBody::ApplyFill { fill_id, .. } = &command.body {
if let Some(index) = self.fills.get(fill_id) {
let receipt = &self.receipts[*index];
if receipt.command.body != command.body
|| receipt.command.event_time != command.event_time
{
return Err(LedgerError::FillConflict);
}
let mut outcome = receipt.outcome.clone();
outcome.replayed = true;
self.record(command, outcome.clone());
return Ok(outcome);
}
}
let revision = Counter::try_from(self.revision.get() + 1)
.map_err(|_| LedgerError::RevisionOverflow)?;
// Each method performs all fallible checks/calculations before writing.
let effects = match &command.body {
EngineCommandBody::ApplyFill { .. } => self.apply_fill(command)?,
EngineCommandBody::Mark {
instrument_id,
price,
} => self.apply_mark(command, instrument_id, *price)?,
EngineCommandBody::RiskSessionBoundary { risk_session } => {
if risk_session.calendar_id != self.config.risk_session.calendar_id
|| risk_session.calendar_revision != self.config.risk_session.calendar_revision
|| risk_session.starts_at.get() < self.risk_session.starts_at.get()
|| (risk_session.session_id == self.risk_session.session_id
&& risk_session.starts_at != self.risk_session.starts_at)
|| (risk_session.session_id != self.risk_session.session_id
&& risk_session.starts_at == self.risk_session.starts_at)
{
return Err(LedgerError::InvalidRiskSession);
}
// Identity only. RiskAccount owns baseline/peak/halt policies.
if self.risk_session == *risk_session {
Vec::new()
} else {
self.risk_session = risk_session.clone();
vec![FinancialEffect::RiskSessionChanged {
risk_session: risk_session.clone(),
}]
}
}
};
self.revision = revision;
let outcome = ApplyOutcome {
replayed: false,
effects: FinancialEffects {
version: Version,
session_id: self.config.session_id.clone(),
account_id: self.config.account_id.clone(),
command_id: command.command_id.clone(),
event_time: command.event_time,
revision,
effects,
},
};
self.record(command, outcome.clone());
Ok(outcome)
}
fn record(&mut self, command: &EngineFinancialCommand, outcome: ApplyOutcome) {
self.commands
.insert(command.command_id.clone(), self.receipts.len());
self.receipts.push(LedgerReceipt {
command: command.clone(),
outcome,
});
}
/// Stage a fill in its owner's book and update account aggregates together.
/// Sells release proportional cost basis and cannot use another owner's
/// inventory. Fees reduce shared cash separately from gross realized P&L;
/// all calculations use checked fixed-decimal postings.
fn apply_fill(
&mut self,
command: &EngineFinancialCommand,
) -> Result<Vec<FinancialEffect>, LedgerError> {
let EngineCommandBody::ApplyFill {
decision,
order_id,
fill_id,
instrument_id,
side,
quantity,
price,
fee,
} = &command.body
else {
unreachable!("fill dispatch")
};
let owner = self
.owners
.get(&decision.owner_id)
.copied()
.ok_or(LedgerError::UnknownOwner)?;
if self.fees.contains_key(&fee.fee_id) {
return Err(LedgerError::FeeConflict);
}
let binding = OrderBinding {
decision: decision.clone(),
instrument_id: instrument_id.clone(),
side: *side,
};
if self
.orders
.get(order_id)
.is_some_and(|stored| *stored != binding)
{
return Err(LedgerError::OrderConflict);
}
let instrument = self.instruments.get(instrument_id);
let old = instrument
.and_then(|i| i.books.get(&decision.owner_id))
.copied()
.unwrap_or_default();
let quantity: Posting = (*quantity).into();
let fee_amount: Posting = fee.amount.into();
let notional = Posting::notional(quantity, (*price).into())?;
let (book, cash_delta, quantity_delta, released_basis, realized) = match side {
Side::Buy => (
Book {
quantity: old.quantity.checked_add(quantity)?,
cost: old.cost.checked_add(notional)?,
realized: old.realized,
},
negative(notional)?,
quantity,
Posting::ZERO,
Posting::ZERO,
),
Side::Sell => {
if quantity > old.quantity {
return Err(LedgerError::InsufficientInventory);
}
let basis = Posting::released_basis(old.cost, quantity, old.quantity)?;
let realized = notional.checked_sub(basis)?;
(
Book {
quantity: old.quantity.checked_sub(quantity)?,
cost: old.cost.checked_sub(basis)?,
realized: old.realized.checked_add(realized)?,
},
notional,
negative(quantity)?,
basis,
realized,
)
}
};
let cash = Posting::sum([self.cash, cash_delta, negative(fee_amount)?])?;
if cash.is_negative() {
return Err(LedgerError::InsufficientCash);
}
let mark = instrument.and_then(|i| i.mark.as_ref());
let old_value = match mark {
Some(m) => Posting::notional(old.quantity, m.price.into())?,
None => Posting::ZERO,
};
let new_value = match mark {
Some(m) => Posting::notional(book.quantity, m.price.into())?,
None => Posting::ZERO,
};
let old_unmarked = usize::from(mark.is_none() && !old.quantity.is_zero());
let new_unmarked = usize::from(mark.is_none() && !book.quantity.is_zero());
let update = |totals: Totals| -> Result<Totals, LedgerError> {
Ok(Totals {
cost: replace(totals.cost, old.cost, book.cost)?,
realized: totals.realized.checked_add(realized)?,
fees: totals.fees.checked_add(fee_amount)?,
marked: replace(totals.marked, old_value, new_value)?,
unmarked: totals.unmarked - old_unmarked + new_unmarked,
})
};
let owner = update(owner)?;
let totals = update(self.totals)?;
// Even partial known holdings plus cash cannot exceed representable equity.
cash.checked_add(totals.marked)?;
if owner.unmarked == 0 {
owner.owner_valuation(decision.owner_id.clone(), Posting::ZERO)?;
}
let aggregate_quantity = replace(
instrument.map(|i| i.quantity).unwrap_or(Posting::ZERO),
old.quantity,
book.quantity,
)?;
let aggregate_cost = replace(
instrument.map(|i| i.cost).unwrap_or(Posting::ZERO),
old.cost,
book.cost,
)?;
let aggregate_marked = replace(
instrument.map(|i| i.marked).unwrap_or(Posting::ZERO),
old_value,
new_value,
)?;
let effects = vec![
FinancialEffect::FillApplied {
owner_id: decision.owner_id.clone(),
order_id: order_id.clone(),
fill_id: fill_id.clone(),
instrument_id: instrument_id.clone(),
price: *price,
cash_delta,
quantity_delta,
released_basis: nonnegative(released_basis),
realized_gross_pnl: realized,
},
FinancialEffect::FeeApplied {
owner_id: decision.owner_id.clone(),
fill_id: fill_id.clone(),
fee_id: fee.fee_id.clone(),
amount: fee.amount,
},
];
// Infallible commit: no financial arithmetic after this point.
let instrument = self.instruments.entry(instrument_id.clone()).or_default();
instrument.books.insert(decision.owner_id.clone(), book);
instrument.quantity = aggregate_quantity;
instrument.cost = aggregate_cost;
instrument.marked = aggregate_marked;
self.owners.insert(decision.owner_id.clone(), owner);
self.cash = cash;
self.totals = totals;
self.fills.insert(fill_id.clone(), self.receipts.len());
self.fees.insert(fee.fee_id.clone(), fill_id.clone());
self.orders.insert(order_id.clone(), binding);
Ok(effects)
}
fn apply_mark(
&mut self,
command: &EngineFinancialCommand,
instrument_id: &Id,
price: Positive,
) -> Result<Vec<FinancialEffect>, LedgerError> {
let instrument = self.instruments.get(instrument_id);
let mut marked = Posting::ZERO;
let mut owners = Vec::new();
let mut totals = self.totals;
if let Some(instrument) = instrument {
for (owner_id, book) in &instrument.books {
let old_value = match &instrument.mark {
Some(mark) => Posting::notional(book.quantity, mark.price.into())?,
None => Posting::ZERO,
};
let value = Posting::notional(book.quantity, price.into())?;
marked = marked.checked_add(value)?;
let mut owner = self.owners[owner_id];
owner.marked = replace(owner.marked, old_value, value)?;
if instrument.mark.is_none() && !book.quantity.is_zero() {
owner.unmarked -= 1;
totals.unmarked -= 1;
}
if owner.unmarked == 0 {
owner.owner_valuation(owner_id.clone(), Posting::ZERO)?;
}
owners.push((owner_id.clone(), owner));
}
}
totals.marked = replace(
totals.marked,
instrument.map(|i| i.marked).unwrap_or(Posting::ZERO),
marked,
)?;
self.cash.checked_add(totals.marked)?;
let mark = LedgerMark {
instrument_id: instrument_id.clone(),
price,
event_time: command.event_time,
command_id: command.command_id.clone(),
};
let effects = vec![FinancialEffect::MarkUpdated {
instrument_id: instrument_id.clone(),
price,
}];
let instrument = self.instruments.entry(instrument_id.clone()).or_default();
instrument.mark = Some(mark);
instrument.marked = marked;
for (owner_id, owner) in owners {
self.owners.insert(owner_id, owner);
}
self.totals = totals;
Ok(effects)
}
/// Explicit marks retain their event time. Commands apply in caller arrival
/// order, including backdated marks; F06 owns monotonic replay admission and
/// F04 owns stale-price checks. A fill never substitutes its price for a mark.
pub fn mark(&self, instrument_id: &Id) -> Option<&LedgerMark> {
self.instruments
.get(instrument_id)
.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()
.filter(|(_, i)| !i.books.is_empty())
.map(|(id, i)| AggregatePosition {
instrument_id: id.clone(),
quantity: i.quantity,
remaining_cost: i.cost,
})
.collect()
}
pub fn economic_snapshot(&self) -> FinancialSnapshot {
FinancialSnapshot {
version: Version,
session_id: self.config.session_id.clone(),
account_id: self.config.account_id.clone(),
revision: self.revision,
base_currency: self.config.base_currency.clone(),
reserve_owner_id: self.config.reserve_owner_id.clone(),
cash: nonnegative(self.cash),
positions: self
.instruments
.iter()
.flat_map(|(instrument_id, instrument)| {
instrument
.books
.iter()
.map(|(owner_id, book)| OwnerPosition {
owner_id: owner_id.clone(),
instrument_id: instrument_id.clone(),
quantity: nonnegative(book.quantity),
remaining_cost: nonnegative(book.cost),
realized_gross_pnl: book.realized,
})
})
.collect(),
fees: self
.owners
.iter()
.map(|(owner_id, totals)| OwnerFees {
owner_id: owner_id.clone(),
amount: nonnegative(totals.fees),
})
.collect(),
risk_session: self.risk_session.clone(),
}
}
/// Value actual holdings without synthesizing a liquidation trade.
/// Owner contributions plus reserve capital reconcile to account equity;
/// contributions are attribution, not separate spendable cash balances.
/// Any unmarked open holding makes valuation an error rather than zero.
pub fn valuation(&self) -> Result<LedgerValuation, LedgerError> {
if self.totals.unmarked != 0 {
return Err(LedgerError::MissingMark);
}
let mut owners = vec![Totals::default().owner_valuation(
self.config.reserve_owner_id.clone(),
self.config.initial_capital.into(),
)?];
for (owner_id, totals) in &self.owners {
owners.push(totals.owner_valuation(owner_id.clone(), Posting::ZERO)?);
}
owners.sort_by(|a, b| a.owner_id.cmp(&b.owner_id));
Ok(LedgerValuation {
cash: self.cash,
marked_holdings: self.totals.marked,
equity: self.cash.checked_add(self.totals.marked)?,
remaining_cost: self.totals.cost,
realized_gross_pnl: self.totals.realized,
unrealized_pnl: self.totals.marked.checked_sub(self.totals.cost)?,
fees: self.totals.fees,
owners,
})
}
/// Read-only accepted financial history, including replay-labelled aliases.
/// Reporting must skip aliases; this does not copy a restorable checkpoint.
pub fn receipts(&self) -> &[LedgerReceipt] {
&self.receipts
}
pub fn checkpoint(&self) -> LedgerCheckpoint {
LedgerCheckpoint {
version: Version,
config: self.config.clone(),
economic: self.economic_snapshot(),
marks: self
.instruments
.values()
.filter_map(|i| i.mark.clone())
.collect(),
receipts: self.receipts.clone(),
}
}
/// Replay accepted receipts from genesis and compare the resulting snapshot.
/// This reconstructs indexes and validates consistency, not authenticity;
/// the durable host must retain and authenticate the checkpoint's provenance.
pub fn restore(checkpoint: LedgerCheckpoint) -> Result<Self, LedgerError> {
let mut ledger =
Self::new(checkpoint.config.clone()).map_err(|_| LedgerError::InvalidCheckpoint)?;
for receipt in &checkpoint.receipts {
let outcome = ledger
.apply(&receipt.command)
.map_err(|_| LedgerError::InvalidCheckpoint)?;
if outcome != receipt.outcome {
return Err(LedgerError::InvalidCheckpoint);
}
}
if ledger.checkpoint() != checkpoint {
return Err(LedgerError::InvalidCheckpoint);
}
Ok(ledger)
}
}