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. Gated on the clients that use it
83// so a build selecting none of them does not compile it unused. Alpaca deduplicates too, but
84// against a raw `SmolStr` fill key rather than this cache, so it is deliberately not in this list.
85#[cfg(any(feature = "binance", feature = "hyperliquid", feature = "ibkr"))]
86pub(crate) mod dedup;
87
88// What a client knows of its live orders, and the reconnect check of how those orders ended while
89// its account stream was down. Gated on the clients that use it, like `dedup`.
90#[cfg(any(
91    feature = "alpaca",
92    feature = "binance",
93    feature = "hyperliquid",
94    feature = "ibkr"
95))]
96pub(crate) mod order_recovery;
97
98// Alpaca ExecutionClient implementation (options, equities, crypto — single unified API)
99#[cfg(feature = "alpaca")]
100pub mod alpaca;
101
102// Binance ExecutionClient implementations: Spot (live) and Cross Margin (identity/config scaffolding)
103#[cfg(feature = "binance")]
104pub mod binance;
105
106// Hyperliquid perpetual futures and spot ExecutionClient implementations
107#[cfg(feature = "hyperliquid")]
108pub mod hyperliquid;
109
110// Interactive Brokers ExecutionClient implementation (equities, futures, options, forex)
111#[cfg(feature = "ibkr")]
112pub mod ibkr;
113
114pub mod mock;
115
116/// An instrument an [`ExecutionClient`] is about to be built to trade, as
117/// [`ExecutionClient::validate_config`] sees it.
118///
119/// `#[non_exhaustive]`, so further detail can be added without breaking an implementation that
120/// reads these fields; construct one with [`Self::new`].
121#[derive(Debug, Clone, Copy, Eq, PartialEq)]
122#[non_exhaustive]
123pub struct ClientInstrument<'a> {
124    /// The name the venue knows the instrument by, which is what a client's requests carry.
125    pub name_exchange: &'a InstrumentNameExchange,
126    /// The instrument's kind.
127    pub kind: InstrumentKindDiscriminant,
128}
129
130impl<'a> ClientInstrument<'a> {
131    /// The view of an instrument named `name_exchange`, of kind `kind`.
132    pub fn new(
133        name_exchange: &'a InstrumentNameExchange,
134        kind: InstrumentKindDiscriminant,
135    ) -> Self {
136        Self {
137            name_exchange,
138            kind,
139        }
140    }
141}
142
143// `+ Send` bounds on async method return types required for multi-threaded
144// Tokio runtime. This is a breaking change vs upstream — any `!Send` executor
145// implementation would fail to compile.
146pub trait ExecutionClient
147where
148    Self: Clone,
149{
150    const EXCHANGE: ExchangeId;
151
152    /// The [`InstrumentKindDiscriminant`]s this client can trade.
153    ///
154    /// A client works off [`InstrumentNameExchange`] strings and never inspects an instrument's
155    /// kind, so nothing downstream can infer this from the implementation — routing a `Future`
156    /// through a spot-only venue produces a rejected or, worse, misinterpreted order rather than a
157    /// type error. Declaring the set here lets [`ExecutionBuilder`] reject an unsupported
158    /// instrument set at build time, before any order is sent.
159    ///
160    /// Declare what the *venue and this implementation together* can actually route, not what the
161    /// exchange's product catalogue advertises. A kind the exchange offers but this client builds
162    /// no request for does not belong in the set.
163    ///
164    /// There is deliberately no default. A new client must state its capabilities rather than
165    /// inherit a permissive set that would silently admit every kind.
166    ///
167    /// It is a `const` and not a `fn supported_kinds(&self)` because [`ExecutionBuilder`] validates
168    /// the instrument set *before* [`Self::new`] is ever called — there is no instance to ask at the
169    /// point the answer is needed, and deferring validation until after construction would mean
170    /// standing up a client for a venue the engine is about to reject. A capability set that varies
171    /// with `Self::Config` therefore cannot be expressed here; it would need a separate
172    /// pre-construction hook on the config.
173    ///
174    /// [`ExecutionBuilder`]: https://docs.rs/rustrade/latest/rustrade/execution/builder/struct.ExecutionBuilder.html
175    const SUPPORTED_KINDS: &'static [InstrumentKindDiscriminant];
176
177    type Config: Clone;
178
179    /// Checks `config` against the instruments this client is about to be built to trade, before
180    /// [`Self::new`] is called. `Err` names what is wrong.
181    ///
182    /// [`SUPPORTED_KINDS`](Self::SUPPORTED_KINDS) rejects a kind the client cannot route at all.
183    /// This catches what only the config knows: a per-instrument entry that is invalid, or that
184    /// disagrees with the instrument it is keyed to, such as a contract registered as a stock for
185    /// an instrument modelled as an option. Each such entry would otherwise be skipped or acted on
186    /// silently once the client runs.
187    ///
188    /// The default accepts every config. Override it when `Self::Config` carries per-instrument
189    /// detail.
190    ///
191    /// [`ExecutionBuilder`] calls it, after checking `SUPPORTED_KINDS`, with the instruments
192    /// registered on this client's exchange. A client constructed by calling `new` directly is not
193    /// checked; call this first to get the same check.
194    ///
195    /// [`ExecutionBuilder`]: https://docs.rs/rustrade/latest/rustrade/execution/builder/struct.ExecutionBuilder.html
196    fn validate_config(
197        config: &Self::Config,
198        instruments: &[ClientInstrument<'_>],
199    ) -> Result<(), String> {
200        let _ = (config, instruments);
201        Ok(())
202    }
203
204    // `+ Send` required so generic code (e.g. ExecutionManager) can pass
205    // the stream to tokio::spawn, which requires Send.
206    type AccountStream: Stream<Item = UnindexedAccountEvent> + Send;
207
208    fn new(config: Self::Config) -> Self;
209
210    /// Reads the account's balances, and its open orders and positions for `instruments`, from the
211    /// venue.
212    ///
213    /// Besides startup, the engine's `ExecutionManager` calls this again on every account-stream
214    /// reconnect, and emits the result ahead of the new stream's updates. It is how the engine
215    /// catches up on what changed while the stream was down.
216    ///
217    /// # Order completeness
218    ///
219    /// Each [`InstrumentAccountSnapshot`](crate::InstrumentAccountSnapshot) states through
220    /// `orders_complete` whether its `orders` list is every order open at the venue for that
221    /// instrument. Set it only when it is true: the engine retires a tracked order that a complete
222    /// list omits, so a list that can miss an open order (a capped page, an order dropped on
223    /// conversion, an order reported under an id other than the one it was placed with) must say
224    /// `false`. `false` is always safe; it only forgoes that reconciliation.
225    fn account_snapshot(
226        &self,
227        assets: &[AssetNameExchange],
228        instruments: &[InstrumentNameExchange],
229    ) -> impl Future<Output = Result<UnindexedAccountSnapshot, UnindexedClientError>> + Send;
230
231    /// Returns a live stream of account events (fills, order updates, balance changes).
232    ///
233    /// # Startup race window
234    ///
235    /// There is an unavoidable gap between the WebSocket subscribe response and the
236    /// first event being delivered: fills arriving in this window (typically milliseconds,
237    /// no sub-millisecond guarantee) are silently dropped. `account_snapshot` reconciles
238    /// open-order state, but TRADE fills in this window are not recoverable from the stream
239    /// alone. Callers that require fill completeness at startup **must** call
240    /// [`ExecutionClient::fetch_trades`] with at least a 1-second lookback after this method returns.
241    ///
242    /// # Backpressure
243    ///
244    /// Implementations use unbounded internal channels. If the consumer cannot keep up,
245    /// events queue in memory rather than being dropped — per library philosophy, OOM
246    /// crashes are preferable to silent data loss. Consumers requiring backpressure
247    /// should implement it at their boundary (e.g., bounded channel with overflow policy).
248    fn account_stream(
249        &self,
250        assets: &[AssetNameExchange],
251        instruments: &[InstrumentNameExchange],
252    ) -> impl Future<Output = Result<Self::AccountStream, UnindexedClientError>> + Send;
253
254    /// Cancel an order at the venue.
255    ///
256    /// # Return value
257    ///
258    /// Every request gets exactly one answer, which the engine's `ExecutionManager` forwards as the
259    /// order's response. An implementation must not swallow a request: a failure to send it, or to
260    /// read the venue's answer, is an `Err`.
261    ///
262    /// - `Ok(Cancelled)`: the venue took the cancel. Whether the order has *ended* by then depends
263    ///   on the venue; see below.
264    /// - `Err`: the venue refused the cancel, or it could not be sent or answered. The order may
265    ///   still be open, or may have ended some other way, such as by filling. The account stream
266    ///   reports which.
267    ///
268    /// # A taken cancel is not always an ended order
269    ///
270    /// Some venues answer a cancel before carrying it out. Until they do, the order is live and can
271    /// still fill. From those venues `Ok(Cancelled)` means only that the cancel was accepted, and
272    /// the account stream reports how the order actually ended, including any fill in between. The
273    /// engine stops tracking an order on `Ok(Cancelled)` from any venue.
274    ///
275    /// Binance, Hyperliquid and the mock venue answer once the order is cancelled. Alpaca answers
276    /// once it has accepted the cancel, and IBKR once the cancel is submitted. The
277    /// [connector comparison](crate::client#connector-comparison) lists the same for each
278    /// connector; the mock venue is not one, so it has no row there.
279    ///
280    /// # `filled_quantity` and `time_exchange`
281    ///
282    /// `Cancelled::filled_quantity` is the quantity the venue reported filled where the answer
283    /// carries one, which Binance's and the mock venue's do. Alpaca, IBKR and Hyperliquid answer
284    /// without it and report zero, which does not mean nothing filled. The fill total comes from
285    /// the account stream, or from [`Self::fetch_trades`]. Likewise `time_exchange` is the venue's
286    /// time where the answer carries one, and the local time the answer arrived otherwise.
287    fn cancel_order(
288        &self,
289        request: OrderRequestCancel<ExchangeId, &InstrumentNameExchange>,
290    ) -> impl Future<Output = UnindexedOrderResponseCancel> + Send;
291
292    // `+ Send` on default method return types for multi-threaded Tokio runtime
293    fn cancel_orders<'a>(
294        &self,
295        requests: impl IntoIterator<Item = OrderRequestCancel<ExchangeId, &'a InstrumentNameExchange>>,
296    ) -> impl Stream<Item = UnindexedOrderResponseCancel> + Send {
297        futures::stream::FuturesUnordered::from_iter(
298            requests
299                .into_iter()
300                .map(|request| self.cancel_order(request)),
301        )
302    }
303
304    /// Place an order on the exchange.
305    ///
306    /// # Return value
307    ///
308    /// Every request gets exactly one answer, which the engine's `ExecutionManager` forwards as the
309    /// order's response. An implementation must not swallow a request: a failure to send it, or to
310    /// read the venue's answer, is `OpenFailed`.
311    ///
312    /// Returns `OrderState` directly rather than `Result<Open, OrderError>`:
313    /// - `OrderState::Active(Open)` - order is resting on the order book
314    /// - `OrderState::Inactive(FullyFilled)` - order was immediately filled (includes `avg_price` when available)
315    /// - `OrderState::Inactive(Expired)` - order ended in the response itself without filling
316    ///   completely, carrying what filled: an IOC or FOK order that found too little liquidity,
317    ///   or one expired by self-trade prevention
318    /// - `OrderState::Inactive(Cancelled)` - order the venue reports cancelled in the response
319    ///   itself, carrying what filled
320    /// - `OrderState::Inactive(OpenFailed)` - order placement failed (API error, connectivity, a
321    ///   rejection the venue reports in the response, etc.)
322    ///
323    /// An implementation returns `Expired` or `Cancelled` only when its venue reports the order's
324    /// status in the placement response (currently Binance Spot and Margin). The others return
325    /// `Open` for such an order, and their account stream reports how it ended.
326    ///
327    /// This design allows immediate fills to carry metadata (e.g., `avg_price`) that
328    /// would be lost if we had to infer terminal state from `Open::filled_quantity`.
329    fn open_order(
330        &self,
331        request: OrderRequestOpen<ExchangeId, &InstrumentNameExchange>,
332    ) -> impl Future<Output = Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>> + Send;
333
334    // `+ Send` on default method return types for multi-threaded Tokio runtime
335    fn open_orders<'a>(
336        &self,
337        requests: impl IntoIterator<Item = OrderRequestOpen<ExchangeId, &'a InstrumentNameExchange>>,
338    ) -> impl Stream<Item = Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>> + Send
339    {
340        futures::stream::FuturesUnordered::from_iter(
341            requests.into_iter().map(|request| self.open_order(request)),
342        )
343    }
344
345    /// Fetch current balances for the specified assets.
346    ///
347    /// An empty `assets` slice is the "return all" sentinel: implementations must return
348    /// balances for every asset held. When non-empty, only the listed assets are returned.
349    fn fetch_balances(
350        &self,
351        assets: &[AssetNameExchange],
352    ) -> impl Future<Output = Result<Vec<AssetBalance<AssetNameExchange>>, UnindexedClientError>> + Send;
353
354    /// Fetch currently open orders, optionally filtered by instrument.
355    ///
356    /// An empty `instruments` slice is the "return all" sentinel: implementations must
357    /// return open orders across all instruments. When non-empty, only orders for the
358    /// listed instruments are returned.
359    fn fetch_open_orders(
360        &self,
361        instruments: &[InstrumentNameExchange],
362    ) -> impl Future<
363        Output = Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError>,
364    > + Send;
365
366    /// Read the trades (fills) from `start` to `end`, both inclusive, optionally filtered by
367    /// instrument.
368    ///
369    /// An empty `instruments` slice is the "return all" sentinel: implementations must
370    /// return trades across all instruments. When non-empty, only trades for the listed
371    /// instruments are returned.
372    ///
373    /// # Bounded, resumable reads
374    ///
375    /// One call is bounded by the venue's limits, so it may stop before `end`.
376    /// [`TradesRead::resume`] says whether it did:
377    /// - `None`: every fill in the span the venue still holds was read.
378    /// - `Some(t)`: call again with `start = t` and the same `end` to read on. That read can
379    ///   return again fills the previous one returned, so match them by instrument and
380    ///   [`TradeId`](crate::trade::TradeId).
381    ///
382    /// The caller owns the loop, and with it how many calls, and how long, it spends on a span.
383    /// A `start` after `end` is an empty span, read as no trades and `resume: None`.
384    ///
385    /// # Venue limits
386    ///
387    /// `resume: None` covers what the venue still holds, which can be less than the span:
388    /// - IBKR returns the current trading day's executions only.
389    /// - Hyperliquid keeps only each wallet's 10,000 most recent fills.
390    ///
391    /// Binance needs instruments: an empty slice reads nothing. Each client documents its limits.
392    ///
393    /// # Errors
394    ///
395    /// [`Truncated`](crate::error::ClientError::Truncated) when a read cannot advance, because
396    /// more fills share the span's first moment than one call can read past.
397    ///
398    /// The fee asset (`AssetNameExchange`) may be quote, base, or third-party (e.g., BNB).
399    /// Use `fees.fees_quote` for quote-equivalent value when available.
400    fn fetch_trades(
401        &self,
402        start: DateTime<Utc>,
403        end: DateTime<Utc>,
404        instruments: &[InstrumentNameExchange],
405    ) -> impl Future<
406        Output = Result<
407            TradesRead<AssetNameExchange, InstrumentNameExchange>,
408            UnindexedClientError,
409        >,
410    > + Send;
411}
412
413/// Extension trait for exchanges that support native bracket orders.
414///
415/// A bracket order consists of three linked orders:
416/// 1. **Entry**: Limit order to enter the position
417/// 2. **Take Profit**: Limit order to exit at profit target
418/// 3. **Stop Loss**: Stop (or stop-limit) order to exit at loss limit
419///
420/// When either exit leg fills, the exchange automatically cancels the other.
421///
422/// # Type-Level Capability
423///
424/// This is a supertrait of [`ExecutionClient`], enabling compile-time capability checks:
425/// - `impl ExecutionClient` — basic order operations
426/// - `impl ExecutionClient + BracketOrderClient` — includes bracket orders
427///
428/// This follows Rust idioms like `Read + Seek` or `Iterator + ExactSizeIterator`.
429///
430/// # Why Supertrait Over Alternatives
431///
432/// **vs. associated types on `ExecutionClient`**: Callers can't construct
433/// `Self::BracketRequest` without knowing the concrete type — adds trait surface
434/// without enabling generic use.
435///
436/// **vs. default impl returning `Unsupported`**: Puts a "dead method" on every
437/// client (MockExecution, BinanceSpot, HyperliquidClient). Compile-time capability
438/// via trait bounds is better than runtime errors.
439///
440/// # Result Types
441///
442/// [`BracketOrderResult`] uses `Option<Order>` for child legs to document API divergence:
443///
444/// | Exchange | `take_profit` | `stop_loss` | Reason |
445/// |----------|---------------|-------------|--------|
446/// | IBKR     | `Some(...)` | `Some(...)` | Returns all three orders immediately |
447/// | Alpaca   | `None` | `None` | Child legs created server-side |
448///
449/// # Example
450///
451/// ```ignore
452/// use rustrade_execution::client::{ExecutionClient, BracketOrderClient};
453/// use rustrade_execution::order::bracket::{BracketOrderRequest, RequestOpenBracket};
454///
455/// async fn place_bracket<C: ExecutionClient + BracketOrderClient>(
456///     client: &C,
457///     request: BracketOrderRequest<ExchangeId, &InstrumentNameExchange>,
458/// ) -> BracketOrderResult {
459///     client.open_bracket_order(request).await
460/// }
461/// ```
462pub trait BracketOrderClient: ExecutionClient {
463    /// Place a bracket order (entry + take-profit + stop-loss).
464    ///
465    /// # Request
466    ///
467    /// The [`BracketOrderRequest`] contains:
468    /// - `key`: Order key (exchange, instrument, strategy, client order ID)
469    /// - `state`: [`RequestOpenBracket`](crate::order::bracket::RequestOpenBracket) with
470    ///   side, quantity, prices, and optional stop-loss limit price
471    ///
472    /// # Constraints
473    ///
474    /// - `time_in_force` must be `Day` or `GoodUntilCancelled` on most exchanges
475    /// - Entry order type is always `Limit`
476    /// - Price ordering must be valid for the side (see [`RequestOpenBracket`](crate::order::bracket::RequestOpenBracket))
477    ///
478    /// # Exchange-Specific Field Handling
479    ///
480    /// `RequestOpenBracket::stop_loss_limit_price` is **not honored uniformly**:
481    /// - **Alpaca**: When `Some`, the stop-loss leg becomes a stop-limit order at that price.
482    /// - **IBKR**: Silently ignored — the stop-loss leg is always a stop (market) order.
483    ///
484    /// Generic callers `T: BracketOrderClient` must treat this field as advisory.
485    ///
486    /// # Return Value
487    ///
488    /// Returns [`BracketOrderResult`] with:
489    /// - `parent`: Always present (entry order)
490    /// - `take_profit`: `Some` if exchange returns legs immediately (IBKR), `None` otherwise (Alpaca)
491    /// - `stop_loss`: `Some` if exchange returns legs immediately (IBKR), `None` otherwise (Alpaca)
492    ///
493    /// Either all orders are `Active(Open)` or all are `Inactive` (placement failed), with one
494    /// exception: a leg of a failed placement whose fate at the venue is unknown (no status
495    /// arrived, or it was accepted and its rollback cancel could not be sent) is returned
496    /// `Active(Open)`, so the account stream can resolve it. Only IBKR returns such legs today;
497    /// see its `open_bracket_order`.
498    fn open_bracket_order(
499        &self,
500        request: BracketOrderRequest<ExchangeId, &InstrumentNameExchange>,
501    ) -> impl Future<Output = BracketOrderResult> + Send;
502}
503
504/// Extension trait for clients that can say how an order ended at the venue.
505///
506/// A client that loses its account stream recovers the fills it missed when it reconnects, but not
507/// an order that was cancelled, expired or rejected in the meantime: the event that said so went
508/// out while nothing was listening. The engine then keeps such an order as live until a complete
509/// account snapshot no longer lists it, and even then cannot tell how it ended. This trait is the
510/// lookup that answers that: given the orders a caller still holds as live, it returns how each one
511/// that has ended did end.
512///
513/// # By order, not by time
514///
515/// The obvious alternative, asking the venue for every order closed since the disconnect, does not
516/// work. Binance's `allOrders` and Alpaca's `GET /v2/orders?status=closed` both filter their time
517/// window on when an order was **created**, so a window opening at the disconnect cannot see an
518/// order placed before it and cancelled during it — which is the order that matters, because the
519/// caller is tracking it. Looking each order up by its client order id finds it whenever it was
520/// placed.
521///
522/// # Type-Level Capability
523///
524/// A supertrait of [`ExecutionClient`], for the reason [`BracketOrderClient`] is one: a client that
525/// cannot look orders up does not implement it, rather than carrying a method that fails at run
526/// time. A caller that needs the lookup bounds on `ExecutionClient + OrderStatusClient`.
527pub trait OrderStatusClient: ExecutionClient {
528    /// How each of `orders` ended, for those that have.
529    ///
530    /// # Contract
531    ///
532    /// - One entry per order that has ended, in no particular order:
533    ///   [`FullyFilled`](crate::order::state::InactiveOrderState::FullyFilled),
534    ///   [`Cancelled`](crate::order::state::InactiveOrderState::Cancelled) carrying what filled
535    ///   before it, [`Expired`](crate::order::state::InactiveOrderState::Expired), or
536    ///   [`OpenFailed`](crate::order::state::InactiveOrderState::OpenFailed) for an order the venue
537    ///   accepted for processing and later rejected (Binance `REJECTED`, Alpaca `rejected`). An
538    ///   order rejected in the response to its open request was answered there and is not expected
539    ///   here.
540    /// - An order still live is **omitted**, and so is one the venue does not know. Neither is an
541    ///   error. A caller compares the result with what it asked for.
542    /// - An empty `orders` returns an empty list. Unlike
543    ///   [`ExecutionClient::fetch_open_orders`]'s empty slice, it does not mean "all".
544    /// - An order is found by its [`cid`](crate::order::OrderKey::cid), and each returned order
545    ///   carries the key it was asked for, so a `strategy` the venue does not record survives.
546    /// - A key whose `instrument` is not the one the order traded is treated as unknown. The
547    ///   `exchange` is not checked: a client answers for its own venue.
548    /// - A `cid` asked about more than once is reported at most once, under the first key that
549    ///   finds it.
550    ///
551    /// # Errors
552    ///
553    /// `Err` if the venue could not answer for every order. A partial list is never returned,
554    /// because an order missing from it would read as still live.
555    fn fetch_ended_orders(
556        &self,
557        orders: &[UnindexedOrderKey],
558    ) -> impl Future<Output = Result<Vec<UnindexedInactiveOrder>, UnindexedClientError>> + Send;
559}
560
561/// Extension trait for clients that can say what the venue would lend for a short sale.
562///
563/// Answers, before an order is sent, the question a short sale otherwise learns only from its
564/// rejection: whether the instrument may be sold short, whether it is easy to borrow, how much the
565/// venue has to lend and at what fee. Each venue reports a different subset, so each field of the
566/// [`Shortability`] it returns is optional; the implementations say which fields they fill.
567///
568/// # Type-Level Capability
569///
570/// A supertrait of [`ExecutionClient`], for the reason [`BracketOrderClient`] is one: a client
571/// whose venue has nothing to lend, or that does not report it, does not implement it. A simulated
572/// venue reads the same [`Shortability`] from a
573/// [`ShortabilityProvider`](crate::shortability::ShortabilityProvider) instead.
574pub trait ShortabilityClient: ExecutionClient {
575    /// What the venue says about lending `instrument` for a short sale.
576    ///
577    /// # Contract
578    ///
579    /// - **Advisory.** `Ok` describes the venue's lending as it reported it, not a promise to lend:
580    ///   a short sale must still handle
581    ///   [`ApiError::BorrowRejected`](crate::error::ApiError::BorrowRejected).
582    /// - **Not this account's capacity.** [`Shortability::available`] is what the venue has to
583    ///   lend, not what is left of it for this account; that is
584    ///   [`BorrowCapacityClient::fetch_borrow_capacity`], where a venue reports it.
585    /// - **May be expensive.** An implementation may make several requests, some of them heavy
586    ///   against the venue's rate limit, or hold a scarce resource such as a market data line;
587    ///   each says what it costs. Fetch it when deciding on a short, not on every tick.
588    /// - **May be slow.** Where the venue streams its answer rather than replying to a request,
589    ///   the call waits for it, up to a timeout the implementation documents: seconds, not
590    ///   milliseconds.
591    /// - **May outlive its future.** An implementation that reads on a blocking thread finishes
592    ///   that read, and releases what it holds, even when the returned future is dropped first;
593    ///   each says so.
594    ///
595    /// # Errors
596    ///
597    /// - [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) for an
598    ///   instrument the venue does not know, or one of a kind that is not sold short by borrowing
599    ///   it, such as an option.
600    /// - An error, rather than a [`Shortability`] with nothing known, when the venue does not
601    ///   answer, including when the account is not entitled to the answer, such as one without the
602    ///   market data subscription a venue sends it through.
603    fn fetch_shortability(
604        &self,
605        instrument: &InstrumentNameExchange,
606    ) -> impl Future<Output = Result<Shortability, UnindexedClientError>> + Send;
607}
608
609/// Extension trait for clients that can say how much more this account can borrow.
610///
611/// Where [`ShortabilityClient`] says what the venue has to lend, this says how much of it this
612/// account could take now, given its collateral, its limit and what it has already borrowed. The
613/// two are separate types because they are different facts; see [`BorrowCapacity`].
614///
615/// # Type-Level Capability
616///
617/// A supertrait of [`ExecutionClient`], for the reason [`BracketOrderClient`] is one. Only a venue
618/// that lends against an account's collateral and reports what is left of it implements it.
619pub trait BorrowCapacityClient: ExecutionClient {
620    /// How much this account can borrow now for an order on `instrument` on `side`.
621    ///
622    /// A sell borrows the instrument's base asset, which is a short; a buy borrows its quote asset,
623    /// which is a leveraged long. The result names that asset, and its amounts are in its units.
624    ///
625    /// # Contract
626    ///
627    /// **Advisory**, as [`BorrowCapacity`] says: the amounts are not reserved, so an order sized to
628    /// them must still handle [`ApiError::BorrowRejected`](crate::error::ApiError::BorrowRejected).
629    ///
630    /// # Errors
631    ///
632    /// [`ApiError::InstrumentInvalid`](crate::error::ApiError::InstrumentInvalid) for an instrument
633    /// the client cannot borrow against, such as a pair the venue does not trade on margin.
634    fn fetch_borrow_capacity(
635        &self,
636        instrument: &InstrumentNameExchange,
637        side: Side,
638    ) -> impl Future<Output = Result<BorrowCapacity, UnindexedClientError>> + Send;
639}
640
641/// The capability table, pinned.
642///
643/// [`ExecutionClient::SUPPORTED_KINDS`] is a `const`: widening one, or adding a kind a client builds
644/// no request for, compiles and passes clippy. The only thing it changes is which instruments
645/// [`ExecutionBuilder`](https://docs.rs/rustrade/latest/rustrade/execution/builder/struct.ExecutionBuilder.html)
646/// admits — so the failure mode is not a broken build but an instrument reaching a venue that cannot
647/// encode it, as a silently wrong order. These assertions exist so that changing a client's declared
648/// capabilities is a deliberate edit to a test that says what the venue can route, rather than a
649/// one-word diff nothing observes.
650///
651/// The real-client cases are each gated on their own feature, matching the module gates above; the
652/// mock case is ungated, like its module. So with `default = []`, a bare
653/// `cargo test -p rustrade-execution` compiles only the mock assertion — pinning a real client's
654/// capabilities requires `--features <name>` or `--all-features`.
655#[cfg(test)]
656mod tests {
657    use super::*;
658    use crate::client::mock::MockExecution;
659
660    #[test]
661    fn mock_supports_only_the_kinds_it_can_model() {
662        // No expiry, funding schedule or contract chain in `MockExchange`, so `Perpetual`, `Future`
663        // and `Option` have no faithful projection onto it. Kept in step with the projection in
664        // `generate_mock_exchange_instruments`, which panics on a kind it cannot project.
665        assert_eq!(
666            <MockExecution<fn() -> DateTime<Utc>> as ExecutionClient>::SUPPORTED_KINDS,
667            &[
668                InstrumentKindDiscriminant::Spot,
669                InstrumentKindDiscriminant::Cfd
670            ]
671        );
672    }
673
674    #[cfg(feature = "binance")]
675    #[test]
676    fn binance_spot_and_margin_are_spot_only() {
677        use crate::client::binance::{BinanceMargin, BinanceSpot};
678
679        assert_eq!(
680            BinanceSpot::SUPPORTED_KINDS,
681            &[InstrumentKindDiscriminant::Spot]
682        );
683        // Cross margin trades the same spot instruments on borrowed funds -- the leverage is in the
684        // account, not the instrument kind.
685        assert_eq!(
686            BinanceMargin::SUPPORTED_KINDS,
687            &[InstrumentKindDiscriminant::Spot]
688        );
689    }
690
691    #[cfg(feature = "hyperliquid")]
692    #[test]
693    fn hyperliquid_splits_perpetual_and_spot_across_two_clients() {
694        use crate::client::hyperliquid::{HyperliquidClient, spot::HyperliquidSpotClient};
695
696        assert_eq!(
697            HyperliquidClient::SUPPORTED_KINDS,
698            &[InstrumentKindDiscriminant::Perpetual]
699        );
700        assert_eq!(
701            HyperliquidSpotClient::SUPPORTED_KINDS,
702            &[InstrumentKindDiscriminant::Spot]
703        );
704    }
705
706    #[cfg(feature = "alpaca")]
707    #[test]
708    fn alpaca_trades_equities_and_options() {
709        use crate::client::alpaca::AlpacaClient;
710
711        assert_eq!(
712            AlpacaClient::SUPPORTED_KINDS,
713            &[
714                InstrumentKindDiscriminant::Spot,
715                InstrumentKindDiscriminant::Option
716            ]
717        );
718    }
719
720    #[cfg(feature = "ibkr")]
721    #[test]
722    fn ibkr_omits_cfd_because_it_builds_no_contract_for_one() {
723        use crate::client::ibkr::IbkrClient;
724
725        // `ContractConfig::to_contract` builds `STK`, `FUT`, `OPT` and `CASH` and nothing else, so a
726        // CFD routed here would be encoded as some other security type -- exactly the silent
727        // wrong-symbol order this const exists to reject. Adding `Cfd` to the list requires adding
728        // the arm first.
729        assert_eq!(
730            IbkrClient::SUPPORTED_KINDS,
731            &[
732                InstrumentKindDiscriminant::Spot,
733                InstrumentKindDiscriminant::Future,
734                InstrumentKindDiscriminant::Option
735            ]
736        );
737    }
738}