Skip to main content

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