feat(research): add financial contracts and availability-aware datasets

Implement reviewed F01/D01 foundations without changing active trading runtimes. Validate strict Rust/TypeScript financial wire contracts, decimal postings, versioned datasets, explicit calendars, provenance, and v1 compatibility.
This commit is contained in:
Boki 2026-10-22 20:51:25 -04:00
parent 243e9ab43f
commit b4af840d4e
25 changed files with 4071 additions and 43 deletions

View file

@ -0,0 +1,368 @@
//! 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, 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>,
}

View file

@ -0,0 +1,9 @@
//! Canonical financial contracts, not yet connected to either legacy simulator.
//!
//! F01 defines transport and checked posting primitives. F02 owns ledger
//! transitions/idempotency; F04 owns risk; F06/F07 own replay/session state.
pub mod contract;
pub mod scalar;
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,107 @@
use rust_decimal::{Decimal, RoundingStrategy};
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::{fmt, str::FromStr};
pub const POSTING_SCALE: u32 = 8;
/// The entire 96-bit coefficient remains available at the fixed posting scale.
pub const MAX_POSTING: &str = "792281625142643375935.43950335";
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum ScalarError {
#[error("expected a plain decimal string with at most 8 fractional digits")]
InvalidDecimal,
#[error("financial posting exceeds the fixed-8 decimal range")]
Overflow,
}
/// Money/quantity transport uses strings, never f64. No float constructor or
/// unchecked arithmetic operator is exposed. Multiplication and proportional
/// division are intentionally left to F02's operation-specific implementation:
/// checked decimal operations can still round intermediate precision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Posting(Decimal);
impl Posting {
pub const ZERO: Self = Self(Decimal::ZERO);
pub fn is_negative(self) -> bool {
self.0.is_sign_negative() && !self.0.is_zero()
}
pub fn is_zero(self) -> bool {
self.0.is_zero()
}
pub fn checked_add(self, other: Self) -> Result<Self, ScalarError> {
Self::from_exact_decimal(self.0.checked_add(other.0).ok_or(ScalarError::Overflow)?)
}
pub fn checked_sub(self, other: Self) -> Result<Self, ScalarError> {
Self::from_exact_decimal(self.0.checked_sub(other.0).ok_or(ScalarError::Overflow)?)
}
/// Posting boundary for an already exact internal decimal calculation.
/// Callers must not pass a previously precision-losing intermediate.
/// https://docs.rs/rust_decimal/1.43.0/rust_decimal/enum.RoundingStrategy.html
pub fn from_exact_decimal(value: Decimal) -> Result<Self, ScalarError> {
let max = Decimal::from_str_exact(MAX_POSTING).expect("fixed decimal constant");
// Reject out-of-range intermediates before rounding as well as after it.
if value.abs() > max {
return Err(ScalarError::Overflow);
}
let mut rounded =
value.round_dp_with_strategy(POSTING_SCALE, RoundingStrategy::MidpointAwayFromZero);
if rounded.abs() > max {
return Err(ScalarError::Overflow);
}
if rounded.is_zero() {
rounded = Decimal::ZERO;
}
rounded.rescale(POSTING_SCALE);
// rescale is infallible and may silently use less precision. Never allow
// that behavior through the authoritative fixed-8 boundary.
if rounded.scale() != POSTING_SCALE {
return Err(ScalarError::Overflow);
}
Ok(Self(rounded))
}
}
impl FromStr for Posting {
type Err = ScalarError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let unsigned = text.strip_prefix('-').unwrap_or(text);
let (integer, fraction) = unsigned.split_once('.').unwrap_or((unsigned, ""));
if integer.is_empty()
|| !integer.bytes().all(|c| c.is_ascii_digit())
|| (integer.len() > 1 && integer.starts_with('0'))
|| (unsigned.contains('.') && fraction.is_empty())
|| fraction.len() > POSTING_SCALE as usize
|| !fraction.bytes().all(|c| c.is_ascii_digit())
{
return Err(ScalarError::InvalidDecimal);
}
let value = Decimal::from_str_exact(text).map_err(|_| ScalarError::Overflow)?;
Self::from_exact_decimal(value)
}
}
impl fmt::Display for Posting {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:.8}", self.0)
}
}
impl Serialize for Posting {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for Posting {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(de::Error::custom)
}
}

