rustrade_execution/cash_flow.rs
1//! Cash that moves into or out of an account other than by a trade: perpetual funding, margin
2//! interest, stock borrow fees and rebates.
3//!
4//! An account stream reports each such movement the venue posts as
5//! [`AccountEventKind::CashFlow`](crate::AccountEventKind::CashFlow), carrying a [`CashFlow`]. The
6//! library delivers the venue's own figures; rates, day counts and what to do with the flows stay
7//! the consumer's.
8
9use chrono::{DateTime, Utc};
10use derive_more::{Constructor, From};
11use rust_decimal::Decimal;
12use serde::{Deserialize, Serialize};
13use smol_str::SmolStr;
14use std::fmt::{Display, Formatter};
15
16/// One movement of cash into or out of an account that is not a trade, as the venue posted it.
17///
18/// Sent as [`AccountEventKind::CashFlow`](crate::AccountEventKind::CashFlow). A flow is a delta:
19/// apply each one once. The engine adds a flow attributed to an instrument to the `carry` of that
20/// instrument's open position (see `Position::carry` in `rustrade`), and applies none to
21/// balances. A venue's balances already include the flows it has posted, so adding a flow to a
22/// balance read after it counts the flow twice. Carry a venue has accrued but not yet posted is no
23/// flow: a venue that reports it puts it in
24/// [`Balance::accrued`](crate::balance::Balance::accrued).
25///
26/// # Delivery
27///
28/// Each producer says how it avoids sending one flow twice, and what identifies a flow when the
29/// venue gives it no [`id`](Self::id). Known producers, as of writing:
30/// - Hyperliquid perpetuals: funding, as [`CashFlowKind::Funding`]. See the client's rustdoc.
31/// - Alpaca: margin interest, fees and pass-through charges and rebates, read on request by
32/// `AlpacaClient::fetch_cash_flows` rather than streamed, with Alpaca's activity id. The caller
33/// drops what it has already read.
34/// - Binance margin: interest, as [`CashFlowKind::MarginInterest`], read on request by
35/// `BinanceMargin::fetch_margin_interest` rather than streamed, with Binance's transaction id.
36/// The caller drops what it has already read.
37/// - The simulated venue: whatever its configured
38/// [`HoldingCostModel`](crate::holding_cost::HoldingCostModel)s and
39/// [`MarginInterestModel`](crate::margin::MarginInterestModel) charge, each flow once, with an
40/// id from its own sequence.
41#[non_exhaustive]
42#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, Constructor)]
43pub struct CashFlow<AssetKey, InstrumentKey> {
44 /// What the flow is for.
45 pub kind: CashFlowKind,
46 /// The asset the cash moved in.
47 pub asset: AssetKey,
48 /// How much moved, signed: positive when the account received it, negative when it paid.
49 pub amount: Decimal,
50 /// The instrument whose position caused the flow, when the venue attributes it to one, as it
51 /// does funding. `None` for a flow on the account as a whole.
52 pub instrument: Option<InstrumentKey>,
53 /// When the venue posted the flow.
54 pub time_exchange: DateTime<Utc>,
55 /// The venue's identifier for the flow, when it gives one. See [`CashFlowId`].
56 pub id: Option<CashFlowId>,
57}
58
59/// What a [`CashFlow`] is for.
60///
61/// Each variant carries the venue's own figures where it reports them, and `None` where it does
62/// not.
63#[non_exhaustive]
64#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
65pub enum CashFlowKind {
66 /// A perpetual's funding payment, paid or received on a position held at a funding time.
67 Funding {
68 /// The funding rate the payment was charged at, per funding interval, in the venue's
69 /// sign convention.
70 rate: Option<Decimal>,
71 /// The signed position the payment was charged on: positive long, negative short.
72 position_quantity: Option<Decimal>,
73 },
74 /// A fee for borrowing a security to sell it short.
75 BorrowFee {
76 /// The fee rate charged, as the venue quotes it: usually annualised.
77 rate: Option<Decimal>,
78 /// The quantity borrowed that the fee was charged on.
79 quantity: Option<Decimal>,
80 },
81 /// Interest on borrowed cash or assets.
82 MarginInterest {
83 /// The interest rate charged, as its source quotes it: per the venue's own period from a
84 /// live venue (daily from Binance), annualised from the simulated venue's
85 /// [`PeriodicMarginInterest`](crate::margin::PeriodicMarginInterest).
86 rate: Option<Decimal>,
87 /// The amount borrowed that the interest was charged on.
88 principal: Option<Decimal>,
89 },
90 /// The financing of a leveraged position held past a venue's daily cutoff, such as a CFD's
91 /// overnight financing.
92 ///
93 /// Charged on the position rather than on a loan: a long and a short in one instrument are
94 /// charged at different rates, and a short may receive rather than pay. Interest on a loan of
95 /// cash or assets is [`MarginInterest`](Self::MarginInterest).
96 Financing {
97 /// The financing rate charged, as the venue quotes it: usually annualised.
98 rate: Option<Decimal>,
99 /// The notional value of the position the financing was charged on.
100 notional: Option<Decimal>,
101 },
102 /// A rebate paid to the account, such as on cash collateral for a short sale.
103 Rebate,
104 /// A flow of a kind no other variant names, with the venue's own name for it.
105 Other(String),
106}
107
108/// A venue's own identifier for one [`CashFlow`], carried through opaquely.
109///
110/// Like [`TradeId`](crate::trade::TradeId), its uniqueness is the venue's to define and may be
111/// scoped to an asset or instrument rather than global. A consumer that needs a key should
112/// qualify it by exchange and asset or instrument. `Ord` is byte order, not time order.
113#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, From)]
114pub struct CashFlowId(pub SmolStr);
115
116impl Display for CashFlowId {
117 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
118 Display::fmt(&self.0, f)
119 }
120}
121
122impl CashFlowId {
123 pub fn new<S: AsRef<str>>(id: S) -> Self {
124 Self(SmolStr::new(id))
125 }
126}
127
128/// What one read of a venue's cash flows over a span returned, for a venue that serves them in
129/// bounded calls.
130///
131/// `resume` says whether the read stopped before the span's end:
132/// - `None`: every flow in the span the venue still holds, and the client reports, is in `flows`.
133/// Each client documents the records it leaves out.
134/// - `Some(t)`: the read stopped at its bound, and flows from `t` on may be missing from `flows`.
135/// Read on from `start = t` with the same end. That read can return again flows this one
136/// returned at or after `t`, so match them by [`CashFlowId`].
137#[non_exhaustive]
138#[must_use = "`resume` says whether the span was read to its end"]
139#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Constructor)]
140pub struct CashFlowsRead<AssetKey, InstrumentKey> {
141 /// The flows read, in the span.
142 pub flows: Vec<CashFlow<AssetKey, InstrumentKey>>,
143 /// Where to read on from, or `None` when the read reached the span's end.
144 pub resume: Option<DateTime<Utc>>,
145}
146
147impl<AssetKey, InstrumentKey> CashFlowsRead<AssetKey, InstrumentKey> {
148 /// A read that reached the span's end.
149 pub fn complete(flows: Vec<CashFlow<AssetKey, InstrumentKey>>) -> Self {
150 Self {
151 flows,
152 resume: None,
153 }
154 }
155}