feat(engine): add canonical risk and order matching
This commit is contained in:
parent
b65acccd91
commit
ccf333cc0a
13 changed files with 5129 additions and 36 deletions
|
|
@ -589,6 +589,37 @@ impl Ledger {
|
|||
.and_then(|i| i.mark.as_ref())
|
||||
}
|
||||
|
||||
/// Small immutable views for the risk gate; no economic snapshot/history
|
||||
/// allocation is necessary for an ordinary transition.
|
||||
pub fn cash(&self) -> Posting {
|
||||
self.cash
|
||||
}
|
||||
|
||||
pub fn equity(&self) -> Result<Posting, LedgerError> {
|
||||
if self.totals.unmarked != 0 {
|
||||
return Err(LedgerError::MissingMark);
|
||||
}
|
||||
Ok(self.cash.checked_add(self.totals.marked)?)
|
||||
}
|
||||
|
||||
pub fn owner_quantity(&self, owner_id: &Id, instrument_id: &Id) -> Posting {
|
||||
self.instruments
|
||||
.get(instrument_id)
|
||||
.and_then(|i| i.books.get(owner_id))
|
||||
.map(|b| b.quantity)
|
||||
.unwrap_or(Posting::ZERO)
|
||||
}
|
||||
|
||||
pub fn owned_quantities(&self) -> impl Iterator<Item = (&Id, &Id, Posting)> {
|
||||
self.instruments.iter().flat_map(|(id, instrument)| {
|
||||
instrument
|
||||
.books
|
||||
.iter()
|
||||
.filter(|(_, book)| !book.quantity.is_zero())
|
||||
.map(move |(owner, book)| (id, owner, book.quantity))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn aggregate_positions(&self) -> Vec<AggregatePosition> {
|
||||
self.instruments
|
||||
.iter()
|
||||
|
|
|
|||
1374
apps/stock/engine/src/financial/matching.rs
Normal file
1374
apps/stock/engine/src/financial/matching.rs
Normal file
File diff suppressed because it is too large
Load diff
1612
apps/stock/engine/src/financial/matching_tests.rs
Normal file
1612
apps/stock/engine/src/financial/matching_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -4,6 +4,8 @@
|
|||
//! transitions/idempotency; F04 owns risk; F06/F07 own replay/session state.
|
||||
pub mod contract;
|
||||
pub mod ledger;
|
||||
pub mod matching;
|
||||
pub mod risk;
|
||||
pub mod scalar;
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -11,3 +13,9 @@ mod tests;
|
|||
|
||||
#[cfg(test)]
|
||||
mod ledger_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod risk_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod matching_tests;
|
||||
|
|
|
|||
897
apps/stock/engine/src/financial/risk.rs
Normal file
897
apps/stock/engine/src/financial/risk.rs
Normal file
|
|
@ -0,0 +1,897 @@
|
|||
//! Additive authoritative cash/risk gate. Not connected to legacy execution.
|
||||
//! F05 supplies normalized orders/matching; F06 supplies the engine clock.
|
||||
//! Limit crossing, TIF and execution-event eligibility are not certified here.
|
||||
//! This host API is not a sandbox for arbitrary in-process Rust code.
|
||||
use super::{
|
||||
contract::*,
|
||||
ledger::*,
|
||||
scalar::{Posting, ScalarError},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct RiskConfig {
|
||||
pub ledger: LedgerConfig,
|
||||
pub fee_rate: NonNegative,
|
||||
pub max_order_quantity: Positive,
|
||||
pub max_position_quantity: Positive,
|
||||
pub max_symbol_exposure: Positive,
|
||||
pub max_gross_exposure: Positive,
|
||||
pub max_daily_loss: Positive,
|
||||
pub max_drawdown_amount: Positive,
|
||||
pub max_mark_age_ms: Counter,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum OrderOrigin {
|
||||
Explicit,
|
||||
Target,
|
||||
}
|
||||
|
||||
/// Already normalized by the future order coordinator. Origin is provenance,
|
||||
/// never an alternate risk path. No target expansion, TIF or matching here.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct RiskOrder {
|
||||
pub order_id: Id,
|
||||
pub decision: DecisionIdentity,
|
||||
pub instrument_id: Id,
|
||||
pub side: Side,
|
||||
pub quantity: Positive,
|
||||
pub limit_price: Option<Positive>,
|
||||
pub origin: OrderOrigin,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ReleaseReason {
|
||||
Cancelled,
|
||||
Rejected,
|
||||
Expired,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(
|
||||
tag = "kind",
|
||||
rename_all = "camelCase",
|
||||
rename_all_fields = "camelCase",
|
||||
deny_unknown_fields
|
||||
)]
|
||||
pub enum RiskCommandBody {
|
||||
Admit {
|
||||
order: RiskOrder,
|
||||
},
|
||||
Fill {
|
||||
order_id: Id,
|
||||
fill_id: Id,
|
||||
fee_id: Id,
|
||||
quantity: Positive,
|
||||
price: Positive,
|
||||
},
|
||||
Mark {
|
||||
instrument_id: Id,
|
||||
price: Positive,
|
||||
observed_at: EventTime,
|
||||
},
|
||||
Release {
|
||||
owner_id: Id,
|
||||
order_id: Id,
|
||||
reason: ReleaseReason,
|
||||
},
|
||||
RiskSessionBoundary {
|
||||
risk_session: RiskSessionIdentity,
|
||||
},
|
||||
}
|
||||
|
||||
/// Commands are scoped to this account instance. Time comes from the engine,
|
||||
/// not a strategy-supplied timestamp. There is intentionally no reset variant.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct RiskCommand {
|
||||
pub command_id: Id,
|
||||
pub event_time: EventTime,
|
||||
pub body: RiskCommandBody,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Reservation {
|
||||
pub order: RiskOrder,
|
||||
pub remaining: Positive,
|
||||
pub cash: NonNegative,
|
||||
/// Buy reservation price, never a synthetic ledger mark. Sells reserve
|
||||
/// inventory, require no fresh mark and have no reservation price.
|
||||
pub price: Option<Positive>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum RiskRejection {
|
||||
OrderSize,
|
||||
PositionSize,
|
||||
SymbolExposure,
|
||||
GrossExposure,
|
||||
InsufficientCash,
|
||||
InsufficientInventory,
|
||||
MissingMark,
|
||||
StaleMark,
|
||||
DailyLoss,
|
||||
Drawdown,
|
||||
InactiveOrder,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum RiskDisposition {
|
||||
Accepted,
|
||||
Rejected(RiskRejection),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct RiskOutcome {
|
||||
/// Returns the ORIGINAL receipt. When true, do not publish/apply any of
|
||||
/// its effects again, even if nested financial.replayed is originally false.
|
||||
/// A retry does not update risk state, reservations or the current clock.
|
||||
pub replayed: bool,
|
||||
pub revision: Counter,
|
||||
pub disposition: RiskDisposition,
|
||||
pub financial: Option<ApplyOutcome>,
|
||||
pub remaining: Option<Reservation>,
|
||||
pub released_order: Option<Id>,
|
||||
pub reset_baseline: Option<NonNegative>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct RiskState {
|
||||
pub daily_baseline: NonNegative,
|
||||
pub peak_equity: NonNegative,
|
||||
pub daily_halted: bool,
|
||||
pub drawdown_halted: bool,
|
||||
pub risk_session: RiskSessionIdentity,
|
||||
pub last_event_time: EventTime,
|
||||
}
|
||||
|
||||
/// Host-issued instance capability. No Deserialize/Clone or public constructor;
|
||||
/// do not give it to strategy code. This is API separation, not authentication.
|
||||
#[derive(Debug)]
|
||||
pub struct OperatorAuthority(Arc<()>);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct OperatorReset {
|
||||
pub command_id: Id,
|
||||
pub event_time: EventTime,
|
||||
pub actor_id: Id,
|
||||
pub reason: Id,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "source", content = "command", deny_unknown_fields)]
|
||||
pub enum RiskInput {
|
||||
Engine(RiskCommand),
|
||||
Operator(OperatorReset),
|
||||
}
|
||||
impl RiskInput {
|
||||
fn id(&self) -> &Id {
|
||||
match self {
|
||||
Self::Engine(c) => &c.command_id,
|
||||
Self::Operator(c) => &c.command_id,
|
||||
}
|
||||
}
|
||||
fn time(&self) -> EventTime {
|
||||
match self {
|
||||
Self::Engine(c) => c.event_time,
|
||||
Self::Operator(c) => c.event_time,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct RiskReceipt {
|
||||
pub input: RiskInput,
|
||||
pub outcome: RiskOutcome,
|
||||
}
|
||||
|
||||
/// Journal replay validates consistency, not authenticity of genesis/history.
|
||||
/// Durable provenance and operator authentication belong to the host. This is
|
||||
/// risk+ledger recovery only, not F07 replay/strategy/RNG recovery.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct RiskCheckpoint {
|
||||
pub version: Version,
|
||||
pub config: RiskConfig,
|
||||
pub ledger: LedgerCheckpoint,
|
||||
pub revision: Counter,
|
||||
pub state: RiskState,
|
||||
pub reservations: Vec<Reservation>,
|
||||
pub receipts: Vec<RiskReceipt>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum RiskError {
|
||||
#[error(transparent)]
|
||||
Ledger(#[from] LedgerError),
|
||||
#[error(transparent)]
|
||||
Arithmetic(#[from] ScalarError),
|
||||
#[error("fee rate must be in [0, 1]")]
|
||||
InvalidFeeRate,
|
||||
#[error("command ID reused with a conflicting payload")]
|
||||
CommandConflict,
|
||||
#[error("order ID is unknown or reused")]
|
||||
OrderConflict,
|
||||
#[error("fill ID reused with conflicting payload/time")]
|
||||
FillConflict,
|
||||
#[error("fee ID reused by another fill")]
|
||||
FeeConflict,
|
||||
#[error("owner is unregistered or does not own this order")]
|
||||
WrongOwner,
|
||||
#[error("fill quantity exceeds remaining reserved quantity")]
|
||||
ExcessFill,
|
||||
#[error("engine command time is backdated")]
|
||||
BackdatedCommand,
|
||||
#[error("mark is future-dated or older than the retained mark")]
|
||||
InvalidMarkTime,
|
||||
#[error("new risk boundary must occur at its declared start")]
|
||||
InvalidBoundaryTime,
|
||||
#[error("operator capability does not belong to this account instance")]
|
||||
UnauthorizedReset,
|
||||
#[error("cannot reset against stale or missing marks")]
|
||||
InvalidResetMarks,
|
||||
#[error("risk revision exhausted safe integer range")]
|
||||
RevisionOverflow,
|
||||
#[error("checkpoint is inconsistent with its genesis and receipts")]
|
||||
InvalidCheckpoint,
|
||||
}
|
||||
|
||||
/// No Clone, mutable ledger access, or unrestricted fill entry point. Ordinary
|
||||
/// transitions touch scalar state and active reservations, never copy history.
|
||||
#[derive(Debug)]
|
||||
pub struct RiskAccount {
|
||||
config: RiskConfig,
|
||||
ledger: Ledger,
|
||||
revision: Counter,
|
||||
state: RiskState,
|
||||
pending: BTreeMap<Id, Reservation>,
|
||||
orders: BTreeMap<Id, RiskOrder>,
|
||||
reserved_cash: Posting,
|
||||
receipts: Vec<RiskReceipt>,
|
||||
commands: BTreeMap<Id, usize>,
|
||||
fills: BTreeMap<Id, usize>,
|
||||
fees: BTreeMap<Id, Id>,
|
||||
authority: Arc<()>,
|
||||
}
|
||||
|
||||
fn nn(p: Posting) -> NonNegative {
|
||||
p.try_into().expect("nonnegative risk invariant")
|
||||
}
|
||||
fn pos(p: Posting) -> Positive {
|
||||
p.try_into().expect("positive remaining quantity")
|
||||
}
|
||||
|
||||
impl RiskAccount {
|
||||
pub fn new(mut config: RiskConfig) -> Result<(Self, OperatorAuthority), RiskError> {
|
||||
if Posting::from(config.fee_rate) > "1".parse::<Posting>()? {
|
||||
return Err(RiskError::InvalidFeeRate);
|
||||
}
|
||||
config.ledger.owner_ids.sort();
|
||||
let ledger = Ledger::new(config.ledger.clone())?;
|
||||
let authority = Arc::new(());
|
||||
let capability = OperatorAuthority(authority.clone());
|
||||
let state = RiskState {
|
||||
daily_baseline: config.ledger.initial_capital,
|
||||
peak_equity: config.ledger.initial_capital,
|
||||
daily_halted: false,
|
||||
drawdown_halted: false,
|
||||
risk_session: config.ledger.risk_session.clone(),
|
||||
last_event_time: config.ledger.risk_session.starts_at,
|
||||
};
|
||||
Ok((
|
||||
Self {
|
||||
config,
|
||||
ledger,
|
||||
state,
|
||||
revision: Counter::try_from(0).unwrap(),
|
||||
pending: BTreeMap::new(),
|
||||
orders: BTreeMap::new(),
|
||||
reserved_cash: Posting::ZERO,
|
||||
receipts: Vec::new(),
|
||||
commands: BTreeMap::new(),
|
||||
fills: BTreeMap::new(),
|
||||
fees: BTreeMap::new(),
|
||||
authority,
|
||||
},
|
||||
capability,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn ledger(&self) -> &Ledger {
|
||||
&self.ledger
|
||||
}
|
||||
pub fn state(&self) -> &RiskState {
|
||||
&self.state
|
||||
}
|
||||
pub fn reservations(&self) -> impl Iterator<Item = &Reservation> {
|
||||
self.pending.values()
|
||||
}
|
||||
pub fn available_cash(&self) -> Posting {
|
||||
self.ledger
|
||||
.cash()
|
||||
.checked_sub(self.reserved_cash)
|
||||
.expect("cash reservations are funded")
|
||||
}
|
||||
pub fn apply(&mut self, command: &RiskCommand) -> Result<RiskOutcome, RiskError> {
|
||||
self.apply_input(&RiskInput::Engine(command.clone()))
|
||||
}
|
||||
pub fn reset(
|
||||
&mut self,
|
||||
authority: &OperatorAuthority,
|
||||
reset: &OperatorReset,
|
||||
) -> Result<RiskOutcome, RiskError> {
|
||||
self.validate_authority(authority)?;
|
||||
self.apply_input(&RiskInput::Operator(reset.clone()))
|
||||
}
|
||||
|
||||
pub(super) fn validate_authority(
|
||||
&self,
|
||||
authority: &OperatorAuthority,
|
||||
) -> Result<(), RiskError> {
|
||||
if Arc::ptr_eq(&self.authority, &authority.0) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RiskError::UnauthorizedReset)
|
||||
}
|
||||
}
|
||||
|
||||
fn financial(
|
||||
&self,
|
||||
id: &Id,
|
||||
time: EventTime,
|
||||
body: EngineCommandBody,
|
||||
) -> EngineFinancialCommand {
|
||||
EngineFinancialCommand {
|
||||
version: Version,
|
||||
session_id: self.config.ledger.session_id.clone(),
|
||||
account_id: self.config.ledger.account_id.clone(),
|
||||
command_id: id.clone(),
|
||||
event_time: time,
|
||||
body,
|
||||
}
|
||||
}
|
||||
fn fee(&self, quantity: Posting, price: Posting) -> Result<Posting, RiskError> {
|
||||
Ok(Posting::rate_fee(
|
||||
quantity,
|
||||
price,
|
||||
self.config.fee_rate.into(),
|
||||
)?)
|
||||
}
|
||||
fn cash_for(&self, quantity: Posting, price: Posting) -> Result<Posting, RiskError> {
|
||||
Ok(Posting::notional(quantity, price)?.checked_add(self.fee(quantity, price)?)?)
|
||||
}
|
||||
fn fresh(&self, instrument: &Id, time: EventTime) -> Result<Positive, RiskRejection> {
|
||||
let mark = self
|
||||
.ledger
|
||||
.mark(instrument)
|
||||
.ok_or(RiskRejection::MissingMark)?;
|
||||
let age = i128::from(time.get()) - i128::from(mark.event_time.get());
|
||||
if age < 0 || age > i128::from(self.config.max_mark_age_ms.get()) {
|
||||
return Err(RiskRejection::StaleMark);
|
||||
}
|
||||
Ok(mark.price)
|
||||
}
|
||||
fn fresh_all(&self, time: EventTime) -> Result<(), RiskRejection> {
|
||||
for (id, _, _) in self.ledger.owned_quantities() {
|
||||
self.fresh(id, time)?;
|
||||
}
|
||||
for r in self.pending.values() {
|
||||
self.fresh(&r.order.instrument_id, time)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scan current owned books + live buy commitments, not historical orders.
|
||||
/// Per-owner rounding matches the canonical marked holdings identity.
|
||||
fn increase_check(
|
||||
&self,
|
||||
candidate: &Reservation,
|
||||
time: EventTime,
|
||||
replacing: bool,
|
||||
) -> Result<Option<RiskRejection>, RiskError> {
|
||||
if let Err(reason) = self.fresh_all(time) {
|
||||
return Ok(Some(reason));
|
||||
}
|
||||
if self.state.daily_halted {
|
||||
return Ok(Some(RiskRejection::DailyLoss));
|
||||
}
|
||||
if self.state.drawdown_halted {
|
||||
return Ok(Some(RiskRejection::Drawdown));
|
||||
}
|
||||
let mut books = BTreeMap::<(Id, Id), (Posting, Posting)>::new();
|
||||
let candidate_price: Posting = candidate.price.expect("buy reservation price").into();
|
||||
let mut add =
|
||||
|id: &Id, owner: &Id, quantity: Posting, price: Posting| -> Result<(), RiskError> {
|
||||
let entry = books
|
||||
.entry((id.clone(), owner.clone()))
|
||||
.or_insert((Posting::ZERO, Posting::ZERO));
|
||||
entry.0 = entry.0.checked_add(quantity)?;
|
||||
entry.1 = entry.1.max(price);
|
||||
Ok(())
|
||||
};
|
||||
for (id, owner, quantity) in self.ledger.owned_quantities() {
|
||||
let mark: Posting = self.ledger.mark(id).expect("fresh owned mark").price.into();
|
||||
add(
|
||||
id,
|
||||
owner,
|
||||
quantity,
|
||||
if *id == candidate.order.instrument_id {
|
||||
mark.max(candidate_price)
|
||||
} else {
|
||||
mark
|
||||
},
|
||||
)?;
|
||||
}
|
||||
for r in self.pending.values() {
|
||||
if r.order.side != Side::Buy
|
||||
|| (replacing && r.order.order_id == candidate.order.order_id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mark: Posting = self
|
||||
.ledger
|
||||
.mark(&r.order.instrument_id)
|
||||
.expect("fresh pending mark")
|
||||
.price
|
||||
.into();
|
||||
let mut price = mark.max(r.price.expect("buy price").into());
|
||||
if r.order.instrument_id == candidate.order.instrument_id {
|
||||
price = price.max(candidate_price);
|
||||
}
|
||||
add(
|
||||
&r.order.instrument_id,
|
||||
&r.order.decision.owner_id,
|
||||
r.remaining.into(),
|
||||
price,
|
||||
)?;
|
||||
}
|
||||
add(
|
||||
&candidate.order.instrument_id,
|
||||
&candidate.order.decision.owner_id,
|
||||
candidate.remaining.into(),
|
||||
candidate_price,
|
||||
)?;
|
||||
// Sum prospective quantity per owner/book BEFORE rounding its value.
|
||||
// Separately rounding tiny existing/pending lots can understate the
|
||||
// value after those lots join one canonical owner book. Conservatively
|
||||
// value each prospective book at its greatest committed/market price.
|
||||
let mut quantities = BTreeMap::<Id, Posting>::new();
|
||||
let mut exposure = BTreeMap::<Id, Posting>::new();
|
||||
for ((id, _), (quantity, price)) in books {
|
||||
let q = quantities
|
||||
.get(&id)
|
||||
.copied()
|
||||
.unwrap_or(Posting::ZERO)
|
||||
.checked_add(quantity)?;
|
||||
let e = exposure
|
||||
.get(&id)
|
||||
.copied()
|
||||
.unwrap_or(Posting::ZERO)
|
||||
.checked_add(Posting::notional(quantity, price)?)?;
|
||||
quantities.insert(id.clone(), q);
|
||||
exposure.insert(id, e);
|
||||
}
|
||||
if quantities
|
||||
.values()
|
||||
.any(|q| *q > self.config.max_position_quantity.into())
|
||||
{
|
||||
return Ok(Some(RiskRejection::PositionSize));
|
||||
}
|
||||
if exposure
|
||||
.values()
|
||||
.any(|e| *e > self.config.max_symbol_exposure.into())
|
||||
{
|
||||
return Ok(Some(RiskRejection::SymbolExposure));
|
||||
}
|
||||
if Posting::sum(exposure.values().copied())? > self.config.max_gross_exposure.into() {
|
||||
return Ok(Some(RiskRejection::GrossExposure));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn reservation(
|
||||
&self,
|
||||
order: &RiskOrder,
|
||||
time: EventTime,
|
||||
) -> Result<Result<Reservation, RiskRejection>, RiskError> {
|
||||
let quantity: Posting = order.quantity.into();
|
||||
if quantity > self.config.max_order_quantity.into() {
|
||||
return Ok(Err(RiskRejection::OrderSize));
|
||||
}
|
||||
if order.side == Side::Sell {
|
||||
let committed = Posting::sum(
|
||||
self.pending
|
||||
.values()
|
||||
.filter(|r| {
|
||||
r.order.side == Side::Sell
|
||||
&& r.order.decision.owner_id == order.decision.owner_id
|
||||
&& r.order.instrument_id == order.instrument_id
|
||||
})
|
||||
.map(|r| r.remaining.into()),
|
||||
)?;
|
||||
if quantity.checked_add(committed)?
|
||||
> self
|
||||
.ledger
|
||||
.owner_quantity(&order.decision.owner_id, &order.instrument_id)
|
||||
{
|
||||
return Ok(Err(RiskRejection::InsufficientInventory));
|
||||
}
|
||||
return Ok(Ok(Reservation {
|
||||
order: order.clone(),
|
||||
remaining: order.quantity,
|
||||
cash: nn(Posting::ZERO),
|
||||
price: None,
|
||||
}));
|
||||
}
|
||||
let mark = match self.fresh(&order.instrument_id, time) {
|
||||
Ok(p) => p,
|
||||
Err(r) => return Ok(Err(r)),
|
||||
};
|
||||
let price = pos(Posting::from(mark).max(
|
||||
order
|
||||
.limit_price
|
||||
.map(Posting::from)
|
||||
.unwrap_or(Posting::ZERO),
|
||||
));
|
||||
let cash = self.cash_for(quantity, price.into())?;
|
||||
let reservation = Reservation {
|
||||
order: order.clone(),
|
||||
remaining: order.quantity,
|
||||
cash: nn(cash),
|
||||
price: Some(price),
|
||||
};
|
||||
if cash > self.available_cash() {
|
||||
return Ok(Err(RiskRejection::InsufficientCash));
|
||||
}
|
||||
if let Some(reason) = self.increase_check(&reservation, time, false)? {
|
||||
return Ok(Err(reason));
|
||||
}
|
||||
Ok(Ok(reservation))
|
||||
}
|
||||
|
||||
/// All operands are nonnegative representable ledger equity values, so
|
||||
/// their ordered differences cannot overflow. No fallible state arithmetic
|
||||
/// occurs after a ledger commit.
|
||||
fn observe_equity(&mut self) {
|
||||
let equity = self
|
||||
.ledger
|
||||
.equity()
|
||||
.expect("risk permits only explicitly marked inventory");
|
||||
let peak = Posting::from(self.state.peak_equity).max(equity);
|
||||
self.state.peak_equity = nn(peak);
|
||||
let baseline: Posting = self.state.daily_baseline.into();
|
||||
if baseline >= equity
|
||||
&& baseline
|
||||
.checked_sub(equity)
|
||||
.expect("nonnegative bounded difference")
|
||||
>= self.config.max_daily_loss.into()
|
||||
{
|
||||
self.state.daily_halted = true;
|
||||
}
|
||||
if peak
|
||||
.checked_sub(equity)
|
||||
.expect("nonnegative bounded difference")
|
||||
>= self.config.max_drawdown_amount.into()
|
||||
{
|
||||
self.state.drawdown_halted = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn record(&mut self, input: &RiskInput, outcome: &RiskOutcome) {
|
||||
self.commands
|
||||
.insert(input.id().clone(), self.receipts.len());
|
||||
self.receipts.push(RiskReceipt {
|
||||
input: input.clone(),
|
||||
outcome: outcome.clone(),
|
||||
});
|
||||
}
|
||||
fn apply_input(&mut self, input: &RiskInput) -> Result<RiskOutcome, RiskError> {
|
||||
if let Some(index) = self.commands.get(input.id()) {
|
||||
let receipt = &self.receipts[*index];
|
||||
if receipt.input != *input {
|
||||
return Err(RiskError::CommandConflict);
|
||||
}
|
||||
let mut outcome = receipt.outcome.clone();
|
||||
outcome.replayed = true;
|
||||
return Ok(outcome);
|
||||
}
|
||||
if let RiskInput::Engine(RiskCommand {
|
||||
body: RiskCommandBody::Fill { fill_id, .. },
|
||||
..
|
||||
}) = input
|
||||
{
|
||||
if let Some(index) = self.fills.get(fill_id) {
|
||||
let receipt = &self.receipts[*index];
|
||||
let RiskInput::Engine(original) = &receipt.input else {
|
||||
unreachable!()
|
||||
};
|
||||
let RiskInput::Engine(command) = input else {
|
||||
unreachable!()
|
||||
};
|
||||
if original.body != command.body || original.event_time != command.event_time {
|
||||
return Err(RiskError::FillConflict);
|
||||
}
|
||||
let mut outcome = receipt.outcome.clone();
|
||||
outcome.replayed = true;
|
||||
self.record(input, &outcome);
|
||||
return Ok(outcome);
|
||||
}
|
||||
}
|
||||
if input.time().get() < self.state.last_event_time.get() {
|
||||
return Err(RiskError::BackdatedCommand);
|
||||
}
|
||||
let revision =
|
||||
Counter::try_from(self.revision.get() + 1).map_err(|_| RiskError::RevisionOverflow)?;
|
||||
let mut outcome = RiskOutcome {
|
||||
replayed: false,
|
||||
revision,
|
||||
disposition: RiskDisposition::Accepted,
|
||||
financial: None,
|
||||
remaining: None,
|
||||
released_order: None,
|
||||
reset_baseline: None,
|
||||
};
|
||||
match input {
|
||||
RiskInput::Operator(_) => {
|
||||
self.fresh_all(input.time())
|
||||
.map_err(|_| RiskError::InvalidResetMarks)?;
|
||||
let equity = self.ledger.equity()?;
|
||||
self.state.daily_baseline = nn(equity);
|
||||
self.state.peak_equity = nn(equity);
|
||||
self.state.daily_halted = false;
|
||||
self.state.drawdown_halted = false;
|
||||
outcome.reset_baseline = Some(nn(equity));
|
||||
}
|
||||
RiskInput::Engine(command) => match &command.body {
|
||||
RiskCommandBody::Admit { order } => {
|
||||
if !self
|
||||
.config
|
||||
.ledger
|
||||
.owner_ids
|
||||
.contains(&order.decision.owner_id)
|
||||
{
|
||||
return Err(RiskError::WrongOwner);
|
||||
}
|
||||
if self.orders.contains_key(&order.order_id) {
|
||||
return Err(RiskError::OrderConflict);
|
||||
}
|
||||
match self.reservation(order, command.event_time)? {
|
||||
Ok(reservation) => {
|
||||
let cash = self.reserved_cash.checked_add(reservation.cash.into())?;
|
||||
outcome.remaining = Some(reservation.clone());
|
||||
self.pending.insert(order.order_id.clone(), reservation);
|
||||
self.reserved_cash = cash;
|
||||
}
|
||||
Err(reason) => outcome.disposition = RiskDisposition::Rejected(reason),
|
||||
}
|
||||
self.orders.insert(order.order_id.clone(), order.clone());
|
||||
}
|
||||
RiskCommandBody::Release {
|
||||
owner_id, order_id, ..
|
||||
} => {
|
||||
let order = self.orders.get(order_id).ok_or(RiskError::OrderConflict)?;
|
||||
if order.decision.owner_id != *owner_id {
|
||||
return Err(RiskError::WrongOwner);
|
||||
}
|
||||
if let Some(r) = self.pending.get(order_id) {
|
||||
let cash = self.reserved_cash.checked_sub(r.cash.into())?;
|
||||
self.pending.remove(order_id);
|
||||
self.reserved_cash = cash;
|
||||
outcome.released_order = Some(order_id.clone());
|
||||
}
|
||||
}
|
||||
RiskCommandBody::Mark {
|
||||
instrument_id,
|
||||
price,
|
||||
observed_at,
|
||||
} => {
|
||||
if observed_at.get() > command.event_time.get()
|
||||
|| self
|
||||
.ledger
|
||||
.mark(instrument_id)
|
||||
.is_some_and(|m| observed_at.get() < m.event_time.get())
|
||||
{
|
||||
return Err(RiskError::InvalidMarkTime);
|
||||
}
|
||||
outcome.financial = Some(self.ledger.apply(&self.financial(
|
||||
&command.command_id,
|
||||
*observed_at,
|
||||
EngineCommandBody::Mark {
|
||||
instrument_id: instrument_id.clone(),
|
||||
price: *price,
|
||||
},
|
||||
))?);
|
||||
self.observe_equity();
|
||||
}
|
||||
RiskCommandBody::RiskSessionBoundary { risk_session } => {
|
||||
if *risk_session != self.state.risk_session
|
||||
&& risk_session.starts_at != command.event_time
|
||||
{
|
||||
return Err(RiskError::InvalidBoundaryTime);
|
||||
}
|
||||
let equity = self.ledger.equity()?;
|
||||
let changed = *risk_session != self.state.risk_session;
|
||||
outcome.financial = Some(self.ledger.apply(&self.financial(
|
||||
&command.command_id,
|
||||
command.event_time,
|
||||
EngineCommandBody::RiskSessionBoundary {
|
||||
risk_session: risk_session.clone(),
|
||||
},
|
||||
))?);
|
||||
if changed {
|
||||
self.state.risk_session = risk_session.clone();
|
||||
self.state.daily_baseline = nn(equity);
|
||||
self.state.daily_halted = false;
|
||||
}
|
||||
}
|
||||
RiskCommandBody::Fill {
|
||||
order_id,
|
||||
fill_id,
|
||||
fee_id,
|
||||
quantity,
|
||||
price,
|
||||
} => {
|
||||
if !self.orders.contains_key(order_id) {
|
||||
return Err(RiskError::OrderConflict);
|
||||
}
|
||||
if self.fees.contains_key(fee_id) {
|
||||
return Err(RiskError::FeeConflict);
|
||||
}
|
||||
let Some(reservation) = self.pending.get(order_id).cloned() else {
|
||||
outcome.disposition =
|
||||
RiskDisposition::Rejected(RiskRejection::InactiveOrder);
|
||||
self.finish_fill(input, &outcome, fill_id, fee_id);
|
||||
return Ok(outcome);
|
||||
};
|
||||
if Posting::from(*quantity) > reservation.remaining.into() {
|
||||
return Err(RiskError::ExcessFill);
|
||||
}
|
||||
let remainder =
|
||||
Posting::from(reservation.remaining).checked_sub((*quantity).into())?;
|
||||
let other_cash = self.reserved_cash.checked_sub(reservation.cash.into())?;
|
||||
let fee = self.fee((*quantity).into(), (*price).into())?;
|
||||
let mut next = None;
|
||||
let mut rejected = None;
|
||||
if reservation.order.side == Side::Buy {
|
||||
let mark = match self
|
||||
.fresh(&reservation.order.instrument_id, command.event_time)
|
||||
{
|
||||
Ok(mark) => Posting::from(mark),
|
||||
Err(reason) => {
|
||||
rejected = Some(reason);
|
||||
Posting::ZERO
|
||||
}
|
||||
};
|
||||
let reserve_price = pos(Posting::from(*price)
|
||||
.max(mark)
|
||||
.max(reservation.price.expect("buy price").into()));
|
||||
if !remainder.is_zero() {
|
||||
next = Some(Reservation {
|
||||
remaining: pos(remainder),
|
||||
cash: nn(self.cash_for(remainder, reserve_price.into())?),
|
||||
price: Some(reserve_price),
|
||||
..reservation.clone()
|
||||
});
|
||||
}
|
||||
let cost = self.cash_for((*quantity).into(), (*price).into())?;
|
||||
let needed = Posting::sum([
|
||||
other_cash,
|
||||
cost,
|
||||
next.as_ref()
|
||||
.map(|r| r.cash.into())
|
||||
.unwrap_or(Posting::ZERO),
|
||||
])?;
|
||||
if needed > self.ledger.cash() {
|
||||
rejected = Some(RiskRejection::InsufficientCash);
|
||||
}
|
||||
if rejected.is_none() {
|
||||
let all_remaining = Reservation {
|
||||
price: Some(reserve_price),
|
||||
..reservation.clone()
|
||||
};
|
||||
rejected =
|
||||
self.increase_check(&all_remaining, command.event_time, true)?;
|
||||
}
|
||||
} else if !remainder.is_zero() {
|
||||
next = Some(Reservation {
|
||||
remaining: pos(remainder),
|
||||
..reservation.clone()
|
||||
});
|
||||
}
|
||||
let reserved_cash = if rejected.is_some() {
|
||||
other_cash
|
||||
} else {
|
||||
other_cash.checked_add(
|
||||
next.as_ref()
|
||||
.map(|r| r.cash.into())
|
||||
.unwrap_or(Posting::ZERO),
|
||||
)?
|
||||
};
|
||||
if let Some(reason) = rejected {
|
||||
outcome.disposition = RiskDisposition::Rejected(reason);
|
||||
outcome.released_order = Some(order_id.clone());
|
||||
} else {
|
||||
outcome.financial = Some(self.ledger.apply(&self.financial(
|
||||
&command.command_id,
|
||||
command.event_time,
|
||||
EngineCommandBody::ApplyFill {
|
||||
decision: reservation.order.decision.clone(),
|
||||
order_id: order_id.clone(),
|
||||
fill_id: fill_id.clone(),
|
||||
instrument_id: reservation.order.instrument_id.clone(),
|
||||
side: reservation.order.side,
|
||||
quantity: *quantity,
|
||||
price: *price,
|
||||
fee: Fee {
|
||||
fee_id: fee_id.clone(),
|
||||
amount: nn(fee),
|
||||
},
|
||||
},
|
||||
))?);
|
||||
outcome.remaining = next.clone();
|
||||
self.observe_equity();
|
||||
}
|
||||
self.pending.remove(order_id);
|
||||
if rejected.is_none() {
|
||||
if let Some(r) = next {
|
||||
self.pending.insert(order_id.clone(), r);
|
||||
}
|
||||
}
|
||||
self.reserved_cash = reserved_cash;
|
||||
self.finish_fill(input, &outcome, fill_id, fee_id);
|
||||
return Ok(outcome);
|
||||
}
|
||||
},
|
||||
}
|
||||
self.revision = revision;
|
||||
self.state.last_event_time = input.time();
|
||||
self.record(input, &outcome);
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
fn finish_fill(&mut self, input: &RiskInput, outcome: &RiskOutcome, fill_id: &Id, fee_id: &Id) {
|
||||
self.fills.insert(fill_id.clone(), self.receipts.len());
|
||||
self.fees.insert(fee_id.clone(), fill_id.clone());
|
||||
self.revision = outcome.revision;
|
||||
self.state.last_event_time = input.time();
|
||||
self.record(input, outcome);
|
||||
}
|
||||
pub fn checkpoint(&self) -> RiskCheckpoint {
|
||||
RiskCheckpoint {
|
||||
version: Version,
|
||||
config: self.config.clone(),
|
||||
ledger: self.ledger.checkpoint(),
|
||||
revision: self.revision,
|
||||
state: self.state.clone(),
|
||||
reservations: self.pending.values().cloned().collect(),
|
||||
receipts: self.receipts.clone(),
|
||||
}
|
||||
}
|
||||
/// Restoring issues a new instance capability; the previous account's
|
||||
/// capability cannot authorize operations on this restored instance.
|
||||
pub fn restore(checkpoint: RiskCheckpoint) -> Result<(Self, OperatorAuthority), RiskError> {
|
||||
let (mut account, authority) =
|
||||
Self::new(checkpoint.config.clone()).map_err(|_| RiskError::InvalidCheckpoint)?;
|
||||
for receipt in &checkpoint.receipts {
|
||||
let outcome = account
|
||||
.apply_input(&receipt.input)
|
||||
.map_err(|_| RiskError::InvalidCheckpoint)?;
|
||||
if outcome != receipt.outcome {
|
||||
return Err(RiskError::InvalidCheckpoint);
|
||||
}
|
||||
}
|
||||
if account.checkpoint() != checkpoint {
|
||||
return Err(RiskError::InvalidCheckpoint);
|
||||
}
|
||||
Ok((account, authority))
|
||||
}
|
||||
}
|
||||
884
apps/stock/engine/src/financial/risk_tests.rs
Normal file
884
apps/stock/engine/src/financial/risk_tests.rs
Normal file
|
|
@ -0,0 +1,884 @@
|
|||
use super::{
|
||||
contract::*,
|
||||
ledger::LedgerError,
|
||||
risk::*,
|
||||
scalar::{Posting, ScalarError, MAX_POSTING},
|
||||
};
|
||||
use serde_json::json;
|
||||
use std::time::Instant;
|
||||
|
||||
fn p(v: &str) -> Posting {
|
||||
v.parse().unwrap()
|
||||
}
|
||||
fn id(v: &str) -> Id {
|
||||
serde_json::from_value(json!(v)).unwrap()
|
||||
}
|
||||
fn positive(v: &str) -> Positive {
|
||||
p(v).try_into().unwrap()
|
||||
}
|
||||
fn time(v: i64) -> EventTime {
|
||||
v.try_into().unwrap()
|
||||
}
|
||||
fn config(capital: &str) -> RiskConfig {
|
||||
serde_json::from_value(json!({
|
||||
"ledger":{"version":1,"sessionId":"run","accountId":"account","baseCurrency":"USD",
|
||||
"reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":capital,
|
||||
"riskSession":{"calendarId":"account-calendar","calendarRevision":"v1","sessionId":"day1","startsAt":0}},
|
||||
"feeRate":"0","maxOrderQuantity":"1000000","maxPositionQuantity":"1000000",
|
||||
"maxSymbolExposure":"1000000","maxGrossExposure":"1000000","maxDailyLoss":"1000000",
|
||||
"maxDrawdownAmount":"1000000","maxMarkAgeMs":100
|
||||
})).unwrap()
|
||||
}
|
||||
fn account(capital: &str) -> RiskAccount {
|
||||
RiskAccount::new(config(capital)).unwrap().0
|
||||
}
|
||||
fn cmd(key: &str, t: i64, body: RiskCommandBody) -> RiskCommand {
|
||||
RiskCommand {
|
||||
command_id: id(key),
|
||||
event_time: time(t),
|
||||
body,
|
||||
}
|
||||
}
|
||||
fn mark_command(key: &str, instrument: &str, price: &str, t: i64, observed: i64) -> RiskCommand {
|
||||
cmd(
|
||||
key,
|
||||
t,
|
||||
RiskCommandBody::Mark {
|
||||
instrument_id: id(instrument),
|
||||
price: positive(price),
|
||||
observed_at: time(observed),
|
||||
},
|
||||
)
|
||||
}
|
||||
fn mark(a: &mut RiskAccount, key: &str, instrument: &str, price: &str, t: i64) {
|
||||
accepted(
|
||||
a.apply(&mark_command(key, instrument, price, t, t))
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
fn order(key: &str, owner: &str, instrument: &str, side: Side, quantity: &str) -> RiskOrder {
|
||||
RiskOrder {
|
||||
order_id: id(key),
|
||||
decision: DecisionIdentity {
|
||||
owner_id: id(owner),
|
||||
decision_id: id(&format!("decision-{key}")),
|
||||
sequence: 0.try_into().unwrap(),
|
||||
},
|
||||
instrument_id: id(instrument),
|
||||
side,
|
||||
quantity: positive(quantity),
|
||||
limit_price: None,
|
||||
origin: OrderOrigin::Explicit,
|
||||
}
|
||||
}
|
||||
fn admit_command(o: RiskOrder, t: i64) -> RiskCommand {
|
||||
cmd(
|
||||
&format!("admit-{}", serde_json::to_string(&o.order_id).unwrap()),
|
||||
t,
|
||||
RiskCommandBody::Admit { order: o },
|
||||
)
|
||||
}
|
||||
fn admit(a: &mut RiskAccount, o: RiskOrder, t: i64) -> RiskOutcome {
|
||||
a.apply(&admit_command(o, t)).unwrap()
|
||||
}
|
||||
fn fill_command(order: &str, fill: &str, quantity: &str, price: &str, t: i64) -> RiskCommand {
|
||||
cmd(
|
||||
fill,
|
||||
t,
|
||||
RiskCommandBody::Fill {
|
||||
order_id: id(order),
|
||||
fill_id: id(fill),
|
||||
fee_id: id(&format!("fee-{fill}")),
|
||||
quantity: positive(quantity),
|
||||
price: positive(price),
|
||||
},
|
||||
)
|
||||
}
|
||||
fn fill(
|
||||
a: &mut RiskAccount,
|
||||
order: &str,
|
||||
key: &str,
|
||||
quantity: &str,
|
||||
price: &str,
|
||||
t: i64,
|
||||
) -> RiskOutcome {
|
||||
a.apply(&fill_command(order, key, quantity, price, t))
|
||||
.unwrap()
|
||||
}
|
||||
fn release(
|
||||
a: &mut RiskAccount,
|
||||
key: &str,
|
||||
order: &str,
|
||||
owner: &str,
|
||||
reason: ReleaseReason,
|
||||
t: i64,
|
||||
) -> RiskOutcome {
|
||||
a.apply(&cmd(
|
||||
key,
|
||||
t,
|
||||
RiskCommandBody::Release {
|
||||
owner_id: id(owner),
|
||||
order_id: id(order),
|
||||
reason,
|
||||
},
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
fn accepted(out: RiskOutcome) {
|
||||
assert_eq!(out.disposition, RiskDisposition::Accepted);
|
||||
}
|
||||
fn rejected(out: RiskOutcome, reason: RiskRejection) {
|
||||
assert_eq!(out.disposition, RiskDisposition::Rejected(reason));
|
||||
}
|
||||
fn unchanged(a: &mut RiskAccount, c: &RiskCommand, error: RiskError) {
|
||||
let before = a.checkpoint();
|
||||
assert_eq!(a.apply(c), Err(error));
|
||||
assert_eq!(a.checkpoint(), before);
|
||||
}
|
||||
fn buy(
|
||||
a: &mut RiskAccount,
|
||||
key: &str,
|
||||
owner: &str,
|
||||
instrument: &str,
|
||||
quantity: &str,
|
||||
price: &str,
|
||||
t: i64,
|
||||
) {
|
||||
accepted(admit(
|
||||
a,
|
||||
order(key, owner, instrument, Side::Buy, quantity),
|
||||
t,
|
||||
));
|
||||
accepted(fill(a, key, &format!("fill-{key}"), quantity, price, t));
|
||||
}
|
||||
fn boundary(key: &str, session: &str, starts: i64, t: i64) -> RiskCommand {
|
||||
cmd(
|
||||
key,
|
||||
t,
|
||||
RiskCommandBody::RiskSessionBoundary {
|
||||
risk_session: RiskSessionIdentity {
|
||||
calendar_id: id("account-calendar"),
|
||||
calendar_revision: id("v1"),
|
||||
session_id: id(session),
|
||||
starts_at: time(starts),
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
fn reset(key: &str, t: i64) -> OperatorReset {
|
||||
OperatorReset {
|
||||
command_id: id(key),
|
||||
event_time: time(t),
|
||||
actor_id: id("operator"),
|
||||
reason: id("reviewed incident"),
|
||||
}
|
||||
}
|
||||
fn reconcile(a: &RiskAccount) {
|
||||
let value = a.ledger().valuation().unwrap();
|
||||
assert_eq!(
|
||||
value.equity,
|
||||
value.cash.checked_add(value.marked_holdings).unwrap()
|
||||
);
|
||||
let reserved = Posting::sum(a.reservations().map(|r| r.cash.into())).unwrap();
|
||||
assert_eq!(
|
||||
a.available_cash().checked_add(reserved).unwrap(),
|
||||
value.cash
|
||||
);
|
||||
assert!(!a.available_cash().is_negative());
|
||||
assert_eq!(
|
||||
value.equity,
|
||||
Posting::sum(value.owners.iter().map(|o| o.equity_contribution)).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn competing_reservations_and_all_release_reasons() {
|
||||
let mut c = config("100");
|
||||
c.fee_rate = p("0.01").try_into().unwrap();
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
accepted(admit(&mut a, order("one", "A", "X", Side::Buy, "6"), 0));
|
||||
assert_eq!(a.available_cash(), p("39.4"));
|
||||
rejected(
|
||||
admit(&mut a, order("two", "B", "X", Side::Buy, "4"), 0),
|
||||
RiskRejection::InsufficientCash,
|
||||
);
|
||||
assert_eq!(a.reservations().count(), 1);
|
||||
accepted(fill(&mut a, "one", "part", "2", "10", 1));
|
||||
assert_eq!(
|
||||
a.reservations().next().unwrap().cash,
|
||||
p("40.4").try_into().unwrap()
|
||||
);
|
||||
assert_eq!(a.available_cash(), p("39.4"));
|
||||
accepted(release(
|
||||
&mut a,
|
||||
"cancel",
|
||||
"one",
|
||||
"A",
|
||||
ReleaseReason::Cancelled,
|
||||
1,
|
||||
));
|
||||
assert_eq!(a.available_cash(), p("79.8"));
|
||||
for (i, reason) in [ReleaseReason::Rejected, ReleaseReason::Expired]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let oid = format!("later-{i}");
|
||||
accepted(admit(&mut a, order(&oid, "A", "X", Side::Buy, "1"), 1));
|
||||
accepted(release(
|
||||
&mut a,
|
||||
&format!("release-{i}"),
|
||||
&oid,
|
||||
"A",
|
||||
reason,
|
||||
1,
|
||||
));
|
||||
}
|
||||
assert_eq!(a.reservations().count(), 0);
|
||||
reconcile(&a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adverse_gap_reject_remainder_preserves_prior_fills_and_receipts() {
|
||||
let mut a = account("100");
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
accepted(admit(&mut a, order("o", "A", "X", Side::Buy, "10"), 0));
|
||||
accepted(fill(&mut a, "o", "first", "2", "10", 1));
|
||||
let command = fill_command("o", "gap", "2", "11", 2);
|
||||
let outcome = a.apply(&command).unwrap();
|
||||
rejected(outcome.clone(), RiskRejection::InsufficientCash);
|
||||
assert_eq!(outcome.released_order, Some(id("o")));
|
||||
assert!(outcome.financial.is_none());
|
||||
assert_eq!(a.ledger().cash(), p("80"));
|
||||
assert_eq!(a.ledger().owner_quantity(&id("A"), &id("X")), p("2"));
|
||||
assert_eq!(a.reservations().count(), 0);
|
||||
let checkpoint = a.checkpoint();
|
||||
let mut retry = outcome.clone();
|
||||
retry.replayed = true;
|
||||
assert_eq!(a.apply(&command).unwrap(), retry);
|
||||
assert_eq!(a.checkpoint(), checkpoint);
|
||||
let mut alias = command.clone();
|
||||
alias.command_id = id("gap-alias");
|
||||
assert_eq!(a.apply(&alias).unwrap(), retry);
|
||||
assert_eq!(a.ledger().cash(), p("80"));
|
||||
let mut restored = RiskAccount::restore(a.checkpoint()).unwrap().0;
|
||||
assert_eq!(restored.apply(&alias).unwrap(), retry);
|
||||
reconcile(&restored);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_other_symbol_and_other_pending_symbol_block_increases_not_reductions() {
|
||||
for pending_only in [false, true] {
|
||||
let mut a = account("1000");
|
||||
mark(&mut a, "mx", "X", "10", 0);
|
||||
accepted(admit(&mut a, order("old", "A", "X", Side::Buy, "1"), 0));
|
||||
if !pending_only {
|
||||
accepted(fill(&mut a, "old", "old-fill", "1", "10", 0));
|
||||
}
|
||||
mark(&mut a, "my", "Y", "10", 101);
|
||||
rejected(
|
||||
admit(&mut a, order("new", "B", "Y", Side::Buy, "1"), 101),
|
||||
RiskRejection::StaleMark,
|
||||
);
|
||||
if !pending_only {
|
||||
accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "1"), 101));
|
||||
accepted(fill(&mut a, "sell", "sell-fill", "1", "9", 101));
|
||||
}
|
||||
reconcile(&a);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delayed_mark_is_not_freshened_and_future_or_backdated_time_is_atomic() {
|
||||
let mut a = account("100");
|
||||
accepted(
|
||||
a.apply(&mark_command("delayed", "X", "10", 101, 0))
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(a.ledger().mark(&id("X")).unwrap().event_time, time(0));
|
||||
rejected(
|
||||
admit(&mut a, order("o", "A", "X", Side::Buy, "1"), 101),
|
||||
RiskRejection::StaleMark,
|
||||
);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&mark_command("future", "Y", "10", 101, 102),
|
||||
RiskError::InvalidMarkTime,
|
||||
);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&mark_command("backdated", "Y", "10", 100, 100),
|
||||
RiskError::BackdatedCommand,
|
||||
);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&mark_command("older", "X", "10", 101, -1),
|
||||
RiskError::InvalidMarkTime,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marked_loss_halt_and_explicit_risk_session_boundary() {
|
||||
let mut c = config("100");
|
||||
c.max_daily_loss = positive("10");
|
||||
c.max_drawdown_amount = positive("50");
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
buy(&mut a, "buy", "A", "X", "5", "10", 0);
|
||||
mark(&mut a, "loss", "X", "8", 1);
|
||||
assert_eq!(a.ledger().valuation().unwrap().realized_gross_pnl, p("0"));
|
||||
assert!(a.state().daily_halted);
|
||||
rejected(
|
||||
admit(&mut a, order("halted", "A", "X", Side::Buy, "1"), 1),
|
||||
RiskRejection::DailyLoss,
|
||||
);
|
||||
accepted(a.apply(&boundary("same", "day1", 0, 1)).unwrap());
|
||||
assert!(a.state().daily_halted);
|
||||
mark(&mut a, "recover", "X", "10", 2);
|
||||
assert!(a.state().daily_halted);
|
||||
accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "1"), 2));
|
||||
accepted(fill(&mut a, "sell", "sell-fill", "1", "10", 2));
|
||||
accepted(a.apply(&boundary("next", "day2", 3, 3)).unwrap());
|
||||
assert!(!a.state().daily_halted);
|
||||
assert_eq!(a.state().daily_baseline, p("100").try_into().unwrap());
|
||||
accepted(admit(&mut a, order("after", "A", "X", Side::Buy, "1"), 3));
|
||||
reconcile(&a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawdown_halt_survives_rollover_restore_and_requires_authorized_reset() {
|
||||
let mut c = config("100");
|
||||
c.max_drawdown_amount = positive("10");
|
||||
let (mut a, authority) = RiskAccount::new(c).unwrap();
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
buy(&mut a, "buy", "A", "X", "5", "10", 0);
|
||||
mark(&mut a, "peak", "X", "12", 1);
|
||||
mark(&mut a, "loss", "X", "10", 2);
|
||||
assert!(a.state().drawdown_halted);
|
||||
accepted(a.apply(&boundary("next", "day2", 3, 3)).unwrap());
|
||||
assert_eq!(a.state().peak_equity, p("110").try_into().unwrap());
|
||||
let (mut restored, restored_authority) = RiskAccount::restore(a.checkpoint()).unwrap();
|
||||
assert!(restored.state().drawdown_halted);
|
||||
rejected(
|
||||
admit(&mut restored, order("halted", "A", "X", Side::Buy, "1"), 3),
|
||||
RiskRejection::Drawdown,
|
||||
);
|
||||
let before = restored.checkpoint();
|
||||
assert_eq!(
|
||||
restored.reset(&authority, &reset("bad", 3)),
|
||||
Err(RiskError::UnauthorizedReset)
|
||||
);
|
||||
assert_eq!(restored.checkpoint(), before);
|
||||
let outcome = restored
|
||||
.reset(&restored_authority, &reset("reset", 3))
|
||||
.unwrap();
|
||||
assert_eq!(outcome.reset_baseline, Some(p("100").try_into().unwrap()));
|
||||
assert!(!restored.state().drawdown_halted);
|
||||
assert!(!restored.state().daily_halted);
|
||||
assert_eq!(restored.state().peak_equity, p("100").try_into().unwrap());
|
||||
assert_eq!(
|
||||
RiskAccount::restore(restored.checkpoint())
|
||||
.unwrap()
|
||||
.0
|
||||
.checkpoint(),
|
||||
restored.checkpoint()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unauthorized_reset_denied_and_not_deserializable_as_engine_command() {
|
||||
let (mut a, _) = RiskAccount::new(config("100")).unwrap();
|
||||
let (_, wrong_authority) = RiskAccount::new(config("100")).unwrap();
|
||||
let before = a.checkpoint();
|
||||
assert_eq!(
|
||||
a.reset(&wrong_authority, &reset("unauthorized", 0)),
|
||||
Err(RiskError::UnauthorizedReset)
|
||||
);
|
||||
assert_eq!(a.checkpoint(), before);
|
||||
assert!(serde_json::from_value::<RiskCommandBody>(
|
||||
json!({"kind":"reset","actorId":"operator"})
|
||||
)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alternate_venue_does_not_reset_account_day_and_invalid_boundaries_are_atomic() {
|
||||
let mut a = account("100");
|
||||
mark(&mut a, "m", "X", "10", 10);
|
||||
let mut venue = boundary("venue", "day2", 10, 10);
|
||||
if let RiskCommandBody::RiskSessionBoundary { risk_session } = &mut venue.body {
|
||||
risk_session.calendar_id = id("another-venue");
|
||||
}
|
||||
unchanged(
|
||||
&mut a,
|
||||
&venue,
|
||||
RiskError::Ledger(LedgerError::InvalidRiskSession),
|
||||
);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&boundary("future", "day2", 11, 10),
|
||||
RiskError::InvalidBoundaryTime,
|
||||
);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&boundary("past", "day2", 9, 10),
|
||||
RiskError::InvalidBoundaryTime,
|
||||
);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&boundary("changed-start", "day1", 10, 10),
|
||||
RiskError::Ledger(LedgerError::InvalidRiskSession),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inventory_reservations_wrong_owner_and_zero_cash_sell() {
|
||||
let mut c = config("110");
|
||||
c.fee_rate = p("0.1").try_into().unwrap();
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
buy(&mut a, "buy", "A", "X", "10", "10", 0);
|
||||
assert_eq!(a.ledger().cash(), p("0"));
|
||||
rejected(
|
||||
admit(&mut a, order("steal", "B", "X", Side::Sell, "1"), 0),
|
||||
RiskRejection::InsufficientInventory,
|
||||
);
|
||||
accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "6"), 101));
|
||||
rejected(
|
||||
admit(&mut a, order("oversell", "A", "X", Side::Sell, "5"), 101),
|
||||
RiskRejection::InsufficientInventory,
|
||||
);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&cmd(
|
||||
"steal-cancel",
|
||||
101,
|
||||
RiskCommandBody::Release {
|
||||
owner_id: id("B"),
|
||||
order_id: id("sell"),
|
||||
reason: ReleaseReason::Cancelled,
|
||||
},
|
||||
),
|
||||
RiskError::WrongOwner,
|
||||
);
|
||||
accepted(fill(&mut a, "sell", "sell-fill", "2", "10", 101));
|
||||
assert_eq!(a.ledger().cash(), p("18"));
|
||||
accepted(release(
|
||||
&mut a,
|
||||
"release",
|
||||
"sell",
|
||||
"A",
|
||||
ReleaseReason::Expired,
|
||||
101,
|
||||
));
|
||||
accepted(admit(&mut a, order("rest", "A", "X", Side::Sell, "8"), 101));
|
||||
accepted(fill(&mut a, "rest", "rest-fill", "8", "10", 101));
|
||||
assert_eq!(a.ledger().cash(), p("90"));
|
||||
reconcile(&a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_sells_never_fund_buys_or_reduce_exposure_and_fill_price_is_checked() {
|
||||
let mut c = config("200");
|
||||
c.max_gross_exposure = positive("100");
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "mx", "X", "10", 0);
|
||||
mark(&mut a, "my", "Y", "10", 0);
|
||||
buy(&mut a, "buy", "A", "X", "10", "10", 0);
|
||||
accepted(admit(&mut a, order("sell", "A", "X", Side::Sell, "10"), 0));
|
||||
rejected(
|
||||
admit(&mut a, order("new", "B", "Y", Side::Buy, "1"), 0),
|
||||
RiskRejection::GrossExposure,
|
||||
);
|
||||
let mut b = account("100");
|
||||
mark(&mut b, "m", "X", "10", 0);
|
||||
buy(&mut b, "buy", "A", "X", "10", "10", 0);
|
||||
accepted(admit(&mut b, order("sell", "A", "X", Side::Sell, "10"), 0));
|
||||
rejected(
|
||||
admit(&mut b, order("fund", "B", "X", Side::Buy, "1"), 0),
|
||||
RiskRejection::InsufficientCash,
|
||||
);
|
||||
let mut c = config("1000");
|
||||
c.max_symbol_exposure = positive("100");
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
accepted(admit(&mut a, order("o", "A", "X", Side::Buy, "10"), 0));
|
||||
rejected(
|
||||
fill(&mut a, "o", "gap", "1", "11", 1),
|
||||
RiskRejection::SymbolExposure,
|
||||
);
|
||||
assert_eq!(a.ledger().cash(), p("1000"));
|
||||
assert_eq!(a.reservations().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fee_is_rounded_once_and_quantum_partial_fill_cannot_leave_unfunded_remainder() {
|
||||
let mut c = config("0.00000001");
|
||||
c.fee_rate = p("0.5").try_into().unwrap();
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "0.5", 0);
|
||||
buy(&mut a, "buy", "A", "X", "0.00000001", "0.5", 0);
|
||||
assert_eq!(a.ledger().cash(), p("0"));
|
||||
assert_eq!(a.ledger().valuation().unwrap().fees, p("0"));
|
||||
let mut a = account("0.00000001");
|
||||
mark(&mut a, "m", "X", "0.5", 0);
|
||||
accepted(admit(
|
||||
&mut a,
|
||||
order("o", "A", "X", Side::Buy, "0.00000002"),
|
||||
0,
|
||||
));
|
||||
rejected(
|
||||
fill(&mut a, "o", "split", "0.00000001", "0.5", 0),
|
||||
RiskRejection::InsufficientCash,
|
||||
);
|
||||
assert_eq!(a.ledger().cash(), p("0.00000001"));
|
||||
assert_eq!(a.reservations().count(), 0);
|
||||
reconcile(&a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exposure_respects_owner_rounding_and_combined_pending_quantities() {
|
||||
let mut c = config("1");
|
||||
c.max_gross_exposure = positive("0.00000002");
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "0.5", 0);
|
||||
buy(&mut a, "a", "A", "X", "0.00000001", "0.5", 0);
|
||||
buy(&mut a, "b", "B", "X", "0.00000001", "0.5", 0);
|
||||
assert_eq!(
|
||||
a.ledger().valuation().unwrap().marked_holdings,
|
||||
p("0.00000002")
|
||||
);
|
||||
rejected(
|
||||
admit(&mut a, order("c", "A", "X", Side::Buy, "0.00000002"), 0),
|
||||
RiskRejection::GrossExposure,
|
||||
);
|
||||
let mut c = config("1");
|
||||
c.max_symbol_exposure = positive("0.00000001");
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "0.49", 0);
|
||||
buy(&mut a, "existing", "A", "X", "0.00000003", "0.49", 0);
|
||||
rejected(
|
||||
admit(
|
||||
&mut a,
|
||||
order("candidate", "A", "X", Side::Buy, "0.00000001"),
|
||||
0,
|
||||
),
|
||||
RiskRejection::SymbolExposure,
|
||||
);
|
||||
let mut c = config("1");
|
||||
c.max_symbol_exposure = positive("0.00000001");
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "0.49", 0);
|
||||
accepted(admit(
|
||||
&mut a,
|
||||
order("pending", "A", "X", Side::Buy, "0.00000003"),
|
||||
0,
|
||||
));
|
||||
rejected(
|
||||
admit(
|
||||
&mut a,
|
||||
order("candidate", "A", "X", Side::Buy, "0.00000001"),
|
||||
0,
|
||||
),
|
||||
RiskRejection::SymbolExposure,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_accepted_rejected_and_conflicting_ids_preserve_state() {
|
||||
let mut a = account("100");
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
for (key, quantity) in [("good", "1"), ("bad", "100")] {
|
||||
let command = admit_command(order(key, "A", "X", Side::Buy, quantity), 0);
|
||||
let mut expected = a.apply(&command).unwrap();
|
||||
expected.replayed = true;
|
||||
let checkpoint = a.checkpoint();
|
||||
assert_eq!(a.apply(&command).unwrap(), expected);
|
||||
assert_eq!(a.checkpoint(), checkpoint);
|
||||
let mut conflicting = command.clone();
|
||||
conflicting.event_time = time(1);
|
||||
unchanged(&mut a, &conflicting, RiskError::CommandConflict);
|
||||
conflicting.command_id = id(&format!("new-{key}"));
|
||||
unchanged(&mut a, &conflicting, RiskError::OrderConflict);
|
||||
}
|
||||
let fill = fill_command("good", "fill", "1", "10", 0);
|
||||
let mut expected = a.apply(&fill).unwrap();
|
||||
expected.replayed = true;
|
||||
let mut alias = fill.clone();
|
||||
alias.command_id = id("alias");
|
||||
assert_eq!(a.apply(&alias).unwrap(), expected);
|
||||
let mut conflict = alias.clone();
|
||||
conflict.command_id = id("conflict");
|
||||
conflict.event_time = time(1);
|
||||
unchanged(&mut a, &conflict, RiskError::FillConflict);
|
||||
accepted(admit(&mut a, order("later", "A", "X", Side::Buy, "1"), 0));
|
||||
let mut fee_conflict = fill_command("later", "later-fill", "1", "10", 0);
|
||||
if let RiskCommandBody::Fill { fee_id, .. } = &mut fee_conflict.body {
|
||||
*fee_id = id("fee-fill");
|
||||
}
|
||||
unchanged(&mut a, &fee_conflict, RiskError::FeeConflict);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&fill_command("unreserved", "bypass", "1", "10", 0),
|
||||
RiskError::OrderConflict,
|
||||
);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&fill_command("later", "too-big", "2", "10", 0),
|
||||
RiskError::ExcessFill,
|
||||
);
|
||||
reconcile(&a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_after_clock_advance_returns_original_receipt_without_republishing() {
|
||||
let mut a = account("100");
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
let rejected_command = admit_command(order("bad", "A", "X", Side::Buy, "100"), 0);
|
||||
let mut rejected_outcome = a.apply(&rejected_command).unwrap();
|
||||
rejected_outcome.replayed = true;
|
||||
accepted(admit(&mut a, order("good", "A", "X", Side::Buy, "1"), 0));
|
||||
let fill = fill_command("good", "filled", "1", "10", 0);
|
||||
let mut outcome = a.apply(&fill).unwrap();
|
||||
outcome.replayed = true;
|
||||
assert!(!outcome.financial.as_ref().unwrap().replayed);
|
||||
mark(&mut a, "later-mark", "X", "11", 10);
|
||||
let before = a.checkpoint();
|
||||
assert_eq!(a.apply(&rejected_command).unwrap(), rejected_outcome);
|
||||
assert_eq!(a.apply(&fill).unwrap(), outcome);
|
||||
assert_eq!(a.checkpoint(), before);
|
||||
let mut alias = fill.clone();
|
||||
alias.command_id = id("later-alias");
|
||||
assert_eq!(a.apply(&alias).unwrap(), outcome);
|
||||
assert_eq!(a.state().last_event_time, time(10));
|
||||
assert_eq!(a.checkpoint().revision, before.revision);
|
||||
assert_eq!(a.ledger().checkpoint(), before.ledger);
|
||||
let mut restored = RiskAccount::restore(a.checkpoint()).unwrap().0;
|
||||
let checkpoint = restored.checkpoint();
|
||||
assert_eq!(restored.apply(&alias).unwrap(), outcome);
|
||||
assert_eq!(restored.checkpoint(), checkpoint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantity_limits_limit_reservations_and_pending_mark_repricing() {
|
||||
let mut c = config("1000");
|
||||
c.max_order_quantity = positive("2");
|
||||
c.max_position_quantity = positive("3");
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
rejected(
|
||||
admit(&mut a, order("large", "A", "X", Side::Buy, "3"), 0),
|
||||
RiskRejection::OrderSize,
|
||||
);
|
||||
accepted(admit(&mut a, order("a", "A", "X", Side::Buy, "2"), 0));
|
||||
rejected(
|
||||
admit(&mut a, order("b", "B", "X", Side::Buy, "2"), 0),
|
||||
RiskRejection::PositionSize,
|
||||
);
|
||||
accepted(fill(&mut a, "a", "fill-a", "2", "10", 0));
|
||||
rejected(
|
||||
admit(&mut a, order("sell-large", "A", "X", Side::Sell, "3"), 0),
|
||||
RiskRejection::OrderSize,
|
||||
);
|
||||
let mut c = config("1000");
|
||||
c.max_gross_exposure = positive("100");
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "mx", "X", "10", 0);
|
||||
mark(&mut a, "my", "Y", "10", 0);
|
||||
let mut limit = order("limit", "A", "X", Side::Buy, "5");
|
||||
limit.limit_price = Some(positive("11"));
|
||||
accepted(admit(&mut a, limit, 0));
|
||||
assert_eq!(a.available_cash(), p("945"));
|
||||
mark(&mut a, "up", "X", "20", 1);
|
||||
// The pending reservation remains funded at its admitted price, but risk
|
||||
// exposure revalues the open commitment at the new canonical mark.
|
||||
assert_eq!(a.available_cash(), p("945"));
|
||||
rejected(
|
||||
admit(&mut a, order("new", "B", "Y", Side::Buy, "1"), 1),
|
||||
RiskRejection::GrossExposure,
|
||||
);
|
||||
// Limit crossing remains F05's job; F04's fill rejection here is freshness.
|
||||
rejected(
|
||||
fill(&mut a, "limit", "stale", "1", "10", 102),
|
||||
RiskRejection::StaleMark,
|
||||
);
|
||||
assert_eq!(a.reservations().count(), 0);
|
||||
reconcile(&a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkpoint_tamper_is_rejected_and_replay_is_byte_identical() {
|
||||
let (mut a, authority) = RiskAccount::new(config("100")).unwrap();
|
||||
mark(&mut a, "m", "X", "10", 0);
|
||||
accepted(admit(&mut a, order("o", "A", "X", Side::Buy, "5"), 0));
|
||||
accepted(fill(&mut a, "o", "part", "2", "10", 1));
|
||||
accepted(a.reset(&authority, &reset("reset", 1)).unwrap());
|
||||
let checkpoint = a.checkpoint();
|
||||
let encoded = serde_json::to_vec(&checkpoint).unwrap();
|
||||
let restored = RiskAccount::restore(serde_json::from_slice(&encoded).unwrap())
|
||||
.unwrap()
|
||||
.0;
|
||||
assert_eq!(serde_json::to_vec(&restored.checkpoint()).unwrap(), encoded);
|
||||
for variant in 0..8 {
|
||||
let mut changed = checkpoint.clone();
|
||||
match variant {
|
||||
0 => changed.state.drawdown_halted = true,
|
||||
1 => changed.reservations[0].cash = p("1").try_into().unwrap(),
|
||||
2 => changed.state.last_event_time = time(999),
|
||||
3 => {
|
||||
changed.receipts[1].outcome.disposition =
|
||||
RiskDisposition::Rejected(RiskRejection::DailyLoss)
|
||||
}
|
||||
4 => changed.receipts.swap(0, 1),
|
||||
5 => changed.state.daily_baseline = p("99").try_into().unwrap(),
|
||||
6 => changed.ledger.economic.cash = p("99").try_into().unwrap(),
|
||||
_ => {
|
||||
changed.receipts.last_mut().unwrap().outcome.reset_baseline =
|
||||
Some(p("99").try_into().unwrap())
|
||||
}
|
||||
}
|
||||
assert!(matches!(
|
||||
RiskAccount::restore(changed),
|
||||
Err(RiskError::InvalidCheckpoint)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_limits_overflow_and_failed_marks_are_atomic() {
|
||||
let mut invalid = config("100");
|
||||
invalid.fee_rate = p("1.00000001").try_into().unwrap();
|
||||
assert!(matches!(
|
||||
RiskAccount::new(invalid),
|
||||
Err(RiskError::InvalidFeeRate)
|
||||
));
|
||||
let mut a = account("100");
|
||||
mark(&mut a, "m", "X", "1", 0);
|
||||
buy(&mut a, "a", "A", "X", "1", "1", 0);
|
||||
buy(&mut a, "b", "B", "X", "2", "1", 0);
|
||||
unchanged(
|
||||
&mut a,
|
||||
&mark_command("overflow", "X", MAX_POSTING, 1, 1),
|
||||
RiskError::Ledger(LedgerError::Arithmetic(ScalarError::Overflow)),
|
||||
);
|
||||
let mut c = config(MAX_POSTING);
|
||||
c.max_order_quantity = positive(MAX_POSTING);
|
||||
c.max_position_quantity = positive(MAX_POSTING);
|
||||
c.max_symbol_exposure = positive(MAX_POSTING);
|
||||
c.max_gross_exposure = positive(MAX_POSTING);
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
mark(&mut a, "m", "X", "0.00000001", 0);
|
||||
accepted(admit(
|
||||
&mut a,
|
||||
order("large", "A", "X", Side::Buy, MAX_POSTING),
|
||||
0,
|
||||
));
|
||||
unchanged(
|
||||
&mut a,
|
||||
&admit_command(order("more", "A", "X", Side::Buy, "1"), 0),
|
||||
RiskError::Arithmetic(ScalarError::Overflow),
|
||||
);
|
||||
// Unrepresentable arithmetic is an atomic command error, not an ordinary
|
||||
// affordable-range risk rejection. The host must fail the unsupported
|
||||
// attempt rather than silently borrowing, resizing or retrying forever.
|
||||
unchanged(
|
||||
&mut a,
|
||||
&fill_command("large", "overflow-fill", MAX_POSTING, "2", 1),
|
||||
RiskError::Arithmetic(ScalarError::Overflow),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_order_and_target_normalization_cannot_bypass_identical_policy() {
|
||||
// Exhaustive bounded parameter property, including fee/cash rejection and
|
||||
// fill gaps. The actual target expansion/mode coordinator belongs to F05.
|
||||
for capital in 1..=12 {
|
||||
for quantity in 1..=15 {
|
||||
let mut c = config(&capital.to_string());
|
||||
c.fee_rate = p("0.1").try_into().unwrap();
|
||||
let mut explicit = RiskAccount::new(c.clone()).unwrap().0;
|
||||
let mut target = RiskAccount::new(c).unwrap().0;
|
||||
for a in [&mut explicit, &mut target] {
|
||||
mark(a, "m", "X", "1", 0);
|
||||
}
|
||||
let original = order("o", "A", "X", Side::Buy, &quantity.to_string());
|
||||
let mut normalized = original.clone();
|
||||
normalized.origin = OrderOrigin::Target;
|
||||
let raw = admit(&mut explicit, original, 0);
|
||||
let target_out = admit(&mut target, normalized, 0);
|
||||
assert_eq!(raw.disposition, target_out.disposition);
|
||||
assert_eq!(explicit.available_cash(), target.available_cash());
|
||||
if raw.disposition == RiskDisposition::Accepted {
|
||||
let raw_fill = fill(&mut explicit, "o", "fill", &quantity.to_string(), "1.1", 1);
|
||||
let target_fill = fill(&mut target, "o", "fill", &quantity.to_string(), "1.1", 1);
|
||||
assert_eq!(raw_fill.disposition, target_fill.disposition);
|
||||
assert_eq!(raw_fill.financial, target_fill.financial);
|
||||
}
|
||||
assert_eq!(explicit.ledger().checkpoint(), target.ledger().checkpoint());
|
||||
reconcile(&explicit);
|
||||
reconcile(&target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual release workload; no unstable timing assertion"]
|
||||
fn risk_transition_measurement() {
|
||||
for multi in [false, true] {
|
||||
for count in [1000, 10000] {
|
||||
let mut inputs = Vec::new();
|
||||
for n in 0..count / 4 {
|
||||
let symbol = if multi {
|
||||
format!("asset-{}", n % 4)
|
||||
} else {
|
||||
"asset".into()
|
||||
};
|
||||
let owner = if multi && n % 2 == 1 { "B" } else { "A" };
|
||||
let oid = format!("order-{n}");
|
||||
let t = n as i64;
|
||||
inputs.push(mark_command(&format!("mark-{n}"), &symbol, "10", t, t));
|
||||
inputs.push(admit_command(
|
||||
order(&oid, owner, &symbol, Side::Buy, "2"),
|
||||
t,
|
||||
));
|
||||
inputs.push(fill_command(&oid, &format!("fill-{n}"), "1", "10", t));
|
||||
inputs.push(cmd(
|
||||
&format!("release-{n}"),
|
||||
t,
|
||||
RiskCommandBody::Release {
|
||||
owner_id: id(owner),
|
||||
order_id: id(&oid),
|
||||
reason: ReleaseReason::Cancelled,
|
||||
},
|
||||
));
|
||||
}
|
||||
let mut expected = None;
|
||||
for repeat in 0..3 {
|
||||
let mut c = config("1000000");
|
||||
c.fee_rate = p("0.01").try_into().unwrap();
|
||||
let mut a = RiskAccount::new(c).unwrap().0;
|
||||
let started = Instant::now();
|
||||
let outcomes: Vec<_> = inputs.iter().map(|c| a.apply(c).unwrap()).collect();
|
||||
let elapsed = started.elapsed();
|
||||
let snap_start = Instant::now();
|
||||
let checkpoint = a.checkpoint();
|
||||
let snapshot_elapsed = snap_start.elapsed();
|
||||
let bytes = serde_json::to_vec(&checkpoint).unwrap();
|
||||
let economic_and_receipts =
|
||||
serde_json::to_vec(&(checkpoint.clone(), outcomes)).unwrap();
|
||||
if let Some(expected) = &expected {
|
||||
assert_eq!(&economic_and_receipts, expected);
|
||||
} else {
|
||||
expected = Some(economic_and_receipts);
|
||||
}
|
||||
let restore_start = Instant::now();
|
||||
let restored = RiskAccount::restore(checkpoint).unwrap().0;
|
||||
let restore_elapsed = restore_start.elapsed();
|
||||
assert_eq!(serde_json::to_vec(&restored.checkpoint()).unwrap(), bytes);
|
||||
reconcile(&restored);
|
||||
println!("risk multi={multi} commands={count} repeat={repeat} apply_us={} checkpoint_us={} restore_us={} checkpoint_bytes={} open_orders={} owners={} assets={}",
|
||||
elapsed.as_micros(), snapshot_elapsed.as_micros(), restore_elapsed.as_micros(), bytes.len(), a.reservations().count(), if multi {2} else {1}, if multi {4} else {1});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -67,6 +67,20 @@ impl Posting {
|
|||
Self::rounded_units(units)
|
||||
}
|
||||
|
||||
/// Rate-only execution fee: multiply all three exact values before the
|
||||
/// single posting boundary (never charge a percentage of rounded notional).
|
||||
pub(super) fn rate_fee(quantity: Self, price: Self, rate: Self) -> Result<Self, ScalarError> {
|
||||
Self::rounded_units(BigRational::new(
|
||||
quantity.units() * price.units() * rate.units(),
|
||||
BigInt::from(10u32).pow(POSTING_SCALE * 2),
|
||||
))
|
||||
}
|
||||
|
||||
/// Quote midpoint, with one rounding boundary and no overflowing a+b.
|
||||
pub(super) fn midpoint(a: Self, b: Self) -> Result<Self, ScalarError> {
|
||||
Self::rounded_units(BigRational::new(a.units() + b.units(), BigInt::from(2)))
|
||||
}
|
||||
|
||||
/// Partial disposal only: quantity is positive and <= owned quantity.
|
||||
/// A final disposal deliberately bypasses division and releases residue.
|
||||
pub(super) fn released_basis(
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
# Revised development roadmap
|
||||
|
||||
Baseline `b7aeca4` · reviewed 2026-10-22 · **First six waves committed; F02/D02 validated, uncommitted**
|
||||
Baseline `b7aeca4` · reviewed 2026-10-22 · **F04/F05 independently reviewed and validated, uncommitted**
|
||||
|
||||
Authorization update: after explicitly approving ADR-002/003/004 and the validated F01/D01 implementation, the owner requested “commit and continue.” F01/D01 are committed as `b4af840`; F02/D02 were independently reviewed, integrated and validated from isolated worktrees. No other ADR is approved. Seventh-wave commits, pushes, PRs and trading operations remain outside scope.
|
||||
Authorization update: the latest owner request “do it” authorizes the explicitly proposed F05 continuation on accepted, independently reviewed and validated F04. No commit was requested: F04's exact source is applied as an explicit prerequisite overlay to F05's isolated worktree based on `b65accc`. No other ADR is approved. Commits, pushes, PRs and trading operations remain outside scope.
|
||||
|
||||
## Strategy and review outcome
|
||||
|
||||
|
|
@ -190,7 +190,7 @@ Existing v1 snapshots and financial runtimes remain unchanged. F01 is not a work
|
|||
|
||||
## Seventh-wave handoff — 2026-10-22
|
||||
|
||||
F02/D02 are independently accepted and `review` / `validated_uncommitted`. Base `b4af840`; isolated worktrees under `/tmp/stock-bot-wave7.UIkAQD/`. Financial and data owners implemented in parallel; an independent reviewer checked both; root integrated all ten reviewed files with matching hashes.
|
||||
F02/D02 were independently accepted and subsequently committed as `b65accc` at owner request. Base `b4af840`; isolated worktrees under `/tmp/stock-bot-wave7.UIkAQD/`. Financial and data owners implemented in parallel; an independent reviewer checked both; root integrated all ten reviewed files with matching hashes.
|
||||
|
||||
- **F02:** Owner-keyed quantity, remaining basis, realized P&L and fees; exact rational intermediates rounded once into the maintained decimal posting type. Fee-inclusive funding, wrong-owner disposal, overflow and identity conflicts reject atomically. Command/fill aliases return original replay-labelled receipts, including after intervening operations. Explicit market marks remain separate from fill prices; owner-level marked postings reconcile to account equity. Same-session boundary repetition is an accepted no-op, not a false session-change effect. Ledger-only checkpoints retain and validate ordered receipts by replay; ordinary transitions touch only affected state.
|
||||
- **D02:** Existing EOD `1m`/`5m`/`1h` Mongo collections now feed the common research storage admission path. Unix-second timestamps/listing identities validate; supported-provider capability reports distinguish configuration/connectivity from coverage. Default QuestDB priority remains, explicit provider selection is available at the storage API, and missing/error ranges never switch to daily/synthetic data. Real writer/read/normalizer composition and repeated legacy native runs are tested on synthetic provider records; HTTP/Mongo transport alone is replaced.
|
||||
|
|
@ -206,7 +206,36 @@ The manual release measurement also passed on the final integrated checkout (1 t
|
|||
|
||||
Limits: no F04 reservation/portfolio-risk policy, matcher, F06 replay, native session API, SQL/paper cutover, order/strategy/RNG session restoration or canonical-engine release. D02's provider selector is not a web/run-configuration control; no Mongo server-conformance, range-completeness or live-availability claim. Provider delayed-finalization caveats and the explicit bar-close simulation assumption are retained in the task evidence. PostgreSQL/Redis and Chromium suites were not rerun because their persistence/API/UI boundaries did not change. Existing build warnings remain.
|
||||
|
||||
Only exact identified stalled D02 sandbox test/worker processes were terminated after the successful escalated rerun; no development services/data were changed. Worktrees and logs remain available. The sixth-wave commit was made as requested; no seventh-wave commit, push, PR or trading operation occurred. Next after acceptance/commit: **F04 central cash reservations and portfolio risk enforcement**. Product/AI work remains subject to its unapproved ADRs.
|
||||
Only exact identified stalled D02 sandbox test/worker processes were terminated after the successful escalated rerun; no development services/data were changed. Worktrees and logs remain available. The subsequent owner request authorized the seventh-wave commit and **F04 central cash reservations and portfolio risk enforcement**. No push, PR or trading operation occurred. Product/AI work remains subject to its unapproved ADRs.
|
||||
|
||||
## Eighth-wave handoff — 2026-10-22
|
||||
|
||||
F04 is independently accepted and `review` / `validated_uncommitted`. Base `b65accc`; isolated worktree `/tmp/stock-bot-wave8.pKzr7p/f04`. One owner implemented five financial files, two read-only reviewers accepted them, and root integrated exactly matching hashes. See [execution policy clarifications](backlog/tasks/F04.md#execution-policy-clarifications).
|
||||
|
||||
- **RiskAccount** privately owns the existing Ledger. Explicit and target-derived normalized orders share funded admission; strategy-owned sells cannot borrow inventory or credit anticipated proceeds. Fill-time checks account for other reservations, adverse gaps and split-fill rounding; rejection releases the remainder without changing prior fills. Commission is computed from exact quantity × price × rate, rounded once.
|
||||
- Portfolio quantity/exposure uses owner-book rounding, including pending buys. Increasing risk requires fresh marks across held/pending assets. Reductions remain possible during stale data and marked-loss halts. Explicit account boundaries reset daily state only; drawdown peak/halt persists through rollover and restore. Instance-bound operator reset records its baseline, separate from strategy input.
|
||||
- Recorded accepted/rejected outcomes and fill aliases replay without reapplying effects or moving the clock. Checkpoints reconstruct and verify risk/ledger state, reservations and receipts. Overflow/malformed internal commands remain atomic errors, not ordinary risk rejections. Future adapters must honor the outer replay flag before publishing nested financial effects.
|
||||
|
||||
Validation: `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit plus 60 tooling, 43 utility, 35 calculation, 342 integration and 77 Rust tests. Independent risk suites passed 18 cases; the broader financial suite passed 40 (overlapping totals). Two manual benchmarks are excluded from ordinary Rust runs; the new risk release benchmark was separately executed successfully in both author and integrated checkouts. Scoped rustfmt, diff checks and manifest DAG/readiness validation passed. Existing repository-wide rustfmt and planning-manifest Prettier style deviations were confirmed outside this change's formatting scope; no unrelated formatting rewrite.
|
||||
|
||||
The narrow release workload uses 1k/10k prebuilt mark/admit/partial-fill/release commands, three repeats, one active owner/asset or two active owners/four assets. Full checkpoint/outcome bytes and restored checkpoints match. Integrated 10k transition time was approximately 42–45ms single and 55–56ms multi, excluding build/loading/serialization; checkpoint and restore are measured separately. Only zero/one live reservation is exercised. This is not full backtest throughput or a scaling guarantee: normal risk checks scan retained book keys and live commitments with ordered-map costs; retained journal memory/restore work grows with history. Raw commands, logs, artifact/source hashes and measurements are in the manifest.
|
||||
|
||||
Limits: active legacy engines unchanged; no F05 matcher, target expansion/mode coordination, limit/TIF/capacity eligibility, F06 calendar/replay, F07 native sessions, paper/SQL cutover or full strategy/replay/RNG recovery. Operator capability is API separation, not untrusted-code security. PostgreSQL/Redis, browser and Python suites were not rerun because those boundaries did not change. No services/data were removed. No new-wave commit, push, PR or trading operation. Next after acceptance/commit: **F05 matching and order lifecycle on the canonical ledger/risk facade**; replay release remains gated by F06.
|
||||
|
||||
## Ninth-wave handoff — 2026-10-22
|
||||
|
||||
F05 is independently reviewed and `review` / `validated_uncommitted`. Its isolated worktree `/tmp/stock-bot-wave9.P8EKsc/f05` uses base `b65accc` plus the five exact F04 prerequisite files. The owner accepted continuation without requesting a prerequisite commit. One financial owner implemented; execution and quant reviewers accepted the final source; root integrated exactly matching hashes. See [F05 execution policies](backlog/tasks/F05.md#execution-policy-clarifications).
|
||||
|
||||
- **MatchingAccount** privately owns RiskAccount, with no competing ledger, fee or funding logic. Open-only and quote execution have explicit spread/slippage rounding, limit crossing, latency, session eligibility and shared liquidity. IOC/FOK/DAY/GTC transitions, partial fills, cancellation, rejection and terminal cancellation are deterministic. No synthetic end-of-run liquidation is introduced.
|
||||
- Owner-scoped absolute targets account for holdings and live commitments. Omitted assets remain unchanged; repeated targets preserve partial orders. Changed targets cancel only the owner's relevant commitments before risk-checked replacement. Declared target-array order is priority, not an atomic portfolio rebalance. Target and explicit-order modes cannot be mixed for an owner.
|
||||
- Structural batch validation precedes mutation. Physical execution identity prevents capacity reuse under changed delivery keys; delayed quotes retain their physical time and cannot fill orders that were not yet eligible. Exact retries replay original receipts without republishing nested effects. Checkpoints reconstruct matching, risk and ledger state. Unexpected numerical failure records the committed prefix and makes the attempt terminal; adapters must fail the run, never publish successful metrics from that prefix.
|
||||
- Admission uses a coordinator revision, distinct from the nested ledger snapshot revision. F06 must honor that token, physical event timing and failure contract; it must not restamp missed opens. Full replay/strategy/RNG session restoration remains later work.
|
||||
|
||||
Combined validation: `CARGO_BUILD_JOBS=2 bun run check` passed build/types/contracts/lint/audit plus 60 tooling, 43 utility, 35 calculation, 342 integration and **106 Rust tests**, zero failures. The 29 matching regressions also passed independently in both reviews (overlapping totals). Three manual benchmarks are ignored by the ordinary Rust suite; the new matching release measurement passed separately in both author and integrated builds. Scoped rustfmt, diff checks and final manifest/source verification passed.
|
||||
|
||||
The narrow release workload uses 1k/10k execution events and fills, each preceded by a submit (2k/20k coordinator commands plus setup), over one owner/asset or two owners/two assets, with three repeats. Integrated 10k apply time was 214–235ms single and 234–238ms multi. Apply includes fixture construction/assertions/outcome collection; checkpoint copying is separate, and restore includes cloning its checkpoint input. Serialization is outside these timers. Exact economics, checkpoint/outcome repeatability and restored checkpoint equality are asserted. Serialized checkpoint plus returned outcomes are approximately 12.6MB/128MB at 1k/10k; this is not RSS. Retained journals grow with history. These are component measurements, not end-to-end backtest throughput, a speedup claim or a reason to introduce caching/compaction prematurely. Full raw rows and artifact/source identities are in the manifest.
|
||||
|
||||
Limits: active legacy simulator and NAPI unchanged; no replay scheduler, paper/SQL cutover or full session restore. Checkpoints validate consistency, not authenticity or arbitrary-code security. PostgreSQL/Redis, browser and Python suites were not rerun because their boundaries did not change. Existing build warnings remain. No services/data removed; worktree/logs retained. **F04/F05 remain uncommitted. Next after acceptance: F06 deterministic availability-aware replay**, still the release gate for this matcher. No commit, push, PR or trading operation occurred.
|
||||
|
||||
## Deferred and rejected
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Canonical development backlog
|
||||
|
||||
**First six waves committed; F02/D02 validated, uncommitted.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). ADR-002/003/004 are approved; F02/D02 await owner acceptance/commit, and other tasks/policies remain gated.
|
||||
**First seven waves committed; F04/F05 independently reviewed and validated, uncommitted.** Consult manifest execution_scope, [ROADMAP](../ROADMAP.md), [skeptical review](../REVIEW.md) and [first-wave handoff](../FIRST-WAVE.md). ADR-002/003/004 are approved. The owner authorized F05 on F04's validated integrated source without requesting a commit. Other tasks/policies remain gated.
|
||||
|
||||
## One source of truth
|
||||
|
||||
|
|
@ -30,10 +30,10 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [F01 Define the minimal financial contract and economic fixtures](tasks/F01.md) | P0 / done | ADR-002, ADR-003, ADR-004 (approved) | — | Rust financial contract owner / M |
|
||||
| [F02 Implement one owner-aware financial ledger](tasks/F02.md) | P0 / review | F01, ADR-002 | — | Rust accounting / L |
|
||||
| [F02 Implement one owner-aware financial ledger](tasks/F02.md) | P0 / done | F01, ADR-002 | — | Rust accounting / L |
|
||||
| [F03 Add strategy-owned position books and fill allocations](tasks/F03.md) | P0 / merged → F02 | None | — | Rust portfolio accounting / M |
|
||||
| [F04 Enforce cash reservations and portfolio risk centrally](tasks/F04.md) | P0 / blocked | F02, ADR-002, ADR-003 | — | Rust financial risk / L |
|
||||
| [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / blocked | F04, ADR-003 | F06 | Rust execution semantics / L |
|
||||
| [F04 Enforce cash reservations and portfolio risk centrally](tasks/F04.md) | P0 / review | F02, ADR-002, ADR-003 | — | Rust financial risk / L |
|
||||
| [F05 Unify matching and order lifecycle on the ledger](tasks/F05.md) | P0 / review | F04, ADR-003 | F06 | Rust execution semantics / L |
|
||||
| [F06 Implement deterministic replay once, with linear historical traversal](tasks/F06.md) | P0 / blocked | F05, D01, P01, ADR-003 | — | Rust deterministic replay / M |
|
||||
| [F07 Expose bounded Rust step sessions through existing NAPI workers](tasks/F07.md) | P0 / blocked | F06, C02, ADR-004 | — | Rust/TypeScript integration / M |
|
||||
| [F08 Publish canonical metrics and versioned result projections](tasks/F08.md) | P1 / blocked | F06, ADR-002, ADR-003 | — | Quant analytics/Rust integration / M |
|
||||
|
|
@ -43,7 +43,7 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
| Task | Priority / status | Implementation prerequisites | Release gate | Specialist / size |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| [D01 Introduce availability-aware dataset v2](tasks/D01.md) | P0 / done | ADR-003 (approved) | — | TypeScript trading infrastructure / M |
|
||||
| [D02 Connect supported intraday storage to research datasets](tasks/D02.md) | P1 / review | D01 | — | TypeScript trading infrastructure / M |
|
||||
| [D02 Connect supported intraday storage to research datasets](tasks/D02.md) | P1 / done | D01 | — | TypeScript trading infrastructure / M |
|
||||
| [D03 Add dataset eligibility and corporate-action safeguards](tasks/D03.md) | P1 / merged → D01 | None | — | TypeScript trading infrastructure / M |
|
||||
| [D04 Provide prefix-safe shared feature calculation](tasks/D04.md) | P1 / deferred | S01, P01 | — | Quantitative feature engineering / M |
|
||||
|
||||
|
|
@ -115,4 +115,4 @@ Relative size: S narrow correction, M coherent boundary, L sensitive owner-contr
|
|||
|
||||
Before any wave: unique IDs; existing task/ADR references; acyclic implementation graph; no scheduled task dependent on merged/deferred work; approvals/readiness; actual file locks; isolated native build outputs/workspace dependencies and test databases. Release gates are checked separately at activation.
|
||||
|
||||
The first five waves are independently reviewed, validated and committed with owner approval. **W04** is committed as `550d8b7`. Evidence is recorded in [FIRST-WAVE.md](../FIRST-WAVE.md#execution-record--2026-10-22), the [ROADMAP handoffs](../ROADMAP.md#fifth-wave-handoff--2026-10-22) and the manifest. The owner's subsequent explicit approval of ADR-002/003/004 authorizes **F01 + D01** in parallel. R01 still needs ADR-006; other consumers wait for their dependencies. Deferred work remains deferred. No sixth-wave commit/push/PR or trading operation is authorized.
|
||||
The first seven waves are independently reviewed, validated and committed with owner approval. Evidence is recorded in [FIRST-WAVE.md](../FIRST-WAVE.md#execution-record--2026-10-22), the [ROADMAP handoffs](../ROADMAP.md#ninth-wave-handoff--2026-10-22) and the manifest. The latest owner request authorized **F05** using accepted integrated F04. Both implementations are now independently reviewed and `validated_uncommitted`; F05's explicit integration overlay pins its prerequisite source, and ninth-wave validation records the resulting cumulative seven-file financial overlay. Next after acceptance: F06. R01 still needs ADR-006; other consumers wait for their dependencies. No commit, push, PR or trading operation is authorized.
|
||||
|
|
|
|||
|
|
@ -1,24 +1,22 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"plan_revision": "2026-10-22.18",
|
||||
"plan_revision": "2026-10-22.21",
|
||||
"repository_base": "b7aeca4",
|
||||
"plan_status": "seventh_wave_validated_uncommitted",
|
||||
"plan_status": "ninth_wave_validated_uncommitted",
|
||||
"execution_authorized": true,
|
||||
"execution_scope": {
|
||||
"authorized_by": "User: commit and continue (2026-10-22); commit accepted F01/D01 and continue with the explicitly proposed F02/D02 pair",
|
||||
"authorized_by": "User: do it (2026-10-22), authorizing the explicitly proposed F05 continuation on accepted integrated F04; no commit requested",
|
||||
"tasks": [
|
||||
"F02",
|
||||
"D02"
|
||||
"F05"
|
||||
],
|
||||
"permissions": [
|
||||
"commit_validated_sixth_wave",
|
||||
"isolated_implementation",
|
||||
"local_tests",
|
||||
"local_integration_review",
|
||||
"planning_progress_updates"
|
||||
],
|
||||
"excluded": [
|
||||
"seventh_wave_commits_without_further_approval",
|
||||
"commits_without_further_approval",
|
||||
"push",
|
||||
"pull_requests",
|
||||
"live_or_paper_operations",
|
||||
|
|
@ -368,7 +366,7 @@
|
|||
"epic": "E2",
|
||||
"priority": "P0",
|
||||
"severity": "Critical",
|
||||
"status": "review",
|
||||
"status": "done",
|
||||
"dependencies": [
|
||||
"F01"
|
||||
],
|
||||
|
|
@ -392,7 +390,7 @@
|
|||
"assignment": "/root/wave7_f02",
|
||||
"branch": "wave7/f02-owned-ledger",
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "b65acccd91c15a7fd82536c0c6b3a65e01055113",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"worktree": "/tmp/stock-bot-wave7.UIkAQD/f02",
|
||||
|
|
@ -403,8 +401,8 @@
|
|||
"Cargo.lock",
|
||||
"test/fixtures/economics/"
|
||||
],
|
||||
"review_notes": "Independently accepted, exact frozen files integrated, combined repository checks passed. Seventh-wave changes remain uncommitted pending owner acceptance/commit; no downstream task started.",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"review_notes": "Independently accepted, frozen source integrated and combined gates passed. Owner authorized commit and continuation; completed_commit contains F02/D02.",
|
||||
"integration_state": "validated_committed",
|
||||
"reviewed_by": "/root/wave7_review",
|
||||
"verification_reference": "ROADMAP.md#seventh-wave-handoff--2026-10-22"
|
||||
},
|
||||
|
|
@ -439,7 +437,7 @@
|
|||
"epic": "E2",
|
||||
"priority": "P0",
|
||||
"severity": "Critical",
|
||||
"status": "blocked",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"F02"
|
||||
],
|
||||
|
|
@ -459,12 +457,25 @@
|
|||
"risk-policy"
|
||||
],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"branch": null,
|
||||
"assignment": "/root/wave8_f04",
|
||||
"branch": "wave8/f04-financial-risk",
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": []
|
||||
"release_gates": [],
|
||||
"worktree": "/tmp/stock-bot-wave8.pKzr7p/f04",
|
||||
"integration_base": "b65acccd91c15a7fd82536c0c6b3a65e01055113",
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/engine/src/financial/"
|
||||
],
|
||||
"integration_state": "validated_uncommitted",
|
||||
"reviewed_by": [
|
||||
"/root/wave8_risk_review",
|
||||
"/root/wave8_quant_review"
|
||||
],
|
||||
"review_notes": "Both independent reviewers and combined gates passed; owner accepted continuation to F05. Integrated F04 remains uncommitted, with frozen source hashes recorded in eighth_wave_validation.",
|
||||
"verification_reference": "ROADMAP.md#eighth-wave-handoff--2026-10-22",
|
||||
"accepted_by": "Owner: do it, authorizing proposed F05 continuation on validated integrated F04 (2026-10-22)"
|
||||
},
|
||||
{
|
||||
"id": "F05",
|
||||
|
|
@ -472,7 +483,7 @@
|
|||
"epic": "E2",
|
||||
"priority": "P0",
|
||||
"severity": "Critical",
|
||||
"status": "blocked",
|
||||
"status": "review",
|
||||
"dependencies": [
|
||||
"F04"
|
||||
],
|
||||
|
|
@ -493,14 +504,32 @@
|
|||
"financial-contract"
|
||||
],
|
||||
"parallel_policy": "Allowed only with satisfied dependencies/approvals and disjoint write locks AND actual files; see agents/integration.md.",
|
||||
"assignment": null,
|
||||
"branch": null,
|
||||
"assignment": "/root/wave9_f05",
|
||||
"branch": "wave9/f05-matching",
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"blocker": null,
|
||||
"release_gates": [
|
||||
"F06"
|
||||
]
|
||||
],
|
||||
"worktree": "/tmp/stock-bot-wave9.P8EKsc/f05",
|
||||
"integration_base": "b65acccd91c15a7fd82536c0c6b3a65e01055113",
|
||||
"integration_overlay": {
|
||||
"task": "F04",
|
||||
"source_hashes_reference": "eighth_wave_validation.source_hashes",
|
||||
"accepted_integration": true,
|
||||
"note": "Exact validated source copied with apply_patch into isolated worktree; no implicit commit required or created."
|
||||
},
|
||||
"concrete_write_scope": [
|
||||
"apps/stock/engine/src/financial/"
|
||||
],
|
||||
"integration_state": "validated_uncommitted",
|
||||
"review_notes": "Both independent reviewers accepted the final frozen source; root integrated matching hashes and passed all repository checks plus the release matching measurement. No active runtime cutover; F06 remains the replay release gate.",
|
||||
"reviewed_by": [
|
||||
"/root/wave9_execution_review",
|
||||
"/root/wave9_quant_review"
|
||||
],
|
||||
"verification_reference": "ROADMAP.md#ninth-wave-handoff--2026-10-22"
|
||||
},
|
||||
{
|
||||
"id": "F06",
|
||||
|
|
@ -652,7 +681,7 @@
|
|||
"epic": "E3",
|
||||
"priority": "P1",
|
||||
"severity": "High",
|
||||
"status": "review",
|
||||
"status": "done",
|
||||
"dependencies": [
|
||||
"D01"
|
||||
],
|
||||
|
|
@ -670,7 +699,7 @@
|
|||
"assignment": "/root/wave7_d02",
|
||||
"branch": "wave7/d02-intraday-storage",
|
||||
"pull_request": null,
|
||||
"completed_commit": null,
|
||||
"completed_commit": "b65acccd91c15a7fd82536c0c6b3a65e01055113",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"worktree": "/tmp/stock-bot-wave7.UIkAQD/d02",
|
||||
|
|
@ -681,8 +710,8 @@
|
|||
"test/integration/intraday-storage.test.ts",
|
||||
"test/fixtures/intraday/"
|
||||
],
|
||||
"review_notes": "Independently accepted, exact frozen files integrated, combined repository checks passed. Seventh-wave changes remain uncommitted pending owner acceptance/commit; no downstream task started.",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"review_notes": "Independently accepted, frozen source integrated and combined gates passed. Owner authorized commit and continuation; completed_commit contains F02/D02.",
|
||||
"integration_state": "validated_committed",
|
||||
"reviewed_by": "/root/wave7_review",
|
||||
"verification_reference": "ROADMAP.md#seventh-wave-handoff--2026-10-22"
|
||||
},
|
||||
|
|
@ -3015,6 +3044,191 @@
|
|||
"Initial isolated D02 builds needed existing logger/config dependencies; native sandbox attempt timed out. Escalated tests and independent rerun passed unchanged. Existing build warnings remain."
|
||||
],
|
||||
"cleanup": "Only D02 stale test980112/worker980619 were terminated after exact PID/cwd checks; original session exited143 and process absence verified. No development services, databases or data touched. Worktrees/logs retained.",
|
||||
"handoff": "F01/D01 committedb4af840 at owner request. F02/D02 independently accepted and validated_uncommitted, awaiting owner acceptance/commit. F04 is next prerequisite-dependent task; other ADR approvals unchanged. No push/PR/trading operation or extra task."
|
||||
"handoff": "Owner subsequently authorized F02/D02 commit b65accc and F04 continuation. Seventh-wave validation remains recorded here; other ADR approvals unchanged. No push, PR or trading operation."
|
||||
},
|
||||
"eighth_wave": [
|
||||
"F04"
|
||||
],
|
||||
"eighth_wave_base": "b65acccd91c15a7fd82536c0c6b3a65e01055113",
|
||||
"eighth_wave_notes": [
|
||||
"One isolated financial implementation owner; two read-only reviewers. Root owns planning and integration.",
|
||||
"Additive RiskAccount privately owns Ledger; no active runtime cutover, F05 matching/target expansion, F06 replay, F07 NAPI or SQL/paper changes.",
|
||||
"Task execution-policy clarifications pin units, fee rounding, cash/inventory commitments, event-time mark freshness, risk halts and operator-reset API authority."
|
||||
],
|
||||
"eighth_wave_validation": {
|
||||
"base": "b65acccd91c15a7fd82536c0c6b3a65e01055113",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"repository_check": {
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"log": "/tmp/stock-bot-wave8.pKzr7p/integration-check.log",
|
||||
"exit_code": 0,
|
||||
"passed": {
|
||||
"tooling": 60,
|
||||
"utils": 43,
|
||||
"calculations": 35,
|
||||
"integration": 342,
|
||||
"rust": 77
|
||||
},
|
||||
"rust_manual_benchmarks_ignored": 2,
|
||||
"other_gates": "Build, typecheck, contracts, lint and secret audit passed."
|
||||
},
|
||||
"independent_review": {
|
||||
"risk": "/root/wave8_risk_review: frozen five-file hashes verified; 18 risk tests and 40 financial tests passed, overlapping totals. Log /tmp/stock-bot-wave8.pKzr7p/f04-independent-financial.log.",
|
||||
"quant": "/root/wave8_quant_review: frozen hashes verified;18 risk tests passed. Reviewed once-rounded fees, owner-book exposure, fill-time commitments and atomic overflow."
|
||||
},
|
||||
"scoped_checks": [
|
||||
"rustfmt --edition 2021 --check --config skip_children=true on five changed financial files passed.",
|
||||
"git diff --check and manifest task-file/DAG/authorized dependency/ADR readiness checks passed.",
|
||||
"Whole-repository rustfmt baseline differs outside owned scope; no unrelated rewrite. Planning manifest Prettier check also differs on HEAD baseline; retained existing JSON formatting."
|
||||
],
|
||||
"source_hashes": {
|
||||
"apps/stock/engine/src/financial/ledger.rs": "f2092937bd0ef60d3267751629dae573900680edb777330a09e5ec8e7fc2d854",
|
||||
"apps/stock/engine/src/financial/mod.rs": "63d0cd994ccfc7dec0a421f9d900ec46877fc2d3e1faa69dffbe3e58f0d8bddc",
|
||||
"apps/stock/engine/src/financial/scalar.rs": "6150e0de5be8432ef13f5d10c2d9a9b50c0387bf8c86810d917eb347bf33d7b2",
|
||||
"apps/stock/engine/src/financial/risk.rs": "9d6189177b158afc87f32ee9b9c8ffd2f24bab269de5f1fedd8c8ab515d237ce",
|
||||
"apps/stock/engine/src/financial/risk_tests.rs": "bcaff321cbe84ef6253ce3552f312b0a2057553ad41ea69247a02db92822d098"
|
||||
},
|
||||
"native_artifact": {
|
||||
"path": "apps/stock/engine/dist/engine.node",
|
||||
"sha256": "3987253b57e515acbb58c1e0e83a9d63309fb36aea267de1995ccc18637e256d",
|
||||
"note": "Independently built from integrated checkout; active simulator remains legacy."
|
||||
},
|
||||
"measurement": {
|
||||
"command": "CARGO_BUILD_JOBS=2 cargo test -p engine --lib --release --offline risk_transition_measurement -- --ignored --nocapture",
|
||||
"author_log": "/tmp/stock-bot-wave8.pKzr7p/f04-risk-release.log",
|
||||
"integrated_log": "/tmp/stock-bot-wave8.pKzr7p/integration-risk-release.log",
|
||||
"result": "1 passed, 0 failed;78 filtered. Author and integrated builds both passed; the earlier ledger-only manual measurement was not repeated this wave.",
|
||||
"artifact": "target/release/deps/engine-abe56cbc3e15ae30",
|
||||
"artifact_sha256": "fd30aea3b087bea9961f5e9d8dd96bf1317f5551ba652560d5538dc5c0880338",
|
||||
"host": "AMD Ryzen9 9950X3D; Linux6.8 x86_64; Rust/Cargo1.88.0; build jobs2. Same artifact hash in author/integrated worktrees.",
|
||||
"workload": "Prebuilt 1k/10k commands: mark10, admit2shares, fill1share, cancel remainder. Fee1%,capital1m. One active owner/asset or two active owners/four assets;3repeats,no explicit warmup. At most1live reservation. Apply includes receipt/outcome collection; checkpoint copying and restore separately timed; serialization/input generation/build excluded.",
|
||||
"equality": "Full checkpoint plus returned outcomes byte-equal across three repeats; restored checkpoint byte-equal. No cross-platform determinism claim.",
|
||||
"raw_integrated_rows": [
|
||||
"risk multi=false commands=1000 repeat=0 apply_us=4764 checkpoint_us=639 restore_us=5273 checkpoint_bytes=990585 open_orders=0 owners=1 assets=1",
|
||||
"risk multi=false commands=1000 repeat=1 apply_us=3964 checkpoint_us=303 restore_us=4891 checkpoint_bytes=990585 open_orders=0 owners=1 assets=1",
|
||||
"risk multi=false commands=1000 repeat=2 apply_us=4026 checkpoint_us=292 restore_us=5049 checkpoint_bytes=990585 open_orders=0 owners=1 assets=1",
|
||||
"risk multi=false commands=10000 repeat=0 apply_us=45071 checkpoint_us=7485 restore_us=58692 checkpoint_bytes=10019596 open_orders=0 owners=1 assets=1",
|
||||
"risk multi=false commands=10000 repeat=1 apply_us=42218 checkpoint_us=4706 restore_us=56548 checkpoint_bytes=10019596 open_orders=0 owners=1 assets=1",
|
||||
"risk multi=false commands=10000 repeat=2 apply_us=41986 checkpoint_us=4951 restore_us=57307 checkpoint_bytes=10019596 open_orders=0 owners=1 assets=1",
|
||||
"risk multi=true commands=1000 repeat=0 apply_us=5195 checkpoint_us=343 restore_us=6067 checkpoint_bytes=996239 open_orders=0 owners=2 assets=4",
|
||||
"risk multi=true commands=1000 repeat=1 apply_us=5171 checkpoint_us=291 restore_us=6012 checkpoint_bytes=996239 open_orders=0 owners=2 assets=4",
|
||||
"risk multi=true commands=1000 repeat=2 apply_us=5189 checkpoint_us=295 restore_us=6004 checkpoint_bytes=996239 open_orders=0 owners=2 assets=4",
|
||||
"risk multi=true commands=10000 repeat=0 apply_us=55959 checkpoint_us=5995 restore_us=74884 checkpoint_bytes=10070263 open_orders=0 owners=2 assets=4",
|
||||
"risk multi=true commands=10000 repeat=1 apply_us=56209 checkpoint_us=6110 restore_us=74580 checkpoint_bytes=10070263 open_orders=0 owners=2 assets=4",
|
||||
"risk multi=true commands=10000 repeat=2 apply_us=54665 checkpoint_us=4800 restore_us=69609 checkpoint_bytes=10070263 open_orders=0 owners=2 assets=4"
|
||||
],
|
||||
"limits": "Narrow component workload, not end-to-end backtesting, batch scaling or speedup evidence. Risk checks scan retained book keys and active commitments with ordered-map factors. Journal memory and restore work grow with history; no compaction."
|
||||
},
|
||||
"not_run": [
|
||||
"Disposable PostgreSQL/Redis, browser and Python suites: persistence/API/UI/Python boundaries unchanged."
|
||||
],
|
||||
"limitations": [
|
||||
"No active-engine cutover, F05 matcher/limit/TIF/capacity eligibility or target expansion/mode coordinator, F06 replay, F07 NAPI, or paper/SQL integration.",
|
||||
"Checkpoint covers risk+ledger, not replay cursors/strategy/RNG. Reconstruction checks consistency, not authenticity.",
|
||||
"Host instance operator capability is API authority separation, not authentication or an arbitrary-code sandbox.",
|
||||
"RiskOutcome.replayed gates publication of all nested original financial effects. Arithmetic overflow is an atomic command error; host must fail unsupported attempts."
|
||||
],
|
||||
"handoff": "F02/D02 committed b65accc at owner request. F04 independently accepted and validated_uncommitted. Owner subsequently authorized F05 on this accepted source without requesting a commit; exact overlay is recorded under F05. F06 remains the replay release gate. No commit, push, PR or trading operation.",
|
||||
"cleanup": "No services/data removed; isolated worktree and logs retained."
|
||||
},
|
||||
"ninth_wave": [
|
||||
"F05"
|
||||
],
|
||||
"ninth_wave_base": "b65acccd91c15a7fd82536c0c6b3a65e01055113",
|
||||
"ninth_wave_overlay_reference": "eighth_wave_validation.source_hashes",
|
||||
"ninth_wave_notes": [
|
||||
"The owner authorized F05 on accepted integrated F04 without requesting commits. Its five exact financial source files were applied and hash-verified in the isolated worktree.",
|
||||
"One financial implementation owner; independent execution and quant reviewers; root owns planning/integration.",
|
||||
"Additive matching/order lifecycle privately owns RiskAccount. No legacy simulator, replay scheduler, native API, paper/SQL or brokerage change.",
|
||||
"F05 task clarifies price stages, shared liquidity, target omission/replacement, coordinator-vs-ledger revisions and terminal failed-attempt prefix receipts."
|
||||
],
|
||||
"ninth_wave_validation": {
|
||||
"base": "b65acccd91c15a7fd82536c0c6b3a65e01055113",
|
||||
"integration_state": "validated_uncommitted",
|
||||
"prerequisite_overlay": "Accepted F04 source in eighth_wave_validation.source_hashes; no prerequisite commit required or created.",
|
||||
"repository_check": {
|
||||
"command": "CARGO_BUILD_JOBS=2 bun run check",
|
||||
"log": "/tmp/stock-bot-wave9.P8EKsc/integration-check.log",
|
||||
"exit_code": 0,
|
||||
"passed": {
|
||||
"tooling": 60,
|
||||
"utils": 43,
|
||||
"calculations": 35,
|
||||
"integration": 342,
|
||||
"rust": 106
|
||||
},
|
||||
"rust_manual_benchmarks_ignored": 3,
|
||||
"other_gates": "Build, typecheck, contracts, lint and secret audit passed."
|
||||
},
|
||||
"independent_review": {
|
||||
"execution": "/root/wave9_execution_review: final frozen five-file hashes accepted; 29 matching regressions passed, one manual benchmark ignored.",
|
||||
"quant": "/root/wave9_quant_review: final frozen hashes accepted; 29 matching regressions passed. Reviewed fee/funding authority, limit pricing, physical quote eligibility, capacity dedup, target commitments and terminal partial failures."
|
||||
},
|
||||
"scoped_checks": [
|
||||
"rustfmt --edition 2021 --check --config skip_children=true on five changed financial files passed.",
|
||||
"git diff --check and manifest task-file/DAG/authorized dependency/ADR readiness checks passed.",
|
||||
"Cumulative seven-file source hashes below include unchanged F04 ledger.rs/risk_tests.rs; final five F05 source files match the isolated reviewed worktree exactly."
|
||||
],
|
||||
"changed_source_files": [
|
||||
"apps/stock/engine/src/financial/mod.rs",
|
||||
"apps/stock/engine/src/financial/scalar.rs",
|
||||
"apps/stock/engine/src/financial/risk.rs",
|
||||
"apps/stock/engine/src/financial/matching.rs",
|
||||
"apps/stock/engine/src/financial/matching_tests.rs"
|
||||
],
|
||||
"source_hashes": {
|
||||
"apps/stock/engine/src/financial/ledger.rs": "f2092937bd0ef60d3267751629dae573900680edb777330a09e5ec8e7fc2d854",
|
||||
"apps/stock/engine/src/financial/mod.rs": "45ec9613eb0db8194cc9b21979043f7edff5ad3dc0116a03209e157ae784013d",
|
||||
"apps/stock/engine/src/financial/scalar.rs": "280cefdc8da4f04e1f3ad9fec999e7b7974c06504191ccace1c8eaec3768e189",
|
||||
"apps/stock/engine/src/financial/risk.rs": "ad57837ef631df4b54f24dc752914964e5f6bf891aa74946e054d960584b3c64",
|
||||
"apps/stock/engine/src/financial/risk_tests.rs": "bcaff321cbe84ef6253ce3552f312b0a2057553ad41ea69247a02db92822d098",
|
||||
"apps/stock/engine/src/financial/matching.rs": "98cda1d4ee802c87dbf948e1bc7b40e8a5b6aff6d44b4f3e0571c27ae40cf7b6",
|
||||
"apps/stock/engine/src/financial/matching_tests.rs": "b718de809e2ea76b4a31284aae946eb257d466c916eae0d00c3f174fe7dae43b"
|
||||
},
|
||||
"native_artifact": {
|
||||
"path": "apps/stock/engine/dist/engine.node",
|
||||
"sha256": "d81b0324c111ff05e54584f311a3d6f3bec907ce0e52e288ca3b97590dfe8062",
|
||||
"note": "Built from integrated checkout; active simulator remains legacy."
|
||||
},
|
||||
"measurement": {
|
||||
"command": "CARGO_BUILD_JOBS=2 cargo test -p engine --lib --release --offline matching_transition_measurement -- --ignored --nocapture",
|
||||
"author_log": "/tmp/stock-bot-wave9.P8EKsc/f05-matching-release-final.log",
|
||||
"integrated_log": "/tmp/stock-bot-wave9.P8EKsc/integration-matching-release.log",
|
||||
"result": "1 passed, 0 failed;108 filtered. Author and integrated builds both passed; earlier ledger/risk manual measurements not repeated this wave.",
|
||||
"artifact": "target/release/deps/engine-abe56cbc3e15ae30",
|
||||
"artifact_sha256": "ed9ac89737bcd57e671c59ef818f7411c7b29c9158bc5eb9dc5e4fc2e777a2bc",
|
||||
"host": "AMD Ryzen9 9950X3D; Linux6.8 x86_64; Rust/Cargo1.88.0; build jobs2. Same artifact hash in author/integrated worktrees.",
|
||||
"workload": "1k/10k execution events/fills, each preceded by one Submit =2k/20k coordinator commands plus4setup. Alternate buy/sell quantity1 at10; fee0.001,capital1m. One active owner/asset or two owners/two assets;3repeats,no explicit warmup.",
|
||||
"timing": "Apply includes fixture construction, helper assertions and outcome collection, unlike the earlier prebuilt F04 workload. Checkpoint copying is separate; restore includes checkpoint.clone() input copying. Serialization/build excluded.",
|
||||
"equality": "Expected fills/fees/cash/flat holdings asserted. Full checkpoint and returned outcome bytes equal across repeats; restored checkpoint equal. No cross-platform determinism claim.",
|
||||
"raw_integrated_rows": [
|
||||
"matching multi=false events=1000 fills=1000 repeat=0 apply_us=24361 checkpoint_us=5945 restore_us=42809 checkpoint_effect_bytes=12635053",
|
||||
"matching multi=false events=1000 fills=1000 repeat=1 apply_us=20561 checkpoint_us=4586 restore_us=37263 checkpoint_effect_bytes=12635053",
|
||||
"matching multi=false events=1000 fills=1000 repeat=2 apply_us=19960 checkpoint_us=4580 restore_us=34314 checkpoint_effect_bytes=12635053",
|
||||
"matching multi=false events=10000 fills=10000 repeat=0 apply_us=235326 checkpoint_us=77381 restore_us=437521 checkpoint_effect_bytes=128041656",
|
||||
"matching multi=false events=10000 fills=10000 repeat=1 apply_us=213718 checkpoint_us=55617 restore_us=455499 checkpoint_effect_bytes=128041656",
|
||||
"matching multi=false events=10000 fills=10000 repeat=2 apply_us=213643 checkpoint_us=55453 restore_us=437177 checkpoint_effect_bytes=128041656",
|
||||
"matching multi=true events=1000 fills=1000 repeat=0 apply_us=22787 checkpoint_us=4393 restore_us=36271 checkpoint_effect_bytes=12635409",
|
||||
"matching multi=true events=1000 fills=1000 repeat=1 apply_us=22417 checkpoint_us=3633 restore_us=36277 checkpoint_effect_bytes=12635409",
|
||||
"matching multi=true events=1000 fills=1000 repeat=2 apply_us=22572 checkpoint_us=3776 restore_us=35502 checkpoint_effect_bytes=12635409",
|
||||
"matching multi=true events=10000 fills=10000 repeat=0 apply_us=238015 checkpoint_us=50975 restore_us=434694 checkpoint_effect_bytes=128042015",
|
||||
"matching multi=true events=10000 fills=10000 repeat=1 apply_us=234303 checkpoint_us=51207 restore_us=434431 checkpoint_effect_bytes=128042015",
|
||||
"matching multi=true events=10000 fills=10000 repeat=2 apply_us=235764 checkpoint_us=51505 restore_us=437413 checkpoint_effect_bytes=128042015"
|
||||
],
|
||||
"limits": "Narrow component-plus-fixture workload, not end-to-end backtesting, batch scaling or speedup evidence. Serialized checkpoint plus external outcomes ~12.6MB/128MB for1k/10k; not RSS. Retained journals grow with history; no compaction."
|
||||
},
|
||||
"not_run": [
|
||||
"Disposable PostgreSQL/Redis, browser and Python suites: persistence/API/UI/Python boundaries unchanged."
|
||||
],
|
||||
"limitations": [
|
||||
"No active-engine cutover, F06 replay scheduler, F07 NAPI sessions or paper/SQL integration. F06 remains matcher replay release gate.",
|
||||
"Checkpoint covers matching+risk+ledger, not strategy/replay/RNG state; validates retained-history consistency, not authenticity or sandbox security.",
|
||||
"Coordinator admission_revision differs from nested FinancialSnapshot ledger revision. F06/F07 must expose the correct barrier token.",
|
||||
"Unexpected numeric errors can follow committed subtransitions: terminal Failed outcome retains the committed prefix. Host must fail/discard the attempt; no successful performance metrics may be published.",
|
||||
"MatchingOutcome.replayed gates all nested original effects. Physical execution dedup uses open instrument+opens_at or quote instrument+observed_at+source_sequence; source sequence need not be chronological.",
|
||||
"Owner target-array order is explicit priority, not an atomic portfolio rebalance. Existing build warnings remain."
|
||||
],
|
||||
"handoff": "F04/F05 independently reviewed and validated, uncommitted. Next after owner acceptance: F06 availability-aware deterministic replay. No commit, push, PR, other task implementation or trading operation.",
|
||||
"cleanup": "No services/data removed; isolated worktree and logs retained."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,9 +17,20 @@ Implement canonical cash-long-only funding, pending fee-inclusive reservations,
|
|||
|
||||
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
|
||||
|
||||
## Execution policy clarifications
|
||||
|
||||
The approved ADRs remain unchanged. The initial additive implementation pins these explicit configuration semantics; no default production thresholds or active-account migration are introduced:
|
||||
|
||||
- Quantity units for order/position limits; base-currency amounts for symbol/gross exposure, daily loss and explicitly named maximum drawdown amount. Commission is an immutable Rust rate in [0, 1], calculated from exact quantity × price × rate and rounded once at eight places.
|
||||
- Pending buys reserve fee-inclusive cash at the canonical mark (market) or max(mark, limit). Pending sells reserve owner inventory, never anticipated buying power; their fill proceeds fund fees. Pending sells do not offset buy exposure. Actual fills recheck other commitments and the remainder, including split-fill rounding. Unaffordable remainder rejects/releases without resizing or borrowing.
|
||||
- Increasing risk requires fresh non-future canonical marks across held and pending assets, using explicit engine event time and a configured maximum mark age. Reductions still enforce inventory/funding/order-size rules. Daily and drawdown halts latch on marked loss; explicit account boundaries reset only daily state, including when retained marks are old. Same-session repetition cannot rebase, and future/backdated boundaries reject.
|
||||
- A private-owned Ledger facade is the only canonical risk entry point. Normalized explicit-order and target-derived admission share one policy; actual target expansion, mode enforcement, matching, venue expiry scheduling and replay remain F05/F06. Resource-release hooks are not a second matcher.
|
||||
- Operator reset is a separate host-held capability with recorded reason/baseline, absent from strategy inputs. This is API authority separation, not authentication or an untrusted-code sandbox. F07 must expose only the risk-governed facade; later host/auth adapters must enforce their own authority.
|
||||
- Checkpoints validate reservations, risk state and recorded outcomes by deterministic reconstruction. They do not authenticate an attacker-modified history and are not full replay/strategy/RNG or SQL recovery snapshots. Normal transitions must not copy/replay the entire retained history.
|
||||
|
||||
## Likely files and ownership
|
||||
|
||||
- apps/stock/engine/src/risk/mod.rs
|
||||
- apps/stock/engine/src/risk/mod.rs (reference only during additive implementation)
|
||||
- apps/stock/engine/src/financial/risk.rs (new)
|
||||
- apps/stock/engine/src/financial/ledger.rs
|
||||
|
||||
|
|
@ -44,6 +55,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
|
|||
- competing_reservations, adverse_gap_reject_remainder, stale_other_symbol, marked_loss_halt, explicit_risk_session_boundary.
|
||||
- drawdown_halt_survives_rollover_restore, unauthorized_reset_denied, alternate_venue_does_not_reset_account_day.
|
||||
- Property test raw order and target paths cannot bypass the same policy.
|
||||
- Partial-fill quantum rounding, zero-cash funded sell, pending sells do not credit buy exposure, stale/future other pending symbol, wrong-owner sell/cancel, accepted/rejected command replay and conflicting reuse, same-session no-rebase, future/backdated boundary rejection, restored reservation tamper and overflow atomicity.
|
||||
|
||||
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
|
||||
|
||||
|
|
|
|||
|
|
@ -19,10 +19,25 @@ Implement pure matcher/order-transition functions over explicit execution events
|
|||
|
||||
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
|
||||
|
||||
## Execution policy clarifications
|
||||
|
||||
The initial component remains additive and Rust-only, privately owning F04 RiskAccount; no mutable risk/ledger escape hatch, parallel accounting, legacy engine or NAPI cutover. F06 derives and schedules events/calendars; F07/S01 supply actual strategy barriers. This task consumes explicit host inputs and proves component behavior.
|
||||
|
||||
- Event eligibility uses availability time, phase, instrument and source sequence plus the pinned execution-series identity. Reject prior/observed execution keys; adjacent next-open at the same timestamp may be eligible under zero latency. Configured latency delays eligibility. No retroactive decision insertion into consumed execution phases. Open events cannot carry future OHLCV. A bar has one shared capacity pool across sides/owners; quotes have explicit bid/ask capacity. Only accepted fills consume it.
|
||||
- Physical quote time is separate from delivery/availability time. Preserve it on marks and require it to be at or after order readiness: late delivery cannot fill an order that did not yet exist. Ineligible old quotes do not consume IOC/FOK opportunities. Explicit open time must match its execution key; F06 must skip/reject missed opens rather than freshen them.
|
||||
- Deduplicate physical opens by instrument/open time and quotes by instrument/observation time/source sequence, independently of delivery key. Exact-key retries return receipts; changed-key redelivery of the same physical event rejects without minting capacity. Do not assume source sequences increase chronologically; distinct quotes sharing a millisecond remain possible.
|
||||
- Pin relative half-spread and slippage rates in [0, 1). For bar opens, derive fixed-eight-place executable bid/ask first; then apply adverse slippage at another declared posting boundary. Quotes already include spread. Limits must cross the executable quote before slippage; qualifying prices are clamped to the limit, never filled through it. Quote financial marks use an exact once-rounded midpoint. F04 alone computes fees and funding.
|
||||
- DAY binds an explicit open venue session and expires at its close; account risk-session reset is separate. IOC/FOK use their first eligible opportunity: IOC cancels remainder; FOK fills the whole remainder once or cancels without fills/fees. Unknown/zero liquidity cannot fill. GTC survives venue closure; run termination cancels without invented liquidation.
|
||||
- Registered strategy mode is fixed. Each listed target is an absolute owner quantity; omitted instruments are unchanged, duplicate entries reject, and explicit zero closes that instrument. Holdings plus signed outstanding commitments determine unchanged targets. Changed targets cancel only that owner's instrument commitments before recomputing; if replacement risk rejects, cancellation remains a recorded outcome.
|
||||
- Owners use stable configured identity order and each decision preserves its explicit intent/target array priority. Sparse target updates are not an atomic portfolio rebalance: earlier entries can reserve cash before later entries release commitments. No anticipated sell proceeds or hidden release-all reordering.
|
||||
- Preflight structural errors across the entire submitted batch/event before mutation. Generated IDs encode tuples unambiguously. Exact repeated events/decisions return original receipts without refilling capacity or replaying effects; conflicting identity reuse rejects. Checkpoints retain order state, priority, identity/cursor/session state and F04 state.
|
||||
- Decision admission uses one coordinator revision for the shared portfolio/order/reservation view. This token is distinct from the nested economic-only FinancialSnapshot ledger revision; F07 must expose the coordinator token for submitting a batch. No wire shape or TypeScript financial arithmetic changes here.
|
||||
- A later internal numeric failure after successful subtransitions is a terminal failed-attempt receipt containing the ordered committed prefix, not a retryable generic error or successful event. All further mutations refuse; restore preserves failure. F06/F07 must discard failed attempts and never publish successful results. This keeps individual F04 transitions atomic without whole-account/history cloning or a second rollback engine.
|
||||
|
||||
## Likely files and ownership
|
||||
|
||||
- apps/stock/engine/src/financial/matching.rs (new)
|
||||
- apps/stock/engine/src/backtest/engine.rs
|
||||
- apps/stock/engine/src/backtest/engine.rs (reference only during additive implementation)
|
||||
|
||||
Write locks: rust-matching, financial-contract. One agent owns this change. Lock names do not override actual overlapping files.
|
||||
|
||||
|
|
@ -47,6 +62,7 @@ Parallel eligibility: only with disjoint actual files and reserved write locks;
|
|||
|
||||
- matcher_gap_limit, shared_volume_capacity, partial_cancel, IOC_remainder, FOK_atomicity, DAY_expiry, target_GTC_replace.
|
||||
- unchanged_target_no_duplicate, mixed_intent_mode_rejected, wrong_owner_cancel, ineligible_event_key_rejected.
|
||||
- Adjacent-open/positive-latency eligibility, same quote/key conflict, pinned execution series, unknown/zero capacity, risk rejection preserves shared capacity, later invalid batch member is atomic, terminal numeric failure records prefix and survives restore, partial-fill/target replay and omitted-target semantics.
|
||||
|
||||
Apply relevant [quality gates](../../QUALITY-GATES.md). Report exact commands/results and unavailable checks; named new cases are requirements, not claims of existing passing tests.
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ Scheduling source of truth: [manifest entry F06](../manifest.json). No task is a
|
|||
|
||||
Implement the replay cursor once: sorted immutable events with stable availability/phase/instrument/sequence ordering; add a small pending-event queue only where required. Absorb P02's nonquadratic load and disabled-by-default hot-loop trade logging. Generate open-only execution events from one designated execution series; feature-only frames do not add liquidity or undeclared decision triggers. Publish completed observations, evaluate declared decision barriers, then next-interval opens under recorded zero/nonzero latency policy.
|
||||
|
||||
Consume F05's explicit event contract without reconstructing a second matcher: quote observation time is not delivery time, and eligibility requires an order to be ready by physical quote time. Open time must equal its execution key; skip/reject missed opens, never relabel them as newly occurring. Decision admission uses the coordinator's shared portfolio/order revision, distinct from the nested economic ledger revision. Terminal F05 failures retain diagnostic prefixes but must fail/discard the replay attempt, never produce successful performance results.
|
||||
|
||||
## Exclusions
|
||||
|
||||
No unrelated refactor, new service, broker enablement, or silent reinterpretation of historical results.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue