rustrade_execution/lib.rs
1#![forbid(unsafe_code)]
2#![deny(
3 clippy::unwrap_used,
4 clippy::expect_used,
5 clippy::cast_possible_truncation,
6 clippy::cast_sign_loss
7)]
8#![warn(
9 unused,
10 clippy::cognitive_complexity,
11 unused_crate_dependencies,
12 unused_extern_crates,
13 clippy::unused_self,
14 clippy::useless_let_if_seq,
15 missing_debug_implementations,
16 rust_2018_idioms
17)]
18// Inherited from the barter-rs upstream: the generic, trait-heavy public API legitimately produces
19// complex nested types and many-argument constructors, and `type_alias_bounds` fires on
20// documentation-bearing alias bounds kept intentionally. Denying these adds churn without improving
21// the API.
22#![allow(clippy::type_complexity, clippy::too_many_arguments, type_alias_bounds)]
23// Clippy 1.99 checks each field's span rather than the whole expression's, so the
24// `Self { field: field }` that `derive_more::Constructor` expands to is reported at our own
25// field declarations. Remove once rust-lang/rust-clippy#17525 is fixed in a stable release.
26#![allow(clippy::redundant_field_names)]
27
28//! # Barter-Execution
29//! Stream private account data from financial venues, and execute (live or mock) orders. Also provides
30//! a feature rich MockExchange and MockExecutionClient to assist with backtesting and paper-trading.
31//!
32//! **It is:**
33//! * **Easy**: ExecutionClient trait provides a unified and simple language for interacting with exchanges.
34//! * **Normalised**: Allow your strategy to communicate with every real or MockExchange using the same interface.
35//! * **Extensible**: Barter-Execution is highly extensible, making it easy to contribute by adding new exchange integrations!
36//!
37//! See `README.md` for more information and examples.
38
39// Silence unused_crate_dependencies for dev-dependencies used only in tests
40#[cfg(test)]
41use serial_test as _;
42#[cfg(test)]
43use temp_env as _;
44#[cfg(test)]
45use tokio_tungstenite as _;
46#[cfg(test)]
47use tracing_subscriber as _;
48#[cfg(test)]
49use wiremock as _;
50
51use crate::{
52 balance::{AssetBalance, AssetBalanceUpdate},
53 error::StreamTerminationReason,
54 order::{Order, OrderSnapshot, request::OrderResponseCancel},
55 position::PositionReport,
56 trade::Trade,
57};
58use chrono::{DateTime, Utc};
59use derive_more::{Constructor, From};
60use order::state::OrderState;
61use rust_decimal::Decimal;
62use rustrade_instrument::{
63 asset::{AssetIndex, name::AssetNameExchange},
64 exchange::{ExchangeId, ExchangeIndex},
65 instrument::{InstrumentIndex, name::InstrumentNameExchange},
66};
67use rustrade_integration::collection::snapshot::Snapshot;
68use serde::{Deserialize, Serialize};
69// Only `emit_stream_terminated` (and its tests) name `mpsc`, both gated to the venue features —
70// gate the import the same way so the default-empty feature set does not warn it as unused.
71#[cfg(any(
72 feature = "alpaca",
73 feature = "binance",
74 feature = "ibkr",
75 feature = "hyperliquid"
76))]
77use tokio::sync::mpsc;
78
79pub mod balance;
80pub mod borrow_capacity;
81pub use borrow_capacity::BorrowCapacity;
82pub mod cash_flow;
83pub use cash_flow::{CashFlow, CashFlowId, CashFlowKind, CashFlowsRead, InterestTiming};
84pub mod client;
85pub mod error;
86pub mod exchange;
87pub mod fee;
88pub use fee::{
89 FeeAssetConfig, FeeAssetConfigError, FeeModel, FeeModelConfig, Liquidity, PerContractFeeModel,
90 PercentageFeeModel, SpotFeeAsset, ZeroFeeModel,
91};
92pub mod fill;
93pub use fill::{
94 BidAskFillModel, FillContext, FillModel, LastPriceFillModel, MarketOrderTiming,
95 MidpointFillModel, NextBarPrice, SimFillConfig,
96};
97pub mod fill_recovery;
98pub use fill_recovery::{FillRecoveryFailure, FillRecoveryGap, FillRecoveryScope};
99pub mod holding_cost;
100pub use holding_cost::{
101 AccrualDays, BorrowFeeModel, DailyAccrual, DayCount, FinancingModel, FinancingRates,
102 FundingModel, HeldPosition, HoldingCharge, HoldingCostModel, HolidayCalendar, RateSeries,
103 RateSeriesUnsorted, SettlementCalendar, WeekendsOnly,
104};
105pub mod indexer;
106pub mod map;
107pub mod margin;
108pub use margin::{
109 InterestCharge, InterestDue, InterestSchedule, MarginEffect, MarginInterestModel,
110 PeriodicMarginInterest, SpotMarginConfig, SpotMarginConfigError,
111};
112pub mod margin_debt;
113pub use margin_debt::{MarginDebtKind, MarginDebtUpdate};
114pub mod market;
115pub use market::{MarketBar, MarketDepth, MarketObservation, MarketSnapshot};
116pub mod notice;
117pub use notice::{AccountNotice, NoticeKind};
118pub mod order;
119pub mod position;
120pub mod reduce_only;
121pub mod rules;
122pub use rules::{OrderRules, PreSendRules, ValueRule};
123pub mod shortability;
124pub mod slippage;
125pub use shortability::{Shortability, ShortabilityProvider, ShortabilityTable};
126pub use slippage::{SlippageConfig, SlippageConfigError};
127pub mod trade;
128
129/// Convenient type alias for an [`AccountEvent`] keyed with [`ExchangeId`],
130/// [`AssetNameExchange`], and [`InstrumentNameExchange`].
131pub type UnindexedAccountEvent =
132 AccountEvent<ExchangeId, AssetNameExchange, InstrumentNameExchange>;
133
134/// Convenient type alias for an [`AccountSnapshot`] keyed with [`ExchangeId`],
135/// [`AssetNameExchange`], and [`InstrumentNameExchange`].
136pub type UnindexedAccountSnapshot =
137 AccountSnapshot<ExchangeId, AssetNameExchange, InstrumentNameExchange>;
138
139#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
140pub struct AccountEvent<
141 ExchangeKey = ExchangeIndex,
142 AssetKey = AssetIndex,
143 InstrumentKey = InstrumentIndex,
144> {
145 pub exchange: ExchangeKey,
146 pub kind: AccountEventKind<ExchangeKey, AssetKey, InstrumentKey>,
147}
148
149impl<ExchangeKey, AssetKey, InstrumentKey> AccountEvent<ExchangeKey, AssetKey, InstrumentKey> {
150 pub fn new<K>(exchange: ExchangeKey, kind: K) -> Self
151 where
152 K: Into<AccountEventKind<ExchangeKey, AssetKey, InstrumentKey>>,
153 {
154 Self {
155 exchange,
156 kind: kind.into(),
157 }
158 }
159
160 /// Named constructor for the terminal [`StreamTerminated`](AccountEventKind::StreamTerminated)
161 /// event carrying the given [`StreamTerminationReason`].
162 pub(crate) fn stream_terminated(
163 exchange: ExchangeKey,
164 reason: StreamTerminationReason,
165 ) -> Self {
166 Self {
167 exchange,
168 kind: AccountEventKind::StreamTerminated(reason),
169 }
170 }
171}
172
173/// Best-effort in-band emit of a terminal
174/// [`StreamTerminated`](AccountEventKind::StreamTerminated) on the account-event channel, sent just
175/// before a venue's stream task exits so stream death is delivered in-band rather than inferred from
176/// channel EOF.
177///
178/// Shared by the channel-based venue connectors (Binance spot/margin, Alpaca, IBKR, Hyperliquid)
179/// so the single send of the terminal event lives in one place, at the abstraction level where
180/// [`AccountEvent`] is defined rather than inside any one vendor module. (The Mock client yields
181/// into a `Stream` rather than an mpsc channel, so it builds the terminal event via
182/// `UnindexedAccountEvent::stream_terminated` directly and does not funnel through this helper.)
183/// The send is best-effort: if the consumer already dropped the receiver it is a silent no-op —
184/// which is the consumer-initiated-drop case, deliberately *not* signalled (there is no one left
185/// to deliver to).
186//
187// Gated to the venues that send terminal events through an mpsc channel from a spawned stream task,
188// so the crate's default-empty feature set does not warn this as unused (mirrors `parse_env_bool`
189// below). The Mock client is always compiled but is excluded by design — see the note above.
190#[cfg(any(
191 feature = "alpaca",
192 feature = "binance",
193 feature = "ibkr",
194 feature = "hyperliquid"
195))]
196pub(crate) fn emit_stream_terminated(
197 tx: &mpsc::UnboundedSender<UnindexedAccountEvent>,
198 exchange: ExchangeId,
199 reason: StreamTerminationReason,
200) {
201 let _ = tx.send(UnindexedAccountEvent::stream_terminated(exchange, reason));
202}
203
204/// Parse a boolean environment-variable value using the single cross-venue policy.
205///
206/// Accepts only `"true"` / `"false"` (case-insensitive, surrounding whitespace trimmed); every other
207/// value returns `None` so the caller can surface an explicit "must be true or false" error rather
208/// than silently coercing. Deliberately does **not** accept `"1"`/`"0"` or other truthy spellings —
209/// one strict, unambiguous spelling shared by every venue's `from_env` (Alpaca `ALPACA_PAPER`,
210/// Binance `BINANCE_TESTNET`, Hyperliquid `HYPERLIQUID_TESTNET`) keeps the network-selection toggle
211/// impossible to misread.
212//
213// Gated to the venues that read env-bool toggles so the crate's default-empty feature set does not
214// warn this as unused.
215#[cfg(any(feature = "alpaca", feature = "binance", feature = "hyperliquid"))]
216pub(crate) fn parse_env_bool(value: &str) -> Option<bool> {
217 let trimmed = value.trim();
218 if trimmed.eq_ignore_ascii_case("true") {
219 Some(true)
220 } else if trimmed.eq_ignore_ascii_case("false") {
221 Some(false)
222 } else {
223 None
224 }
225}
226
227#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, From)]
228#[non_exhaustive]
229pub enum AccountEventKind<ExchangeKey, AssetKey, InstrumentKey> {
230 /// Full [`AccountSnapshot`] - replaces all existing state.
231 Snapshot(AccountSnapshot<ExchangeKey, AssetKey, InstrumentKey>),
232
233 /// Single [`AssetBalance`] snapshot - replaces existing balance state.
234 ///
235 /// Sourced from a REST account snapshot: carries the **full** balance including any per-asset
236 /// margin debt (`borrowed`/`interest`). This is the authoritative source for debt totals.
237 BalanceSnapshot(Snapshot<AssetBalance<AssetKey>>),
238
239 /// Single [`AssetBalanceUpdate`] - applies a WS partial (`free`/`locked` only).
240 ///
241 /// Sourced from an exchange WS user-data stream (e.g. Binance `outboundAccountPosition`). It
242 /// carries **no** margin debt, so applying it updates `free`/`locked` while **preserving** any
243 /// existing [`MarginDetails`](balance::MarginDetails) — debt cannot be silently clobbered by a
244 /// stream update. Debt totals remain as fresh as the last [`BalanceSnapshot`](Self::BalanceSnapshot)
245 /// or [`MarginDebt`](Self::MarginDebt).
246 BalanceStreamUpdate(Snapshot<AssetBalanceUpdate<AssetKey>>),
247
248 /// Live per-instrument isolated-margin balance update (`free`/`locked` of one asset of a pair).
249 ///
250 /// The stream counterpart of [`InstrumentAccountSnapshot::isolated`] for venues with per-pair
251 /// isolated sub-accounts (e.g. Binance isolated margin). Carries a point-in-time `free`/`locked`
252 /// **snapshot** of one of the pair's assets — NOT a delta — keyed by instrument as well as
253 /// asset, because isolated balances are per-`(pair, asset)` and cannot be folded into the
254 /// asset-keyed balance state without collision (see [`InstrumentBalanceUpdate`]).
255 ///
256 /// The engine deliberately does **not** store this (the per-asset balance state is informational
257 /// only and the engine never reads it for sizing/gating); a consumer reads it off the account
258 /// event feed. A pair's debt arrives apart, as a [`MarginDebt`](Self::MarginDebt) naming the
259 /// pair, from a venue that streams it.
260 InstrumentBalanceUpdate(InstrumentBalanceUpdate<AssetKey, InstrumentKey>),
261
262 /// Single [`Order`] snapshot - used to upsert existing order state if it's more recent.
263 ///
264 /// This variant covers general order updates, and open order responses.
265 OrderSnapshot(Snapshot<Order<ExchangeKey, InstrumentKey, OrderState<AssetKey, InstrumentKey>>>),
266
267 /// Response to an [`OrderRequestCancel<ExchangeKey, InstrumentKey>`](order::request::OrderRequestOpen).
268 OrderCancelled(OrderResponseCancel<ExchangeKey, AssetKey, InstrumentKey>),
269
270 /// [`Order<ExchangeKey, InstrumentKey, Open>`] partial or full-fill.
271 ///
272 /// The fee asset (`AssetKey`) may be the quote asset, base asset, or a third-party
273 /// asset (e.g., BNB on Binance). Use `fees.fees_quote` for quote-equivalent value
274 /// when available.
275 Trade(Trade<AssetKey, InstrumentKey>),
276
277 /// The account event stream has ended; no further events will arrive on it.
278 ///
279 /// This is the in-band, programmatic signal that a stream died — delivered on the **same**
280 /// account feed as every other event rather than being inferred from channel EOF or read from
281 /// logs. The [`StreamTerminationReason`] distinguishes a venue that exhausted its reconnect
282 /// budget from an unrecoverable error, so the consumer can apply its own recovery policy
283 /// (re-establish the stream, re-sync via REST, halt trading). The library reports *that* and
284 /// *why* the stream ended; it does not prescribe the response.
285 ///
286 /// Only terminations deliverable while the consumer is still listening are signalled: a
287 /// consumer-initiated drop closes the receiver, so there is no one left to deliver to (see
288 /// [`StreamTerminationReason`] for the deliverable-only rationale).
289 StreamTerminated(StreamTerminationReason),
290
291 /// Fill recovery gave up on a span of fills: fills in it may not have been delivered.
292 ///
293 /// Sent by venues that recover missed fills after a reconnect (Binance Spot and Margin,
294 /// Alpaca) when a recovery read fails for good, once per failed read. The stream carries on.
295 /// The engine logs it and changes no state; reconciling is the consumer's policy. See
296 /// [`FillRecoveryGap`] for what the span covers and how to read it again.
297 FillRecoveryGaveUp(FillRecoveryGap<InstrumentKey>),
298
299 /// A trade delivered earlier was busted or corrected by the venue.
300 ///
301 /// The earlier [`Trade`](Self::Trade) is not withdrawn, so state built on it is wrong until
302 /// the consumer applies this. The engine logs it and changes no state; reversing the trade is
303 /// the consumer's policy. See [`TradeAmendment`](trade::TradeAmendment).
304 TradeAmended(trade::TradeAmendment<AssetKey, InstrumentKey>),
305
306 /// An attempt to re-initialise the account stream after it ended failed. Attempts continue
307 /// with backoff.
308 ///
309 /// Sent by a consumer that re-initialises the account stream itself, such as the `rustrade`
310 /// crate's `ExecutionManager`, once per failed attempt and in order with the other account
311 /// events. It reports that the account link is still down, so it is not evidence the link is
312 /// up. The engine logs it and changes no state. How long to keep waiting, and whether to halt
313 /// or alert, is the consumer's policy. See [`AccountReinitFailure`](error::AccountReinitFailure).
314 ReinitFailed(error::AccountReinitFailure<AssetKey, InstrumentKey>),
315
316 /// Cash moved into or out of the account other than by a trade: funding, interest, a borrow
317 /// fee or a rebate, as the venue posted it.
318 ///
319 /// A flow is a delta, signed positive when the account received it. The engine adds a flow
320 /// attributed to an instrument to the `carry` of that instrument's open position (see
321 /// `Position::carry` in `rustrade`), and applies none to balances: the venue's balances already
322 /// include what it has posted. See [`CashFlow`] for which venues send it.
323 CashFlow(cash_flow::CashFlow<AssetKey, InstrumentKey>),
324
325 /// The venue reported a change in the account's margin or liquidation state: a margin call, a
326 /// liquidation warning, a liquidation under way, or that one of those no longer holds.
327 ///
328 /// A notice changes no balance or position. The engine logs it, at `warn` when
329 /// [`NoticeKind::is_escalation`] and at `info` otherwise, and changes no state; what to do
330 /// about it is the consumer's policy. A notice sent while the stream was disconnected is not
331 /// recovered. See [`AccountNotice`] for which venues send it.
332 Notice(notice::AccountNotice<InstrumentKey>),
333
334 /// What a margin account owes in one asset changed: a borrow, a repay or an interest charge.
335 ///
336 /// Carries the principal and interest owed **after** the change, both totals, so applying one
337 /// replaces the debt held and applying it twice changes nothing. The engine applies an update
338 /// that names no instrument to the asset's [`Balance::margin`](balance::Balance::margin),
339 /// ordered by its time against earlier debt alone, and leaves `free`/`locked` as they are. An
340 /// update that names an isolated pair changes no engine state; a consumer reads it off the
341 /// account event feed. See [`MarginDebtUpdate`] for which venues
342 /// send it.
343 MarginDebt(margin_debt::MarginDebtUpdate<AssetKey, InstrumentKey>),
344}
345
346impl<ExchangeKey, AssetKey, InstrumentKey> AccountEvent<ExchangeKey, AssetKey, InstrumentKey>
347where
348 AssetKey: Eq,
349 InstrumentKey: Eq,
350{
351 pub fn snapshot(self) -> Option<AccountSnapshot<ExchangeKey, AssetKey, InstrumentKey>> {
352 match self.kind {
353 AccountEventKind::Snapshot(snapshot) => Some(snapshot),
354 _ => None,
355 }
356 }
357}
358
359#[derive(
360 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
361)]
362pub struct AccountSnapshot<
363 ExchangeKey = ExchangeIndex,
364 AssetKey = AssetIndex,
365 InstrumentKey = InstrumentIndex,
366> {
367 pub exchange: ExchangeKey,
368 pub balances: Vec<AssetBalance<AssetKey>>,
369 pub instruments: Vec<InstrumentAccountSnapshot<ExchangeKey, AssetKey, InstrumentKey>>,
370}
371
372/// serde `default` for an `Option` field whose inner type is generic — returns `None` without
373/// requiring the inner type to be `Default` (see the `isolated` field below).
374fn none_option<T>() -> Option<T> {
375 None
376}
377
378/// One instrument's slice of an [`AccountSnapshot`]: its orders, and its position or isolated
379/// balances where the venue has them.
380#[derive(
381 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
382)]
383pub struct InstrumentAccountSnapshot<
384 ExchangeKey = ExchangeIndex,
385 AssetKey = AssetIndex,
386 InstrumentKey = InstrumentIndex,
387> {
388 pub instrument: InstrumentKey,
389 /// Orders the venue reported for this instrument, keyed by the `ClientOrderId` the order was
390 /// placed with where the venue reports it.
391 ///
392 /// Whether this is **every** order open at the venue is stated by
393 /// [`orders_complete`](Self::orders_complete), not implied by the list.
394 #[serde(default = "Vec::new")]
395 pub orders: Vec<OrderSnapshot<ExchangeKey, AssetKey, InstrumentKey>>,
396 /// `true` only when [`orders`](Self::orders) lists every order open at the venue for this
397 /// instrument when it was read, each under the `ClientOrderId` it was placed with.
398 ///
399 /// A consumer may then read an order's **absence** as "no longer open": it filled, was
400 /// cancelled or expired. The engine does exactly that, retiring a tracked order a complete
401 /// list omits. A wrong `true` therefore retires live orders, so a client sets it only when
402 /// nothing can be missing:
403 /// - the read covered every open order, with no page cap or partial result;
404 /// - no open order was dropped on conversion;
405 /// - each order carries the id it was placed with, so a tracked order can be found in it.
406 ///
407 /// `false` claims nothing about absent orders, and is the default for a snapshot that does not
408 /// say.
409 #[serde(default)]
410 pub orders_complete: bool,
411 /// The venue's position in this instrument, for any instrument whose holding the venue
412 /// tracks separately from cash balances: perpetuals, futures, options, and equities (e.g.
413 /// Alpaca).
414 ///
415 /// [`PositionReport::Unreported`] when the venue does not report positions, for holdings
416 /// reported as asset balances instead, such as spot crypto, and when the read could not
417 /// establish the position. [`PositionReport::Flat`] is a claim that the venue holds none, so
418 /// a client reports it only when it read every position the venue has for the instrument. See
419 /// each client's `account_snapshot` for what it reports.
420 ///
421 /// A client that reports positions lists each instrument it was asked for whose position it
422 /// can establish, flat ones included. An instrument it leaves out, like one it reports as
423 /// `Unreported`, is unknown, never flat: a client can be unable to establish a position (see
424 /// its `account_snapshot`). Asked for all instruments (an empty list), it may list only those
425 /// with something to report.
426 #[serde(default, skip_serializing_if = "PositionReport::is_unreported")]
427 pub position: PositionReport,
428 /// Per-pair isolated-margin balances and risk, for venues with isolated sub-accounts
429 /// (e.g. Binance isolated margin). `None` for cross margin, spot, and all other contexts.
430 ///
431 /// Surfaced here — attached to the instrument — rather than folded into the asset-keyed
432 /// [`AccountSnapshot::balances`] because isolated sub-accounts are per-`(pair, asset)`: the same
433 /// asset (e.g. `USDT`) in two isolated pairs is a separate pool, which the asset-keyed balance
434 /// model cannot represent without collision. The engine does not store this; a consumer reads
435 /// it off the snapshot to compose per-pair risk. See [`IsolatedInstrumentState`].
436 ///
437 // `default = "none_option"` (not a bare `#[serde(default)]`) avoids serde inferring a spurious
438 // `AssetKey: Default` bound: a bare default on a generic-typed field conservatively requires the
439 // field type to be `Default` (the `position` field escapes this only because `PositionReport` is
440 // concrete). Naming a function makes serde *call* it instead, requiring only `AssetKey: Deserialize`.
441 #[serde(default = "none_option", skip_serializing_if = "Option::is_none")]
442 pub isolated: Option<IsolatedInstrumentState<AssetKey>>,
443}
444
445/// Per-pair isolated-margin state attached to an [`InstrumentAccountSnapshot`].
446///
447/// Binance isolated margin (and other CEX isolated/per-pair sub-accounts) hold balances
448/// per-`(pair, asset)`, not per-asset, so they are surfaced attached to the instrument rather than
449/// in the asset-keyed [`AccountSnapshot::balances`]. A consumer composes per-pair risk from `base`,
450/// `quote`, and `risk`.
451#[derive(
452 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
453)]
454pub struct IsolatedInstrumentState<AssetKey = AssetIndex> {
455 /// Base-asset balance of the pair's isolated sub-account (carries per-asset debt).
456 pub base: AssetBalance<AssetKey>,
457 /// Quote-asset balance of the pair's isolated sub-account (carries per-asset debt).
458 pub quote: AssetBalance<AssetKey>,
459 /// Per-pair risk metrics — snapshot-fresh, not live (see [`IsolatedMarginRisk`]).
460 pub risk: IsolatedMarginRisk,
461}
462
463/// Per-pair isolated-margin risk metrics, surfaced on [`IsolatedInstrumentState`].
464///
465/// Every field is `Option` — a venue may omit any given metric, and a missing metric must not
466/// drop the surrounding balance snapshot.
467///
468/// # Freshness
469/// These are **snapshot-only**: authoritative as of the last `account_snapshot` and refreshed on
470/// snapshot. Unlike balances, there is **no live-stream twin** — the WS `outboundAccountPosition`
471/// frame carries no margin-level / liquidation data. The live signal for risk crossing a threshold
472/// is the venue's margin-level notice, such as Binance's `marginLevelChange` (surfaced as an
473/// [`AccountEventKind::Notice`], not accumulated here).
474#[derive(
475 Debug,
476 Copy,
477 Clone,
478 PartialEq,
479 Eq,
480 PartialOrd,
481 Ord,
482 Hash,
483 Default,
484 Deserialize,
485 Serialize,
486 Constructor,
487)]
488pub struct IsolatedMarginRisk {
489 /// Margin level of the isolated pair (collateral-to-debt ratio); higher is safer.
490 pub margin_level: Option<Decimal>,
491 /// Margin ratio of the isolated pair.
492 pub margin_ratio: Option<Decimal>,
493 /// Estimated liquidation price for the isolated pair.
494 pub liquidation_price: Option<Decimal>,
495}
496
497/// Live per-instrument isolated-margin balance update payload (the
498/// [`AccountEventKind::InstrumentBalanceUpdate`] counterpart of [`IsolatedInstrumentState`]).
499///
500/// Carries a point-in-time `free`/`locked` **snapshot** of one asset (the pair's base or its
501/// quote) in the pair's isolated sub-account — NOT a delta. It is the per-instrument counterpart of
502/// [`AccountEventKind::BalanceStreamUpdate`]: one event per asset, so a venue frame that lists only
503/// the asset that changed yields one event, and a frame listing both yields two. Apply each one
504/// to the `(instrument, asset)` it names and leave the pair's other asset as it was. Which side
505/// it is follows from comparing [`AssetBalanceUpdate::asset`] with the instrument's base and
506/// quote. The two events from one frame share a `time_exchange` but arrive separately, so a
507/// consumer can see one side updated before the other.
508///
509/// It carries no debt, so applying it keeps `free`/`locked` live while preserving any known
510/// per-asset debt (use [`Balance::apply_stream_update`](balance::Balance::apply_stream_update)).
511#[derive(
512 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
513)]
514pub struct InstrumentBalanceUpdate<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
515 /// Instrument (isolated pair) the update applies to.
516 pub instrument: InstrumentKey,
517 /// `free`/`locked` of one of the pair's assets in its isolated sub-account.
518 pub balance: AssetBalanceUpdate<AssetKey>,
519}
520
521impl<ExchangeKey, AssetKey, InstrumentKey> AccountSnapshot<ExchangeKey, AssetKey, InstrumentKey> {
522 pub fn time_most_recent(&self) -> Option<DateTime<Utc>> {
523 let order_times = self.instruments.iter().flat_map(|instrument| {
524 instrument
525 .orders
526 .iter()
527 .filter_map(|order| order.state.time_exchange())
528 });
529 let balance_times = self.balances.iter().map(|balance| balance.time_exchange);
530
531 order_times.chain(balance_times).max()
532 }
533
534 pub fn assets(&self) -> impl Iterator<Item = &AssetKey> {
535 self.balances.iter().map(|balance| &balance.asset)
536 }
537
538 pub fn instruments(&self) -> impl Iterator<Item = &InstrumentKey> {
539 self.instruments.iter().map(|snapshot| &snapshot.instrument)
540 }
541}
542
543// Both tests exercise the feature-gated `emit_stream_terminated`, so this module compiles under the
544// same venue features — no feature → no function → no test for it.
545#[cfg(all(
546 test,
547 any(
548 feature = "alpaca",
549 feature = "binance",
550 feature = "ibkr",
551 feature = "hyperliquid"
552 )
553))]
554#[allow(clippy::unwrap_used, clippy::expect_used)] // Test code: panics on bad input are acceptable
555mod tests {
556 use super::*;
557
558 /// The shared terminal-emit helper every venue connector funnels through must deliver an
559 /// in-band [`AccountEventKind::StreamTerminated`] carrying the given exchange and reason.
560 #[test]
561 fn emit_stream_terminated_delivers_event_in_band() {
562 let (tx, mut rx) = mpsc::unbounded_channel::<UnindexedAccountEvent>();
563 let reason = StreamTerminationReason::ReconnectBudgetExhausted {
564 attempts: 7,
565 last_error: "socket reset".to_string(),
566 };
567
568 emit_stream_terminated(&tx, ExchangeId::BinanceSpot, reason.clone());
569
570 let event = rx.try_recv().expect("expected a terminal event");
571 assert_eq!(event.exchange, ExchangeId::BinanceSpot);
572 assert!(
573 matches!(event.kind, AccountEventKind::StreamTerminated(r) if r == reason),
574 "expected StreamTerminated carrying the supplied reason",
575 );
576 }
577
578 /// A failed re-init survives a serde round trip, so audit and replay keep it, error and all.
579 #[test]
580 fn a_reinit_failure_round_trips_through_serde() {
581 use crate::error::{
582 AccountReinitFailure, AccountStreamInitError, ClientError, ConnectivityError,
583 };
584
585 let event = AccountEvent::new(
586 ExchangeIndex::new(0),
587 AccountEventKind::ReinitFailed(AccountReinitFailure::new(
588 3,
589 AccountStreamInitError::Client(ClientError::Connectivity(
590 ConnectivityError::Timeout,
591 )),
592 )),
593 );
594
595 let json = serde_json::to_string(&event).unwrap();
596 let decoded: AccountEvent = serde_json::from_str(&json).unwrap();
597
598 assert_eq!(decoded, event);
599 }
600
601 /// Per the D6 consumer-drop decision, emitting after the consumer dropped the receiver is a
602 /// best-effort silent no-op — it must not panic (there is no one left to deliver to).
603 #[test]
604 fn emit_stream_terminated_is_noop_when_receiver_dropped() {
605 let (tx, rx) = mpsc::unbounded_channel::<UnindexedAccountEvent>();
606 drop(rx);
607
608 // Must not panic even though the send is dropped on the floor.
609 emit_stream_terminated(
610 &tx,
611 ExchangeId::HyperliquidPerp,
612 StreamTerminationReason::Error("stream closed".to_string()),
613 );
614 }
615}