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