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 ///
69 /// Exception: a venue whose margin is account-level (Alpaca, IBKR) reports only the account's
70 /// cash here, which is negative while the account borrows, with `margin` left `None`. See
71 /// the client's `account_snapshot`.
72 pub total: Decimal,
73 /// Portion of `total` available to trade (not reserved against resting orders).
74 pub free: Decimal,
75 /// Per-asset margin debt, present only for venues that report it (see [`MarginDetails`]).
76 ///
77 /// `None` means a cash / no-debt context — **not** "unknown debt". The REST account snapshot
78 /// always populates this for a margin account, and the WS partial update ([`BalanceUpdate`])
79 /// structurally cannot clear it, so `None` reliably denotes "no margin facility for this
80 /// asset". See [`Balance::net_asset`].
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 pub margin: Option<MarginDetails>,
83}
84
85impl Balance {
86 /// Construct a cash [`Balance`] with no margin debt (`margin: None`).
87 pub const fn new(total: Decimal, free: Decimal) -> Self {
88 Self {
89 total,
90 free,
91 margin: None,
92 }
93 }
94
95 /// Construct a margin [`Balance`] carrying per-asset `borrowed`/`interest` debt.
96 pub const fn new_margin(
97 total: Decimal,
98 free: Decimal,
99 borrowed: Decimal,
100 interest: Decimal,
101 ) -> Self {
102 Self {
103 total,
104 free,
105 margin: Some(MarginDetails { borrowed, interest }),
106 }
107 }
108
109 /// Portion of `total` reserved against resting orders (`total - free`).
110 pub fn used(&self) -> Decimal {
111 self.total - self.free
112 }
113
114 /// Net asset value after deducting borrowed principal.
115 ///
116 /// Returns `total` when [`Balance::margin`] is `None` (a cash / no-debt context, where net
117 /// asset is simply the gross holding) and `total - borrowed` when `Some`. The result can be
118 /// **negative** — a short position is a negative net holding in the borrowed (base) asset.
119 ///
120 /// Accrued [`MarginDetails::interest`] is intentionally **excluded**: it is tracked separately
121 /// and does not reduce net holdings until the venue actually deducts it.
122 ///
123 /// # Freshness
124 /// The returned value reflects debt only as fresh as the last
125 /// [`BalanceSnapshot`](crate::AccountEventKind::BalanceSnapshot) for this asset. WS partial
126 /// updates keep `free`/`locked` live but never carry debt, so a position **borrowed since the
127 /// last snapshot** reads as zero-debt (`net_asset == total`) until the next snapshot. Consumers
128 /// needing exact live debt should react to the venue's borrow/repay event by refreshing the
129 /// account snapshot.
130 pub fn net_asset(&self) -> Decimal {
131 match self.margin {
132 Some(margin) => self.total - margin.borrowed,
133 None => self.total,
134 }
135 }
136
137 /// Merge a WS partial [`BalanceUpdate`] onto an optional prior [`Balance`], preserving debt.
138 ///
139 /// Applies the stream's live `free`/`locked` (recomputing `total = free + locked`) while
140 /// carrying forward any [`MarginDetails`] from `prior` — a partial update never carries debt, so
141 /// this is the single-sourced "debt fresh as of last snapshot, `free`/`locked` live over the
142 /// stream" merge. On a cold start (`prior = None`) the result has `margin: None`.
143 ///
144 /// This is the same no-clobber merge the engine applies internally for asset-keyed balances. It
145 /// is exposed so consumers applying per-instrument
146 /// [`InstrumentBalanceUpdate`](crate::InstrumentBalanceUpdate) frames — which the engine does
147 /// not store — can reuse it rather than re-implement the contract.
148 pub fn apply_stream_update(prior: Option<Balance>, update: &BalanceUpdate) -> Balance {
149 Balance {
150 total: update.total(),
151 free: update.free,
152 margin: prior.and_then(|b| b.margin),
153 }
154 }
155}
156
157/// Partial balance update carrying only `free`/`locked` — the shape delivered by exchange WS
158/// user-data streams (e.g. Binance `outboundAccountPosition`, which reports `a`/`f`/`l` only).
159///
160/// Deliberately has **no** `margin` field: applying a `BalanceUpdate` therefore *structurally
161/// cannot* clobber known per-asset debt. Authoritative `borrowed`/`interest` totals arrive only via
162/// the REST [`BalanceSnapshot`](crate::AccountEventKind::BalanceSnapshot).
163#[derive(
164 Debug,
165 Copy,
166 Clone,
167 PartialEq,
168 Eq,
169 PartialOrd,
170 Ord,
171 Hash,
172 Default,
173 Deserialize,
174 Serialize,
175 Constructor,
176)]
177pub struct BalanceUpdate {
178 /// Portion of holdings available to trade.
179 pub free: Decimal,
180 /// Portion of holdings reserved against resting orders.
181 pub locked: Decimal,
182}
183
184impl BalanceUpdate {
185 /// Gross holdings of the asset (`free + locked`).
186 pub fn total(&self) -> Decimal {
187 self.free + self.locked
188 }
189}
190
191/// Per-asset WS partial balance update (the [`BalanceUpdate`] counterpart of [`AssetBalance`]).
192#[derive(
193 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
194)]
195pub struct AssetBalanceUpdate<AssetKey> {
196 /// Asset the update applies to (exchange-native name or resolved index).
197 pub asset: AssetKey,
198 /// Partial `free`/`locked` payload delivered by the WS stream.
199 pub update: BalanceUpdate,
200 /// Exchange-reported timestamp of the update.
201 pub time_exchange: DateTime<Utc>,
202}
203
204#[cfg(test)]
205#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
206mod tests {
207 use super::*;
208 use rust_decimal_macros::dec;
209
210 #[test]
211 fn net_asset_cash_returns_total() {
212 // No margin facility → net asset is simply the gross holding.
213 let balance = Balance::new(dec!(100), dec!(80));
214 assert_eq!(balance.net_asset(), dec!(100));
215 assert_eq!(balance.used(), dec!(20));
216 }
217
218 #[test]
219 fn net_asset_margin_deducts_borrowed() {
220 // total - borrowed; interest does not affect net asset.
221 let balance = Balance::new_margin(dec!(100), dec!(100), dec!(30), dec!(2));
222 assert_eq!(balance.net_asset(), dec!(70));
223 }
224
225 #[test]
226 fn net_asset_short_is_negative() {
227 // A short borrows the base asset and sells it: holdings are ~0 but debt remains, so net
228 // asset is negative.
229 let balance = Balance::new_margin(dec!(0), dec!(0), dec!(1.5), dec!(0.001));
230 assert_eq!(balance.net_asset(), dec!(-1.5));
231 }
232
233 #[test]
234 fn balance_update_total() {
235 let update = BalanceUpdate::new(dec!(1.5), dec!(0.5));
236 assert_eq!(update.total(), dec!(2.0));
237 assert_eq!(update.locked, dec!(0.5));
238 }
239
240 #[test]
241 fn balance_default_has_no_margin() {
242 assert_eq!(Balance::default().margin, None);
243 }
244
245 #[test]
246 fn balance_serde_omits_margin_when_none() {
247 let json = serde_json::to_string(&Balance::new(dec!(1), dec!(1))).unwrap();
248 assert!(
249 !json.contains("margin"),
250 "cash balance must not serialise a margin field"
251 );
252
253 let margin = Balance::new_margin(dec!(1), dec!(1), dec!(0.5), dec!(0));
254 let round_trip: Balance =
255 serde_json::from_str(&serde_json::to_string(&margin).unwrap()).unwrap();
256 assert_eq!(round_trip, margin);
257 }
258}