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