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 /// A time no later than when the venue's account held this balance.
13 ///
14 /// Balance state is ordered by it: a balance replaces one held only if it is at least as
15 /// recent, and a stream update older than the balance held is dropped. So it errs early,
16 /// never late. A balance read over REST is stamped no later than the moment its request was
17 /// sent, less how far the venue's REST view can trail its stream (see
18 /// [`ExecutionClient::fetch_balances`](crate::client::ExecutionClient::fetch_balances)): its
19 /// state can be older than the read, never newer. Erring early costs little: a stream event
20 /// from between the stamp and the read that arrives after the balance applies over it, and
21 /// restates what the balance already held, or older holdings until the next event.
22 pub time_exchange: DateTime<Utc>,
23}
24
25/// Per-asset margin debt detail for venues that report borrowing on a per-asset basis
26/// (the CEX per-asset-margin class — Binance / Kraken / Bitfinex / dYdX).
27///
28/// `borrowed` and `interest` are always co-reported by such venues' REST snapshots, so they
29/// are modelled as a single `Option`-of-struct on [`Balance`] rather than two loose `Option`s —
30/// this keeps them co-present and preserves `Balance`'s `Copy`/`Eq`/`Ord`/`Hash`/`Default`.
31///
32/// Account-level-margin venues (e.g. IBKR, which reports only aggregate `EquityWithLoanValue` /
33/// `MaintMarginReq`, never per-asset `borrowed`/`interest`) legitimately leave [`Balance::margin`]
34/// as `None`.
35///
36/// Futures/perps *position* margin (maintenance margin, unrealised PnL) is a different model and
37/// is intentionally **not** represented here.
38#[derive(
39 Debug,
40 Copy,
41 Clone,
42 PartialEq,
43 Eq,
44 PartialOrd,
45 Ord,
46 Hash,
47 Default,
48 Deserialize,
49 Serialize,
50 Constructor,
51)]
52pub struct MarginDetails {
53 /// Outstanding borrowed principal for the asset.
54 pub borrowed: Decimal,
55 /// Accrued, unpaid interest on the borrowed principal.
56 pub interest: Decimal,
57}
58
59/// Per-asset balance: gross holdings, the freely-tradable portion, optional margin debt and
60/// optional accrued carry.
61///
62/// Construct via [`Balance::new`] (cash) or [`Balance::new_margin`] (per-asset debt), then
63/// [`Balance::with_accrued`] where the venue reports an accrual. The struct is
64/// `#[non_exhaustive]`, so code outside this crate builds it only through those, and later fields
65/// are additive. `total` is gross holdings and `free` the freely-tradable portion; the remainder
66/// (`total - free`, exposed by [`Balance::used`]) is reserved against resting orders. Producers
67/// keep `free <= total`.
68///
69/// `margin: None` denotes a cash / no-debt context, **not** "unknown debt" — see [`Balance::margin`]
70/// and [`Balance::net_asset`].
71///
72/// `Ord`/`PartialOrd` are derived and compare lexicographically over
73/// `(total, free, margin, accrued)` (`None` sorts before `Some`); they exist for use as collection
74/// keys and generic bounds, not as a financial ranking. Use [`Balance::net_asset`] for value
75/// comparisons that account for debt.
76#[derive(
77 Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Deserialize, Serialize,
78)]
79#[non_exhaustive]
80pub struct Balance {
81 /// Gross holdings of the asset (`free + locked`). Unaffected by any borrowing — debt is
82 /// carried separately in [`Balance::margin`].
83 ///
84 /// Exception: a venue whose margin is account-level (Alpaca, IBKR) reports only the account's
85 /// cash here, which is negative while the account borrows, with `margin` left `None`. See
86 /// the client's `account_snapshot`.
87 ///
88 /// A carrying cost (funding, margin interest, a borrow fee) reaches `total` only once the venue
89 /// posts it to the account, hourly at some venues and monthly at others. Until then `total`
90 /// leaves it out. A venue that reports the pending amount puts it in [`Balance::accrued`], or,
91 /// for interest on a loan, in [`MarginDetails::interest`]. Each client's rustdoc says what its
92 /// venue posts and when.
93 pub total: Decimal,
94 /// Portion of `total` available to trade (not reserved against resting orders).
95 pub free: Decimal,
96 /// Per-asset margin debt, present only for venues that report it (see [`MarginDetails`]).
97 ///
98 /// `None` means a cash / no-debt context — **not** "unknown debt". The REST account snapshot
99 /// always populates this for a margin account, and the WS partial update ([`BalanceUpdate`])
100 /// structurally cannot clear it, so `None` reliably denotes "no margin facility for this
101 /// asset". See [`Balance::net_asset`].
102 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub margin: Option<MarginDetails>,
104 /// Carry accrued to date and not yet posted to `total`: interest earned or charged, and
105 /// whatever else the venue accrues the same way. Signed: positive is an amount the account
106 /// will receive, negative one it will pay.
107 ///
108 /// The cash the account holds once the accrual posts is `total + accrued`. The venue resets
109 /// the accrual as it posts it, so the two never count the same amount twice. `None` means the
110 /// venue does not report one, not that nothing has accrued.
111 ///
112 /// This differs from [`MarginDetails::interest`], which is interest owed on a loan of the
113 /// asset and is paid out of a later repayment, not added to cash.
114 ///
115 /// It is only as fresh as the last
116 /// [`BalanceSnapshot`](crate::AccountEventKind::BalanceSnapshot) for the asset: a
117 /// [`BalanceUpdate`] carries none, and [`Balance::apply_stream_update`] keeps the prior value.
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub accrued: Option<Decimal>,
120}
121
122impl Balance {
123 /// Construct a cash [`Balance`] with no margin debt (`margin: None`).
124 pub const fn new(total: Decimal, free: Decimal) -> Self {
125 Self {
126 total,
127 free,
128 margin: None,
129 accrued: None,
130 }
131 }
132
133 /// Construct a margin [`Balance`] carrying per-asset `borrowed`/`interest` debt.
134 pub const fn new_margin(
135 total: Decimal,
136 free: Decimal,
137 borrowed: Decimal,
138 interest: Decimal,
139 ) -> Self {
140 Self {
141 total,
142 free,
143 margin: Some(MarginDetails { borrowed, interest }),
144 accrued: None,
145 }
146 }
147
148 /// Set [`Balance::accrued`], the carry accrued and not yet posted to `total`.
149 #[must_use]
150 pub const fn with_accrued(mut self, accrued: Decimal) -> Self {
151 self.accrued = Some(accrued);
152 self
153 }
154
155 /// Portion of `total` reserved against resting orders (`total - free`).
156 pub fn used(&self) -> Decimal {
157 self.total - self.free
158 }
159
160 /// Net asset value: gross holdings less everything owed on the asset's loan.
161 ///
162 /// Returns `total` when [`Balance::margin`] is `None` and `total - borrowed - interest` when
163 /// `Some`, as Binance defines its margin accounts' `netAsset`. The result can be
164 /// **negative**: a short position is a negative net holding in the borrowed (base) asset.
165 ///
166 /// `None` is a cash / no-debt context, where net asset is simply the gross holding, except on
167 /// a venue whose margin is account-level (Alpaca, IBKR): there `total` is already the
168 /// account's cash, negative while it borrows (see [`Balance::total`]), and the result is that
169 /// figure, with no loan or interest itemised.
170 ///
171 /// Accrued [`MarginDetails::interest`] is owed as the principal is, so it is deducted once
172 /// the venue reports it accrued, not when it is repaid. Repaying the loan out of the asset's
173 /// holdings leaves the result unchanged, since `total` falls by what the debt does. For the
174 /// principal alone, read [`MarginDetails::borrowed`].
175 ///
176 /// [`Balance::accrued`] is not counted: it is carry the venue posts to `total` later, not a
177 /// debt of the loan.
178 ///
179 /// # Freshness
180 /// The returned value reflects debt only as fresh as the last
181 /// [`BalanceSnapshot`](crate::AccountEventKind::BalanceSnapshot) or
182 /// [`MarginDebt`](crate::AccountEventKind::MarginDebt) for this asset. WS partial updates keep
183 /// `free`/`locked` live but never carry debt, so on a venue that streams no debt changes a
184 /// position **borrowed since the last snapshot** reads as zero-debt (`net_asset == total`)
185 /// until the next snapshot. Interest is likewise held at its last reported total: it falls in
186 /// steps as snapshots or debt events report it, not continuously as the venue accrues it.
187 /// Each venue client says whether it streams debt changes.
188 pub fn net_asset(&self) -> Decimal {
189 match self.margin {
190 Some(margin) => self.total - margin.borrowed - margin.interest,
191 None => self.total,
192 }
193 }
194
195 /// Merge a WS partial [`BalanceUpdate`] onto an optional prior [`Balance`], preserving debt.
196 ///
197 /// Applies the stream's live `free`/`locked` (recomputing `total = free + locked`) while
198 /// carrying forward any [`MarginDetails`] and [`Balance::accrued`] from `prior` — a partial
199 /// update carries neither, so this is the single-sourced "debt and accruals fresh as of last
200 /// snapshot, `free`/`locked` live over the stream" merge. On a cold start (`prior = None`) the
201 /// result has `margin: None` and `accrued: None`.
202 ///
203 /// This is the same no-clobber merge the engine applies internally for asset-keyed balances. It
204 /// is exposed so consumers applying per-instrument
205 /// [`InstrumentBalanceUpdate`](crate::InstrumentBalanceUpdate) frames — which the engine does
206 /// not store — can reuse it rather than re-implement the contract.
207 pub fn apply_stream_update(prior: Option<Balance>, update: &BalanceUpdate) -> Balance {
208 Balance {
209 total: update.total(),
210 free: update.free,
211 margin: prior.and_then(|b| b.margin),
212 accrued: prior.and_then(|b| b.accrued),
213 }
214 }
215}
216
217/// Partial balance update carrying only `free`/`locked` — the shape delivered by exchange WS
218/// user-data streams (e.g. Binance `outboundAccountPosition`, which reports `a`/`f`/`l` only).
219///
220/// Deliberately has **no** `margin` field: applying a `BalanceUpdate` therefore *structurally
221/// cannot* clobber known per-asset debt. `borrowed`/`interest` totals arrive via the REST
222/// [`BalanceSnapshot`](crate::AccountEventKind::BalanceSnapshot), and from a venue that streams
223/// them, via [`MarginDebt`](crate::AccountEventKind::MarginDebt).
224#[derive(
225 Debug,
226 Copy,
227 Clone,
228 PartialEq,
229 Eq,
230 PartialOrd,
231 Ord,
232 Hash,
233 Default,
234 Deserialize,
235 Serialize,
236 Constructor,
237)]
238pub struct BalanceUpdate {
239 /// Portion of holdings available to trade.
240 pub free: Decimal,
241 /// Portion of holdings reserved against resting orders.
242 pub locked: Decimal,
243}
244
245impl BalanceUpdate {
246 /// Gross holdings of the asset (`free + locked`).
247 pub fn total(&self) -> Decimal {
248 self.free + self.locked
249 }
250}
251
252/// Per-asset WS partial balance update (the [`BalanceUpdate`] counterpart of [`AssetBalance`]).
253#[derive(
254 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
255)]
256pub struct AssetBalanceUpdate<AssetKey> {
257 /// Asset the update applies to (exchange-native name or resolved index).
258 pub asset: AssetKey,
259 /// Partial `free`/`locked` payload delivered by the WS stream.
260 pub update: BalanceUpdate,
261 /// Exchange-reported timestamp of the update.
262 pub time_exchange: DateTime<Utc>,
263}
264
265#[cfg(test)]
266#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
267mod tests {
268 use super::*;
269 use rust_decimal_macros::dec;
270
271 #[test]
272 fn net_asset_cash_returns_total() {
273 // No margin facility → net asset is simply the gross holding.
274 let balance = Balance::new(dec!(100), dec!(80));
275 assert_eq!(balance.net_asset(), dec!(100));
276 assert_eq!(balance.used(), dec!(20));
277 }
278
279 #[test]
280 fn net_asset_margin_deducts_borrowed_and_interest() {
281 // total - borrowed - interest.
282 let balance = Balance::new_margin(dec!(100), dec!(100), dec!(30), dec!(2));
283 assert_eq!(balance.net_asset(), dec!(68));
284 }
285
286 #[test]
287 fn net_asset_short_is_negative() {
288 // A short borrows the base asset and sells it: holdings are ~0 but debt remains, so net
289 // asset is negative.
290 let balance = Balance::new_margin(dec!(0), dec!(0), dec!(1.5), dec!(0.001));
291 assert_eq!(balance.net_asset(), dec!(-1.501));
292 }
293
294 #[test]
295 fn net_asset_is_unchanged_by_a_repayment_and_ignores_accrued() {
296 // 100 held, 30 borrowed, 2 interest: repaying all 32 out of holdings leaves 68 either way.
297 let owing = Balance::new_margin(dec!(100), dec!(100), dec!(30), dec!(2));
298 let repaid = Balance::new_margin(dec!(68), dec!(68), dec!(0), dec!(0));
299 assert_eq!(owing.net_asset(), repaid.net_asset());
300
301 // Accrued carry posts to `total` later; it is not a debt of the loan.
302 assert_eq!(owing.with_accrued(dec!(-5)).net_asset(), dec!(68));
303 }
304
305 #[test]
306 fn balance_update_total() {
307 let update = BalanceUpdate::new(dec!(1.5), dec!(0.5));
308 assert_eq!(update.total(), dec!(2.0));
309 assert_eq!(update.locked, dec!(0.5));
310 }
311
312 #[test]
313 fn balance_default_has_no_margin() {
314 assert_eq!(Balance::default().margin, None);
315 }
316
317 #[test]
318 fn balance_serde_omits_margin_when_none() {
319 let json = serde_json::to_string(&Balance::new(dec!(1), dec!(1))).unwrap();
320 assert!(
321 !json.contains("margin"),
322 "cash balance must not serialise a margin field"
323 );
324
325 let margin = Balance::new_margin(dec!(1), dec!(1), dec!(0.5), dec!(0));
326 let round_trip: Balance =
327 serde_json::from_str(&serde_json::to_string(&margin).unwrap()).unwrap();
328 assert_eq!(round_trip, margin);
329 }
330
331 #[test]
332 fn balance_serde_accrued_is_optional() {
333 let json = serde_json::to_string(&Balance::new(dec!(1), dec!(1))).unwrap();
334 assert!(
335 !json.contains("accrued"),
336 "a balance without an accrual must not serialise the field"
337 );
338 // A balance stored before the field existed still loads.
339 let stored: Balance = serde_json::from_str(r#"{"total":"1","free":"1"}"#).unwrap();
340 assert_eq!(stored.accrued, None);
341
342 let accrued = Balance::new(dec!(1), dec!(1)).with_accrued(dec!(-0.25));
343 let round_trip: Balance =
344 serde_json::from_str(&serde_json::to_string(&accrued).unwrap()).unwrap();
345 assert_eq!(round_trip, accrued);
346 assert_eq!(round_trip.accrued, Some(dec!(-0.25)));
347 }
348
349 #[test]
350 fn apply_stream_update_keeps_debt_and_accrual() {
351 let prior =
352 Balance::new_margin(dec!(10), dec!(10), dec!(3), dec!(0.1)).with_accrued(dec!(1.5));
353 let merged =
354 Balance::apply_stream_update(Some(prior), &BalanceUpdate::new(dec!(4), dec!(2)));
355 assert_eq!(merged.total, dec!(6));
356 assert_eq!(merged.free, dec!(4));
357 assert_eq!(merged.margin, prior.margin);
358 assert_eq!(merged.accrued, Some(dec!(1.5)));
359
360 let cold = Balance::apply_stream_update(None, &BalanceUpdate::new(dec!(4), dec!(2)));
361 assert_eq!((cold.margin, cold.accrued), (None, None));
362 }
363}