Implement reviewed F02/D02: exact owner accounting, atomic funding checks, idempotent receipts and ledger checkpoints; connect existing EOD intraday storage through validated research admission without active financial-engine cutover.
368 lines
10 KiB
Rust
368 lines
10 KiB
Rust
//! Strict v1 economic wire shapes. Internal engine commands are deliberately a
|
|
//! different type from strategy decisions: strategies cannot submit fills,
|
|
//! cash mutations, marks, or account-risk-session boundaries.
|
|
use super::scalar::Posting;
|
|
use serde::{de, Deserialize, Deserializer, Serialize};
|
|
|
|
const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
|
|
#[serde(transparent)]
|
|
pub struct Id(String);
|
|
|
|
impl<'de> Deserialize<'de> for Id {
|
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
|
let s = String::deserialize(d)?;
|
|
// Preserve existing instrument/provider IDs verbatim. Dataset admission
|
|
// validates instrument membership; generic identity is not that parser.
|
|
if s.is_empty() || s.bytes().any(|c| c < 0x20 || c == 0x7f) {
|
|
return Err(de::Error::custom(
|
|
"expected nonempty identity without control characters",
|
|
));
|
|
}
|
|
Ok(Self(s))
|
|
}
|
|
}
|
|
|
|
// JSON.parse accepts integral1.0/1e0 as numbers. Rust uses the same safe-number
|
|
// semantics rather than accepting u64 values JavaScript cannot represent.
|
|
fn safe_integer<'de, D: Deserializer<'de>>(d: D, signed: bool) -> Result<i64, D::Error> {
|
|
let n = serde_json::Number::deserialize(d)?;
|
|
let f = n
|
|
.as_f64()
|
|
.ok_or_else(|| de::Error::custom("expected a safe integer"))?;
|
|
if !f.is_finite()
|
|
|| f.fract() != 0.0
|
|
|| f.abs() > MAX_SAFE_INTEGER as f64
|
|
|| (!signed && f < 0.0)
|
|
{
|
|
return Err(de::Error::custom("expected a safe integer"));
|
|
}
|
|
Ok(f as i64)
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
|
#[serde(transparent)]
|
|
pub struct Counter(u64);
|
|
impl Counter {
|
|
pub fn get(self) -> u64 {
|
|
self.0
|
|
}
|
|
}
|
|
impl TryFrom<u64> for Counter {
|
|
type Error = &'static str;
|
|
fn try_from(value: u64) -> Result<Self, Self::Error> {
|
|
if value <= MAX_SAFE_INTEGER as u64 {
|
|
Ok(Self(value))
|
|
} else {
|
|
Err("expected a safe counter")
|
|
}
|
|
}
|
|
}
|
|
impl<'de> Deserialize<'de> for Counter {
|
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
|
Ok(Self(safe_integer(d, false)? as u64))
|
|
}
|
|
}
|
|
|
|
/// Unix milliseconds; event time, never an inferred processing clock.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
|
#[serde(transparent)]
|
|
pub struct EventTime(i64);
|
|
impl EventTime {
|
|
pub fn get(self) -> i64 {
|
|
self.0
|
|
}
|
|
}
|
|
impl TryFrom<i64> for EventTime {
|
|
type Error = &'static str;
|
|
fn try_from(value: i64) -> Result<Self, Self::Error> {
|
|
if (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&value) {
|
|
Ok(Self(value))
|
|
} else {
|
|
Err("expected a safe event time")
|
|
}
|
|
}
|
|
}
|
|
impl<'de> Deserialize<'de> for EventTime {
|
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
|
Ok(Self(safe_integer(d, true)?))
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(try_from = "Counter", into = "Counter")]
|
|
pub struct Version;
|
|
impl TryFrom<Counter> for Version {
|
|
type Error = &'static str;
|
|
fn try_from(value: Counter) -> Result<Self, Self::Error> {
|
|
if value.0 == 1 {
|
|
Ok(Self)
|
|
} else {
|
|
Err("unsupported financial protocol version")
|
|
}
|
|
}
|
|
}
|
|
impl From<Version> for Counter {
|
|
fn from(_: Version) -> Self {
|
|
Self(1)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(try_from = "Posting", into = "Posting")]
|
|
pub struct NonNegative(Posting);
|
|
impl TryFrom<Posting> for NonNegative {
|
|
type Error = &'static str;
|
|
fn try_from(value: Posting) -> Result<Self, Self::Error> {
|
|
if value.is_negative() {
|
|
Err("expected a nonnegative posting")
|
|
} else {
|
|
Ok(Self(value))
|
|
}
|
|
}
|
|
}
|
|
impl From<NonNegative> for Posting {
|
|
fn from(value: NonNegative) -> Self {
|
|
value.0
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(try_from = "Posting", into = "Posting")]
|
|
pub struct Positive(Posting);
|
|
impl TryFrom<Posting> for Positive {
|
|
type Error = &'static str;
|
|
fn try_from(value: Posting) -> Result<Self, Self::Error> {
|
|
if value.is_negative() || value.is_zero() {
|
|
Err("expected a positive posting")
|
|
} else {
|
|
Ok(Self(value))
|
|
}
|
|
}
|
|
}
|
|
impl From<Positive> for Posting {
|
|
fn from(value: Positive) -> Self {
|
|
value.0
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct DecisionIdentity {
|
|
pub owner_id: Id,
|
|
pub decision_id: Id,
|
|
pub sequence: Counter,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct RiskSessionIdentity {
|
|
pub calendar_id: Id,
|
|
pub calendar_revision: Id,
|
|
pub session_id: Id,
|
|
pub starts_at: EventTime,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct Fee {
|
|
pub fee_id: Id,
|
|
pub amount: NonNegative,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub enum Side {
|
|
Buy,
|
|
Sell,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
pub enum TimeInForce {
|
|
GTC,
|
|
DAY,
|
|
IOC,
|
|
FOK,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(
|
|
tag = "kind",
|
|
rename_all = "camelCase",
|
|
rename_all_fields = "camelCase",
|
|
deny_unknown_fields
|
|
)]
|
|
pub enum EngineCommandBody {
|
|
ApplyFill {
|
|
decision: DecisionIdentity,
|
|
order_id: Id,
|
|
fill_id: Id,
|
|
instrument_id: Id,
|
|
side: Side,
|
|
quantity: Positive,
|
|
price: Positive,
|
|
fee: Fee,
|
|
},
|
|
Mark {
|
|
instrument_id: Id,
|
|
price: Positive,
|
|
},
|
|
RiskSessionBoundary {
|
|
risk_session: RiskSessionIdentity,
|
|
},
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct EngineFinancialCommand {
|
|
pub version: Version,
|
|
pub session_id: Id,
|
|
pub account_id: Id,
|
|
/// Scoped to(sessionId, accountId); identical payload retries are idempotent,
|
|
/// conflicting reuse rejects. F02 implements the receipt store, not F01.
|
|
pub command_id: Id,
|
|
pub event_time: EventTime,
|
|
pub body: EngineCommandBody,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct Target {
|
|
pub instrument_id: Id,
|
|
pub quantity: NonNegative,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(
|
|
tag = "kind",
|
|
rename_all = "camelCase",
|
|
rename_all_fields = "camelCase",
|
|
deny_unknown_fields
|
|
)]
|
|
pub enum OrderIntent {
|
|
Market {
|
|
order_id: Id,
|
|
instrument_id: Id,
|
|
side: Side,
|
|
quantity: Positive,
|
|
time_in_force: TimeInForce,
|
|
},
|
|
Limit {
|
|
order_id: Id,
|
|
instrument_id: Id,
|
|
side: Side,
|
|
quantity: Positive,
|
|
price: Positive,
|
|
time_in_force: TimeInForce,
|
|
},
|
|
Cancel {
|
|
order_id: Id,
|
|
},
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(tag = "mode", rename_all = "camelCase", deny_unknown_fields)]
|
|
pub enum StrategyIntent {
|
|
Target { targets: Vec<Target> },
|
|
Orders { orders: Vec<OrderIntent> },
|
|
}
|
|
|
|
/// A decision in a shared barrier, not an independent mutation endpoint.
|
|
/// Registered per-instance mode, owner authority, complete barrier membership,
|
|
/// stable admission order and staged state/RNG are enforced by F07/S01.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct StrategyDecision {
|
|
pub version: Version,
|
|
pub session_id: Id,
|
|
pub barrier_id: Id,
|
|
pub revision: Counter,
|
|
pub decision: DecisionIdentity,
|
|
pub intent: StrategyIntent,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct OwnerPosition {
|
|
pub owner_id: Id,
|
|
pub instrument_id: Id,
|
|
pub quantity: NonNegative,
|
|
pub remaining_cost: NonNegative,
|
|
pub realized_gross_pnl: Posting,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct OwnerFees {
|
|
pub owner_id: Id,
|
|
pub amount: NonNegative,
|
|
}
|
|
|
|
/// Economic projection ONLY. This is not a complete restorable engine/session
|
|
/// snapshot: F02/F04/F07 own receipts, reservations, open orders, risk state,
|
|
/// replay cursors and strategy/RNG state. Average cost is deliberately absent.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct FinancialSnapshot {
|
|
pub version: Version,
|
|
pub session_id: Id,
|
|
pub account_id: Id,
|
|
pub revision: Counter,
|
|
pub base_currency: Id,
|
|
pub reserve_owner_id: Id,
|
|
pub cash: NonNegative,
|
|
pub positions: Vec<OwnerPosition>,
|
|
pub fees: Vec<OwnerFees>,
|
|
pub risk_session: RiskSessionIdentity,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(
|
|
tag = "kind",
|
|
rename_all = "camelCase",
|
|
rename_all_fields = "camelCase",
|
|
deny_unknown_fields
|
|
)]
|
|
pub enum FinancialEffect {
|
|
FillApplied {
|
|
owner_id: Id,
|
|
order_id: Id,
|
|
fill_id: Id,
|
|
instrument_id: Id,
|
|
price: Positive,
|
|
cash_delta: Posting,
|
|
quantity_delta: Posting,
|
|
released_basis: NonNegative,
|
|
realized_gross_pnl: Posting,
|
|
},
|
|
FeeApplied {
|
|
owner_id: Id,
|
|
fill_id: Id,
|
|
fee_id: Id,
|
|
amount: NonNegative,
|
|
},
|
|
MarkUpdated {
|
|
instrument_id: Id,
|
|
price: Positive,
|
|
},
|
|
RiskSessionChanged {
|
|
risk_session: RiskSessionIdentity,
|
|
},
|
|
Rejected {
|
|
code: Id,
|
|
},
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
pub struct FinancialEffects {
|
|
pub version: Version,
|
|
pub session_id: Id,
|
|
pub account_id: Id,
|
|
pub command_id: Id,
|
|
pub event_time: EventTime,
|
|
pub revision: Counter,
|
|
/// Transition order is authoritative; consumers must not sort these effects.
|
|
pub effects: Vec<FinancialEffect>,
|
|
}
|