perf(research): add compact replay projections and representative profiling
This commit is contained in:
parent
19e9dad68b
commit
e3bd722e31
21 changed files with 2830 additions and 130 deletions
|
|
@ -67,7 +67,8 @@ pub struct LedgerCheckpoint {
|
|||
pub receipts: Vec<LedgerReceipt>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OwnerValuation {
|
||||
pub owner_id: Id,
|
||||
pub initial_capital: Posting,
|
||||
|
|
@ -81,7 +82,8 @@ pub struct OwnerValuation {
|
|||
pub equity_contribution: Posting,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LedgerValuation {
|
||||
pub cash: Posting,
|
||||
pub marked_holdings: Posting,
|
||||
|
|
@ -693,6 +695,12 @@ impl Ledger {
|
|||
})
|
||||
}
|
||||
|
||||
/// Read-only accepted financial history, including replay-labelled aliases.
|
||||
/// Reporting must skip aliases; this does not copy a restorable checkpoint.
|
||||
pub fn receipts(&self) -> &[LedgerReceipt] {
|
||||
&self.receipts
|
||||
}
|
||||
|
||||
pub fn checkpoint(&self) -> LedgerCheckpoint {
|
||||
LedgerCheckpoint {
|
||||
version: Version,
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ pub mod contract;
|
|||
pub mod ledger;
|
||||
pub mod matching;
|
||||
pub mod replay;
|
||||
pub mod result;
|
||||
pub mod risk;
|
||||
pub mod scalar;
|
||||
|
||||
|
|
@ -24,6 +25,9 @@ mod matching_tests;
|
|||
#[cfg(test)]
|
||||
mod replay_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod result_tests;
|
||||
|
||||
// Exercise the pure host adapter without linking every legacy NAPI export.
|
||||
#[cfg(test)]
|
||||
#[path = "../api/replay.rs"]
|
||||
|
|
|
|||
115
apps/stock/engine/src/financial/result.rs
Normal file
115
apps/stock/engine/src/financial/result.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
//! Read-only reporting from committed financial facts. No matching, accounting,
|
||||
//! history replay, checkpoint copies or statistical/round-trip interpretation.
|
||||
use super::{
|
||||
contract::*,
|
||||
ledger::{Ledger, LedgerError, LedgerValuation},
|
||||
scalar::Posting,
|
||||
};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OwnedFill<'a> {
|
||||
pub command_id: &'a Id,
|
||||
pub event_time: EventTime,
|
||||
pub owner_id: &'a Id,
|
||||
pub decision: &'a DecisionIdentity,
|
||||
pub order_id: &'a Id,
|
||||
pub fill_id: &'a Id,
|
||||
pub instrument_id: &'a Id,
|
||||
pub side: Side,
|
||||
pub quantity: Positive,
|
||||
pub price: Positive,
|
||||
pub fee: &'a Fee,
|
||||
pub cash_delta: Posting,
|
||||
pub quantity_delta: Posting,
|
||||
pub released_basis: NonNegative,
|
||||
pub realized_gross_pnl: Posting,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FinancialProjection<'a> {
|
||||
pub valuation: LedgerValuation,
|
||||
pub fills: Vec<OwnedFill<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ProjectionError {
|
||||
#[error(transparent)]
|
||||
Ledger(#[from] LedgerError),
|
||||
#[error("committed fill receipt has inconsistent financial effects")]
|
||||
InconsistentReceipt,
|
||||
}
|
||||
|
||||
pub fn project(ledger: &Ledger) -> Result<FinancialProjection<'_>, ProjectionError> {
|
||||
let valuation = ledger.valuation()?;
|
||||
let mut fills = Vec::new();
|
||||
for receipt in ledger.receipts() {
|
||||
if receipt.outcome.replayed {
|
||||
continue;
|
||||
}
|
||||
let EngineCommandBody::ApplyFill {
|
||||
decision,
|
||||
order_id,
|
||||
fill_id,
|
||||
instrument_id,
|
||||
side,
|
||||
quantity,
|
||||
price,
|
||||
fee,
|
||||
} = &receipt.command.body
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let [FinancialEffect::FillApplied {
|
||||
owner_id: effect_owner,
|
||||
order_id: effect_order,
|
||||
fill_id: effect_fill,
|
||||
instrument_id: effect_instrument,
|
||||
price: effect_price,
|
||||
cash_delta,
|
||||
quantity_delta,
|
||||
released_basis,
|
||||
realized_gross_pnl,
|
||||
}, FinancialEffect::FeeApplied {
|
||||
owner_id: fee_owner,
|
||||
fill_id: fee_fill,
|
||||
fee_id,
|
||||
amount,
|
||||
}] = receipt.outcome.effects.effects.as_slice()
|
||||
else {
|
||||
return Err(ProjectionError::InconsistentReceipt);
|
||||
};
|
||||
if effect_owner != &decision.owner_id
|
||||
|| effect_order != order_id
|
||||
|| effect_fill != fill_id
|
||||
|| effect_instrument != instrument_id
|
||||
|| effect_price != price
|
||||
|| fee_owner != effect_owner
|
||||
|| fee_fill != fill_id
|
||||
|| fee_id != &fee.fee_id
|
||||
|| amount != &fee.amount
|
||||
{
|
||||
return Err(ProjectionError::InconsistentReceipt);
|
||||
}
|
||||
fills.push(OwnedFill {
|
||||
command_id: &receipt.command.command_id,
|
||||
event_time: receipt.command.event_time,
|
||||
owner_id: &decision.owner_id,
|
||||
decision,
|
||||
order_id,
|
||||
fill_id,
|
||||
instrument_id,
|
||||
side: *side,
|
||||
quantity: *quantity,
|
||||
price: *price,
|
||||
fee,
|
||||
cash_delta: *cash_delta,
|
||||
quantity_delta: *quantity_delta,
|
||||
released_basis: *released_basis,
|
||||
realized_gross_pnl: *realized_gross_pnl,
|
||||
});
|
||||
}
|
||||
Ok(FinancialProjection { valuation, fills })
|
||||
}
|
||||
146
apps/stock/engine/src/financial/result_tests.rs
Normal file
146
apps/stock/engine/src/financial/result_tests.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
use super::{contract::*, ledger::*, result::project};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn ledger() -> Ledger {
|
||||
Ledger::new(
|
||||
serde_json::from_value(json!({
|
||||
"version":1,"sessionId":"s","accountId":"a","baseCurrency":"USD",
|
||||
"reserveOwnerId":"reserve","ownerIds":["A","B"],"initialCapital":"10000",
|
||||
"riskSession":{"calendarId":"c","calendarRevision":"1","sessionId":"d","startsAt":0}
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
fn apply(ledger: &mut Ledger, id: &str, at: i64, body: Value) -> EngineFinancialCommand {
|
||||
let command = serde_json::from_value(json!({"version":1,"sessionId":"s","accountId":"a",
|
||||
"commandId":id,"eventTime":at,"body":body}))
|
||||
.unwrap();
|
||||
ledger.apply(&command).unwrap();
|
||||
command
|
||||
}
|
||||
fn fill(
|
||||
owner: &str,
|
||||
order: &str,
|
||||
fill: &str,
|
||||
side: &str,
|
||||
quantity: &str,
|
||||
price: &str,
|
||||
fee: &str,
|
||||
) -> Value {
|
||||
json!({"kind":"applyFill","decision":{"ownerId":owner,"decisionId":order,"sequence":0},
|
||||
"orderId":order,"fillId":fill,"instrumentId":"X","side":side,"quantity":quantity,
|
||||
"price":price,"fee":{"feeId":format!("fee-{fill}"),"amount":fee}})
|
||||
}
|
||||
fn output(ledger: &Ledger) -> Value {
|
||||
serde_json::to_value(project(ledger).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projection_aliases_once_and_is_read_only_after_restore() {
|
||||
let mut ledger = ledger();
|
||||
apply(
|
||||
&mut ledger,
|
||||
"mark",
|
||||
0,
|
||||
json!({"kind":"mark","instrumentId":"X","price":"12"}),
|
||||
);
|
||||
let command = apply(
|
||||
&mut ledger,
|
||||
"fill",
|
||||
1,
|
||||
fill("A", "buy", "f1", "buy", "2", "12", "0.24"),
|
||||
);
|
||||
assert!(ledger.apply(&command).unwrap().replayed);
|
||||
let mut alias = command;
|
||||
alias.command_id = serde_json::from_value(json!("alias")).unwrap();
|
||||
assert!(ledger.apply(&alias).unwrap().replayed);
|
||||
assert_eq!(ledger.receipts().len(), 3);
|
||||
let before = ledger.checkpoint();
|
||||
let projection = output(&ledger);
|
||||
assert_eq!(projection["fills"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(projection["fills"][0]["commandId"], "fill");
|
||||
assert_eq!(projection["fills"][0]["fee"]["amount"], "0.24000000");
|
||||
// cashDelta is gross; fee remains a distinct canonical posting.
|
||||
assert_eq!(projection["fills"][0]["cashDelta"], "-24.00000000");
|
||||
assert_eq!(projection["valuation"]["cash"], "9975.76000000");
|
||||
assert_eq!(projection["valuation"]["equity"], "9999.76000000");
|
||||
assert_eq!(output(&ledger), projection);
|
||||
assert_eq!(ledger.checkpoint(), before);
|
||||
assert_eq!(output(&Ledger::restore(before).unwrap()), projection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_fill_projection_retains_final_basis_residual_and_actual_fees() {
|
||||
let mut ledger = ledger();
|
||||
apply(
|
||||
&mut ledger,
|
||||
"mark",
|
||||
0,
|
||||
json!({"kind":"mark","instrumentId":"X","price":"3"}),
|
||||
);
|
||||
for (index, body) in [
|
||||
fill("A", "buy", "b1", "buy", "1", "1", "0.01"),
|
||||
fill("A", "buy", "b2", "buy", "2", "2", "0.04"),
|
||||
fill("A", "sell", "s1", "sell", "1", "3", "0.03"),
|
||||
fill("A", "sell", "s2", "sell", "1", "3", "0.03"),
|
||||
fill("A", "sell", "s3", "sell", "1", "3", "0.03"),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
apply(
|
||||
&mut ledger,
|
||||
&format!("command-{index}"),
|
||||
index as i64 + 1,
|
||||
body,
|
||||
);
|
||||
}
|
||||
let projection = output(&ledger);
|
||||
let fills = projection["fills"].as_array().unwrap();
|
||||
assert_eq!(fills.len(), 5);
|
||||
assert_eq!(fills[2]["releasedBasis"], "1.66666667");
|
||||
assert_eq!(fills[3]["releasedBasis"], "1.66666667");
|
||||
assert_eq!(fills[4]["releasedBasis"], "1.66666666");
|
||||
assert_eq!(projection["valuation"]["remainingCost"], "0.00000000");
|
||||
assert_eq!(projection["valuation"]["realizedGrossPnl"], "4.00000000");
|
||||
assert_eq!(projection["valuation"]["fees"], "0.14000000");
|
||||
assert_eq!(projection["valuation"]["equity"], "10003.86000000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_owner_projection_retains_negative_contribution_and_empty_results() {
|
||||
let mut ledger = ledger();
|
||||
let empty = output(&ledger);
|
||||
assert_eq!(empty["fills"], json!([]));
|
||||
assert_eq!(empty["valuation"]["equity"], "10000.00000000");
|
||||
apply(
|
||||
&mut ledger,
|
||||
"mark",
|
||||
0,
|
||||
json!({"kind":"mark","instrumentId":"X","price":"10"}),
|
||||
);
|
||||
apply(
|
||||
&mut ledger,
|
||||
"a",
|
||||
1,
|
||||
fill("A", "a-buy", "a-fill", "buy", "1", "10", "1"),
|
||||
);
|
||||
apply(
|
||||
&mut ledger,
|
||||
"b",
|
||||
2,
|
||||
fill("B", "b-buy", "b-fill", "buy", "2", "8", "0.5"),
|
||||
);
|
||||
let projection = output(&ledger);
|
||||
let owners = projection["valuation"]["owners"].as_array().unwrap();
|
||||
assert_eq!(owners[0]["ownerId"], "A");
|
||||
assert_eq!(owners[0]["equityContribution"], "-1.00000000");
|
||||
assert_eq!(owners[1]["ownerId"], "B");
|
||||
assert_eq!(owners[1]["equityContribution"], "3.50000000");
|
||||
assert_eq!(owners[2]["ownerId"], "reserve");
|
||||
assert_eq!(owners[2]["equityContribution"], "10000.00000000");
|
||||
assert_eq!(projection["valuation"]["equity"], "10002.50000000");
|
||||
assert_eq!(projection["fills"][0]["ownerId"], "A");
|
||||
assert_eq!(projection["fills"][1]["decision"]["ownerId"], "B");
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue