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
24//! # Barter-Execution
25//! Stream private account data from financial venues, and execute (live or mock) orders. Also provides
26//! a feature rich MockExchange and MockExecutionClient to assist with backtesting and paper-trading.
27//!
28//! **It is:**
29//! * **Easy**: ExecutionClient trait provides a unified and simple language for interacting with exchanges.
30//! * **Normalised**: Allow your strategy to communicate with every real or MockExchange using the same interface.
31//! * **Extensible**: Barter-Execution is highly extensible, making it easy to contribute by adding new exchange integrations!
32//!
33//! See `README.md` for more information and examples.
34
35// Silence unused_crate_dependencies for dev-dependencies used only in tests
36#[cfg(test)]
37use serial_test as _;
38#[cfg(test)]
39use temp_env as _;
40#[cfg(test)]
41use tracing_subscriber as _;
42#[cfg(test)]
43use wiremock as _;
44
45use crate::{
46 balance::{AssetBalance, AssetBalanceUpdate},
47 error::StreamTerminationReason,
48 order::{Order, OrderSnapshot, request::OrderResponseCancel},
49 position::Position,
50 trade::Trade,
51};
52use chrono::{DateTime, Utc};
53use derive_more::{Constructor, From};
54use order::state::OrderState;
55use rust_decimal::Decimal;
56use rustrade_instrument::{
57 asset::{AssetIndex, name::AssetNameExchange},
58 exchange::{ExchangeId, ExchangeIndex},
59 instrument::{InstrumentIndex, name::InstrumentNameExchange},
60};
61use rustrade_integration::collection::snapshot::Snapshot;
62use serde::{Deserialize, Serialize};
63// Only `emit_stream_terminated` (and its tests) name `mpsc`, both gated to the venue features —
64// gate the import the same way so the default-empty feature set does not warn it as unused.
65#[cfg(any(
66 feature = "alpaca",
67 feature = "binance",
68 feature = "ibkr",
69 feature = "hyperliquid"
70))]
71use tokio::sync::mpsc;
72
73pub mod balance;
74pub mod client;
75pub mod error;
76pub mod exchange;
77pub mod fee;
78pub use fee::{
79 FeeModel, FeeModelConfig, Liquidity, PerContractFeeModel, PercentageFeeModel, ZeroFeeModel,
80};
81pub mod fill;
82pub use fill::{
83 BidAskFillModel, FillContext, FillModel, LastPriceFillModel, MidpointFillModel, SimFillConfig,
84};
85pub mod indexer;
86pub mod map;
87pub mod market;
88pub use market::{MarketDepth, MarketSnapshot};
89pub mod order;
90pub mod position;
91pub mod trade;
92
93/// Convenient type alias for an [`AccountEvent`] keyed with [`ExchangeId`],
94/// [`AssetNameExchange`], and [`InstrumentNameExchange`].
95pub type UnindexedAccountEvent =
96 AccountEvent<ExchangeId, AssetNameExchange, InstrumentNameExchange>;
97
98/// Convenient type alias for an [`AccountSnapshot`] keyed with [`ExchangeId`],
99/// [`AssetNameExchange`], and [`InstrumentNameExchange`].
100pub type UnindexedAccountSnapshot =
101 AccountSnapshot<ExchangeId, AssetNameExchange, InstrumentNameExchange>;
102
103#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
104pub struct AccountEvent<
105 ExchangeKey = ExchangeIndex,
106 AssetKey = AssetIndex,
107 InstrumentKey = InstrumentIndex,
108> {
109 pub exchange: ExchangeKey,
110 pub kind: AccountEventKind<ExchangeKey, AssetKey, InstrumentKey>,
111}
112
113impl<ExchangeKey, AssetKey, InstrumentKey> AccountEvent<ExchangeKey, AssetKey, InstrumentKey> {
114 pub fn new<K>(exchange: ExchangeKey, kind: K) -> Self
115 where
116 K: Into<AccountEventKind<ExchangeKey, AssetKey, InstrumentKey>>,
117 {
118 Self {
119 exchange,
120 kind: kind.into(),
121 }
122 }
123
124 /// Named constructor for the terminal [`StreamTerminated`](AccountEventKind::StreamTerminated)
125 /// event carrying the given [`StreamTerminationReason`].
126 pub(crate) fn stream_terminated(
127 exchange: ExchangeKey,
128 reason: StreamTerminationReason,
129 ) -> Self {
130 Self {
131 exchange,
132 kind: AccountEventKind::StreamTerminated(reason),
133 }
134 }
135}
136
137/// Best-effort in-band emit of a terminal
138/// [`StreamTerminated`](AccountEventKind::StreamTerminated) on the account-event channel, sent just
139/// before a venue's stream task exits so stream death is delivered in-band rather than inferred from
140/// channel EOF.
141///
142/// Shared by the channel-based venue connectors (Binance spot/margin, Alpaca, IBKR, Hyperliquid)
143/// so the single send of the terminal event lives in one place, at the abstraction level where
144/// [`AccountEvent`] is defined rather than inside any one vendor module. (The Mock client yields
145/// into a `Stream` rather than an mpsc channel, so it builds the terminal event via
146/// `UnindexedAccountEvent::stream_terminated` directly and does not funnel through this helper.)
147/// The send is best-effort: if the consumer already dropped the receiver it is a silent no-op —
148/// which is the consumer-initiated-drop case, deliberately *not* signalled (there is no one left
149/// to deliver to).
150//
151// Gated to the venues that send terminal events through an mpsc channel from a spawned stream task,
152// so the crate's default-empty feature set does not warn this as unused (mirrors `parse_env_bool`
153// below). The Mock client is always compiled but is excluded by design — see the note above.
154#[cfg(any(
155 feature = "alpaca",
156 feature = "binance",
157 feature = "ibkr",
158 feature = "hyperliquid"
159))]
160pub(crate) fn emit_stream_terminated(
161 tx: &mpsc::UnboundedSender<UnindexedAccountEvent>,
162 exchange: ExchangeId,
163 reason: StreamTerminationReason,
164) {
165 let _ = tx.send(UnindexedAccountEvent::stream_terminated(exchange, reason));
166}
167
168/// Parse a boolean environment-variable value using the single cross-venue policy.
169///
170/// Accepts only `"true"` / `"false"` (case-insensitive, surrounding whitespace trimmed); every other
171/// value returns `None` so the caller can surface an explicit "must be true or false" error rather
172/// than silently coercing. Deliberately does **not** accept `"1"`/`"0"` or other truthy spellings —
173/// one strict, unambiguous spelling shared by every venue's `from_env` (Alpaca `ALPACA_PAPER`,
174/// Binance `BINANCE_TESTNET`, Hyperliquid `HYPERLIQUID_TESTNET`) keeps the network-selection toggle
175/// impossible to misread.
176//
177// Gated to the venues that read env-bool toggles so the crate's default-empty feature set does not
178// warn this as unused.
179#[cfg(any(feature = "alpaca", feature = "binance", feature = "hyperliquid"))]
180pub(crate) fn parse_env_bool(value: &str) -> Option<bool> {
181 let trimmed = value.trim();
182 if trimmed.eq_ignore_ascii_case("true") {
183 Some(true)
184 } else if trimmed.eq_ignore_ascii_case("false") {
185 Some(false)
186 } else {
187 None
188 }
189}
190
191#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, From)]
192#[non_exhaustive]
193pub enum AccountEventKind<ExchangeKey, AssetKey, InstrumentKey> {
194 /// Full [`AccountSnapshot`] - replaces all existing state.
195 Snapshot(AccountSnapshot<ExchangeKey, AssetKey, InstrumentKey>),
196
197 /// Single [`AssetBalance`] snapshot - replaces existing balance state.
198 ///
199 /// Sourced from a REST account snapshot: carries the **full** balance including any per-asset
200 /// margin debt (`borrowed`/`interest`). This is the authoritative source for debt totals.
201 BalanceSnapshot(Snapshot<AssetBalance<AssetKey>>),
202
203 /// Single [`AssetBalanceUpdate`] - applies a WS partial (`free`/`locked` only).
204 ///
205 /// Sourced from an exchange WS user-data stream (e.g. Binance `outboundAccountPosition`). It
206 /// carries **no** margin debt, so applying it updates `free`/`locked` while **preserving** any
207 /// existing [`MarginDetails`](balance::MarginDetails) — debt cannot be silently clobbered by a
208 /// stream update. Debt totals remain as fresh as the last [`BalanceSnapshot`](Self::BalanceSnapshot).
209 BalanceStreamUpdate(Snapshot<AssetBalanceUpdate<AssetKey>>),
210
211 /// Live per-instrument isolated-margin balance update (`free`/`locked` per side).
212 ///
213 /// The stream counterpart of [`InstrumentAccountSnapshot::isolated`] for venues with per-pair
214 /// isolated sub-accounts (e.g. Binance isolated margin). Carries a point-in-time `free`/`locked`
215 /// **snapshot** for the pair's `base` and `quote` assets — NOT a delta — keyed by instrument
216 /// rather than asset, because isolated balances are per-`(pair, asset)` and cannot be folded
217 /// into the asset-keyed balance state without collision (see [`InstrumentBalanceUpdate`]).
218 ///
219 /// The engine deliberately does **not** store this (the per-asset balance state is informational
220 /// only and the engine never reads it for sizing/gating); a consumer reads it off the account
221 /// event feed. Debt totals stay as fresh as the last
222 /// [`BalanceSnapshot`](Self::BalanceSnapshot) per the debt-freshness contract.
223 InstrumentBalanceUpdate(InstrumentBalanceUpdate<AssetKey, InstrumentKey>),
224
225 /// Single [`Order`] snapshot - used to upsert existing order state if it's more recent.
226 ///
227 /// This variant covers general order updates, and open order responses.
228 OrderSnapshot(Snapshot<Order<ExchangeKey, InstrumentKey, OrderState<AssetKey, InstrumentKey>>>),
229
230 /// Response to an [`OrderRequestCancel<ExchangeKey, InstrumentKey>`](order::request::OrderRequestOpen).
231 OrderCancelled(OrderResponseCancel<ExchangeKey, AssetKey, InstrumentKey>),
232
233 /// [`Order<ExchangeKey, InstrumentKey, Open>`] partial or full-fill.
234 ///
235 /// The fee asset (`AssetKey`) may be the quote asset, base asset, or a third-party
236 /// asset (e.g., BNB on Binance). Use `fees.fees_quote` for quote-equivalent value
237 /// when available.
238 Trade(Trade<AssetKey, InstrumentKey>),
239
240 /// The account event stream has ended; no further events will arrive on it.
241 ///
242 /// This is the in-band, programmatic signal that a stream died — delivered on the **same**
243 /// account feed as every other event rather than being inferred from channel EOF or read from
244 /// logs. The [`StreamTerminationReason`] distinguishes a venue that exhausted its reconnect
245 /// budget from an unrecoverable error, so the consumer can apply its own recovery policy
246 /// (re-establish the stream, re-sync via REST, halt trading). The library reports *that* and
247 /// *why* the stream ended; it does not prescribe the response.
248 ///
249 /// Only terminations deliverable while the consumer is still listening are signalled: a
250 /// consumer-initiated drop closes the receiver, so there is no one left to deliver to (see
251 /// [`StreamTerminationReason`] for the deliverable-only rationale).
252 StreamTerminated(StreamTerminationReason),
253}
254
255impl<ExchangeKey, AssetKey, InstrumentKey> AccountEvent<ExchangeKey, AssetKey, InstrumentKey>
256where
257 AssetKey: Eq,
258 InstrumentKey: Eq,
259{
260 pub fn snapshot(self) -> Option<AccountSnapshot<ExchangeKey, AssetKey, InstrumentKey>> {
261 match self.kind {
262 AccountEventKind::Snapshot(snapshot) => Some(snapshot),
263 _ => None,
264 }
265 }
266}
267
268#[derive(
269 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
270)]
271pub struct AccountSnapshot<
272 ExchangeKey = ExchangeIndex,
273 AssetKey = AssetIndex,
274 InstrumentKey = InstrumentIndex,
275> {
276 pub exchange: ExchangeKey,
277 pub balances: Vec<AssetBalance<AssetKey>>,
278 pub instruments: Vec<InstrumentAccountSnapshot<ExchangeKey, AssetKey, InstrumentKey>>,
279}
280
281/// serde `default` for an `Option` field whose inner type is generic — returns `None` without
282/// requiring the inner type to be `Default` (see the `isolated` field below).
283fn none_option<T>() -> Option<T> {
284 None
285}
286
287#[derive(
288 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
289)]
290pub struct InstrumentAccountSnapshot<
291 ExchangeKey = ExchangeIndex,
292 AssetKey = AssetIndex,
293 InstrumentKey = InstrumentIndex,
294> {
295 pub instrument: InstrumentKey,
296 #[serde(default = "Vec::new")]
297 pub orders: Vec<OrderSnapshot<ExchangeKey, AssetKey, InstrumentKey>>,
298 /// Open position for derivative instruments (perpetuals, futures, margin).
299 /// `None` for spot instruments where position is implicit in balances.
300 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub position: Option<Position>,
302 /// Per-pair isolated-margin balances and risk, for venues with isolated sub-accounts
303 /// (e.g. Binance isolated margin). `None` for cross margin, spot, and all other contexts.
304 ///
305 /// Surfaced here — attached to the instrument — rather than folded into the asset-keyed
306 /// [`AccountSnapshot::balances`] because isolated sub-accounts are per-`(pair, asset)`: the same
307 /// asset (e.g. `USDT`) in two isolated pairs is a separate pool, which the asset-keyed balance
308 /// model cannot represent without collision. The engine does not store this; a consumer reads
309 /// it off the snapshot to compose per-pair risk. See [`IsolatedInstrumentState`].
310 ///
311 // `default = "none_option"` (not a bare `#[serde(default)]`) avoids serde inferring a spurious
312 // `AssetKey: Default` bound: a bare default on a generic-typed field conservatively requires the
313 // field type to be `Default` (the `position` field escapes this only because `Position` is
314 // concrete). Naming a function makes serde *call* it instead, requiring only `AssetKey: Deserialize`.
315 #[serde(default = "none_option", skip_serializing_if = "Option::is_none")]
316 pub isolated: Option<IsolatedInstrumentState<AssetKey>>,
317}
318
319/// Per-pair isolated-margin state attached to an [`InstrumentAccountSnapshot`].
320///
321/// Binance isolated margin (and other CEX isolated/per-pair sub-accounts) hold balances
322/// per-`(pair, asset)`, not per-asset, so they are surfaced attached to the instrument rather than
323/// in the asset-keyed [`AccountSnapshot::balances`]. A consumer composes per-pair risk from `base`,
324/// `quote`, and `risk`.
325#[derive(
326 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
327)]
328pub struct IsolatedInstrumentState<AssetKey = AssetIndex> {
329 /// Base-asset balance of the pair's isolated sub-account (carries per-asset debt).
330 pub base: AssetBalance<AssetKey>,
331 /// Quote-asset balance of the pair's isolated sub-account (carries per-asset debt).
332 pub quote: AssetBalance<AssetKey>,
333 /// Per-pair risk metrics — snapshot-fresh, not live (see [`IsolatedMarginRisk`]).
334 pub risk: IsolatedMarginRisk,
335}
336
337/// Per-pair isolated-margin risk metrics, surfaced on [`IsolatedInstrumentState`].
338///
339/// Every field is `Option` — a venue may omit any given metric, and a missing metric must not
340/// drop the surrounding balance snapshot.
341///
342/// # Freshness
343/// These are **snapshot-only**: authoritative as of the last `account_snapshot` and refreshed on
344/// snapshot. Unlike balances, there is **no live-stream twin** — the WS `outboundAccountPosition`
345/// frame carries no margin-level / liquidation data. The live signal for risk crossing a threshold
346/// is the venue's `marginLevelStatusChange` event (surfaced observably, not accumulated here).
347#[derive(
348 Debug,
349 Copy,
350 Clone,
351 PartialEq,
352 Eq,
353 PartialOrd,
354 Ord,
355 Hash,
356 Default,
357 Deserialize,
358 Serialize,
359 Constructor,
360)]
361pub struct IsolatedMarginRisk {
362 /// Margin level of the isolated pair (collateral-to-debt ratio); higher is safer.
363 pub margin_level: Option<Decimal>,
364 /// Margin ratio of the isolated pair.
365 pub margin_ratio: Option<Decimal>,
366 /// Estimated liquidation price for the isolated pair.
367 pub liquidation_price: Option<Decimal>,
368}
369
370/// Live per-instrument isolated-margin balance update payload (the
371/// [`AccountEventKind::InstrumentBalanceUpdate`] counterpart of [`IsolatedInstrumentState`]).
372///
373/// Carries a point-in-time `free`/`locked` **snapshot** for the pair's `base` and `quote` assets —
374/// NOT a delta — keyed by instrument. Structurally analogous to [`AssetBalanceUpdate`] but
375/// per-instrument: it carries no debt, so applying it keeps `free`/`locked` live while preserving
376/// any known per-asset debt (use [`Balance::apply_stream_update`](balance::Balance::apply_stream_update)).
377#[derive(
378 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize, Constructor,
379)]
380pub struct InstrumentBalanceUpdate<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
381 /// Instrument (isolated pair) the update applies to.
382 pub instrument: InstrumentKey,
383 /// Base-asset `free`/`locked` update for the pair's isolated sub-account.
384 pub base: AssetBalanceUpdate<AssetKey>,
385 /// Quote-asset `free`/`locked` update for the pair's isolated sub-account.
386 pub quote: AssetBalanceUpdate<AssetKey>,
387}
388
389impl<ExchangeKey, AssetKey, InstrumentKey> AccountSnapshot<ExchangeKey, AssetKey, InstrumentKey> {
390 pub fn time_most_recent(&self) -> Option<DateTime<Utc>> {
391 let order_times = self.instruments.iter().flat_map(|instrument| {
392 instrument
393 .orders
394 .iter()
395 .filter_map(|order| order.state.time_exchange())
396 });
397 let balance_times = self.balances.iter().map(|balance| balance.time_exchange);
398
399 order_times.chain(balance_times).max()
400 }
401
402 pub fn assets(&self) -> impl Iterator<Item = &AssetKey> {
403 self.balances.iter().map(|balance| &balance.asset)
404 }
405
406 pub fn instruments(&self) -> impl Iterator<Item = &InstrumentKey> {
407 self.instruments.iter().map(|snapshot| &snapshot.instrument)
408 }
409}
410
411// Both tests exercise the feature-gated `emit_stream_terminated`, so this module compiles under the
412// same venue features — no feature → no function → no test for it.
413#[cfg(all(
414 test,
415 any(
416 feature = "alpaca",
417 feature = "binance",
418 feature = "ibkr",
419 feature = "hyperliquid"
420 )
421))]
422#[allow(clippy::unwrap_used, clippy::expect_used)] // Test code: panics on bad input are acceptable
423mod tests {
424 use super::*;
425
426 /// The shared terminal-emit helper every venue connector funnels through must deliver an
427 /// in-band [`AccountEventKind::StreamTerminated`] carrying the given exchange and reason.
428 #[test]
429 fn emit_stream_terminated_delivers_event_in_band() {
430 let (tx, mut rx) = mpsc::unbounded_channel::<UnindexedAccountEvent>();
431 let reason = StreamTerminationReason::ReconnectBudgetExhausted {
432 attempts: 7,
433 last_error: "socket reset".to_string(),
434 };
435
436 emit_stream_terminated(&tx, ExchangeId::BinanceSpot, reason.clone());
437
438 let event = rx.try_recv().expect("expected a terminal event");
439 assert_eq!(event.exchange, ExchangeId::BinanceSpot);
440 assert!(
441 matches!(event.kind, AccountEventKind::StreamTerminated(r) if r == reason),
442 "expected StreamTerminated carrying the supplied reason",
443 );
444 }
445
446 /// Per the D6 consumer-drop decision, emitting after the consumer dropped the receiver is a
447 /// best-effort silent no-op — it must not panic (there is no one left to deliver to).
448 #[test]
449 fn emit_stream_terminated_is_noop_when_receiver_dropped() {
450 let (tx, rx) = mpsc::unbounded_channel::<UnindexedAccountEvent>();
451 drop(rx);
452
453 // Must not panic even though the send is dropped on the floor.
454 emit_stream_terminated(
455 &tx,
456 ExchangeId::HyperliquidPerp,
457 StreamTerminationReason::Error("stream closed".to_string()),
458 );
459 }
460}