feat(research): add owner-aware ledger and intraday storage
Implement reviewed F02/D02: exact owner accounting, atomic funding checks, idempotent receipts and ledger checkpoints; connect existing EOD intraday storage through validated research admission without active financial-engine cutover.
This commit is contained in:
parent
b4af840d4e
commit
b65acccd91
15 changed files with 2704 additions and 104 deletions
|
|
@ -1,48 +1,51 @@
|
|||
[package]
|
||||
name = "engine"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
# Core dependencies
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
thiserror = "1.0"
|
||||
anyhow = "1.0"
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
|
||||
# Data structures
|
||||
dashmap = "5.5"
|
||||
parking_lot = "0.12"
|
||||
crossbeam = "0.8"
|
||||
|
||||
# Async runtime
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
async-trait = "0.1"
|
||||
|
||||
# NAPI for Node.js bindings
|
||||
napi = { version = "2", features = ["async", "chrono_date", "serde-json"] }
|
||||
napi-derive = "2"
|
||||
|
||||
# Math and statistics
|
||||
[package]
|
||||
name = "engine"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
# Core dependencies
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
thiserror = "1.0"
|
||||
anyhow = "1.0"
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
|
||||
# Data structures
|
||||
dashmap = "5.5"
|
||||
parking_lot = "0.12"
|
||||
crossbeam = "0.8"
|
||||
|
||||
# Async runtime
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
async-trait = "0.1"
|
||||
|
||||
# NAPI for Node.js bindings
|
||||
napi = { version = "2", features = ["async", "chrono_date", "serde-json"] }
|
||||
napi-derive = "2"
|
||||
|
||||
# Math and statistics
|
||||
rust_decimal = { version = "=1.43.0", default-features = false }
|
||||
statrs = "0.16"
|
||||
rand = "0.8"
|
||||
rand_distr = "0.4"
|
||||
nalgebra = "0.32"
|
||||
|
||||
# Logging
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = "0.3"
|
||||
|
||||
[build-dependencies]
|
||||
napi-build = "2"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
opt-level = 3
|
||||
codegen-units = 1
|
||||
num-bigint = "=0.4.6"
|
||||
num-rational = "=0.4.2"
|
||||
num-traits = "=0.2.19"
|
||||
statrs = "0.16"
|
||||
rand = "0.8"
|
||||
rand_distr = "0.4"
|
||||
nalgebra = "0.32"
|
||||
|
||||
# Logging
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = "0.3"
|
||||
|
||||
[build-dependencies]
|
||||
napi-build = "2"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
opt-level = 3
|
||||
codegen-units = 1
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use serde::{de, Deserialize, Deserializer, Serialize};
|
|||
|
||||
const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Id(String);
|
||||
|
||||
|
|
|
|||
695
apps/stock/engine/src/financial/ledger.rs
Normal file
695
apps/stock/engine/src/financial/ledger.rs
Normal file
|
|
@ -0,0 +1,695 @@
|
|||
//! Additive, cash-funded long-only economic kernel. Not wired to a legacy
|
||||
//! simulator, NAPI, paper persistence, order matching or portfolio risk.
|
||||
//!
|
||||
//! 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;
|
||||
//! future F04 risk rejections are different, accepted/recorded outcomes.
|
||||
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)]
|
||||
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)]
|
||||
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(),
|
||||
})
|
||||
}
|
||||
|
||||
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. F04 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,
|
||||
});
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
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(),
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
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(),
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
903
apps/stock/engine/src/financial/ledger_tests.rs
Normal file
903
apps/stock/engine/src/financial/ledger_tests.rs
Normal file
|
|
@ -0,0 +1,903 @@
|
|||
use super::{
|
||||
contract::*,
|
||||
ledger::*,
|
||||
scalar::{Posting, ScalarError, MAX_POSTING},
|
||||
};
|
||||
use rand::{rngs::StdRng, Rng, SeedableRng};
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
collections::hash_map::DefaultHasher,
|
||||
hash::{Hash, Hasher},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
fn p(value: &str) -> Posting {
|
||||
value.parse().unwrap()
|
||||
}
|
||||
fn id(value: &str) -> Id {
|
||||
serde_json::from_value(json!(value)).unwrap()
|
||||
}
|
||||
fn config(capital: &str) -> LedgerConfig {
|
||||
serde_json::from_value(json!({
|
||||
"version":1,"sessionId":"research:run-1","accountId":"account-1","baseCurrency":"USD",
|
||||
"reserveOwnerId":"reserve","ownerIds":["strategy:B","strategy:A","strategy:C"],"initialCapital":capital,
|
||||
"riskSession":{"calendarId":"XNYS","calendarRevision":"2026-01","sessionId":"day-1","startsAt":0}
|
||||
})).unwrap()
|
||||
}
|
||||
fn ledger(capital: &str) -> Ledger {
|
||||
Ledger::new(config(capital)).unwrap()
|
||||
}
|
||||
fn command(command_id: &str, body: Value) -> EngineFinancialCommand {
|
||||
serde_json::from_value(
|
||||
json!({"version":1,"sessionId":"research:run-1","accountId":"account-1",
|
||||
"commandId":command_id,"eventTime":100,"body":body}),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn fill(
|
||||
n: usize,
|
||||
owner: &str,
|
||||
instrument: &str,
|
||||
side: &str,
|
||||
quantity: &str,
|
||||
price: &str,
|
||||
fee: &str,
|
||||
) -> EngineFinancialCommand {
|
||||
command(
|
||||
&format!("command-{n}"),
|
||||
json!({"kind":"applyFill",
|
||||
"decision":{"ownerId":owner,"decisionId":format!("decision-{n}"),"sequence":n},
|
||||
"orderId":format!("order-{n}"),"fillId":format!("fill-{n}"),"instrumentId":instrument,
|
||||
"side":side,"quantity":quantity,"price":price,"fee":{"feeId":format!("fee-{n}"),"amount":fee}}),
|
||||
)
|
||||
}
|
||||
fn mark(n: usize, instrument: &str, price: &str) -> EngineFinancialCommand {
|
||||
command(
|
||||
&format!("mark-{n}"),
|
||||
json!({"kind":"mark","instrumentId":instrument,"price":price}),
|
||||
)
|
||||
}
|
||||
fn assert_unchanged(ledger: &mut Ledger, command: EngineFinancialCommand, expected: LedgerError) {
|
||||
let before = ledger.checkpoint();
|
||||
assert_eq!(ledger.apply(&command), Err(expected));
|
||||
assert_eq!(ledger.checkpoint(), before);
|
||||
}
|
||||
fn reconcile(ledger: &Ledger) {
|
||||
let value = ledger.valuation().unwrap();
|
||||
assert_eq!(
|
||||
value.equity,
|
||||
value.cash.checked_add(value.marked_holdings).unwrap()
|
||||
);
|
||||
let capital: Posting = ledger.checkpoint().config.initial_capital.into();
|
||||
assert_eq!(
|
||||
value.equity,
|
||||
Posting::sum([
|
||||
capital,
|
||||
value.realized_gross_pnl,
|
||||
value.unrealized_pnl,
|
||||
Posting::ZERO.checked_sub(value.fees).unwrap()
|
||||
])
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
value.equity,
|
||||
Posting::sum(value.owners.iter().map(|o| o.equity_contribution)).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
value.marked_holdings,
|
||||
Posting::sum(value.owners.iter().map(|o| o.marked_holdings)).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
value.remaining_cost,
|
||||
Posting::sum(value.owners.iter().map(|o| o.remaining_cost)).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
value.realized_gross_pnl,
|
||||
Posting::sum(value.owners.iter().map(|o| o.realized_gross_pnl)).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
value.fees,
|
||||
Posting::sum(value.owners.iter().map(|o| o.fees)).unwrap()
|
||||
);
|
||||
let snapshot = ledger.economic_snapshot();
|
||||
assert_eq!(value.cash, Posting::from(snapshot.cash));
|
||||
assert_eq!(
|
||||
value.remaining_cost,
|
||||
Posting::sum(snapshot.positions.iter().map(|b| b.remaining_cost.into())).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
value.realized_gross_pnl,
|
||||
Posting::sum(snapshot.positions.iter().map(|b| b.realized_gross_pnl)).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
value.fees,
|
||||
Posting::sum(snapshot.fees.iter().map(|f| f.amount.into())).unwrap()
|
||||
);
|
||||
let book_value = |book: &OwnerPosition| {
|
||||
let quantity: Posting = book.quantity.into();
|
||||
if quantity.is_zero() {
|
||||
Posting::ZERO
|
||||
} else {
|
||||
Posting::notional(
|
||||
quantity,
|
||||
ledger
|
||||
.mark(&book.instrument_id)
|
||||
.expect("open inventory requires an explicit mark")
|
||||
.price
|
||||
.into(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
value.marked_holdings,
|
||||
Posting::sum(snapshot.positions.iter().map(book_value)).unwrap()
|
||||
);
|
||||
for owner in &value.owners {
|
||||
let books: Vec<_> = snapshot
|
||||
.positions
|
||||
.iter()
|
||||
.filter(|b| b.owner_id == owner.owner_id)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
owner.remaining_cost,
|
||||
Posting::sum(books.iter().map(|b| b.remaining_cost.into())).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
owner.realized_gross_pnl,
|
||||
Posting::sum(books.iter().map(|b| b.realized_gross_pnl)).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
owner.marked_holdings,
|
||||
Posting::sum(books.iter().map(|b| book_value(b))).unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
owner.fees,
|
||||
Posting::sum(
|
||||
snapshot
|
||||
.fees
|
||||
.iter()
|
||||
.filter(|f| f.owner_id == owner.owner_id)
|
||||
.map(|f| f.amount.into())
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
for aggregate in ledger.aggregate_positions() {
|
||||
assert_eq!(
|
||||
aggregate.quantity,
|
||||
Posting::sum(
|
||||
snapshot
|
||||
.positions
|
||||
.iter()
|
||||
.filter(|b| b.instrument_id == aggregate.instrument_id)
|
||||
.map(|b| b.quantity.into())
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
aggregate.remaining_cost,
|
||||
Posting::sum(
|
||||
snapshot
|
||||
.positions
|
||||
.iter()
|
||||
.filter(|b| b.instrument_id == aggregate.instrument_id)
|
||||
.map(|b| b.remaining_cost.into())
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_asset_two_owners_owner_basis_a_b() {
|
||||
let mut l = ledger("10000");
|
||||
l.apply(&mark(0, "A^P.US", "200")).unwrap();
|
||||
let first = l
|
||||
.apply(&fill(1, "strategy:A", "A^P.US", "buy", "10", "100", "1"))
|
||||
.unwrap();
|
||||
l.apply(&fill(2, "strategy:B", "A^P.US", "buy", "10", "200", "2"))
|
||||
.unwrap();
|
||||
l.apply(&fill(3, "strategy:A", "A^P.US", "sell", "10", "200", "3"))
|
||||
.unwrap();
|
||||
let snapshot = l.economic_snapshot();
|
||||
let a = snapshot
|
||||
.positions
|
||||
.iter()
|
||||
.find(|b| b.owner_id == id("strategy:A"))
|
||||
.unwrap();
|
||||
let b = snapshot
|
||||
.positions
|
||||
.iter()
|
||||
.find(|b| b.owner_id == id("strategy:B"))
|
||||
.unwrap();
|
||||
assert_eq!(Posting::from(a.quantity), p("0"));
|
||||
assert_eq!(Posting::from(a.remaining_cost), p("0"));
|
||||
assert_eq!(a.realized_gross_pnl, p("1000"));
|
||||
assert_eq!(Posting::from(b.quantity), p("10"));
|
||||
assert_eq!(Posting::from(b.remaining_cost), p("2000"));
|
||||
assert_eq!(b.realized_gross_pnl, p("0"));
|
||||
assert_eq!(l.valuation().unwrap().cash, p("8994"));
|
||||
assert_eq!(l.valuation().unwrap().equity, p("10994"));
|
||||
assert!(
|
||||
matches!(&first.effects.effects[..],[FinancialEffect::FillApplied{owner_id,..},FinancialEffect::FeeApplied{owner_id: fee_owner,..}] if owner_id==&id("strategy:A") && fee_owner==owner_id)
|
||||
);
|
||||
reconcile(&l);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basis_residual_partial_final_shared_fixture() {
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../../../test/fixtures/economics/ledger-specs.json"
|
||||
))
|
||||
.unwrap();
|
||||
let mut l = ledger("100");
|
||||
l.apply(&mark(0, "A^P.US", "2")).unwrap();
|
||||
for (index, price) in ["1", "2", "2"].iter().enumerate() {
|
||||
l.apply(&fill(index, "strategy:A", "A^P.US", "buy", "1", price, "0"))
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
Posting::from(l.economic_snapshot().positions[0].remaining_cost).to_string(),
|
||||
fixture["basis"]["initialCost"]
|
||||
);
|
||||
let mut sum = Posting::ZERO;
|
||||
for index in 0..3 {
|
||||
let result = l
|
||||
.apply(&fill(
|
||||
index + 3,
|
||||
"strategy:A",
|
||||
"A^P.US",
|
||||
"sell",
|
||||
"1",
|
||||
"2",
|
||||
"0",
|
||||
))
|
||||
.unwrap();
|
||||
let FinancialEffect::FillApplied { released_basis, .. } = result.effects.effects[0] else {
|
||||
panic!("fill effect")
|
||||
};
|
||||
let released: Posting = released_basis.into();
|
||||
assert_eq!(released.to_string(), fixture["basis"]["releases"][index]);
|
||||
assert_eq!(
|
||||
Posting::from(l.economic_snapshot().positions[0].remaining_cost).to_string(),
|
||||
fixture["basis"]["remainingCosts"][index]
|
||||
);
|
||||
sum = sum.checked_add(released).unwrap();
|
||||
reconcile(&l);
|
||||
}
|
||||
assert_eq!(sum, p("5"));
|
||||
assert_eq!(
|
||||
l.economic_snapshot().positions[0].realized_gross_pnl,
|
||||
p("1")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_full_range_notional_and_proportional_basis() {
|
||||
let max = p(MAX_POSTING);
|
||||
assert_eq!(Posting::notional(max, p("1")).unwrap(), max);
|
||||
assert_eq!(Posting::notional(p("1"), max).unwrap(), max);
|
||||
assert_eq!(Posting::notional(max, max), Err(ScalarError::Overflow));
|
||||
assert_eq!(
|
||||
Posting::notional(max, p("1.00000001")),
|
||||
Err(ScalarError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
Posting::notional(p("0.00000001"), p("0.5")).unwrap(),
|
||||
p("0.00000001")
|
||||
);
|
||||
assert_eq!(
|
||||
Posting::notional(p("-0.00000001"), p("0.5")).unwrap(),
|
||||
p("-0.00000001")
|
||||
);
|
||||
assert_eq!(
|
||||
Posting::notional(p("0.00000001"), p("0.49999999")).unwrap(),
|
||||
p("0")
|
||||
);
|
||||
assert_eq!(
|
||||
Posting::released_basis(max, p("1"), p("2")).unwrap(),
|
||||
p("396140812571321687967.71975168")
|
||||
);
|
||||
assert_eq!(
|
||||
Posting::released_basis(max, p("1"), p("3")).unwrap(),
|
||||
p("264093875047547791978.47983445")
|
||||
);
|
||||
// Numerator exceeds both Decimal's96 and i128's127 coefficient bits.
|
||||
assert_eq!(Posting::released_basis(max, max, max).unwrap(), max);
|
||||
let almost = max.checked_sub(p("0.00000001")).unwrap();
|
||||
assert_eq!(Posting::released_basis(max, almost, max).unwrap(), almost);
|
||||
assert_eq!(Posting::sum([max, p("1"), p("-1")]).unwrap(), max);
|
||||
assert_eq!(
|
||||
Posting::released_basis(p("1"), p("1"), p("0")),
|
||||
Err(ScalarError::InvalidDecimal)
|
||||
);
|
||||
let mut l = ledger(MAX_POSTING);
|
||||
l.apply(&fill(
|
||||
1,
|
||||
"strategy:A",
|
||||
"A^P.US",
|
||||
"buy",
|
||||
"1",
|
||||
MAX_POSTING,
|
||||
"0",
|
||||
))
|
||||
.unwrap();
|
||||
l.apply(&mark(1, "A^P.US", MAX_POSTING)).unwrap();
|
||||
reconcile(&l);
|
||||
l.apply(&fill(
|
||||
2,
|
||||
"strategy:A",
|
||||
"A^P.US",
|
||||
"sell",
|
||||
"1",
|
||||
MAX_POSTING,
|
||||
"0",
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(l.valuation().unwrap().equity, max);
|
||||
reconcile(&l);
|
||||
assert_eq!(
|
||||
Ledger::restore(l.checkpoint()).unwrap().checkpoint(),
|
||||
l.checkpoint()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smallest_positive_price_quantity_zero_cost_lifecycle() {
|
||||
let mut l = ledger("1");
|
||||
let buy = l
|
||||
.apply(&fill(
|
||||
1,
|
||||
"strategy:A",
|
||||
"A^P.US",
|
||||
"buy",
|
||||
"0.00000001",
|
||||
"0.00000001",
|
||||
"0.01",
|
||||
))
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(buy.effects.effects[0], FinancialEffect::FillApplied {cash_delta, ..} if cash_delta == Posting::ZERO)
|
||||
);
|
||||
let position = &l.economic_snapshot().positions[0];
|
||||
assert_eq!(Posting::from(position.quantity), p("0.00000001"));
|
||||
assert_eq!(Posting::from(position.remaining_cost), Posting::ZERO);
|
||||
assert_eq!(l.valuation(), Err(LedgerError::MissingMark));
|
||||
l.apply(&mark(1, "A^P.US", "0.00000001")).unwrap();
|
||||
assert_eq!(l.valuation().unwrap().marked_holdings, Posting::ZERO);
|
||||
assert_eq!(l.valuation().unwrap().cash, p("0.99"));
|
||||
reconcile(&l);
|
||||
l = Ledger::restore(l.checkpoint()).unwrap();
|
||||
let sale = l
|
||||
.apply(&fill(
|
||||
2,
|
||||
"strategy:A",
|
||||
"A^P.US",
|
||||
"sell",
|
||||
"0.00000001",
|
||||
"0.00000001",
|
||||
"0.01",
|
||||
))
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(sale.effects.effects[0], FinancialEffect::FillApplied {cash_delta, released_basis, realized_gross_pnl, ..} if cash_delta == Posting::ZERO && Posting::from(released_basis) == Posting::ZERO && realized_gross_pnl == Posting::ZERO)
|
||||
);
|
||||
let position = &l.economic_snapshot().positions[0];
|
||||
assert_eq!(Posting::from(position.quantity), Posting::ZERO);
|
||||
assert_eq!(Posting::from(position.remaining_cost), Posting::ZERO);
|
||||
assert_eq!(l.valuation().unwrap().cash, p("0.98"));
|
||||
reconcile(&l);
|
||||
assert_eq!(
|
||||
Ledger::restore(l.checkpoint()).unwrap().checkpoint(),
|
||||
l.checkpoint()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_partial_fills_share_order_binding_and_charge_each_fee_once() {
|
||||
let mut l = ledger("1000");
|
||||
let first = fill(1, "strategy:A", "A^P.US", "buy", "1", "100", "1");
|
||||
l.apply(&first).unwrap();
|
||||
let mut second = first.clone();
|
||||
second.command_id = id("second-partial-command");
|
||||
if let EngineCommandBody::ApplyFill {
|
||||
fill_id,
|
||||
quantity,
|
||||
price,
|
||||
fee,
|
||||
..
|
||||
} = &mut second.body
|
||||
{
|
||||
*fill_id = id("second-partial-fill");
|
||||
*quantity = Positive::try_from(p("2")).unwrap();
|
||||
*price = Positive::try_from(p("110")).unwrap();
|
||||
fee.fee_id = id("second-partial-fee");
|
||||
fee.amount = NonNegative::try_from(p("2")).unwrap();
|
||||
}
|
||||
let receipt = l.apply(&second).unwrap();
|
||||
assert!(!receipt.replayed);
|
||||
assert_eq!(
|
||||
Posting::from(l.economic_snapshot().positions[0].quantity),
|
||||
p("3")
|
||||
);
|
||||
assert_eq!(
|
||||
Posting::from(l.economic_snapshot().positions[0].remaining_cost),
|
||||
p("320")
|
||||
);
|
||||
assert_eq!(Posting::from(l.economic_snapshot().cash), p("677"));
|
||||
let before = l.checkpoint();
|
||||
assert!(l.apply(&first).unwrap().replayed);
|
||||
assert!(l.apply(&second).unwrap().replayed);
|
||||
assert_eq!(l.checkpoint(), before);
|
||||
let mut restored = Ledger::restore(before).unwrap();
|
||||
assert!(restored.apply(&second).unwrap().replayed);
|
||||
assert_eq!(restored.checkpoint(), l.checkpoint());
|
||||
l.apply(&mark(1, "A^P.US", "110")).unwrap();
|
||||
reconcile(&l);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_command_identity_fixture_runs_through_ledger() {
|
||||
let fixture: Value = serde_json::from_str(include_str!(
|
||||
"../../../../../test/fixtures/economics/ledger-specs.json"
|
||||
))
|
||||
.unwrap();
|
||||
let parse = |name: &str| {
|
||||
serde_json::from_value::<EngineFinancialCommand>(fixture["commandIds"][name].clone())
|
||||
.unwrap()
|
||||
};
|
||||
let mut l = ledger("1000");
|
||||
let original = l.apply(&parse("original")).unwrap();
|
||||
let retry = l.apply(&parse("retry")).unwrap();
|
||||
assert!(retry.replayed);
|
||||
assert_eq!(retry.effects, original.effects);
|
||||
assert_unchanged(&mut l, parse("conflict"), LedgerError::CommandConflict);
|
||||
assert_unchanged(&mut l, parse("independent"), LedgerError::WrongScope);
|
||||
let mut independent_config = config("1000");
|
||||
independent_config.session_id = id("research:run-2");
|
||||
assert!(
|
||||
!Ledger::new(independent_config)
|
||||
.unwrap()
|
||||
.apply(&parse("independent"))
|
||||
.unwrap()
|
||||
.replayed
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_owner_disposal_and_owner_order_conflicts_leave_state_unchanged() {
|
||||
let mut l = ledger("1000");
|
||||
l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "2", "100", "0"))
|
||||
.unwrap();
|
||||
assert_unchanged(
|
||||
&mut l,
|
||||
fill(2, "strategy:B", "A^P.US", "sell", "1", "100", "0"),
|
||||
LedgerError::InsufficientInventory,
|
||||
);
|
||||
assert_unchanged(
|
||||
&mut l,
|
||||
fill(3, "unknown", "A^P.US", "buy", "1", "100", "0"),
|
||||
LedgerError::UnknownOwner,
|
||||
);
|
||||
assert_unchanged(
|
||||
&mut l,
|
||||
fill(4, "reserve", "A^P.US", "buy", "1", "100", "0"),
|
||||
LedgerError::UnknownOwner,
|
||||
);
|
||||
let mut conflict = fill(5, "strategy:B", "A^P.US", "buy", "1", "100", "0");
|
||||
let EngineCommandBody::ApplyFill { order_id, .. } = &mut conflict.body else {
|
||||
unreachable!()
|
||||
};
|
||||
*order_id = id("order-1");
|
||||
assert_unchanged(&mut l, conflict, LedgerError::OrderConflict);
|
||||
let mut config = config("1");
|
||||
config.owner_ids.push(id("strategy:A"));
|
||||
assert!(matches!(
|
||||
Ledger::new(config),
|
||||
Err(LedgerError::InvalidOwners)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_fill_fee_once_retry_after_intervening_commands_and_aliases() {
|
||||
let mut l = ledger("1000");
|
||||
let original = fill(1, "strategy:A", "A^P.US", "buy", "2", "100", "1");
|
||||
let receipt = l.apply(&original).unwrap();
|
||||
l.apply(&mark(2, "A^P.US", "120")).unwrap();
|
||||
let before = l.checkpoint();
|
||||
let mut replay = receipt.clone();
|
||||
replay.replayed = true;
|
||||
assert_eq!(l.apply(&original).unwrap(), replay);
|
||||
assert_eq!(l.checkpoint(), before);
|
||||
let mut alias = original.clone();
|
||||
alias.command_id = id("z-alias");
|
||||
assert_eq!(l.apply(&alias).unwrap(), replay);
|
||||
assert_eq!(l.economic_snapshot(), before.economic);
|
||||
assert_eq!(l.checkpoint().receipts.len(), before.receipts.len() + 1);
|
||||
let before_alias = l.checkpoint();
|
||||
assert_eq!(l.apply(&alias).unwrap(), replay);
|
||||
assert_eq!(l.checkpoint(), before_alias);
|
||||
assert_eq!(l.valuation().unwrap().fees, p("1"));
|
||||
assert_eq!(l.valuation().unwrap().cash, p("799"));
|
||||
let mut restored = Ledger::restore(l.checkpoint()).unwrap();
|
||||
assert_eq!(restored.apply(&alias).unwrap(), replay);
|
||||
assert_eq!(restored.checkpoint(), l.checkpoint());
|
||||
reconcile(&l);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_fill_command_and_fee_ids_reject_atomically() {
|
||||
let mut l = ledger("1000");
|
||||
let original = fill(1, "strategy:A", "A^P.US", "buy", "2", "100", "1");
|
||||
l.apply(&original).unwrap();
|
||||
let mut command_conflict = original.clone();
|
||||
command_conflict.event_time = EventTime::try_from(101).unwrap();
|
||||
assert_unchanged(&mut l, command_conflict, LedgerError::CommandConflict);
|
||||
let mut conflict = original.clone();
|
||||
conflict.command_id = id("alias");
|
||||
conflict.event_time = EventTime::try_from(101).unwrap();
|
||||
assert_unchanged(&mut l, conflict, LedgerError::FillConflict);
|
||||
let mut conflict = original.clone();
|
||||
conflict.command_id = id("alias");
|
||||
if let EngineCommandBody::ApplyFill { fee, .. } = &mut conflict.body {
|
||||
fee.amount = NonNegative::try_from(p("2")).unwrap();
|
||||
}
|
||||
assert_unchanged(&mut l, conflict, LedgerError::FillConflict);
|
||||
let mut conflict = fill(2, "strategy:A", "A^P.US", "buy", "1", "100", "1");
|
||||
if let EngineCommandBody::ApplyFill { fee, .. } = &mut conflict.body {
|
||||
fee.fee_id = id("fee-1");
|
||||
}
|
||||
assert_unchanged(&mut l, conflict, LedgerError::FeeConflict);
|
||||
let mut conflict = original;
|
||||
conflict.account_id = id("another-account");
|
||||
assert_unchanged(&mut l, conflict, LedgerError::WrongScope);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fee_inclusive_funding_and_fail_late_overflow_are_atomic() {
|
||||
let mut l = ledger("10000");
|
||||
assert_unchanged(
|
||||
&mut l,
|
||||
fill(1, "strategy:A", "A^P.US", "buy", "100", "100", "0.01"),
|
||||
LedgerError::InsufficientCash,
|
||||
);
|
||||
l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "100", "99.99", "1"))
|
||||
.unwrap();
|
||||
assert_eq!(Posting::from(l.economic_snapshot().cash), p("0"));
|
||||
let mut l = ledger(MAX_POSTING);
|
||||
l.apply(&mark(1, "A^P.US", "1")).unwrap();
|
||||
// Fill arithmetic itself fits; account equity after applying the existing
|
||||
// mark would overflow. Neither IDs nor a partial owned book may survive.
|
||||
assert_unchanged(
|
||||
&mut l,
|
||||
fill(1, "strategy:A", "A^P.US", "buy", "1", "0.5", "0"),
|
||||
LedgerError::Arithmetic(ScalarError::Overflow),
|
||||
);
|
||||
l.apply(&fill(2, "strategy:A", "A^P.US", "buy", "1", "1", "0"))
|
||||
.unwrap();
|
||||
assert_unchanged(
|
||||
&mut l,
|
||||
mark(2, "A^P.US", "2"),
|
||||
LedgerError::Arithmetic(ScalarError::Overflow),
|
||||
);
|
||||
assert_unchanged(
|
||||
&mut l,
|
||||
fill(
|
||||
3,
|
||||
"strategy:A",
|
||||
"A^P.US",
|
||||
"buy",
|
||||
MAX_POSTING,
|
||||
MAX_POSTING,
|
||||
"0",
|
||||
),
|
||||
LedgerError::Arithmetic(ScalarError::Overflow),
|
||||
);
|
||||
reconcile(&l);
|
||||
let mut l = ledger("100");
|
||||
l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "1", "100", "0"))
|
||||
.unwrap();
|
||||
assert_unchanged(
|
||||
&mut l,
|
||||
fill(2, "strategy:A", "A^P.US", "sell", "1", "100", "100.01"),
|
||||
LedgerError::InsufficientCash,
|
||||
);
|
||||
let mut l = ledger(MAX_POSTING);
|
||||
l.apply(&fill(
|
||||
1,
|
||||
"strategy:A",
|
||||
"A^P.US",
|
||||
"buy",
|
||||
MAX_POSTING,
|
||||
"0.00000001",
|
||||
"0",
|
||||
))
|
||||
.unwrap();
|
||||
assert_unchanged(
|
||||
&mut l,
|
||||
fill(
|
||||
2,
|
||||
"strategy:B",
|
||||
"A^P.US",
|
||||
"buy",
|
||||
"0.00000001",
|
||||
"0.00000001",
|
||||
"0",
|
||||
),
|
||||
LedgerError::Arithmetic(ScalarError::Overflow),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mark_rounding_sums_owned_values_not_aggregate_quantity() {
|
||||
let mut l = ledger("1");
|
||||
l.apply(&fill(
|
||||
1,
|
||||
"strategy:A",
|
||||
"A^P.US",
|
||||
"buy",
|
||||
"0.00000001",
|
||||
"0.5",
|
||||
"0",
|
||||
))
|
||||
.unwrap();
|
||||
l.apply(&fill(
|
||||
2,
|
||||
"strategy:B",
|
||||
"A^P.US",
|
||||
"buy",
|
||||
"0.00000001",
|
||||
"0.5",
|
||||
"0",
|
||||
))
|
||||
.unwrap();
|
||||
l.apply(&mark(1, "A^P.US", "0.5")).unwrap();
|
||||
assert_eq!(l.valuation().unwrap().marked_holdings, p("0.00000002"));
|
||||
assert_eq!(
|
||||
Posting::notional(l.aggregate_positions()[0].quantity, p("0.5")).unwrap(),
|
||||
p("0.00000001")
|
||||
);
|
||||
reconcile(&l);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_mark_retains_positions_without_fill_and_missing_marks_fail() {
|
||||
let mut l = ledger("1000");
|
||||
l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "2", "100", "1"))
|
||||
.unwrap();
|
||||
assert_eq!(l.valuation(), Err(LedgerError::MissingMark));
|
||||
let terminal = l.apply(&mark(1, "A^P.US", "120")).unwrap();
|
||||
assert!(matches!(
|
||||
&terminal.effects.effects[..],
|
||||
[FinancialEffect::MarkUpdated { .. }]
|
||||
));
|
||||
assert_eq!(
|
||||
Posting::from(l.economic_snapshot().positions[0].quantity),
|
||||
p("2")
|
||||
);
|
||||
assert_eq!(l.valuation().unwrap().equity, p("1039"));
|
||||
let previous_mark = l.mark(&id("A^P.US")).unwrap().clone();
|
||||
l.apply(&fill(2, "strategy:A", "A^P.US", "buy", "1", "125", "1"))
|
||||
.unwrap();
|
||||
assert_eq!(l.mark(&id("A^P.US")), Some(&previous_mark));
|
||||
let mut older = mark(2, "A^P.US", "119");
|
||||
older.event_time = EventTime::try_from(90).unwrap();
|
||||
l.apply(&older).unwrap();
|
||||
assert_eq!(l.mark(&id("A^P.US")).unwrap().event_time.get(), 90);
|
||||
reconcile(&l);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_boundary_keeps_calendar_and_does_not_reset_economics() {
|
||||
let mut l = ledger("1000");
|
||||
l.apply(&fill(1, "strategy:A", "A^P.US", "buy", "1", "100", "1"))
|
||||
.unwrap();
|
||||
let before = l.economic_snapshot();
|
||||
let next = command(
|
||||
"boundary",
|
||||
json!({"kind":"riskSessionBoundary","riskSession":{"calendarId":"XNYS","calendarRevision":"2026-01","sessionId":"day-2","startsAt":50}}),
|
||||
);
|
||||
l.apply(&next).unwrap();
|
||||
let after = l.economic_snapshot();
|
||||
assert_eq!(after.cash, before.cash);
|
||||
assert_eq!(after.positions, before.positions);
|
||||
assert_eq!(after.fees, before.fees);
|
||||
let mut repeated = next.clone();
|
||||
repeated.command_id = id("same-boundary-new-command");
|
||||
let noop = l.apply(&repeated).unwrap();
|
||||
assert!(!noop.replayed);
|
||||
assert!(noop.effects.effects.is_empty());
|
||||
assert_eq!(noop.effects.revision.get(), after.revision.get() + 1);
|
||||
let saved = l.checkpoint();
|
||||
let retry = l.apply(&repeated).unwrap();
|
||||
assert!(retry.replayed);
|
||||
assert!(retry.effects.effects.is_empty());
|
||||
assert_eq!(l.checkpoint(), saved);
|
||||
let mut restored = Ledger::restore(saved).unwrap();
|
||||
assert_eq!(restored.apply(&repeated).unwrap(), retry);
|
||||
assert!(matches!(
|
||||
&restored.apply(&next).unwrap().effects.effects[..],
|
||||
[FinancialEffect::RiskSessionChanged { .. }]
|
||||
));
|
||||
assert_eq!(restored.checkpoint(), l.checkpoint());
|
||||
for (calendar, revision, session, starts) in [
|
||||
("OTHER", "2026-01", "day-3", 70),
|
||||
("XNYS", "changed", "day-3", 70),
|
||||
("XNYS", "2026-01", "day-3", 40),
|
||||
("XNYS", "2026-01", "day-2", 70),
|
||||
("XNYS", "2026-01", "day-3", 50),
|
||||
] {
|
||||
let invalid = command(
|
||||
"invalid-boundary",
|
||||
json!({"kind":"riskSessionBoundary","riskSession":{"calendarId":calendar,"calendarRevision":revision,"sessionId":session,"startsAt":starts}}),
|
||||
);
|
||||
assert_unchanged(&mut l, invalid, LedgerError::InvalidRiskSession);
|
||||
}
|
||||
assert_eq!(
|
||||
Ledger::restore(l.checkpoint()).unwrap().checkpoint(),
|
||||
l.checkpoint()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_restore_parity_validation_and_ordered_receipts() {
|
||||
let mut l = ledger("1000");
|
||||
let first = fill(10, "strategy:A", "A^P.US", "buy", "2", "100", "1");
|
||||
l.apply(&first).unwrap();
|
||||
l.apply(&mark(2, "A^P.US", "120")).unwrap();
|
||||
let mut alias = first;
|
||||
alias.command_id = id("a-alias");
|
||||
l.apply(&alias).unwrap();
|
||||
let checkpoint = l.checkpoint();
|
||||
let json = serde_json::to_string(&checkpoint).unwrap();
|
||||
let mut restored = Ledger::restore(serde_json::from_str(&json).unwrap()).unwrap();
|
||||
let next = fill(2, "strategy:A", "A^P.US", "sell", "1", "125", "2");
|
||||
assert_eq!(l.apply(&next).unwrap(), restored.apply(&next).unwrap());
|
||||
assert_eq!(l.checkpoint(), restored.checkpoint());
|
||||
assert_eq!(l.valuation(), restored.valuation());
|
||||
let mut variants = Vec::new();
|
||||
let mut bad = checkpoint.clone();
|
||||
bad.economic.cash = NonNegative::try_from(p("999")).unwrap();
|
||||
variants.push(bad);
|
||||
let mut bad = checkpoint.clone();
|
||||
bad.economic.revision = Counter::try_from(99).unwrap();
|
||||
variants.push(bad);
|
||||
let mut bad = checkpoint.clone();
|
||||
bad.config.initial_capital = NonNegative::try_from(p("1001")).unwrap();
|
||||
variants.push(bad);
|
||||
let mut bad = checkpoint.clone();
|
||||
bad.receipts.swap(0, 2);
|
||||
variants.push(bad);
|
||||
let mut bad = checkpoint.clone();
|
||||
bad.receipts[2].outcome.replayed = false;
|
||||
variants.push(bad);
|
||||
let mut bad = checkpoint.clone();
|
||||
bad.marks.clear();
|
||||
variants.push(bad);
|
||||
let mut bad = checkpoint.clone();
|
||||
bad.receipts[0].command.account_id = id("foreign");
|
||||
variants.push(bad);
|
||||
let mut bad = checkpoint.clone();
|
||||
bad.receipts.push(bad.receipts[2].clone());
|
||||
variants.push(bad);
|
||||
for bad in variants {
|
||||
assert!(matches!(
|
||||
Ledger::restore(bad),
|
||||
Err(LedgerError::InvalidCheckpoint)
|
||||
));
|
||||
}
|
||||
let mut invalid: Value = serde_json::from_str(&json).unwrap();
|
||||
invalid["version"] = json!(2);
|
||||
assert!(serde_json::from_value::<LedgerCheckpoint>(invalid).is_err());
|
||||
assert!(serde_json::from_value::<LedgerCheckpoint>(
|
||||
serde_json::to_value(&checkpoint.economic).unwrap()
|
||||
)
|
||||
.is_err());
|
||||
reconcile(&restored);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deterministic_seeded_valid_sequences_reconcile_and_restore() {
|
||||
fn run(seed: u64) -> LedgerCheckpoint {
|
||||
let mut rng = StdRng::seed_from_u64(seed);
|
||||
let mut l = ledger("1000000");
|
||||
let owners = ["strategy:A", "strategy:B", "strategy:C"];
|
||||
let instruments = ["A^P.US", "B.US", "C.US"];
|
||||
let mut quantities = [[0usize; 3]; 3];
|
||||
for (i, instrument) in instruments.iter().enumerate() {
|
||||
l.apply(&mark(i, instrument, "100")).unwrap();
|
||||
}
|
||||
for step in 0..512 {
|
||||
let owner = rng.gen_range(0..3);
|
||||
let instrument = rng.gen_range(0..3);
|
||||
let price = rng.gen_range(80..121).to_string();
|
||||
if step % 7 == 0 {
|
||||
l.apply(&mark(step + 3, instruments[instrument], &price))
|
||||
.unwrap();
|
||||
}
|
||||
let sell = quantities[owner][instrument] > 0 && rng.gen_bool(0.5);
|
||||
let side = if sell {
|
||||
quantities[owner][instrument] -= 1;
|
||||
"sell"
|
||||
} else {
|
||||
quantities[owner][instrument] += 1;
|
||||
"buy"
|
||||
};
|
||||
l.apply(&fill(
|
||||
step,
|
||||
owners[owner],
|
||||
instruments[instrument],
|
||||
side,
|
||||
"1",
|
||||
&price,
|
||||
"0.01",
|
||||
))
|
||||
.unwrap();
|
||||
reconcile(&l);
|
||||
if step % 127 == 0 {
|
||||
l = Ledger::restore(l.checkpoint()).unwrap();
|
||||
}
|
||||
}
|
||||
l.checkpoint()
|
||||
}
|
||||
assert_eq!(run(0xf02), run(0xf02));
|
||||
assert_ne!(run(0xf02), run(0xf03));
|
||||
}
|
||||
|
||||
fn digest(bytes: &[u8]) -> u64 {
|
||||
let mut h = DefaultHasher::new();
|
||||
bytes.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// Local release sanity workload, not a backtest benchmark or speedup claim.
|
||||
/// Measures resident transitions separately from checkpoint+restore. Inputs
|
||||
/// are prebuilt; effects/history serialization happens outside timed regions.
|
||||
/// Fixed-artifact DefaultHasher is a repeatability checksum, not provenance.
|
||||
#[test]
|
||||
#[ignore = "manual measurement: cargo test -p engine --lib --release --offline ledger_transition_measurement -- --ignored --nocapture"]
|
||||
fn ledger_transition_measurement() {
|
||||
for (count, multi) in [(1000, false), (1000, true), (10000, false), (10000, true)] {
|
||||
let mut commands = Vec::new();
|
||||
for index in 0..count {
|
||||
let owner = if multi {
|
||||
["strategy:A", "strategy:B", "strategy:C"][index % 3]
|
||||
} else {
|
||||
"strategy:A"
|
||||
};
|
||||
let instrument = if multi {
|
||||
["A^P.US", "B.US", "C.US", "D.US"][index % 4]
|
||||
} else {
|
||||
"A^P.US"
|
||||
};
|
||||
commands.push(if index % 5 == 0 {
|
||||
mark(index, instrument, "100")
|
||||
} else {
|
||||
fill(index, owner, instrument, "buy", "0.01", "100", "0.001")
|
||||
});
|
||||
}
|
||||
let mut reference = None;
|
||||
for repeat in 0..3 {
|
||||
let mut l = ledger("1000000");
|
||||
let started = Instant::now();
|
||||
let effects: Vec<_> = commands.iter().map(|c| l.apply(c).unwrap()).collect();
|
||||
let transition_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
let started = Instant::now();
|
||||
let checkpoint = l.checkpoint();
|
||||
let checkpoint_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
let restore_input = checkpoint.clone();
|
||||
let started = Instant::now();
|
||||
let restored = Ledger::restore(restore_input).unwrap();
|
||||
let restore_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
assert_eq!(restored.checkpoint(), checkpoint);
|
||||
let bytes = serde_json::to_vec(&(checkpoint, effects)).unwrap();
|
||||
if let Some(reference) = &reference {
|
||||
assert_eq!(&bytes, reference);
|
||||
} else {
|
||||
reference = Some(bytes.clone());
|
||||
}
|
||||
println!("F02 count={count} multi={multi} repeat={repeat} transition_ms={transition_ms:.3} checkpoint_ms={checkpoint_ms:.3} restore_ms={restore_ms:.3} bytes={} checksum={:016x}",bytes.len(),digest(&bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,11 @@
|
|||
//! F01 defines transport and checked posting primitives. F02 owns ledger
|
||||
//! transitions/idempotency; F04 owns risk; F06/F07 own replay/session state.
|
||||
pub mod contract;
|
||||
pub mod ledger;
|
||||
pub mod scalar;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod ledger_tests;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,6 @@
|
|||
use num_bigint::BigInt;
|
||||
use num_rational::BigRational;
|
||||
use num_traits::ToPrimitive;
|
||||
use rust_decimal::{Decimal, RoundingStrategy};
|
||||
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::{fmt, str::FromStr};
|
||||
|
|
@ -15,9 +18,9 @@ pub enum ScalarError {
|
|||
}
|
||||
|
||||
/// Money/quantity transport uses strings, never f64. No float constructor or
|
||||
/// unchecked arithmetic operator is exposed. Multiplication and proportional
|
||||
/// division are intentionally left to F02's operation-specific implementation:
|
||||
/// checked decimal operations can still round intermediate precision.
|
||||
/// unchecked arithmetic operator is exposed. Operation-specific notional and
|
||||
/// basis calculations use exact rational intermediates; generic decimal
|
||||
/// multiplication/division could silently reduce intermediate precision.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct Posting(Decimal);
|
||||
|
||||
|
|
@ -40,6 +43,65 @@ impl Posting {
|
|||
Self::from_exact_decimal(self.0.checked_sub(other.0).ok_or(ScalarError::Overflow)?)
|
||||
}
|
||||
|
||||
/// Exact integer coefficient at the declared posting scale. ZERO is the
|
||||
/// only internal value whose Decimal scale can be smaller than eight.
|
||||
fn units(self) -> BigInt {
|
||||
BigInt::from(self.0.mantissa()) * BigInt::from(10u32).pow(POSTING_SCALE - self.0.scale())
|
||||
}
|
||||
|
||||
fn from_units(units: BigInt) -> Result<Self, ScalarError> {
|
||||
let coefficient = units.to_i128().ok_or(ScalarError::Overflow)?;
|
||||
let decimal = Decimal::try_from_i128_with_scale(coefficient, POSTING_SCALE)
|
||||
.map_err(|_| ScalarError::Overflow)?;
|
||||
Self::from_exact_decimal(decimal)
|
||||
}
|
||||
|
||||
/// Quantity * price, rounded once at the posting boundary. BigRational
|
||||
/// avoids rust_decimal's possible intermediate precision reduction. Its
|
||||
/// round() is explicitly nearest with half ties away from zero.
|
||||
pub(super) fn notional(quantity: Self, price: Self) -> Result<Self, ScalarError> {
|
||||
let units = BigRational::new(
|
||||
quantity.units() * price.units(),
|
||||
BigInt::from(100_000_000u32),
|
||||
);
|
||||
Self::rounded_units(units)
|
||||
}
|
||||
|
||||
/// Partial disposal only: quantity is positive and <= owned quantity.
|
||||
/// A final disposal deliberately bypasses division and releases residue.
|
||||
pub(super) fn released_basis(
|
||||
cost: Self,
|
||||
quantity: Self,
|
||||
owned_quantity: Self,
|
||||
) -> Result<Self, ScalarError> {
|
||||
if quantity.is_negative() || quantity.is_zero() || quantity > owned_quantity {
|
||||
return Err(ScalarError::InvalidDecimal);
|
||||
}
|
||||
if quantity == owned_quantity {
|
||||
return Ok(cost);
|
||||
}
|
||||
Self::rounded_units(BigRational::new(
|
||||
cost.units() * quantity.units(),
|
||||
owned_quantity.units(),
|
||||
))
|
||||
}
|
||||
|
||||
fn rounded_units(exact: BigRational) -> Result<Self, ScalarError> {
|
||||
// As with from_exact_decimal, reject an out-of-range exact value even
|
||||
// if rounding down would have brought it back inside the range.
|
||||
let max = BigRational::from_integer(BigInt::from((1u128 << 96) - 1));
|
||||
if exact > max || exact < -max {
|
||||
return Err(ScalarError::Overflow);
|
||||
}
|
||||
Self::from_units(exact.round().to_integer())
|
||||
}
|
||||
|
||||
/// Exact sum of already quantized postings, without rejecting a valid
|
||||
/// final result solely because an intermediate partial sum overflows.
|
||||
pub(super) fn sum(values: impl IntoIterator<Item = Self>) -> Result<Self, ScalarError> {
|
||||
Self::from_units(values.into_iter().map(Self::units).sum())
|
||||
}
|
||||
|
||||
/// Posting boundary for an already exact internal decimal calculation.
|
||||
/// Callers must not pass a previously precision-losing intermediate.
|
||||
/// https://docs.rs/rust_decimal/1.43.0/rust_decimal/enum.RoundingStrategy.html
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue