Skip to main content

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 charge, each flow once, with an
39///   id from its own sequence.
40#[non_exhaustive]
41#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, Constructor)]
42pub struct CashFlow<AssetKey, InstrumentKey> {
43    /// What the flow is for.
44    pub kind: CashFlowKind,
45    /// The asset the cash moved in.
46    pub asset: AssetKey,
47    /// How much moved, signed: positive when the account received it, negative when it paid.
48    pub amount: Decimal,
49    /// The instrument whose position caused the flow, when the venue attributes it to one, as it
50    /// does funding. `None` for a flow on the account as a whole.
51    pub instrument: Option<InstrumentKey>,
52    /// When the venue posted the flow.
53    pub time_exchange: DateTime<Utc>,
54    /// The venue's identifier for the flow, when it gives one. See [`CashFlowId`].
55    pub id: Option<CashFlowId>,
56}
57
58/// What a [`CashFlow`] is for.
59///
60/// Each variant carries the venue's own figures where it reports them, and `None` where it does
61/// not.
62#[non_exhaustive]
63#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
64pub enum CashFlowKind {
65    /// A perpetual's funding payment, paid or received on a position held at a funding time.
66    Funding {
67        /// The funding rate the payment was charged at, per funding interval, in the venue's
68        /// sign convention.
69        rate: Option<Decimal>,
70        /// The signed position the payment was charged on: positive long, negative short.
71        position_quantity: Option<Decimal>,
72    },
73    /// A fee for borrowing a security to sell it short.
74    BorrowFee {
75        /// The fee rate charged, as the venue quotes it: usually annualised.
76        rate: Option<Decimal>,
77        /// The quantity borrowed that the fee was charged on.
78        quantity: Option<Decimal>,
79    },
80    /// Interest on borrowed cash or assets.
81    MarginInterest {
82        /// The interest rate charged, per the venue's own period.
83        rate: Option<Decimal>,
84        /// The amount borrowed that the interest was charged on.
85        principal: Option<Decimal>,
86    },
87    /// The financing of a leveraged position held past a venue's daily cutoff, such as a CFD's
88    /// overnight financing.
89    ///
90    /// Charged on the position rather than on a loan: a long and a short in one instrument are
91    /// charged at different rates, and a short may receive rather than pay. Interest on a loan of
92    /// cash or assets is [`MarginInterest`](Self::MarginInterest).
93    Financing {
94        /// The financing rate charged, as the venue quotes it: usually annualised.
95        rate: Option<Decimal>,
96        /// The notional value of the position the financing was charged on.
97        notional: Option<Decimal>,
98    },
99    /// A rebate paid to the account, such as on cash collateral for a short sale.
100    Rebate,
101    /// A flow of a kind no other variant names, with the venue's own name for it.
102    Other(String),
103}
104
105/// A venue's own identifier for one [`CashFlow`], carried through opaquely.
106///
107/// Like [`TradeId`](crate::trade::TradeId), its uniqueness is the venue's to define and may be
108/// scoped to an asset or instrument rather than global. A consumer that needs a key should
109/// qualify it by exchange and asset or instrument. `Ord` is byte order, not time order.
110#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, From)]
111pub struct CashFlowId(pub SmolStr);
112
113impl Display for CashFlowId {
114    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
115        Display::fmt(&self.0, f)
116    }
117}
118
119impl CashFlowId {
120    pub fn new<S: AsRef<str>>(id: S) -> Self {
121        Self(SmolStr::new(id))
122    }
123}
124
125/// What one read of a venue's cash flows over a span returned, for a venue that serves them in
126/// bounded calls.
127///
128/// `resume` says whether the read stopped before the span's end:
129/// - `None`: every flow in the span the venue still holds, and the client reports, is in `flows`.
130///   Each client documents the records it leaves out.
131/// - `Some(t)`: the read stopped at its bound, and flows from `t` on may be missing from `flows`.
132///   Read on from `start = t` with the same end. That read can return again flows this one
133///   returned at or after `t`, so match them by [`CashFlowId`].
134#[non_exhaustive]
135#[must_use = "`resume` says whether the span was read to its end"]
136#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Constructor)]
137pub struct CashFlowsRead<AssetKey, InstrumentKey> {
138    /// The flows read, in the span.
139    pub flows: Vec<CashFlow<AssetKey, InstrumentKey>>,
140    /// Where to read on from, or `None` when the read reached the span's end.
141    pub resume: Option<DateTime<Utc>>,
142}
143
144impl<AssetKey, InstrumentKey> CashFlowsRead<AssetKey, InstrumentKey> {
145    /// A read that reached the span's end.
146    pub fn complete(flows: Vec<CashFlow<AssetKey, InstrumentKey>>) -> Self {
147        Self {
148            flows,
149            resume: None,
150        }
151    }
152}