Skip to main content

rustrade_execution/
balance.rs

1use chrono::{DateTime, Utc};
2use derive_more::Constructor;
3use rust_decimal::Decimal;
4use serde::{Deserialize, Serialize};
5
6#[derive(
7    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
8)]
9pub struct AssetBalance<AssetKey> {
10    pub asset: AssetKey,
11    pub balance: Balance,
12    pub time_exchange: DateTime<Utc>,
13}
14
15/// Per-asset margin debt detail for venues that report borrowing on a per-asset basis
16/// (the CEX per-asset-margin class — Binance / Kraken / Bitfinex / dYdX).
17///
18/// `borrowed` and `interest` are always co-reported by such venues' REST snapshots, so they
19/// are modelled as a single `Option`-of-struct on [`Balance`] rather than two loose `Option`s —
20/// this keeps them co-present and preserves `Balance`'s `Copy`/`Eq`/`Ord`/`Hash`/`Default`.
21///
22/// Account-level-margin venues (e.g. IBKR, which reports only aggregate `EquityWithLoanValue` /
23/// `MaintMarginReq`, never per-asset `borrowed`/`interest`) legitimately leave [`Balance::margin`]
24/// as `None`.
25///
26/// Futures/perps *position* margin (maintenance margin, unrealised PnL) is a different model and
27/// is intentionally **not** represented here.
28#[derive(
29    Debug,
30    Copy,
31    Clone,
32    PartialEq,
33    Eq,
34    PartialOrd,
35    Ord,
36    Hash,
37    Default,
38    Deserialize,
39    Serialize,
40    Constructor,
41)]
42pub struct MarginDetails {
43    /// Outstanding borrowed principal for the asset.
44    pub borrowed: Decimal,
45    /// Accrued, unpaid interest on the borrowed principal.
46    pub interest: Decimal,
47}
48
49/// Per-asset balance: gross holdings, the freely-tradable portion, and optional margin debt.
50///
51/// Construct via [`Balance::new`] (cash) or [`Balance::new_margin`] (per-asset debt). `total` is
52/// gross holdings and `free` the freely-tradable portion; the remainder (`total - free`, exposed
53/// by [`Balance::used`]) is reserved against resting orders. Callers building the struct literally
54/// must keep `free <= total`.
55///
56/// `margin: None` denotes a cash / no-debt context, **not** "unknown debt" — see [`Balance::margin`]
57/// and [`Balance::net_asset`].
58///
59/// `Ord`/`PartialOrd` are derived and compare lexicographically over `(total, free, margin)`
60/// (`None` sorts before `Some`); they exist for use as collection keys and generic bounds, not as a
61/// financial ranking. Use [`Balance::net_asset`] for value comparisons that account for debt.
62#[derive(
63    Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Deserialize, Serialize,
64)]
65pub struct Balance {
66    /// Gross holdings of the asset (`free + locked`). Unaffected by any borrowing — debt is
67    /// carried separately in [`Balance::margin`].
68    pub total: Decimal,
69    /// Portion of `total` available to trade (not reserved against resting orders).
70    pub free: Decimal,
71    /// Per-asset margin debt, present only for venues that report it (see [`MarginDetails`]).
72    ///
73    /// `None` means a cash / no-debt context — **not** "unknown debt". The REST account snapshot
74    /// always populates this for a margin account, and the WS partial update ([`BalanceUpdate`])
75    /// structurally cannot clear it, so `None` reliably denotes "no margin facility for this
76    /// asset". See [`Balance::net_asset`].
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub margin: Option<MarginDetails>,
79}
80
81impl Balance {
82    /// Construct a cash [`Balance`] with no margin debt (`margin: None`).
83    pub const fn new(total: Decimal, free: Decimal) -> Self {
84        Self {
85            total,
86            free,
87            margin: None,
88        }
89    }
90
91    /// Construct a margin [`Balance`] carrying per-asset `borrowed`/`interest` debt.
92    pub const fn new_margin(
93        total: Decimal,
94        free: Decimal,
95        borrowed: Decimal,
96        interest: Decimal,
97    ) -> Self {
98        Self {
99            total,
100            free,
101            margin: Some(MarginDetails { borrowed, interest }),
102        }
103    }
104
105    /// Portion of `total` reserved against resting orders (`total - free`).
106    pub fn used(&self) -> Decimal {
107        self.total - self.free
108    }
109
110    /// Net asset value after deducting borrowed principal.
111    ///
112    /// Returns `total` when [`Balance::margin`] is `None` (a cash / no-debt context, where net
113    /// asset is simply the gross holding) and `total - borrowed` when `Some`. The result can be
114    /// **negative** — a short position is a negative net holding in the borrowed (base) asset.
115    ///
116    /// Accrued [`MarginDetails::interest`] is intentionally **excluded**: it is tracked separately
117    /// and does not reduce net holdings until the venue actually deducts it.
118    ///
119    /// # Freshness
120    /// The returned value reflects debt only as fresh as the last
121    /// [`BalanceSnapshot`](crate::AccountEventKind::BalanceSnapshot) for this asset. WS partial
122    /// updates keep `free`/`locked` live but never carry debt, so a position **borrowed since the
123    /// last snapshot** reads as zero-debt (`net_asset == total`) until the next snapshot. Consumers
124    /// needing exact live debt should react to the venue's borrow/repay event by refreshing the
125    /// account snapshot.
126    pub fn net_asset(&self) -> Decimal {
127        match self.margin {
128            Some(margin) => self.total - margin.borrowed,
129            None => self.total,
130        }
131    }
132
133    /// Merge a WS partial [`BalanceUpdate`] onto an optional prior [`Balance`], preserving debt.
134    ///
135    /// Applies the stream's live `free`/`locked` (recomputing `total = free + locked`) while
136    /// carrying forward any [`MarginDetails`] from `prior` — a partial update never carries debt, so
137    /// this is the single-sourced "debt fresh as of last snapshot, `free`/`locked` live over the
138    /// stream" merge. On a cold start (`prior = None`) the result has `margin: None`.
139    ///
140    /// This is the same no-clobber merge the engine applies internally for asset-keyed balances. It
141    /// is exposed so consumers applying per-instrument
142    /// [`InstrumentBalanceUpdate`](crate::InstrumentBalanceUpdate) frames — which the engine does
143    /// not store — can reuse it rather than re-implement the contract.
144    pub fn apply_stream_update(prior: Option<Balance>, update: &BalanceUpdate) -> Balance {
145        Balance {
146            total: update.total(),
147            free: update.free,
148            margin: prior.and_then(|b| b.margin),
149        }
150    }
151}
152
153/// Partial balance update carrying only `free`/`locked` — the shape delivered by exchange WS
154/// user-data streams (e.g. Binance `outboundAccountPosition`, which reports `a`/`f`/`l` only).
155///
156/// Deliberately has **no** `margin` field: applying a `BalanceUpdate` therefore *structurally
157/// cannot* clobber known per-asset debt. Authoritative `borrowed`/`interest` totals arrive only via
158/// the REST [`BalanceSnapshot`](crate::AccountEventKind::BalanceSnapshot).
159#[derive(
160    Debug,
161    Copy,
162    Clone,
163    PartialEq,
164    Eq,
165    PartialOrd,
166    Ord,
167    Hash,
168    Default,
169    Deserialize,
170    Serialize,
171    Constructor,
172)]
173pub struct BalanceUpdate {
174    /// Portion of holdings available to trade.
175    pub free: Decimal,
176    /// Portion of holdings reserved against resting orders.
177    pub locked: Decimal,
178}
179
180impl BalanceUpdate {
181    /// Gross holdings of the asset (`free + locked`).
182    pub fn total(&self) -> Decimal {
183        self.free + self.locked
184    }
185}
186
187/// Per-asset WS partial balance update (the [`BalanceUpdate`] counterpart of [`AssetBalance`]).
188#[derive(
189    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
190)]
191pub struct AssetBalanceUpdate<AssetKey> {
192    /// Asset the update applies to (exchange-native name or resolved index).
193    pub asset: AssetKey,
194    /// Partial `free`/`locked` payload delivered by the WS stream.
195    pub update: BalanceUpdate,
196    /// Exchange-reported timestamp of the update.
197    pub time_exchange: DateTime<Utc>,
198}
199
200#[cfg(test)]
201#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
202mod tests {
203    use super::*;
204    use rust_decimal_macros::dec;
205
206    #[test]
207    fn net_asset_cash_returns_total() {
208        // No margin facility → net asset is simply the gross holding.
209        let balance = Balance::new(dec!(100), dec!(80));
210        assert_eq!(balance.net_asset(), dec!(100));
211        assert_eq!(balance.used(), dec!(20));
212    }
213
214    #[test]
215    fn net_asset_margin_deducts_borrowed() {
216        // total - borrowed; interest does not affect net asset.
217        let balance = Balance::new_margin(dec!(100), dec!(100), dec!(30), dec!(2));
218        assert_eq!(balance.net_asset(), dec!(70));
219    }
220
221    #[test]
222    fn net_asset_short_is_negative() {
223        // A short borrows the base asset and sells it: holdings are ~0 but debt remains, so net
224        // asset is negative.
225        let balance = Balance::new_margin(dec!(0), dec!(0), dec!(1.5), dec!(0.001));
226        assert_eq!(balance.net_asset(), dec!(-1.5));
227    }
228
229    #[test]
230    fn balance_update_total() {
231        let update = BalanceUpdate::new(dec!(1.5), dec!(0.5));
232        assert_eq!(update.total(), dec!(2.0));
233        assert_eq!(update.locked, dec!(0.5));
234    }
235
236    #[test]
237    fn balance_default_has_no_margin() {
238        assert_eq!(Balance::default().margin, None);
239    }
240
241    #[test]
242    fn balance_serde_omits_margin_when_none() {
243        let json = serde_json::to_string(&Balance::new(dec!(1), dec!(1))).unwrap();
244        assert!(
245            !json.contains("margin"),
246            "cash balance must not serialise a margin field"
247        );
248
249        let margin = Balance::new_margin(dec!(1), dec!(1), dec!(0.5), dec!(0));
250        let round_trip: Balance =
251            serde_json::from_str(&serde_json::to_string(&margin).unwrap()).unwrap();
252        assert_eq!(round_trip, margin);
253    }
254}