View file

@ -0,0 +1,241 @@
use super::{
contract::*,
scalar::{Posting, ScalarError, MAX_POSTING},
};
use rust_decimal::Decimal;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
const SCALARS: &str = include_str!("../../../../../test/fixtures/economics/scalars.json");
const CONTRACTS: &str = include_str!("../../../../../test/fixtures/economics/contracts.json");
const LEDGER_SPECS: &str = include_str!("../../../../../test/fixtures/economics/ledger-specs.json");
fn posting(text: &str) -> Posting {
text.parse().unwrap()
}
fn fixture(text: &str) -> Value {
serde_json::from_str(text).unwrap()
}
fn roundtrip<T: DeserializeOwned + Serialize>(value: Value) -> Result<Value, serde_json::Error> {
serde_json::to_value(serde_json::from_value::<T>(value)?)
}
fn parse_wire(kind: &str, value: Value) -> Result<Value, serde_json::Error> {
match kind {
"command" => roundtrip::<EngineFinancialCommand>(value),
"decision" => roundtrip::<StrategyDecision>(value),
"snapshot" => roundtrip::<FinancialSnapshot>(value),
"effects" => roundtrip::<FinancialEffects>(value),
_ => panic!("unknown fixture kind"),
}
}
fn annotate(case: &Value) {
for field in ["id", "owningTask", "assumptions", "handCalculation"] {
assert!(!case[field].as_str().unwrap().is_empty(), "missing {field}");
}
}
#[test]
fn rust_ts_fixture_parse_parity() {
let scalars = fixture(SCALARS);
for case in scalars["cases"].as_array().unwrap() {
annotate(case);
let parsed = serde_json::from_value::<Posting>(case["input"].clone());
if let Some(expected) = case["canonical"].as_str() {
assert_eq!(parsed.unwrap().to_string(), expected, "{}", case["id"]);
} else {
assert!(parsed.is_err(), "{}", case["id"]);
}
}
let contracts = fixture(CONTRACTS);
let valid = contracts["valid"].as_array().unwrap();
for case in valid {
annotate(case);
let parsed = parse_wire(case["type"].as_str().unwrap(), case["input"].clone()).unwrap();
assert_eq!(parsed, case["canonical"], "{}", case["id"]);
assert_eq!(
parse_wire(case["type"].as_str().unwrap(), parsed.clone()).unwrap(),
parsed
);
}
for case in contracts["invalid"].as_array().unwrap() {
annotate(case);
let base = valid.iter().find(|v| v["id"] == case["base"]).unwrap();
let mut input = base["input"].clone();
let path: Vec<_> = case["path"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap())
.collect();
let pointer = if path.len() == 1 {
String::new()
} else {
format!("/{}", path[..path.len() - 1].join("/"))
};
let parent = input
.pointer_mut(&pointer)
.unwrap()
.as_object_mut()
.unwrap();
parent.insert(path.last().unwrap().to_string(), case["value"].clone());
assert!(
parse_wire(base["type"].as_str().unwrap(), input).is_err(),
"{}",
case["id"]
);
}
}
#[test]
fn safe_integer_json_number_parity() {
let contracts = fixture(CONTRACTS);
annotate(&contracts["numeric"]);
for case in contracts["numeric"]["cases"].as_array().unwrap() {
let raw = case["raw"].as_str().unwrap();
assert_eq!(
serde_json::from_str::<Counter>(raw).is_ok(),
case["counterValid"].as_bool().unwrap(),
"counter {raw}"
);
assert_eq!(
serde_json::from_str::<EventTime>(raw).is_ok(),
case["timestampValid"].as_bool().unwrap(),
"timestamp {raw}"
);
}
assert!(Counter::try_from(u64::MAX).is_err());
assert!(EventTime::try_from(i64::MAX).is_err());
assert!(EventTime::try_from(i64::MIN).is_err());
assert_eq!(
Counter::try_from(9_007_199_254_740_991).unwrap().get(),
9_007_199_254_740_991
);
assert_eq!(
EventTime::try_from(-9_007_199_254_740_991).unwrap().get(),
-9_007_199_254_740_991
);
}
#[test]
fn rounding_ties_positive_negative() {
for case in fixture(SCALARS)["rounding"].as_array().unwrap() {
annotate(case);
let exact = Decimal::from_str_exact(case["input"].as_str().unwrap()).unwrap();
assert_eq!(
Posting::from_exact_decimal(exact).unwrap().to_string(),
case["expected"].as_str().unwrap()
);
// External precision is rejected, not silently rounded like internal postings.
assert!(case["input"].as_str().unwrap().parse::<Posting>().is_err());
}
}
#[test]
fn overflow_rejected() {
let data = fixture(SCALARS);
let case = &data["overflow"];
annotate(case);
let max = posting(MAX_POSTING);
let quantum = posting(case["quantum"].as_str().unwrap());
assert_eq!(max.checked_add(quantum), Err(ScalarError::Overflow));
assert_eq!(
posting(&format!("-{MAX_POSTING}")).checked_sub(quantum),
Err(ScalarError::Overflow)
);
assert_eq!(
max.checked_sub(quantum)
.unwrap()
.checked_add(quantum)
.unwrap(),
max
);
assert_eq!(
Posting::from_exact_decimal(
Decimal::from_str_exact(case["roundingOverflow"].as_str().unwrap()).unwrap()
),
Err(ScalarError::Overflow)
);
assert_eq!(
Posting::from_exact_decimal(Decimal::MAX),
Err(ScalarError::Overflow)
);
assert_eq!(
Posting::from_exact_decimal(Decimal::MIN),
Err(ScalarError::Overflow)
);
assert_eq!(Posting::ZERO.to_string(), "0.00000000");
}
#[test]
fn basis_residual_spec() {
let data = fixture(LEDGER_SPECS);
let case = &data["basis"];
annotate(case);
assert_eq!(case["owningTask"], "F02");
// Check the independent hand calculation, not a replacement ledger simulator.
assert_eq!(
case["releases"],
serde_json::json!(["1.66666667", "1.66666667", "1.66666666"])
);
let midpoint = Decimal::from_str_exact("1.666666665").unwrap();
assert_eq!(
Posting::from_exact_decimal(midpoint).unwrap(),
posting("1.66666667")
);
let initial = posting(case["initialCost"].as_str().unwrap());
let mut remaining = initial;
let mut released = Posting::ZERO;
for (index, value) in case["releases"].as_array().unwrap().iter().enumerate() {
let amount = posting(value.as_str().unwrap());
remaining = remaining.checked_sub(amount).unwrap();
released = released.checked_add(amount).unwrap();
assert_eq!(
remaining.to_string(),
case["remainingCosts"][index].as_str().unwrap()
);
}
assert_eq!(released, initial);
assert_eq!(remaining, Posting::ZERO);
}
#[test]
fn command_id_conflict_spec() {
let data = fixture(LEDGER_SPECS);
let case = &data["commandIds"];
annotate(case);
assert_eq!(case["owningTask"], "F02");
let parse =
|name: &str| serde_json::from_value::<EngineFinancialCommand>(case[name].clone()).unwrap();
let original = parse("original");
let retry = parse("retry");
let conflict = parse("conflict");
let independent = parse("independent");
// Typed payload equality ignores JSON key order and accepted decimal padding.
assert_eq!(original, retry);
assert_eq!(
(
&original.session_id,
&original.account_id,
&original.command_id
),
(
&conflict.session_id,
&conflict.account_id,
&conflict.command_id
)
);
assert_ne!(original.body, conflict.body);
assert_ne!(original.session_id, independent.session_id);
assert_eq!(original.body, independent.body);
}
#[test]
fn strategy_cannot_parse_internal_financial_mutations() {
let contracts = fixture(CONTRACTS);
let command = &contracts["valid"][0]["input"];
assert!(serde_json::from_value::<StrategyDecision>(command.clone()).is_err());
assert!(serde_json::from_value::<EngineFinancialCommand>(
contracts["valid"][3]["input"].clone()
)
.is_err());
}

View file

@ -6,6 +6,7 @@ pub mod adapters;
pub mod orderbook;
pub mod risk;
pub mod positions;
pub mod financial;
#[cfg(not(test))]
pub mod api;
pub mod analytics;
@ -227,4 +228,4 @@ impl TradingCore {
pub fn get_time(&self) -> DateTime<Utc> {
self.time_provider.now()
}
}
}