Skip to main content

rustrade_execution/client/
mod.rs

1//! Execution client implementations for various exchanges.
2//!
3//! # Connector Comparison
4//!
5//! | Connector | Reconnect | Dedup | Fill Recovery | Ended-order Recovery | Heartbeat | Cancel answers once |
6//! |-----------|-----------|-------|---------------|----------------------|-----------|---------------------|
7//! | [`binance`] | Auto (1s→30s backoff, 10 tries) | 10k LRU | REST after reconnect | REST after reconnect | 30s | cancelled |
8//! | [`alpaca`] | Auto (1s→30s backoff, 10 tries) | 2k LRU | REST after reconnect | REST after reconnect | 35s | accepted |
9//! | [`ibkr`] | ibapi-managed | 10k LRU, fills only | Executions request after reconnect | None | N/A | submitted |
10//! | [`hyperliquid`] | SDK-managed (every 1s, no limit) | 10k LRU, fills only | Venue snapshot on resubscribe | REST after reconnect | SDK-managed | cancelled |
11//!
12//! "Reconnect" is how the account stream comes back after its connection drops, and when it gives
13//! up: Binance and Alpaca end the stream once 10 reconnects in a row have failed (see
14//! [`binance`](binance#account-stream-reconnection) and
15//! [`AlpacaClient`](alpaca::AlpacaClient)'s `account_stream`).
16//!
17//! "Ended-order Recovery" is whether a reconnect reports how an order the client held as live
18//! ended while the stream was down, and only those clients implement [`OrderStatusClient`]. The
19//! last column is when [`ExecutionClient::cancel_order`] answers `Ok`. Only for "cancelled" has the
20//! order ended by then; see that method.
21//!
22//! # Resilience Philosophy
23//!
24//! **WebSocket-based connectors** (Binance, Alpaca) implement auto-reconnection with
25//! fill recovery and deduplication. After reconnect, they query REST APIs for missed
26//! fills and deduplicate against the LRU cache to prevent duplicate processing.
27//!
28//! **IBKR** uses TCP to local TWS/Gateway. `ibapi` reconnects that socket itself; the
29//! account stream stays open across it and recovers the missed fills from TWS's executions,
30//! deduplicating against the LRU cache. Replacing a client that is gone for good requires IB
31//! Gateway availability and client ID coordination — decisions that belong in the caller's
32//! wrapper. See [`ibkr`] module docs for caller responsibilities.
33//!
34//! **Hyperliquid** delegates reconnection to the official SDK's `with_reconnect()` mechanism, but
35//! deduplicates fills itself: the SDK resubscribes on reconnect and the venue opens a `userFills`
36//! subscription with a snapshot, so every reconnect redelivers fills already seen. That snapshot
37//! is the only fill recovery: it holds recent fills, how many Hyperliquid does not say, so callers
38//! needing older ones call [`ExecutionClient::fetch_trades`], whose results are not deduplicated
39//! against the stream. Once the snapshot has been sent on, a reconnect checks how the orders the
40//! client holds as live ended, like Binance's and Alpaca's.
41//!
42//! # Known Limitations
43//!
44//! Only Binance (Spot and Margin), Alpaca and Hyperliquid (perpetuals and spot) recover the **order
45//! lifecycle events** (cancelled, expired, rejected, a fill that completes an order) they missed
46//! while disconnected, and only for the orders the client holds as live; IBKR recovers fills only
47//! (#370). [`OrderStatusClient`] is the lookup that recovery is built on: given the orders a caller
48//! still holds as live, it says how each that has ended did end. Binance Spot, Binance Margin,
49//! Alpaca, both Hyperliquid clients and the mock client implement it.
50//!
51//! The engine closes part of that gap from the account snapshot each reconnect produces: an order a
52//! complete list no longer shows is retired (see [`ExecutionClient::account_snapshot`]). That covers
53//! the connectors whose snapshot declares its orders complete — Binance Spot and Margin,
54//! Hyperliquid, Alpaca, and the mock venue — but not IBKR (#371), and it cannot tell how an order
55//! ended. A caller that needs more reconciles against
56//! [`ExecutionClient::fetch_open_orders`] after a reconnect.
57
58use crate::{
59    UnindexedAccountEvent, UnindexedAccountSnapshot,
60    balance::AssetBalance,
61    borrow_capacity::BorrowCapacity,
62    error::UnindexedClientError,
63    order::{
64        Order, UnindexedInactiveOrder, UnindexedOrderKey,
65        bracket::{BracketOrderRequest, BracketOrderResult},
66        request::{OrderRequestCancel, OrderRequestOpen, UnindexedOrderResponseCancel},
67        state::{Open, UnindexedOrderState},
68    },
69    shortability::Shortability,
70    trade::TradesRead,
71};
72use chrono::{DateTime, Utc};
73use futures::Stream;
74use rustrade_instrument::{
75    Side,
76    asset::name::AssetNameExchange,
77    exchange::ExchangeId,
78    instrument::{kind::InstrumentKindDiscriminant, name::InstrumentNameExchange},
79};
80use std::future::Future;
81
82// Account-event deduplication over rustrade's own event type. Alpaca deduplicates too, but against
83// a raw `SmolStr` fill key rather than this cache. Always compiled: `AccountEventDeduper` is public.
84pub mod dedup;
85
86// What a client knows of its live orders, and the reconnect check of how those orders ended while
87// its account stream was down. Gated on the clients that use it.
88#[cfg(any(
89    feature = "alpaca",
90    feature = "binance",
91    feature = "hyperliquid",
92    feature = "ibkr"
93))]
94pub(crate) mod order_recovery;
95
96// The account streams' reconnect budget. Gated on the clients that use it.
97#[cfg(any(feature = "alpaca", feature = "binance"))]
98pub(crate) mod reconnect_budget;
99
100// A REST stub on the test's own runtime, for the reconnect tests on a paused clock.
101#[cfg(all(test, any(feature = "alpaca", feature = "binance")))]
102#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
103pub(crate) mod test_http;
104
105// Alpaca ExecutionClient implementation (options, equities, crypto — single unified API)
106#[cfg(feature = "alpaca")]
107pub mod alpaca;
108
109// Binance ExecutionClient implementations: Spot (live) and Cross Margin (identity/config scaffolding)
110#[cfg(feature = "binance")]
111pub mod binance;
112
113// Hyperliquid perpetual futures and spot ExecutionClient implementations
114#[cfg(feature = "hyperliquid")]
115pub mod hyperliquid;
116
117// Interactive Brokers ExecutionClient implementation (equities, futures, options, forex)
118#[cfg(feature = "ibkr")]
119pub mod ibkr;
120
121pub mod mock;
122
123/// An instrument an [`ExecutionClient`] is about to be built to trade, as
124/// [`ExecutionClient::validate_config`] sees it.
125///
126/// `#[non_exhaustive]`, so further detail can be added without breaking an implementation that
127/// reads these fields; construct one with [`Self::new`].
128#[derive(Debug, Clone, Copy, Eq, PartialEq)]
129#[non_exhaustive]
130pub struct ClientInstrument<'a> {
131    /// The name the venue knows the instrument by, which is what a client's requests carry.
132    pub name_exchange: &'a InstrumentNameExchange,
133    /// The instrument's kind.
134    pub kind: InstrumentKindDiscriminant,
135}
136
137impl<'a> ClientInstrument<'a> {
138    /// The view of an instrument named `name_exchange`, of kind `kind`.
139    pub fn new(
140        name_exchange: &'a InstrumentNameExchange,
141        kind: InstrumentKindDiscriminant,
142    ) -> Self {
143        Self {
144            name_exchange,
145            kind,
146        }
147    }
148}
149
150// `+ Send` bounds on async method return types required for multi-threaded
151// Tokio runtime. This is a breaking change vs upstream — any `!Send` executor
152// implementation would fail to compile.
153/// A venue's account and order API, as the engine's `ExecutionManager` drives it.
154///
155/// # Wrapping a client
156///
157/// To add behaviour around a venue client without reimplementing it, wrap it in a generic
158/// decorator that implements `ExecutionClient` itself. Typical uses are choosing which fills on a
159/// shared account reach the engine, logging, and metrics.
160///
161/// - **Take the inner client's identity.** Set `const EXCHANGE: ExchangeId = C::EXCHANGE` and
162///   `SUPPORTED_KINDS = C::SUPPORTED_KINDS`. The `ExecutionManager` refuses a venue client whose
163///   `EXCHANGE` differs from its instrument map's exchange (only the `Mock` and `Simulated` ids
164///   are exempt), so one generic wrapper then serves every venue client.
165/// - **Forward every method, the provided ones included.** That is
166///   [`open_orders`](Self::open_orders), [`cancel_orders`](Self::cancel_orders) and
167///   [`validate_config`](Self::validate_config): left to the trait's defaults, they would bypass
168///   any batching or config check the inner client has. Implement the extension traits the inner
169///   client implements as well, with impls bounded on it:
170///   - [`BracketOrderClient`]
171///   - [`OrderStatusClient`]
172///   - [`ShortabilityClient`]
173///   - [`BorrowCapacityClient`]
174/// - **Withhold a fill from [`account_stream`](Self::account_stream) and
175///   [`fetch_trades`](Self::fetch_trades) alike, by the same rule.** One fill can reach the engine
176///   either way: live on the stream, or in a read made after a disconnect. A fill withheld from
177///   only one of them still reaches the engine once.
178///   - **Choose a key both paths carry.** [`Trade::client_order_id`] marks the orders a consumer
179///     placed, but not every venue reports it on `fetch_trades` (its rustdoc lists which do).
180///     Binance's is one that does not. A rule keyed on it has to decide what to do with a fill it
181///     cannot classify. Keeping it, as the example below does, delivers too much rather than too
182///     little: on such a venue every fill a `fetch_trades` read returns is kept, and only the
183///     stream is filtered. To withhold those fills as well, match them another way, such as by
184///     [`Trade::order_id`] against the orders the wrapper placed.
185///   - **Keep fills the venue forced** ([`TradeOrigin::is_forced`]). They moved the position,
186///     whoever placed the order.
187///   - **Leave `resume` alone.** Filtering a [`TradesRead`] keeps its `resume` as it was: it marks
188///     where the venue's read stopped, not which fills the wrapper kept.
189/// - **One inner client per engine.** A wrapper that owns one client counts as that one client.
190///   Two clients on one account whose account streams both reach one engine deliver every fill
191///   twice.
192/// - **Withhold here, not later.** The engine applies a fill that matches none of its orders too.
193///   In `OmsMode::Netting` it moves the netting position like any other fill, and the engine
194///   cannot tell it from a fill of its own. In `OmsMode::Hedging` an ordinary fill
195///   ([`TradeOrigin::Order`] or [`TradeOrigin::External`]) opens a position of its own, and a
196///   settlement fill is handled as [`InstrumentState::update_from_trade`] describes.
197///
198/// ```
199/// use chrono::{DateTime, Utc};
200/// use futures::{Stream, StreamExt, stream::BoxStream};
201/// use rustrade_execution::{
202///     AccountEventKind, UnindexedAccountEvent, UnindexedAccountSnapshot,
203///     balance::AssetBalance,
204///     client::{ClientInstrument, ExecutionClient},
205///     error::UnindexedClientError,
206///     order::{
207///         Order,
208///         request::{OrderRequestCancel, OrderRequestOpen, UnindexedOrderResponseCancel},
209///         state::{Open, UnindexedOrderState},
210///     },
211///     trade::{Trade, TradesRead},
212/// };
213/// use rustrade_instrument::{
214///     asset::name::AssetNameExchange,
215///     exchange::ExchangeId,
216///     instrument::{kind::InstrumentKindDiscriminant, name::InstrumentNameExchange},
217/// };
218///
219/// /// Delivers the fills of orders whose client order id starts with `prefix`, fills whose
220/// /// client order id the venue did not report, and every fill the venue forced.
221/// ///
222/// /// Keeping a fill without a client order id is a choice: on a venue whose `fetch_trades`
223/// /// reports none, this filters the account stream only.
224/// #[derive(Debug, Clone)]
225/// pub struct OwnFills<C> {
226///     inner: C,
227///     prefix: String,
228/// }
229///
230/// #[derive(Debug, Clone)]
231/// pub struct OwnFillsConfig<Config> {
232///     pub inner: Config,
233///     pub prefix: String,
234/// }
235///
236/// fn keeps<AssetKey, InstrumentKey>(prefix: &str, trade: &Trade<AssetKey, InstrumentKey>) -> bool {
237///     trade.origin.is_forced()
238///         || trade
239///             .client_order_id
240///             .as_ref()
241///             .is_none_or(|cid| cid.0.starts_with(prefix))
242/// }
243///
244/// // `Sync` makes the wrapper's method futures `Send`, as the trait requires. `'static` lets the
245/// // filtered account stream be boxed.
246/// impl<C> ExecutionClient for OwnFills<C>
247/// where
248///     C: ExecutionClient + Sync,
249///     C::AccountStream: 'static,
250/// {
251///     const EXCHANGE: ExchangeId = C::EXCHANGE;
252///     const SUPPORTED_KINDS: &'static [InstrumentKindDiscriminant] = C::SUPPORTED_KINDS;
253///     type Config = OwnFillsConfig<C::Config>;
254///     type AccountStream = BoxStream<'static, UnindexedAccountEvent>;
255///
256///     fn validate_config(
257///         config: &Self::Config,
258///         instruments: &[ClientInstrument<'_>],
259///     ) -> Result<(), String> {
260///         C::validate_config(&config.inner, instruments)
261///     }
262///
263///     fn new(config: Self::Config) -> Self {
264///         Self {
265///             inner: C::new(config.inner),
266///             prefix: config.prefix,
267///         }
268///     }
269///
270///     async fn account_stream(
271///         &self,
272///         assets: &[AssetNameExchange],
273///         instruments: &[InstrumentNameExchange],
274///     ) -> Result<Self::AccountStream, UnindexedClientError> {
275///         let prefix = self.prefix.clone();
276///         let stream = self.inner.account_stream(assets, instruments).await?;
277///         Ok(stream
278///             .filter(move |event| {
279///                 let keep = match &event.kind {
280///                     AccountEventKind::Trade(trade) => keeps(&prefix, trade),
281///                     _ => true,
282///                 };
283///                 std::future::ready(keep)
284///             })
285///             .boxed())
286///     }
287///
288///     async fn fetch_trades(
289///         &self,
290///         start: DateTime<Utc>,
291///         end: DateTime<Utc>,
292///         instruments: &[InstrumentNameExchange],
293///     ) -> Result<TradesRead<AssetNameExchange, InstrumentNameExchange>, UnindexedClientError> {
294///         let mut read = self.inner.fetch_trades(start, end, instruments).await?;
295///         read.trades.retain(|trade| keeps(&self.prefix, trade));
296///         Ok(read)
297///     }
298///
299///     // Everything else is forwarded unchanged.
300///
301///     async fn account_snapshot(
302///         &self,
303///         assets: &[AssetNameExchange],
304///         instruments: &[InstrumentNameExchange],
305///     ) -> Result<UnindexedAccountSnapshot, UnindexedClientError> {
306///         self.inner.account_snapshot(assets, instruments).await
307///     }
308///
309///     async fn cancel_order(
310///         &self,
311///         request: OrderRequestCancel<ExchangeId, &InstrumentNameExchange>,
312///     ) -> UnindexedOrderResponseCancel {
313///         self.inner.cancel_order(request).await
314///     }
315///
316///     fn cancel_orders<'a>(
317///         &self,
318///         requests: impl IntoIterator<Item = OrderRequestCancel<ExchangeId, &'a InstrumentNameExchange>>,
319///     ) -> impl Stream<Item = UnindexedOrderResponseCancel> + Send {
320///         self.inner.cancel_orders(requests)
321///     }
322///
323///     async fn open_order(
324///         &self,
325///         request: OrderRequestOpen<ExchangeId, &InstrumentNameExchange>,
326///     ) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
327///         self.inner.open_order(request).await
328///     }
329///
330///     fn open_orders<'a>(
331///         &self,
332///         requests: impl IntoIterator<Item = OrderRequestOpen<ExchangeId, &'a InstrumentNameExchange>>,
333///     ) -> impl Stream<Item = Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>> + Send
334///     {
335///         self.inner.open_orders(requests)
336///     }
337///
338///     async fn fetch_balances(
339///         &self,
340///         assets: &[AssetNameExchange],
341///     ) -> Result<Vec<AssetBalance<AssetNameExchange>>, UnindexedClientError> {
342///         self.inner.fetch_balances(assets).await
343///     }
344///
345///     async fn fetch_open_orders(
346///         &self,
347///         instruments: &[InstrumentNameExchange],
348///     ) -> Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError> {
349///         self.inner.fetch_open_orders(instruments).await
350///     }
351/// }
352/// ```
353///
354/// [`Trade::client_order_id`]: crate::trade::Trade::client_order_id
355/// [`Trade::order_id`]: crate::trade::Trade::order_id
356/// [`TradeOrigin::is_forced`]: crate::trade::TradeOrigin::is_forced
357/// [`TradeOrigin::Order`]: crate::trade::TradeOrigin::Order
358/// [`TradeOrigin::External`]: crate::trade::TradeOrigin::External
359/// [`TradesRead`]: crate::trade::TradesRead
360/// [`InstrumentState::update_from_trade`]: https://docs.rs/rustrade/latest/rustrade/engine/state/instrument/struct.InstrumentState.html#method.update_from_trade
361pub trait ExecutionClient
362where
363    Self: Clone,
364{
365    const EXCHANGE: ExchangeId;
366
367    /// The [`InstrumentKindDiscriminant`]s this client can trade.
368    ///
369    /// A client works off [`InstrumentNameExchange`] strings and never inspects an instrument's
370    /// kind, so nothing downstream can infer this from the implementation — routing a `Future`
371    /// through a spot-only venue produces a rejected or, worse, misinterpreted order rather than a
372    /// type error. Declaring the set here lets [`ExecutionBuilder`] reject an unsupported
373    /// instrument set at build time, before any order is sent.
374    ///
375    /// Declare what the *venue and this implementation together* can actually route, not what the
376    /// exchange's product catalogue advertises. A kind the exchange offers but this client builds
377    /// no request for does not belong in the set.
378    ///
379    /// There is deliberately no default. A new client must state its capabilities rather than
380    /// inherit a permissive set that would silently admit every kind.
381    ///
382    /// It is a `const` and not a `fn supported_kinds(&self)` because [`ExecutionBuilder`] validates
383    /// the instrument set *before* [`Self::new`] is ever called — there is no instance to ask at the
384    /// point the answer is needed, and deferring validation until after construction would mean
385    /// standing up a client for a venue the engine is about to reject. A capability set that varies
386    /// with `Self::Config` therefore cannot be expressed here; it would need a separate
387    /// pre-construction hook on the config.
388    ///
389    /// [`ExecutionBuilder`]: https://docs.rs/rustrade/latest/rustrade/execution/builder/struct.ExecutionBuilder.html
390    const SUPPORTED_KINDS: &'static [InstrumentKindDiscriminant];
391
392    type Config: Clone;
393
394    /// Checks `config` against the instruments this client is about to be built to trade, before
395    /// [`Self::new`] is called. `Err` names what is wrong.
396    ///
397    /// [`SUPPORTED_KINDS`](Self::SUPPORTED_KINDS) rejects a kind the client cannot route at all.
398    /// This catches what only the config knows: a per-instrument entry that is invalid, or that
399    /// disagrees with the instrument it is keyed to, such as a contract registered as a stock for
400    /// an instrument modelled as an option. Each such entry would otherwise be skipped or acted on
401    /// silently once the client runs.
402    ///
403    /// The default accepts every config. Override it when `Self::Config` carries per-instrument
404    /// detail.
405    ///
406    /// [`ExecutionBuilder`] calls it, after checking `SUPPORTED_KINDS`, with the instruments
407    /// registered on this client's exchange. A client constructed by calling `new` directly is not
408    /// checked; call this first to get the same check.
409    ///
410    /// [`ExecutionBuilder`]: https://docs.rs/rustrade/latest/rustrade/execution/builder/struct.ExecutionBuilder.html
411    fn validate_config(
412        config: &Self::Config,
413        instruments: &[ClientInstrument<'_>],
414    ) -> Result<(), String> {
415        let _ = (config, instruments);
416        Ok(())
417    }
418
419    // `+ Send` required so generic code (e.g. ExecutionManager) can pass
420    // the stream to tokio::spawn, which requires Send.
421    type AccountStream: Stream<Item = UnindexedAccountEvent> + Send;
422
423    fn new(config: Self::Config) -> Self;
424
425    /// Reads the account's balances, and its open orders and positions for `instruments`, from the
426    /// venue.
427    ///
428    /// Besides startup, the engine's `ExecutionManager` calls this again on every account-stream
429    /// reconnect, and emits the result ahead of the new stream's updates. It is how the engine
430    /// catches up on what changed while the stream was down.
431    ///
432    /// # Assets
433    ///
434    /// `assets` are the ones the caller registered. Return balances for those only when the venue
435    /// lets you ask, which saves bandwidth. A balance for another asset is not an error: the
436    /// `ExecutionManager` drops it and logs the asset names once per snapshot.
437    ///
438    /// # Order completeness
439    ///
440    /// Each [`InstrumentAccountSnapshot`](crate::InstrumentAccountSnapshot) states through
441    /// `orders_complete` whether its `orders` list is every order open at the venue for that
442    /// instrument. Set it only when it is true: the engine retires a tracked order that a complete
443    /// list omits, so a list that can miss an open order (a capped page, an order dropped on
444    /// conversion, an order reported under an id other than the one it was placed with) must say
445    /// `false`. `false` is always safe; it only forgoes that reconciliation.
446    fn account_snapshot(
447        &self,
448        assets: &[AssetNameExchange],
449        instruments: &[InstrumentNameExchange],
450    ) -> impl Future<Output = Result<UnindexedAccountSnapshot, UnindexedClientError>> + Send;
451
452    /// Returns a live stream of account events (fills, order updates, balance changes).
453    ///
454    /// # Startup race window
455    ///
456    /// There is an unavoidable gap between the WebSocket subscribe response and the
457    /// first event being delivered: fills arriving in this window (typically milliseconds,
458    /// no sub-millisecond guarantee) are silently dropped. `account_snapshot` reconciles
459    /// open-order state, but TRADE fills in this window are not recoverable from the stream
460    /// alone. Callers that require fill completeness at startup **must** call
461    /// [`ExecutionClient::fetch_trades`] with at least a 1-second lookback after this method returns.
462    ///
463    /// # Backpressure
464    ///
465    /// Implementations use unbounded internal channels. If the consumer cannot keep up,
466    /// events queue in memory rather than being dropped — per library philosophy, OOM
467    /// crashes are preferable to silent data loss. Consumers requiring backpressure
468    /// should implement it at their boundary (e.g., bounded channel with overflow policy).
469    fn account_stream(
470        &self,
471        assets: &[AssetNameExchange],
472        instruments: &[InstrumentNameExchange],
473    ) -> impl Future<Output = Result<Self::AccountStream, UnindexedClientError>> + Send;
474
475    /// Cancel an order at the venue.
476    ///
477    /// # Return value
478    ///
479    /// Every request gets exactly one answer, which the engine's `ExecutionManager` forwards as the
480    /// order's response. An implementation must not swallow a request: a failure to send it, or to
481    /// read the venue's answer, is an `Err`.
482    ///
483    /// - `Ok(Cancelled)`: the venue took the cancel. Whether the order has *ended* by then depends
484    ///   on the venue; see below.
485    /// - `Err`: the venue refused the cancel, or it could not be sent or answered. The order may
486    ///   still be open, or may have ended some other way, such as by filling. The account stream
487    ///   reports which.
488    ///
489    /// # A taken cancel is not always an ended order
490    ///
491    /// Some venues answer a cancel before carrying it out. Until they do, the order is live and can
492    /// still fill. From those venues `Ok(Cancelled)` means only that the cancel was accepted, and
493    /// the account stream reports how the order actually ended, including any fill in between. The
494    /// engine stops tracking an order on `Ok(Cancelled)` from any venue.
495    ///
496    /// Binance, Hyperliquid and the mock venue answer once the order is cancelled. Alpaca answers
497    /// once it has accepted the cancel, and IBKR once the cancel is submitted. The
498    /// [connector comparison](crate::client#connector-comparison) lists the same for each
499    /// connector; the mock venue is not one, so it has no row there.
500    ///
501    /// # `filled_quantity` and `time_exchange`
502    ///
503    /// `Cancelled::filled_quantity` is the quantity the venue reported filled where the answer
504    /// carries one, which Binance's and the mock venue's do. Alpaca, IBKR and Hyperliquid answer
505    /// without it and report zero, which does not mean nothing filled. The fill total comes from
506    /// the account stream, or from [`Self::fetch_trades`]. Likewise `time_exchange` is the venue's
507    /// time where the answer carries one, and the local time the answer arrived otherwise.
508    fn cancel_order(
509        &self,
510        request: OrderRequestCancel<ExchangeId, &InstrumentNameExchange>,
511    ) -> impl Future<Output = UnindexedOrderResponseCancel> + Send;
512
513    // `+ Send` on default method return types for multi-threaded Tokio runtime
514    fn cancel_orders<'a>(
515        &self,
516        requests: impl IntoIterator<Item = OrderRequestCancel<ExchangeId, &'a InstrumentNameExchange>>,
517    ) -> impl Stream<Item = UnindexedOrderResponseCancel> + Send {
518        futures::stream::FuturesUnordered::from_iter(
519            requests
520                .into_iter()
521                .map(|request| self.cancel_order(request)),
522        )
523    }
524
525    /// Place an order on the exchange.
526    ///
527    /// # Return value
528    ///
529    /// Every request gets exactly one answer, which the engine's `ExecutionManager` forwards as the
530    /// order's response. An implementation must not swallow a request: a failure to send it, or to
531    /// read the venue's answer, is `OpenFailed`.
532    ///
533    /// Returns `OrderState` directly rather than `Result<Open, OrderError>`:
534    /// - `OrderState::Active(Open)` - order is resting on the order book
535    /// - `OrderState::Inactive(FullyFilled)` - order was immediately filled (includes `avg_price` when available)
536    /// - `OrderState::Inactive(Expired)` - order ended in the response itself without filling
537    ///   completely, carrying what filled: an IOC or FOK order that found too little liquidity,
538    ///   or one expired by self-trade prevention
539    /// - `OrderState::Inactive(Cancelled)` - order the venue reports cancelled in the response
540    ///   itself, carrying what filled
541    /// - `OrderState::Inactive(OpenFailed)` - order placement failed (API error, connectivity, a
542    ///   rejection the venue reports in the response, etc.)
543    ///
544    /// An implementation returns `Expired` or `Cancelled` only when its venue reports the order's
545    /// status in the placement response (currently Binance Spot and Margin). The others return
546    /// `Open` for such an order, and their account stream reports how it ended.
547    ///
548    /// This design allows immediate fills to carry metadata (e.g., `avg_price`) that
549    /// would be lost if we had to infer terminal state from `Open::filled_quantity`.
550    fn open_order(
551        &self,
552        request: OrderRequestOpen<ExchangeId, &InstrumentNameExchange>,
553    ) -> impl Future<Output = Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>> + Send;
554
555    // `+ Send` on default method return types for multi-threaded Tokio runtime
556    fn open_orders<'a>(
557        &self,
558        requests: impl IntoIterator<Item = OrderRequestOpen<ExchangeId, &'a InstrumentNameExchange>>,
559    ) -> impl Stream<Item = Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>> + Send
560    {
561        futures::stream::FuturesUnordered::from_iter(
562            requests.into_iter().map(|request| self.open_order(request)),
563        )
564    }
565
566    /// Fetch current balances for the specified assets.
567    ///
568    /// An empty `assets` slice is the "return all" sentinel: implementations must return
569    /// balances for every asset held. When non-empty, only the listed assets are returned.
570    fn fetch_balances(
571        &self,
572        assets: &[AssetNameExchange],
573    ) -> impl Future<Output = Result<Vec<AssetBalance<AssetNameExchange>>, UnindexedClientError>> + Send;
574
575    /// Fetch currently open orders, optionally filtered by instrument.
576    ///
577    /// An empty `instruments` slice is the "return all" sentinel: implementations must
578    /// return open orders across all instruments. When non-empty, only orders for the
579    /// listed instruments are returned.
580    fn fetch_open_orders(
581        &self,
582        instruments: &[InstrumentNameExchange],
583    ) -> impl Future<
584        Output = Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError>,
585    > + Send;
586
587    /// Read the trades (fills) from `start` to `end`, both inclusive, optionally filtered by
588    /// instrument.
589    ///
590    /// An empty `instruments` slice is the "return all" sentinel: implementations must
591    /// return trades across all instruments. When non-empty, only trades for the listed
592    /// instruments are returned.
593    ///
594    /// # Bounded, resumable reads
595    ///
596    /// One call is bounded by the venue's limits, so it may stop before `end`.
597    /// [`TradesRead::resume`] says whether it did:
598    /// - `None`: every fill in the span the venue still holds was read.
599    /// - `Some(t)`: call again with `start = t` and the same `end` to read on. That read can
600    ///   return again fills the previous one returned, so match them by instrument and
601    ///   [`TradeId`](crate::trade::TradeId).
602    ///
603    /// The caller owns the loop, and with it how many calls, and how long, it spends on a span.
604    /// A `start` after `end` is an empty span, read as no trades and `resume: None`.
605    ///
606    /// # Venue limits
607    ///
608    /// `resume: None` covers what the venue still holds, which can be less than the span:
609    /// - IBKR lists the last 7 days' executions at most.
610    /// - Hyperliquid keeps only each wallet's 10,000 most recent fills.
611    ///
612    /// Binance needs instruments: an empty slice reads nothing. Each client documents its limits.
613    ///
614    /// # Errors
615    ///
616    /// [`Truncated`](crate::error::ClientError::Truncated) when a read cannot advance, because
617    /// more fills share the span's first moment than one call can read past.
618    ///
619    /// The fee asset (`AssetNameExchange`) may be quote, base, or third-party (e.g., BNB).
620    /// Use `fees.fees_quote` for quote-equivalent value when available.
621    fn fetch_trades(
622        &self,
623        start: DateTime<Utc>,
624        end: DateTime<Utc>,
625        instruments: &[InstrumentNameExchange],
626    ) -> impl Future<
627        Output = Result<
628            TradesRead<AssetNameExchange, InstrumentNameExchange>,
629            UnindexedClientError,
630        >,
631    > + Send;
632}
633
634/// Extension trait for exchanges that support native bracket orders.
635///
636/// A bracket order consists of three linked orders:
637/// 1. **Entry**: Limit order to enter the position
638/// 2. **Take Profit**: Limit order to exit at profit target
639/// 3. **Stop Loss**: Stop (or stop-limit) order to exit at loss limit
640///
641/// When either exit leg fills, the exchange automatically cancels the other.
642///
643/// # Type-Level Capability
644///
645/// This is a supertrait of [`ExecutionClient`], enabling compile-time capability checks:
646/// - `impl ExecutionClient` — basic order operations
647/// - `impl ExecutionClient + BracketOrderClient` — includes bracket orders
648///
649/// This follows Rust idioms like `Read + Seek` or `Iterator + ExactSizeIterator`.
650///
651/// # Why Supertrait Over Alternatives
652///
653/// **vs. associated types on `ExecutionClient`**: Callers can't construct
654/// `Self::BracketRequest` without knowing the concrete type — adds trait surface
655/// without enabling generic use.
656///
657/// **vs. default impl returning `Unsupported`**: Puts a "dead method" on every
658/// client (MockExecution, BinanceSpot, HyperliquidClient). Compile-time capability
659/// via trait bounds is better than runtime errors.
660///
661/// # Result Types
662///
663/// [`BracketOrderResult`] uses `Option<Order>` for child legs to document API divergence:
664///
665/// | Exchange | `take_profit` | `stop_loss` | Reason |
666/// |----------|---------------|-------------|--------|
667/// | IBKR     | `Some(...)` | `Some(...)` | Returns all three orders immediately |
668/// | Alpaca   | `None` | `None` | Child legs created server-side |
669///
670/// # Example
671///
672/// ```ignore
673/// use rustrade_execution::client::{ExecutionClient, BracketOrderClient};
674/// use rustrade_execution::order::bracket::{BracketOrderRequest, RequestOpenBracket};
675///
676/// async fn place_bracket<C: ExecutionClient + BracketOrderClient>(
677///     client: &C,
678///     request: BracketOrderRequest<ExchangeId, &InstrumentNameExchange>,
679/// ) -> BracketOrderResult {
680///     client.open_bracket_order(request).await
681/// }
682/// ```
683pub trait BracketOrderClient: ExecutionClient {
684    /// Place a bracket order (entry + take-profit + stop-loss).
685    ///
686    /// # Request
687    ///
688    /// The [`BracketOrderRequest`] contains:
689    /// - `key`: Order key (exchange, instrument, strategy, client order ID)
690    /// - `state`: [`RequestOpenBracket`](crate::order::bracket::RequestOpenBracket) with
691    ///   side, quantity, prices, and optional stop-loss limit price
692    ///
693    /// # Constraints
694    ///
695    /// - `time_in_force` must be `Day` or `GoodUntilCancelled` on most exchanges
696    /// - Entry order type is always `Limit`
697    /// - Price ordering must be valid for the side (see [`RequestOpenBracket`](crate::order::bracket::RequestOpenBracket))
698    ///
699    /// # Exchange-Specific Field Handling
700    ///
701    /// `RequestOpenBracket::stop_loss_limit_price` is **not honored uniformly**:
702    /// - **Alpaca**: When `Some`, the stop-loss leg becomes a stop-limit order at that price.
703    /// - **IBKR**: Silently ignored — the stop-loss leg is always a stop (market) order.
704    ///
705    /// Generic callers `T: BracketOrderClient` must treat this field as advisory.
706    ///
707    /// # Return Value
708    ///
709    /// Returns [`BracketOrderResult`] with:
710    /// - `parent`: Always present (entry order)
711    /// - `take_profit`: `Some` if exchange returns legs immediately (IBKR), `None` otherwise (Alpaca)
712    /// - `stop_loss`: `Some` if exchange returns legs immediately (IBKR), `None` otherwise (Alpaca)
713    ///
714    /// Either all orders are `Active(Open)` or all are `Inactive` (placement failed), with one
715    /// exception: a leg of a failed placement whose fate at the venue is unknown (no status
716    /// arrived, or it was accepted and its rollback cancel could not be sent) is returned
717    /// `Active(Open)`, so the account stream can resolve it. Only IBKR returns such legs today;
718    /// see its `open_bracket_order`.
719    fn open_bracket_order(
720        &self,
721        request: BracketOrderRequest<ExchangeId, &InstrumentNameExchange>,
722    ) -> impl Future<Output = BracketOrderResult> + Send;
723}
724
725/// Extension trait for clients that can say how an order ended at the venue.
726///
727/// A client that loses its account stream recovers the fills it missed when it reconnects, but not
728/// an order that was cancelled, expired or rejected in the meantime: the event that said so went
729/// out while nothing was listening. The engine then keeps such an order as live until a complete
730/// account snapshot no longer lists it, and even then cannot tell how it ended. This trait is the
731/// lookup that answers that: given the orders a caller still holds as live, it returns how each one
732/// that has ended did end.
733///
734/// # By order, not by time
735///
736/// The obvious alternative, asking the venue for every order closed since the disconnect, does not
737/// work. Binance's `allOrders` and Alpaca's `GET /v2/orders?status=closed` both filter their time
738/// window on when an order was **created**, so a window opening at the disconnect cannot see an
739/// order placed before it and cancelled during it — which is the order that matters, because the
740/// caller is tracking it. Looking each order up by its client order id finds it whenever it was
741/// placed.
742///
743/// # Type-Level Capability
744///
745/// A supertrait of [`ExecutionClient`], for the reason [`BracketOrderClient`] is one: a client that
746/// cannot look orders up does not implement it, rather than carrying a method that fails at run
747/// time. A caller that needs the lookup bounds on `ExecutionClient + OrderStatusClient`.
748pub trait OrderStatusClient: ExecutionClient {
749    /// How each of `orders` ended, for those that have.
750    ///
751    /// # Contract
752    ///
753    /// - One entry per order that has ended, in no particular order:
754    ///   [`FullyFilled`](crate::order::state::InactiveOrderState::FullyFilled),
755    ///   [`Cancelled`](crate::order::state::InactiveOrderState::Cancelled) carrying what filled
756    ///   before it, [`Expired`](crate::order::state::InactiveOrderState::Expired), or
757    ///   [`OpenFailed`](crate::order::state::InactiveOrderState::OpenFailed) for an order the venue
758    ///   accepted for processing and later rejected (Binance `REJECTED`, Alpaca `rejected`). An
759    ///   order rejected in the response to its open request was answered there and is not expected
760    ///   here.
761    /// - An order still live is **omitted**, and so is one the venue does not know. Neither is an
762    ///   error. A caller compares the result with what it asked for.
763    /// - An empty `orders` returns an empty list. Unlike
764    ///   [`ExecutionClient::fetch_open_orders`]'s empty slice, it does not mean "all".
765    /// - An order is found by its [`cid`](crate::order::OrderKey::cid), and each returned order
766    ///   carries the key it was asked for, so a `strategy` the venue does not record survives.
767    /// - A key whose `instrument` is not the one the order traded is treated as unknown. The
768    ///   `exchange` is not checked: a client answers for its own venue.
769    /// - A `cid` asked about more than once is reported at most once, under the first key that
770    ///   finds it.
771    ///
772    /// # Errors
773    ///
774    /// `Err` if the venue could not answer for every order. A partial list is never returned,
775    /// because an order missing from it would read as still live.
776    fn fetch_ended_orders(
777        &self,
778        orders: &[UnindexedOrderKey],
779    ) -> impl Future<Output = Result<Vec<UnindexedInactiveOrder>, UnindexedClientError>> + Send;
780}
781
782/// Extension trait for clients that can say what the venue would lend for a short sale.
783///
784/// Answers, before an order is sent, the question a short sale otherwise learns only from its
785/// rejection: whether the instrument may be sold short, whether it is easy to borrow, how much the
786/// venue has to lend and at what fee. Each venue reports a different subset, so each field of the
787/// [`Shortability`] it returns is optional; the implementations say which fields they fill.
788///
789/// # Type-Level Capability
790///
791/// A supertrait of [`ExecutionClient`], for the reason [`BracketOrderClient`] is one: a client
792/// whose venue has nothing to lend, or that does not report it, does not implement it. A simulated
793/// venue reads the same [`Shortability`] from a
794/// [`ShortabilityProvider`](crate::shortability::ShortabilityProvider) instead.
795pub trait ShortabilityClient: ExecutionClient {
796    /// What the venue says about lending `instrument` for a short sale.
797    ///
798    /// # Contract
799    ///
800    /// - **Advisory.** `Ok` describes the venue's lending as it reported it, not a promise to lend:
801    ///   a short sale must still handle
802    ///   [`ApiError::BorrowRejected`](crate::error::ApiError::BorrowRejected).
803    /// - **Not this account's capacity.** [`Shortability::available`] is what the venue has to
804    ///   lend, not what is left of it for this account; that is
805    ///   [`BorrowCapacityClient::fetch_borrow_capacity`], where a venue reports it.
806    /// - **May be expensive.** An implementation may make several requests, some of them heavy
807    ///   against the venue's rate limit, or hold a scarce resource such as a market data line;
808    ///   each says what it costs. Fetch it when deciding on a short, not on every tick.
809    /// - **May be slow.** Where the venue streams its answer rather than replying to a request,
810    ///   the call waits for it, up to a timeout the implementation documents: seconds, not
811    ///   milliseconds.
812    /// - **May outlive its future.** An implementation that reads on a blocking thread finishes
813    ///   that read, and releases what it holds, even when the returned future is dropped first;
814    ///   each says so.
815    ///
816    /// # Errors
817    ///
818    /// - [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) for an
819    ///   instrument the venue does not know, or one of a kind that is not sold short by borrowing
820    ///   it, such as an option.
821    /// - An error, rather than a [`Shortability`] with nothing known, when the venue does not
822    ///   answer, including when the account is not entitled to the answer, such as one without the
823    ///   market data subscription a venue sends it through.
824    fn fetch_shortability(
825        &self,
826        instrument: &InstrumentNameExchange,
827    ) -> impl Future<Output = Result<Shortability, UnindexedClientError>> + Send;
828}
829
830/// Extension trait for clients that can say how much more this account can borrow.
831///
832/// Where [`ShortabilityClient`] says what the venue has to lend, this says how much of it this
833/// account could take now, given its collateral, its limit and what it has already borrowed. The
834/// two are separate types because they are different facts; see [`BorrowCapacity`].
835///
836/// # Type-Level Capability
837///
838/// A supertrait of [`ExecutionClient`], for the reason [`BracketOrderClient`] is one. Only a venue
839/// that lends against an account's collateral and reports what is left of it implements it.
840pub trait BorrowCapacityClient: ExecutionClient {
841    /// How much this account can borrow now for an order on `instrument` on `side`.
842    ///
843    /// A sell borrows the instrument's base asset, which is a short; a buy borrows its quote asset,
844    /// which is a leveraged long. The result names that asset, and its amounts are in its units.
845    ///
846    /// # Contract
847    ///
848    /// **Advisory**, as [`BorrowCapacity`] says: the amounts are not reserved, so an order sized to
849    /// them must still handle [`ApiError::BorrowRejected`](crate::error::ApiError::BorrowRejected).
850    ///
851    /// # Errors
852    ///
853    /// [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) for an instrument
854    /// the client cannot borrow against, such as a pair the venue does not trade on margin.
855    fn fetch_borrow_capacity(
856        &self,
857        instrument: &InstrumentNameExchange,
858        side: Side,
859    ) -> impl Future<Output = Result<BorrowCapacity, UnindexedClientError>> + Send;
860}
861
862/// The capability table, pinned.
863///
864/// [`ExecutionClient::SUPPORTED_KINDS`] is a `const`: widening one, or adding a kind a client builds
865/// no request for, compiles and passes clippy. The only thing it changes is which instruments
866/// [`ExecutionBuilder`](https://docs.rs/rustrade/latest/rustrade/execution/builder/struct.ExecutionBuilder.html)
867/// admits — so the failure mode is not a broken build but an instrument reaching a venue that cannot
868/// encode it, as a silently wrong order. These assertions exist so that changing a client's declared
869/// capabilities is a deliberate edit to a test that says what the venue can route, rather than a
870/// one-word diff nothing observes.
871///
872/// The real-client cases are each gated on their own feature, matching the module gates above; the
873/// mock case is ungated, like its module. So with `default = []`, a bare
874/// `cargo test -p rustrade-execution` compiles only the mock assertion — pinning a real client's
875/// capabilities requires `--features <name>` or `--all-features`.
876#[cfg(test)]
877mod tests {
878    use super::*;
879    use crate::client::mock::MockExecution;
880
881    #[test]
882    fn mock_supports_only_the_kinds_it_can_model() {
883        // No expiry, funding schedule or contract chain in `MockExchange`, so `Perpetual`, `Future`
884        // and `Option` have no faithful projection onto it. Kept in step with the projection in
885        // `generate_mock_exchange_instruments`, which panics on a kind it cannot project.
886        assert_eq!(
887            <MockExecution<fn() -> DateTime<Utc>> as ExecutionClient>::SUPPORTED_KINDS,
888            &[
889                InstrumentKindDiscriminant::Spot,
890                InstrumentKindDiscriminant::Cfd
891            ]
892        );
893    }
894
895    #[cfg(feature = "binance")]
896    #[test]
897    fn binance_spot_and_margin_are_spot_only() {
898        use crate::client::binance::{BinanceMargin, BinanceSpot};
899
900        assert_eq!(
901            BinanceSpot::SUPPORTED_KINDS,
902            &[InstrumentKindDiscriminant::Spot]
903        );
904        // Cross margin trades the same spot instruments on borrowed funds -- the leverage is in the
905        // account, not the instrument kind.
906        assert_eq!(
907            BinanceMargin::SUPPORTED_KINDS,
908            &[InstrumentKindDiscriminant::Spot]
909        );
910    }
911
912    #[cfg(feature = "hyperliquid")]
913    #[test]
914    fn hyperliquid_splits_perpetual_and_spot_across_two_clients() {
915        use crate::client::hyperliquid::{HyperliquidClient, spot::HyperliquidSpotClient};
916
917        assert_eq!(
918            HyperliquidClient::SUPPORTED_KINDS,
919            &[InstrumentKindDiscriminant::Perpetual]
920        );
921        assert_eq!(
922            HyperliquidSpotClient::SUPPORTED_KINDS,
923            &[InstrumentKindDiscriminant::Spot]
924        );
925    }
926
927    #[cfg(feature = "alpaca")]
928    #[test]
929    fn alpaca_trades_equities_and_options() {
930        use crate::client::alpaca::AlpacaClient;
931
932        assert_eq!(
933            AlpacaClient::SUPPORTED_KINDS,
934            &[
935                InstrumentKindDiscriminant::Spot,
936                InstrumentKindDiscriminant::Option
937            ]
938        );
939    }
940
941    #[cfg(feature = "ibkr")]
942    #[test]
943    fn ibkr_omits_cfd_because_it_builds_no_contract_for_one() {
944        use crate::client::ibkr::IbkrClient;
945
946        // `ContractConfig::to_contract` builds `STK`, `FUT`, `OPT` and `CASH` and nothing else, so a
947        // CFD routed here would be encoded as some other security type -- exactly the silent
948        // wrong-symbol order this const exists to reject. Adding `Cfd` to the list requires adding
949        // the arm first.
950        assert_eq!(
951            IbkrClient::SUPPORTED_KINDS,
952            &[
953                InstrumentKindDiscriminant::Spot,
954                InstrumentKindDiscriminant::Future,
955                InstrumentKindDiscriminant::Option
956            ]
957        );
958    }
959}