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, such as cross-margin interest.
52 ///
53 /// The `rustrade` engine applies a `None` flow to no position, and does not guess one. A
54 /// consumer that knows which position a flow belongs to sets this before the engine sees the
55 /// event. See `EngineState::update_from_account` in `rustrade` for why and how.
56 pub instrument: Option<InstrumentKey>,
57 /// When the venue posted the flow.
58 pub time_exchange: DateTime<Utc>,
59 /// The venue's identifier for the flow, when it gives one. See [`CashFlowId`].
60 pub id: Option<CashFlowId>,
61}
62
63/// What a [`CashFlow`] is for.
64///
65/// Each variant carries the venue's own figures where it reports them, and `None` where it does
66/// not.
67#[non_exhaustive]
68#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
69pub enum CashFlowKind {
70 /// A perpetual's funding payment, paid or received on a position held at a funding time.
71 Funding {
72 /// The funding rate the payment was charged at, per funding interval, in the venue's
73 /// sign convention.
74 rate: Option<Decimal>,
75 /// The signed position the payment was charged on: positive long, negative short.
76 position_quantity: Option<Decimal>,
77 },
78 /// A fee for borrowing a security to sell it short.
79 BorrowFee {
80 /// The fee rate charged, as the venue quotes it: usually annualised.
81 rate: Option<Decimal>,
82 /// The quantity borrowed that the fee was charged on.
83 quantity: Option<Decimal>,
84 },
85 /// Interest on borrowed cash or assets.
86 MarginInterest {
87 /// The interest rate charged, as its source quotes it: per the venue's own period from a
88 /// live venue (daily from Binance), annualised from the simulated venue's
89 /// [`PeriodicMarginInterest`](crate::margin::PeriodicMarginInterest).
90 rate: Option<Decimal>,
91 /// The amount borrowed that the interest was charged on.
92 principal: Option<Decimal>,
93 /// When in the loan's life the charge falls, where the venue says.
94 timing: Option<InterestTiming>,
95 },
96 /// The financing of a leveraged position held past a venue's daily cutoff, such as a CFD's
97 /// overnight financing.
98 ///
99 /// Charged on the position rather than on a loan: a long and a short in one instrument are
100 /// charged at different rates, and a short may receive rather than pay. Interest on a loan of
101 /// cash or assets is [`MarginInterest`](Self::MarginInterest).
102 Financing {
103 /// The financing rate charged, as the venue quotes it: usually annualised.
104 rate: Option<Decimal>,
105 /// The notional value of the position the financing was charged on.
106 notional: Option<Decimal>,
107 },
108 /// A rebate paid to the account, such as on cash collateral for a short sale.
109 Rebate,
110 /// A flow of a kind no other variant names, with the venue's own name for it.
111 Other(String),
112}
113
114/// When in a loan's life a [`CashFlowKind::MarginInterest`] charge falls.
115///
116/// A venue charges the interest on a new loan when it is taken and again at each of its charging
117/// boundaries. A charge on a new loan can carry a time before the position it belongs to opened,
118/// since a venue may stamp it at the start of the period the loan was taken in.
119#[non_exhaustive]
120#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
121pub enum InterestTiming {
122 /// The charge for holding the loan over a charging period, at one of the venue's boundaries.
123 Periodic,
124 /// The first charge, made when the loan is taken.
125 OnBorrow,
126 /// A timing neither variant names, with the venue's own name for it. Like an absent timing
127 /// (`None`), it is unknown: do not treat it as either named variant.
128 Other(SmolStr),
129}
130
131/// A venue's own identifier for one [`CashFlow`], carried through opaquely.
132///
133/// Like [`TradeId`](crate::trade::TradeId), its uniqueness is the venue's to define and may be
134/// scoped to an asset or instrument rather than global. A consumer that needs a key should
135/// qualify it by exchange and asset or instrument. `Ord` is byte order, not time order.
136#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, From)]
137pub struct CashFlowId(pub SmolStr);
138
139impl Display for CashFlowId {
140 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
141 Display::fmt(&self.0, f)
142 }
143}
144
145impl CashFlowId {
146 pub fn new<S: AsRef<str>>(id: S) -> Self {
147 Self(SmolStr::new(id))
148 }
149}
150
151/// What one read of a venue's cash flows over a span returned.
152///
153/// `resume` says whether the read stopped before the span's end:
154/// - `None`: every flow in the span the venue still holds, and the client reports, is in `flows`.
155/// Each client documents the records it leaves out.
156/// - `Some(t)`: the read stopped at its bound, and flows from `t` on may be missing from `flows`.
157/// Read on from `start = t` with the same end. That read can return again flows this one
158/// returned at or after `t`, so match them by [`CashFlowId`].
159///
160/// A venue also keeps its records for a limited time. `held_since` says when that limit cuts
161/// into the span, so a caller can tell flows the venue no longer has from flows that never
162/// happened.
163#[non_exhaustive]
164#[must_use = "`resume` and `held_since` say whether the span was read in full"]
165#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize)]
166pub struct CashFlowsRead<AssetKey, InstrumentKey> {
167 /// The flows read, in the span.
168 pub flows: Vec<CashFlow<AssetKey, InstrumentKey>>,
169 /// Where to read on from, or `None` when the read reached the span's end.
170 pub resume: Option<DateTime<Utc>>,
171 /// The earliest moment the read covers, when the span starts before it; flows before it may
172 /// exist but cannot be read. It is after the span's end when none of the span can be read.
173 /// `None` when the venue's limit is not known to cut into the span, which is no claim that
174 /// the venue holds flows without limit.
175 ///
176 /// A caller that needs every flow in the span, such as one adding up a position's whole
177 /// interest, treats the part before `held_since` as a gap: `resume: None` covers what the
178 /// venue holds, not what it held. The limit cuts into the span from its start, so only the
179 /// first read of a span can report it; a caller reading on from `resume` has nothing to learn
180 /// from a later read's.
181 pub held_since: Option<DateTime<Utc>>,
182}
183
184impl<AssetKey, InstrumentKey> CashFlowsRead<AssetKey, InstrumentKey> {
185 /// A read that stopped at `resume` (`None`: it reached the span's end), with no venue limit
186 /// cutting into the span.
187 pub fn new(
188 flows: Vec<CashFlow<AssetKey, InstrumentKey>>,
189 resume: Option<DateTime<Utc>>,
190 ) -> Self {
191 Self {
192 flows,
193 resume,
194 held_since: None,
195 }
196 }
197
198 /// A read that reached the span's end.
199 pub fn complete(flows: Vec<CashFlow<AssetKey, InstrumentKey>>) -> Self {
200 Self::new(flows, None)
201 }
202
203 /// Sets [`held_since`](Self::held_since).
204 pub fn with_held_since(mut self, held_since: Option<DateTime<Utc>>) -> Self {
205 self.held_since = held_since;
206 self
207 }
208}