Skip to main content

rustrade_execution/
error.rs

1//! Error types for [`ExecutionClient`](super::client::ExecutionClient) operations.
2//!
3//! # Retry Semantics
4//!
5//! Use [`ClientError::is_transient`] to determine if an operation should be retried.
6//! Transient errors (connectivity issues, rate limits) may succeed on retry with
7//! appropriate backoff. Non-transient errors (invalid instrument, insufficient
8//! balance) will fail identically on retry — the caller must change the request.
9//!
10//! The `is_transient()` method is the stable contract for retry decisions. Prefer
11//! it over pattern matching on specific variants, as the internal taxonomy may
12//! evolve while `is_transient()` semantics remain stable.
13
14use crate::margin::MarginEffect;
15use derive_more::Constructor;
16use rust_decimal::Decimal;
17use rustrade_instrument::{
18    asset::{AssetIndex, name::AssetNameExchange},
19    exchange::ExchangeId,
20    index::error::IndexError,
21    instrument::{InstrumentIndex, name::InstrumentNameExchange},
22};
23use rustrade_integration::error::SocketError;
24use serde::{Deserialize, Serialize};
25use std::{fmt, time::Duration};
26use thiserror::Error;
27
28/// Type alias for a [`ClientError`] that is keyed on [`AssetNameExchange`] and
29/// [`InstrumentNameExchange`] (yet to be indexed).
30pub type UnindexedClientError = ClientError<AssetNameExchange, InstrumentNameExchange>;
31
32/// Type alias for a [`ApiError`] that is keyed on [`AssetNameExchange`] and
33/// [`InstrumentNameExchange`] (yet to be indexed).
34pub type UnindexedApiError = ApiError<AssetNameExchange, InstrumentNameExchange>;
35
36/// Type alias for a [`OrderError`] that is keyed on [`AssetNameExchange`] and
37/// [`InstrumentNameExchange`] (yet to be indexed).
38pub type UnindexedOrderError = OrderError<AssetNameExchange, InstrumentNameExchange>;
39
40/// Represents all errors produced by an [`ExecutionClient`](super::client::ExecutionClient).
41#[non_exhaustive]
42#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
43pub enum ClientError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
44    /// Connectivity based error.
45    ///
46    /// eg/ Timeout.
47    #[error("Connectivity: {0}")]
48    Connectivity(#[from] ConnectivityError),
49
50    /// API based error.
51    ///
52    /// eg/ RateLimit.
53    #[error("API: {0}")]
54    Api(#[from] ApiError<AssetKey, InstrumentKey>),
55
56    /// A background task panicked or was cancelled during an operation.
57    ///
58    /// This indicates a bug or unexpected runtime condition (e.g., a tokio
59    /// `spawn_blocking` task panicked). The operation was not retried and
60    /// the caller should treat this as non-recoverable, requiring operator
61    /// attention.
62    #[error("task failed: {0}")]
63    TaskFailed(String),
64
65    /// An opaque error from an upstream library that cannot be further classified.
66    ///
67    /// This is a catch-all for errors that don't fit into [`Self::Connectivity`] or
68    /// [`Self::Api`] categories — typically because the upstream library (e.g., ibapi,
69    /// binance-sdk) returns unstructured errors.
70    ///
71    /// Conservatively treated as non-transient. If you encounter this error
72    /// frequently, consider filing an issue to improve error classification.
73    #[error("internal error: {0}")]
74    Internal(String),
75
76    /// A bounded read of fills could not advance past its start: more fills share the span's
77    /// first moment than one call can read, so a read from the same start would stop at the same
78    /// place.
79    ///
80    /// [`ExecutionClient::fetch_trades`](crate::client::ExecutionClient::fetch_trades) returns it
81    /// rather than a [`TradesRead`](crate::trade::TradesRead) whose `resume` could only loop. The
82    /// fills it read are not returned. Callers should alert operators and reconcile the span
83    /// another way.
84    #[error("trade read stopped after {fills_read} fills without advancing past its start")]
85    Truncated {
86        /// How many fills the read returned before it stopped.
87        fills_read: usize,
88    },
89
90    /// Open orders snapshot was truncated at the API's row limit.
91    ///
92    /// Unlike [`Self::Truncated`] (which applies to paginated fill reads), this
93    /// error indicates a single-request endpoint hit its maximum row count.
94    /// Alpaca's `/v2/orders` endpoint caps results at 500; accounts with more
95    /// concurrent open orders will have an incomplete snapshot.
96    ///
97    /// Callers should alert operators — an incomplete order snapshot can cause
98    /// duplicate submissions, missed cancellations, or incorrect position sizing.
99    #[error("open orders snapshot truncated at {limit} results — data may be incomplete")]
100    TruncatedSnapshot {
101        /// Maximum number of rows returned by the single-request endpoint.
102        limit: usize,
103    },
104}
105
106impl<AssetKey, InstrumentKey> ClientError<AssetKey, InstrumentKey> {
107    /// Returns `true` if this error is likely transient and the operation
108    /// may succeed if retried after a suitable backoff.
109    ///
110    /// The caller is responsible for retry limits and backoff strategy.
111    /// This method classifies the error only — it does not implement policy.
112    ///
113    /// # Transient errors
114    /// - [`Connectivity`](Self::Connectivity) errors (timeout, socket, offline)
115    /// - [`Api::RateLimit`](ApiError::RateLimit), though not before its `retry_after`
116    ///
117    /// # Non-transient errors
118    /// - Other [`Api`](Self::Api) errors (invalid instrument, insufficient balance, etc.)
119    /// - [`TaskFailed`](Self::TaskFailed) (indicates a bug)
120    /// - [`Internal`](Self::Internal) (unknown — conservatively non-transient)
121    /// - [`Truncated`](Self::Truncated) / [`TruncatedSnapshot`](Self::TruncatedSnapshot)
122    pub fn is_transient(&self) -> bool {
123        match self {
124            Self::Connectivity(e) => e.is_transient(),
125            Self::Api(ApiError::RateLimit { .. }) => true,
126            Self::Api(_) => false,
127            Self::TaskFailed(_) => false,
128            Self::Internal(_) => false,
129            Self::Truncated { .. } => false,
130            Self::TruncatedSnapshot { .. } => false,
131        }
132    }
133
134    /// The venue's minimum wait before a retry: `Some` only for an
135    /// [`Api::RateLimit`](ApiError::RateLimit) whose venue sent a hint the client could read. See
136    /// [`ApiError::retry_after`].
137    pub fn retry_after(&self) -> Option<Duration> {
138        match self {
139            Self::Api(error) => error.retry_after(),
140            _ => None,
141        }
142    }
143}
144
145/// Represents all connectivity-centric errors.
146///
147/// Connectivity errors are generally intermittent / non-deterministic (eg/ Timeout).
148/// All variants are transient — retry with exponential backoff (typically 1-30s).
149#[non_exhaustive]
150#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
151pub enum ConnectivityError {
152    /// Exchange is offline, likely due to scheduled maintenance.
153    ///
154    /// Transient — retry with backoff. Maintenance windows typically last minutes
155    /// to hours; consider longer backoff intervals (30s-5min) to avoid log spam.
156    #[error("Exchange offline: {0}")]
157    ExchangeOffline(ExchangeId),
158
159    /// Request timed out before a response was received.
160    ///
161    /// Transient — retry with backoff. May indicate network congestion, server
162    /// overload, or an overly aggressive timeout. Consider increasing timeout
163    /// on subsequent attempts.
164    #[error("request timed out")]
165    Timeout,
166
167    /// Network-level socket error (connection refused, reset, DNS failure, etc.).
168    ///
169    /// Transient — retry with backoff. If persistent, may indicate firewall
170    /// issues, incorrect endpoint configuration, or prolonged server outage.
171    #[error("{0}")]
172    Socket(String),
173}
174
175impl From<SocketError> for ConnectivityError {
176    fn from(value: SocketError) -> Self {
177        Self::Socket(value.to_string())
178    }
179}
180
181impl ConnectivityError {
182    /// Returns `true` if this connectivity error is transient.
183    ///
184    /// All connectivity errors are considered transient — they represent
185    /// temporary network or server conditions that may resolve with retry.
186    pub fn is_transient(&self) -> bool {
187        match self {
188            Self::ExchangeOffline(_) => true,
189            Self::Timeout => true,
190            Self::Socket(_) => true,
191        }
192    }
193}
194
195/// Represents all API errors generated by an exchange.
196///
197/// These typically indicate a request is invalid for some reason (eg/ BalanceInsufficient).
198/// Most variants are **not transient** — the same request will fail identically on retry.
199/// The exception is [`RateLimit`](Self::RateLimit), which is transient.
200#[non_exhaustive]
201#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
202pub enum ApiError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
203    /// Provided asset identifier is invalid or not supported.
204    ///
205    /// For example:
206    /// - The [`AssetNameExchange`] was an invalid format.
207    ///
208    /// Not transient — do not retry. The asset identifier must be corrected.
209    ///
210    /// Indexed only when the [`ExecutionInstrumentMap`] holds the asset. Otherwise there is no
211    /// index to carry, and [`AccountEventIndexer`] reports it as
212    /// [`OrderRejected`](Self::OrderRejected) (from an order request) or
213    /// [`RequestRejected`](Self::RequestRejected) (from any other request), holding this error's
214    /// own message.
215    ///
216    /// [`ExecutionInstrumentMap`]: crate::map::ExecutionInstrumentMap
217    /// [`AccountEventIndexer`]: crate::indexer::AccountEventIndexer
218    #[error("asset {0} invalid: {1}")]
219    AssetInvalid(AssetKey, String),
220
221    /// Provided instrument identifier is invalid or not supported.
222    ///
223    /// For example:
224    /// - The exchange does not have a market for an instrument.
225    /// - The [`InstrumentNameExchange`] was an invalid format.
226    ///
227    /// Not transient — do not retry. The instrument identifier must be corrected.
228    ///
229    /// Indexed only when the [`ExecutionInstrumentMap`] holds the instrument; otherwise reported
230    /// as [`AssetInvalid`](Self::AssetInvalid) describes.
231    ///
232    /// [`ExecutionInstrumentMap`]: crate::map::ExecutionInstrumentMap
233    #[error("instrument {0} invalid: {1}")]
234    InstrumentInvalid(InstrumentKey, String),
235
236    /// Request was rejected due to rate limiting.
237    ///
238    /// The exchange enforces request quotas and the caller has exceeded them. The client may
239    /// already have waited and retried within its own bounded retries before surfacing this.
240    ///
241    /// `retry_after` is the venue's own minimum wait, measured from when the client read the
242    /// refusal: do not retry sooner. `None` means the venue sent no hint, or the client cannot
243    /// read it, and is not permission to retry at once. Which clients fill it:
244    /// - **Alpaca:** from a 429's `Retry-After`, or else `X-RateLimit-Reset`, once the client's
245    ///   own retries are exhausted.
246    /// - **Binance:** from a REST 429's or 418's `Retry-After`, or the time a WebSocket API
247    ///   refusal's `retryAfter` names, measured against the local clock. Uncapped, since a ban can
248    ///   last days, so add it to an `Instant` with `checked_add`. A request the client held back
249    ///   unsent, because an earlier refusal's wait had longer left than the client sleeps
250    ///   through, reports the time left.
251    /// - **Hyperliquid:** never: its SDK keeps no headers, and Hyperliquid documents no hint.
252    ///
253    /// A venue ban (Binance's HTTP 418) is reported the same way: its hint, when readable, says
254    /// how long it lasts.
255    ///
256    /// Transient — retry after `retry_after` when given, otherwise with backoff.
257    ///
258    /// The variant is `#[non_exhaustive]`: outside this crate, build one with
259    /// [`ApiError::rate_limited`], match it as `RateLimit { .. }`, and read the wait with
260    /// [`ApiError::retry_after`].
261    #[error("rate limit exceeded{}", RetryAfter(*retry_after))]
262    #[non_exhaustive]
263    RateLimit { retry_after: Option<Duration> },
264
265    /// The venue refused because a cap on something held at once is full, such as IBKR's market
266    /// data lines, which every TWS session and API client on the account shares.
267    ///
268    /// Unlike [`RateLimit`](Self::RateLimit), waiting does not clear it: releasing something
269    /// does, such as cancelling another subscription, whether this client holds it or another
270    /// session on the same account does. The message carries the venue's words.
271    ///
272    /// Not transient: the same request retried with backoff alone meets the same refusal while
273    /// the cap stays full.
274    #[error("venue capacity exceeded: {0}")]
275    CapacityExceeded(String),
276
277    /// Authentication failed (invalid credentials, expired key, bad signature).
278    ///
279    /// Unlike other API errors which affect a single request, authentication
280    /// failures indicate that **all** subsequent requests will fail until
281    /// credentials are corrected. Callers should halt trading and alert operators.
282    ///
283    /// Not transient — do not retry. Fix credentials and restart.
284    #[error("authentication failed: {0}")]
285    Unauthenticated(String),
286
287    /// Balance of an asset is insufficient to execute the requested operation.
288    ///
289    /// The asset is `None` when it is not known which asset ran short:
290    /// - the venue's rejection does not name it (e.g. Binance's "Account has insufficient
291    ///   balance for requested action", or any Hyperliquid margin or spot-balance refusal), and
292    ///   a client does not guess it from the order;
293    /// - the venue named an asset that the [`ExecutionInstrumentMap`] does not hold, so it has no
294    ///   index. [`AccountEventIndexer::api_error`] logs the name it dropped.
295    ///
296    /// The `String` carries the venue's message.
297    ///
298    /// Not transient — do not retry the same request. Reduce order size or
299    /// deposit additional funds.
300    ///
301    /// [`ExecutionInstrumentMap`]: crate::map::ExecutionInstrumentMap
302    /// [`AccountEventIndexer::api_error`]: crate::indexer::AccountEventIndexer::api_error
303    #[error(
304        "balance insufficient{asset}: {1}",
305        asset = .0.as_ref().map(|asset| format!(" for asset {asset}")).unwrap_or_default()
306    )]
307    BalanceInsufficient(Option<AssetKey>, String),
308
309    /// Order was rejected by the exchange for a business rule violation.
310    ///
311    /// Common causes include: price outside allowed range, quantity below
312    /// minimum, post-only order would cross, reduce-only with no position.
313    ///
314    /// Not transient — do not retry the same request. Adjust order parameters.
315    #[error("order rejected: {0}")]
316    OrderRejected(String),
317
318    /// Cancel request failed because the order was already cancelled.
319    ///
320    /// This is a state conflict, not an error per se — the desired end state
321    /// (order cancelled) has already been achieved.
322    ///
323    /// Not transient — do not retry. The order is already in the cancelled state.
324    #[error("order already cancelled")]
325    OrderAlreadyCancelled,
326
327    /// Cancel request failed because the order was already fully filled.
328    ///
329    /// This is a state conflict — the order completed before the cancel arrived.
330    /// The caller should reconcile their local state with the fill.
331    ///
332    /// Not transient — do not retry. The order no longer exists to cancel.
333    #[error("order already fully filled")]
334    OrderAlreadyFullyFilled,
335
336    /// Cancel request failed because the order had already expired.
337    ///
338    /// This is a state conflict — the order's own deadline retired it before the cancel arrived,
339    /// so the desired end state (order no longer working) has already been achieved. Distinct from
340    /// [`OrderAlreadyCancelled`](Self::OrderAlreadyCancelled) because nobody asked for it: a
341    /// time-in-force such as [`GoodTillDate`](crate::order::TimeInForce::GoodTillDate) retired it
342    /// unprompted, and a caller reconciling its local state needs to know which of the two happened.
343    ///
344    /// Not transient — do not retry. The order no longer exists to cancel.
345    #[error("order already expired")]
346    OrderAlreadyExpired,
347
348    /// Open request refused because its [`ClientOrderId`] is already in use at the venue.
349    ///
350    /// The refusal concerns this request alone: the order already under the id is **unaffected**,
351    /// and is not reported ended by it. What "in use" means is the venue's rule. On the
352    /// [`SimulatedVenue`] and the IBKR client it is an order still working under the id, and an id
353    /// is free again once its order has ended. Binance documents an id as unique among open
354    /// orders. The `String` carries the venue's message, or the client's own where it refused the
355    /// request before sending it.
356    ///
357    /// Reported by the [`SimulatedVenue`], by the IBKR client, which refuses the request before it
358    /// reaches TWS, since TWS never sees a client order id, and by the Binance spot and margin
359    /// clients, from Binance's `"Duplicate order sent."`. Other clients report a venue's duplicate
360    /// rejection as [`OrderRejected`](Self::OrderRejected) until its message has been confirmed.
361    ///
362    /// Not transient — the same request fails identically while the order under the id works.
363    /// Use another id, or wait for that order to end.
364    ///
365    /// [`ClientOrderId`]: crate::order::id::ClientOrderId
366    /// [`SimulatedVenue`]: crate::exchange::mock::SimulatedVenue
367    #[error("client order id in use: {0}")]
368    DuplicateClientOrderId(String),
369
370    /// The exchange refused the request itself, rather than an order it carried.
371    ///
372    /// The request was malformed or asked for something the venue does not serve — a missing,
373    /// malformed or out-of-range parameter, such as a query time window longer than the venue
374    /// allows. Distinct from [`OrderRejected`](Self::OrderRejected), which is an order failing a
375    /// business rule; this variant arises from queries and other non-order requests. The message
376    /// carries the venue's own error code where it provides one (e.g. `-1127 ...` on Binance).
377    ///
378    /// Not transient — the same request fails identically on retry. Change the request.
379    #[error("request rejected: {0}")]
380    RequestRejected(String),
381
382    /// Order refused because the venue would not lend what it needed: a short sale, or a margin
383    /// order that borrows to cover itself.
384    ///
385    /// Distinct from [`OrderRejected`](Self::OrderRejected) so a caller can tell a refused borrow
386    /// apart from a malformed order, and from [`BalanceInsufficient`](Self::BalanceInsufficient),
387    /// which is the account's own funds running short. A borrow can be refused for a long too: on
388    /// Binance margin, an order that borrows to buy is refused when the venue has too little of
389    /// the asset to lend or the borrow would exceed the account's limit. [`BorrowReject`] says
390    /// why.
391    ///
392    /// Reported by the Binance margin client, by Binance's code, by the Alpaca client, by the
393    /// text of a 403 or 422, and by the
394    /// [`SimulatedVenue`](crate::exchange::mock::SimulatedVenue), for a CFD short its
395    /// [`ShortabilityProvider`](crate::shortability::ShortabilityProvider) does not allow, and for
396    /// a spot margin borrow past an asset's cap
397    /// ([`SpotMarginConfig::with_max_borrow`](crate::margin::SpotMarginConfig::with_max_borrow)).
398    /// Other clients report such refusals as [`OrderRejected`](Self::OrderRejected) until their
399    /// venue's wording is confirmed.
400    ///
401    /// Not transient — the same request fails identically until the venue's lending changes.
402    #[error("borrow rejected: {0}")]
403    BorrowRejected(BorrowReject),
404}
405
406impl<AssetKey, InstrumentKey> ApiError<AssetKey, InstrumentKey> {
407    /// A [`RateLimit`](Self::RateLimit) refusal, with the venue's minimum wait when it sent one.
408    pub fn rate_limited(retry_after: Option<Duration>) -> Self {
409        Self::RateLimit { retry_after }
410    }
411
412    /// The venue's minimum wait before a retry: `Some` only for a
413    /// [`RateLimit`](Self::RateLimit) whose venue sent a hint the client could read.
414    pub fn retry_after(&self) -> Option<Duration> {
415        match self {
416            Self::RateLimit { retry_after } => *retry_after,
417            _ => None,
418        }
419    }
420}
421
422/// Formats a [`RateLimit`](ApiError::RateLimit)'s hint for its message: nothing when there is
423/// none.
424struct RetryAfter(Option<Duration>);
425
426impl fmt::Display for RetryAfter {
427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428        match self.0 {
429            Some(retry_after) => write!(f, "; retry after {retry_after:?}"),
430            None => Ok(()),
431        }
432    }
433}
434
435/// Why a venue refused to lend for an order, as carried by [`ApiError::BorrowRejected`].
436#[non_exhaustive]
437#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
438pub struct BorrowReject {
439    /// The kind of refusal.
440    pub reason: BorrowRejectReason,
441    /// The venue's own code for the refusal, where it gave one (e.g. `-3045` on Binance,
442    /// `40310000` on Alpaca).
443    ///
444    /// For diagnostics only, not a stable contract: match on [`reason`](Self::reason) instead. A
445    /// venue may reuse a code for several refusals, as Alpaca's generic `40310000` is.
446    pub venue_code: Option<String>,
447    /// The venue's message. It may itself carry the code, as Binance's does.
448    pub message: String,
449    /// How much more the venue could still have lent, in the units the order was sized in, where
450    /// known: for a short sale, the most a smaller order could have sold short; for a spot margin
451    /// sell, the most it could have borrowed, on top of whatever free base the account holds. Set
452    /// by the simulated venue; no live client reports it yet.
453    pub available: Option<Decimal>,
454}
455
456impl BorrowReject {
457    /// A refusal for `reason`, with the venue's code where it gave one, and its message.
458    pub fn new(reason: BorrowRejectReason, venue_code: Option<String>, message: String) -> Self {
459        Self {
460            reason,
461            venue_code,
462            message,
463            available: None,
464        }
465    }
466
467    /// With how much the venue could still have lent.
468    #[must_use]
469    pub fn with_available(mut self, available: Decimal) -> Self {
470        self.available = Some(available);
471        self
472    }
473}
474
475impl fmt::Display for BorrowReject {
476    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477        let Self {
478            reason,
479            venue_code,
480            message,
481            available,
482        } = self;
483        write!(f, "{reason}")?;
484        if let Some(code) = venue_code {
485            write!(f, " (code {code})")?;
486        }
487        write!(f, ": {message}")?;
488        if let Some(available) = available {
489            write!(f, " ({available} available)")?;
490        }
491        Ok(())
492    }
493}
494
495/// The kind of borrow refusal carried by a [`BorrowReject`].
496#[non_exhaustive]
497#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
498pub enum BorrowRejectReason {
499    /// The instrument cannot be sold short at all, whoever asks (e.g. Alpaca's "asset X cannot be
500    /// sold short").
501    NotShortable,
502    /// Borrowing is barred for this account, or for this asset on this account (e.g. Binance
503    /// `-3008`, `-3012` and `-3014`, Alpaca's "account is not allowed to short").
504    BorrowDisabled,
505    /// The venue has too little of the asset to lend right now (e.g. Binance `-3045`). It may
506    /// lend again later.
507    InventoryUnavailable,
508    /// The borrow would exceed what the account may borrow (e.g. Binance `-3006`).
509    BorrowLimitExceeded,
510    /// A short-sale restriction is in effect, such as the SEC's Rule 201 circuit breaker after a
511    /// 10% fall, and the order would sell short at or below the best bid. A short sale priced
512    /// above the bid may still be accepted.
513    ShortSaleRestricted,
514    /// A borrow refusal of a kind not listed here. The [`BorrowReject`] message says which.
515    Other,
516}
517
518impl fmt::Display for BorrowRejectReason {
519    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520        f.write_str(match self {
521            Self::NotShortable => "not shortable",
522            Self::BorrowDisabled => "borrow disabled",
523            Self::InventoryUnavailable => "inventory unavailable",
524            Self::BorrowLimitExceeded => "borrow limit exceeded",
525            Self::ShortSaleRestricted => "short sale restricted",
526            Self::Other => "other",
527        })
528    }
529}
530
531/// Represents all errors that can be generated when cancelling or opening orders.
532///
533/// This is a subset of [`ClientError`] for order-specific operations. Use
534/// [`is_transient()`](Self::is_transient) to determine retry eligibility.
535#[non_exhaustive]
536#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
537pub enum OrderError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
538    /// Connectivity-based error (timeout, socket failure, exchange offline), or a venue failure
539    /// that leaves the order's status unknown.
540    ///
541    /// Transient — retry with backoff. See [`ConnectivityError`] for details. The order may or
542    /// may not have reached the matching engine, so before resubmitting an open request,
543    /// reconcile its state (open orders, fills); a blind retry can place it twice.
544    ///
545    /// For an open request, this means **the outcome is unknown**, not that the open failed: see
546    /// [`is_outcome_unknown`](Self::is_outcome_unknown). A client that knows the request never
547    /// left returns [`NotPlaced`](Self::NotPlaced) instead.
548    #[error("connectivity: {0}")]
549    Connectivity(#[from] ConnectivityError),
550
551    /// The order was not placed, and this is known rather than guessed: see [`NotPlacedReason`].
552    ///
553    /// Unlike [`Connectivity`](Self::Connectivity), it ends the order. Resubmitting the open
554    /// request cannot place the order twice.
555    #[error("not placed: {0}")]
556    NotPlaced(NotPlacedReason),
557
558    /// API-based error (rate limit, invalid instrument, order rejected, etc.).
559    ///
560    /// Retry semantics depend on the specific [`ApiError`] variant. Only
561    /// [`ApiError::RateLimit`] is transient; other variants are not.
562    #[error("order rejected: {0}")]
563    Rejected(#[from] ApiError<AssetKey, InstrumentKey>),
564
565    /// The order type is not supported by this connector, or the venue refused it as a type it
566    /// does not take for this account or instrument.
567    ///
568    /// Non-transient — place a different order type. A connector usually returns this without
569    /// sending the request (e.g., trailing stop orders on a connector that only supports
570    /// market/limit); when the venue's own refusal says so, it can also come back after the round
571    /// trip.
572    #[error("unsupported order type: {0}")]
573    UnsupportedOrderType(String),
574
575    /// A quantity or price in the request has more precision than the venue accepts, so the
576    /// client refused it without sending it.
577    ///
578    /// Non-transient — change the request. A client that refuses this way never rounds a value
579    /// itself, because rounding would place a different order than the one requested; it
580    /// documents how to read the venue's precision so the caller can round first.
581    #[error("invalid precision: {0}")]
582    InvalidPrecision(PrecisionViolation),
583
584    /// A value in the request is outside the range the venue accepts for the instrument, so the
585    /// client refused it without sending it.
586    ///
587    /// Non-transient — change the request. Unlike [`InvalidPrecision`](Self::InvalidPrecision),
588    /// which says a value is badly formed, this says a well-formed value is too small or too
589    /// large: below a minimum price, quantity, notional or trailing offset, or above a maximum.
590    /// The error carries the limit that was broken, so the caller can resize the order. A client
591    /// checks only the rules it has loaded (see [`OrderRules`](crate::rules::OrderRules)); a
592    /// request that passes can still be rejected by the venue.
593    #[error("out of bounds: {0}")]
594    OutOfBounds(BoundsViolation),
595
596    /// The request names a [`MarginEffect`] this client cannot honour, so it refused the order
597    /// without sending it.
598    ///
599    /// Non-transient — drop the effect (`RequestOpen::margin_effect` of `None` takes the client's
600    /// default) or send the order to a client that honours it. A client refuses rather than
601    /// ignores an effect it cannot honour, because placing the order without it would borrow, or
602    /// not repay, against the caller's intent. Which effects a client honours is on its type: a
603    /// spot or cash account takes only [`NoSideEffect`](MarginEffect::NoSideEffect), a venue
604    /// with account-level margin takes none.
605    #[error("unsupported margin effect: {0:?}")]
606    UnsupportedMarginEffect(MarginEffect),
607}
608
609/// How an order is known not to have been placed.
610///
611/// Carried by [`OrderError::NotPlaced`].
612#[non_exhaustive]
613#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
614pub enum NotPlacedReason {
615    /// The open request never left the client, because the connection failed before the send:
616    /// refused, unresolved, or a closed channel to a simulated venue.
617    ///
618    /// A client returns this only where the failure provably came before the send. A failure it
619    /// cannot place is [`OrderError::Connectivity`].
620    #[error("not sent: {0}")]
621    NotSent(ConnectivityError),
622
623    /// The open's outcome was unknown, and the venue, asked about the order by its client order
624    /// id several times since, does not know it.
625    ///
626    /// The engine's `ExecutionManager` reports this, after the lookups its policy sets out.
627    #[error("unknown to the venue")]
628    UnknownToVenue,
629}
630
631/// A value in an order request with more precision than the venue accepts, or that is not
632/// positive.
633///
634/// Carried by [`OrderError::InvalidPrecision`].
635#[non_exhaustive]
636#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
637pub struct PrecisionViolation {
638    /// Which value of the request broke the rule.
639    pub field: OrderField,
640    /// The value as requested.
641    pub value: Decimal,
642    /// The rule it broke.
643    pub limit: PrecisionLimit,
644}
645
646impl PrecisionViolation {
647    /// The request's `field`, of `value`, breaks `limit`.
648    pub fn new(field: OrderField, value: Decimal, limit: PrecisionLimit) -> Self {
649        Self {
650            field,
651            value,
652            limit,
653        }
654    }
655}
656
657impl fmt::Display for PrecisionViolation {
658    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659        let Self {
660            field,
661            value,
662            limit,
663        } = self;
664        write!(f, "{field} {value} ")?;
665        match limit {
666            PrecisionLimit::DecimalPlaces { max } => {
667                write!(f, "has more than {max} decimal places")
668            }
669            PrecisionLimit::SignificantFigures { max } => {
670                write!(
671                    f,
672                    "is not an integer and has more than {max} significant figures"
673                )
674            }
675            PrecisionLimit::NotRepresentable => {
676                write!(f, "cannot be sent exactly in the venue's number format")
677            }
678            PrecisionLimit::NotPositive => write!(f, "is not positive"),
679            PrecisionLimit::NotOnGrid { step } => {
680                write!(f, "is not a multiple of {step}")
681            }
682        }
683    }
684}
685
686/// A value in an order request that is below a venue minimum or above a venue maximum.
687///
688/// Carried by [`OrderError::OutOfBounds`].
689#[non_exhaustive]
690#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
691pub struct BoundsViolation {
692    /// Which value of the request broke the bound.
693    pub field: OrderField,
694    /// Whether `value` is below the minimum or above the maximum.
695    pub bound: Bound,
696    /// The limit `value` broke.
697    pub limit: Decimal,
698    /// The value as requested. For [`OrderField::Notional`] it is the price times the quantity.
699    pub value: Decimal,
700}
701
702impl BoundsViolation {
703    /// The request's `field`, of `value`, is beyond the `bound` at `limit`.
704    pub fn new(field: OrderField, bound: Bound, limit: Decimal, value: Decimal) -> Self {
705        Self {
706            field,
707            bound,
708            limit,
709            value,
710        }
711    }
712}
713
714impl fmt::Display for BoundsViolation {
715    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
716        let Self {
717            field,
718            bound,
719            limit,
720            value,
721        } = self;
722        let (relation, name) = match bound {
723            Bound::Min => ("below", "minimum"),
724            Bound::Max => ("above", "maximum"),
725        };
726        write!(f, "{field} {value} is {relation} the {name} {limit}")
727    }
728}
729
730/// Which end of a range a [`BoundsViolation`] broke.
731#[non_exhaustive]
732#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
733pub enum Bound {
734    /// The value is below the minimum.
735    Min,
736    /// The value is above the maximum.
737    Max,
738}
739
740/// A value of an order request, as named by a [`PrecisionViolation`] or [`BoundsViolation`].
741#[non_exhaustive]
742#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
743pub enum OrderField {
744    /// The order's quantity.
745    Quantity,
746    /// The order's limit price.
747    Price,
748    /// The price that triggers a stop or take-profit order.
749    TriggerPrice,
750    /// A trailing order's offset.
751    TrailingOffset,
752    /// The order's price times its quantity, in the quote asset. Never a request field of its
753    /// own: only a [`BoundsViolation`] names it.
754    Notional,
755}
756
757impl fmt::Display for OrderField {
758    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
759        f.write_str(match self {
760            Self::Quantity => "quantity",
761            Self::Price => "price",
762            Self::TriggerPrice => "trigger price",
763            Self::TrailingOffset => "trailing offset",
764            Self::Notional => "notional",
765        })
766    }
767}
768
769/// A venue's precision rule, as broken by a [`PrecisionViolation`].
770#[non_exhaustive]
771#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
772pub enum PrecisionLimit {
773    /// The value may have at most `max` decimal places.
774    DecimalPlaces {
775        /// The most decimal places allowed.
776        max: u32,
777    },
778    /// The value may have at most `max` significant figures, unless it is an integer.
779    SignificantFigures {
780        /// The most significant figures allowed.
781        max: u32,
782    },
783    /// The value cannot be sent exactly: the venue's client library converts it to a number
784    /// format that would change it.
785    NotRepresentable,
786    /// The value is zero or negative. A quantity, price or trailing offset must be positive.
787    NotPositive,
788    /// The value is not a whole multiple of `step`: a price must sit on the instrument's tick
789    /// grid and a quantity on its lot grid, counted from zero.
790    NotOnGrid {
791        /// The grid's step: the tick size for a price, the lot step for a quantity.
792        step: Decimal,
793    },
794}
795
796impl<AssetKey, InstrumentKey> OrderError<AssetKey, InstrumentKey> {
797    /// Returns `true` if this error is likely transient and the operation
798    /// may succeed if retried after a suitable backoff.
799    ///
800    /// # Transient errors
801    /// - [`Connectivity`](Self::Connectivity) errors (timeout, socket, offline)
802    /// - [`Rejected(ApiError::RateLimit)`](ApiError::RateLimit), though not before its
803    ///   `retry_after`
804    ///
805    /// # Non-transient errors
806    /// - Other [`Rejected`](Self::Rejected) errors (invalid instrument, insufficient balance,
807    ///   refused borrow, etc.)
808    /// - [`UnsupportedOrderType`](Self::UnsupportedOrderType),
809    ///   [`InvalidPrecision`](Self::InvalidPrecision),
810    ///   [`OutOfBounds`](Self::OutOfBounds) and
811    ///   [`UnsupportedMarginEffect`](Self::UnsupportedMarginEffect)
812    ///
813    /// [`NotPlaced`](Self::NotPlaced) is transient when the request was not sent, since a later
814    /// send may get through, and not when the venue does not know the order.
815    pub fn is_transient(&self) -> bool {
816        match self {
817            Self::Connectivity(e) | Self::NotPlaced(NotPlacedReason::NotSent(e)) => {
818                e.is_transient()
819            }
820            Self::NotPlaced(NotPlacedReason::UnknownToVenue) => false,
821            Self::Rejected(ApiError::RateLimit { .. }) => true,
822            Self::Rejected(_) => false,
823            Self::UnsupportedOrderType(_)
824            | Self::InvalidPrecision(_)
825            | Self::OutOfBounds(_)
826            | Self::UnsupportedMarginEffect(_) => false,
827        }
828    }
829
830    /// Returns `true` if, as the answer to an open request, this error leaves the order's outcome
831    /// unknown: the order may be live at the venue.
832    ///
833    /// Only [`Connectivity`](Self::Connectivity) does. Every other error says the order was not
834    /// placed.
835    pub fn is_outcome_unknown(&self) -> bool {
836        matches!(self, Self::Connectivity(_))
837    }
838}
839
840/// Why an account event stream ended.
841///
842/// Delivered in-band as the payload of
843/// [`AccountEventKind::StreamTerminated`](crate::AccountEventKind::StreamTerminated) so that
844/// stream death is a programmatic signal on the account feed rather than a log-only event. A
845/// consumer can react (re-sync via REST, re-establish the stream, halt trading) according to its
846/// own policy — the library reports *why* the stream ended without prescribing the response.
847///
848/// # Only in-band-deliverable terminations are represented
849///
850/// Every variant here is a termination the library can actually deliver to a consumer that is
851/// still listening. A consumer-initiated drop is deliberately **not** a variant: by the time a
852/// stream task observes the drop, the receiving half of the channel is already gone, so a
853/// `StreamTerminated` send would be a guaranteed no-op. `StreamTerminated` therefore always means
854/// "the stream died while you were still listening".
855///
856/// `#[non_exhaustive]` so venues may distinguish further termination causes in future without a
857/// breaking change (e.g. a venue able to signal a graceful shutdown over a still-open channel).
858#[non_exhaustive]
859#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
860pub enum StreamTerminationReason {
861    /// A venue with built-in reconnection exhausted its retry budget and gave up.
862    ///
863    /// Emitted by venues that reconnect internally (e.g. Binance spot/margin, Alpaca) once the
864    /// final attempt fails. Each client documents its budget. `last_error` is the most recent
865    /// underlying failure; `attempts` is the number of reconnects tried before surrendering. The
866    /// stream will not recover on its own — the consumer must re-establish it.
867    #[error("reconnect budget exhausted after {attempts} attempts: {last_error}")]
868    ReconnectBudgetExhausted {
869        /// Number of reconnect attempts made before giving up.
870        attempts: u32,
871        /// The most recent underlying error that triggered surrender.
872        last_error: String,
873    },
874
875    /// The stream ended on an unrecoverable error with no automatic recovery.
876    ///
877    /// Emitted by venues without library-managed reconnection — e.g. IBKR (the underlying
878    /// subscription errored and the client does not retry), Hyperliquid (the SDK closed the
879    /// subscription's channel; its own reconnection never gives up), or the mock exchange (its
880    /// broadcast stream lagged past the buffer). The consumer is responsible for any
881    /// re-establishment.
882    #[error("unrecoverable stream error: {0}")]
883    Error(String),
884
885    /// The venue is refusing this client for exceeding its rate limits, for longer than the
886    /// stream waits through in place.
887    ///
888    /// Emitted by venues that reconnect internally (Binance spot/margin) when a reconnect faces a
889    /// rate-limit cooldown, or a ban, with more than a few seconds left. The stream ends at once
890    /// rather than spend its reconnect budget against a venue that refuses every attempt, and
891    /// reconnects that would lengthen a ban. `retry_after` is how long the cooldown had left: the
892    /// earliest the consumer should re-establish the stream. Opening it sooner fails with
893    /// [`ApiError::RateLimit`], unsent.
894    ///
895    /// Nothing that happens on the account until the stream is re-established reaches the
896    /// consumer through this stream, as after any other termination: re-sync from the new
897    /// stream's snapshot, and read fills of the gap with a trades query. An
898    /// `ExecutionManager` re-opens the stream itself, no sooner than `retry_after`, and reports
899    /// each refused attempt as a `ReinitFailed` carrying the time left.
900    #[error("rate-limited by the venue; retry after {retry_after:?}")]
901    RateLimited {
902        /// How long the venue's cooldown had left when the stream ended.
903        retry_after: Duration,
904    },
905}
906
907/// Type alias for an [`AccountStreamInitError`] that is keyed on [`AssetNameExchange`] and
908/// [`InstrumentNameExchange`] (yet to be indexed).
909pub type UnindexedAccountStreamInitError =
910    AccountStreamInitError<AssetNameExchange, InstrumentNameExchange>;
911
912/// Why an attempt to initialise an account stream, its snapshot and its updates, failed.
913#[non_exhaustive]
914#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
915pub enum AccountStreamInitError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
916    /// The [`ExecutionClient`](crate::client::ExecutionClient) failed to fetch the account
917    /// snapshot or to open the account stream. See [`ClientError::is_transient`].
918    #[error("{0}")]
919    Client(#[from] ClientError<AssetKey, InstrumentKey>),
920
921    /// The account snapshot named an exchange, asset or instrument that is not indexed. This does
922    /// not resolve on retry while the venue keeps reporting it.
923    #[error("IndexError: {0}")]
924    Index(#[from] IndexError),
925}
926
927impl<AssetKey, InstrumentKey> AccountStreamInitError<AssetKey, InstrumentKey> {
928    /// The venue's minimum wait before the next attempt: `Some` only for a client's
929    /// [`Api::RateLimit`](ApiError::RateLimit) whose venue sent a hint the client could read. See
930    /// [`ClientError::retry_after`].
931    pub fn retry_after(&self) -> Option<Duration> {
932        match self {
933            Self::Client(error) => error.retry_after(),
934            Self::Index(_) => None,
935        }
936    }
937}
938
939/// A failed attempt to re-initialise an account stream after it ended.
940///
941/// Delivered in-band as the payload of
942/// [`AccountEventKind::ReinitFailed`](crate::AccountEventKind::ReinitFailed), once per failed
943/// attempt. Attempts continue with backoff; giving up is the consumer's decision.
944#[non_exhaustive]
945#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Constructor)]
946pub struct AccountReinitFailure<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
947    /// Consecutive failed attempts since the stream last initialised, starting at 1.
948    pub attempt: u32,
949    /// Why this attempt failed.
950    pub error: AccountStreamInitError<AssetKey, InstrumentKey>,
951}
952
953/// Represents errors related to exchange, asset and instrument identifier key lookups.
954#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
955pub enum KeyError {
956    /// Indicates an [`ExchangeId`] was encountered that was not indexed, so does not have a
957    /// corresponding `ExchangeIndex`.
958    #[error("ExchangeId: {0}")]
959    ExchangeId(String),
960
961    /// Indicates an [`AssetNameExchange`] was encountered that was not indexed, so does not have a
962    /// corresponding [`AssetIndex`].
963    #[error("AssetKey: {0}")]
964    AssetKey(String),
965
966    /// Indicates an [`InstrumentNameExchange`] was encountered that was no indexed, so does
967    /// not have a corresponding [`InstrumentIndex`].
968    #[error("InstrumentKey: {0}")]
969    InstrumentKey(String),
970}
971
972#[cfg(test)]
973#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
974mod tests {
975    use super::*;
976    use rust_decimal_macros::dec;
977
978    #[test]
979    fn a_rate_limit_carries_and_shows_the_venues_wait() {
980        let hinted: UnindexedApiError = ApiError::rate_limited(Some(Duration::from_secs(7)));
981        assert_eq!(hinted.retry_after(), Some(Duration::from_secs(7)));
982        assert_eq!(hinted.to_string(), "rate limit exceeded; retry after 7s");
983        assert!(UnindexedClientError::Api(hinted.clone()).is_transient());
984        assert!(UnindexedOrderError::Rejected(hinted).is_transient());
985
986        let unhinted: UnindexedApiError = ApiError::rate_limited(None);
987        assert_eq!(unhinted.retry_after(), None);
988        assert_eq!(unhinted.to_string(), "rate limit exceeded");
989
990        let other: UnindexedApiError = ApiError::Unauthenticated("bad key".to_string());
991        assert_eq!(other.retry_after(), None);
992    }
993
994    #[test]
995    fn a_client_or_init_error_reads_the_wait_of_its_rate_limit() {
996        let wait = Some(Duration::from_secs(7));
997        let hinted = UnindexedClientError::Api(ApiError::rate_limited(wait));
998        assert_eq!(hinted.retry_after(), wait);
999        assert_eq!(
1000            UnindexedAccountStreamInitError::Client(hinted).retry_after(),
1001            wait
1002        );
1003
1004        let unhinted = UnindexedClientError::Api(ApiError::rate_limited(None));
1005        assert_eq!(unhinted.retry_after(), None);
1006        let socket = UnindexedClientError::Connectivity(ConnectivityError::Timeout);
1007        assert_eq!(socket.retry_after(), None);
1008        assert_eq!(
1009            UnindexedAccountStreamInitError::Client(socket).retry_after(),
1010            None
1011        );
1012    }
1013
1014    #[test]
1015    fn a_rate_limited_termination_shows_and_round_trips_its_wait() {
1016        let reason = StreamTerminationReason::RateLimited {
1017            retry_after: Duration::from_secs(120),
1018        };
1019        assert_eq!(
1020            reason.to_string(),
1021            "rate-limited by the venue; retry after 120s"
1022        );
1023        let json = serde_json::to_string(&reason).unwrap();
1024        assert_eq!(
1025            serde_json::from_str::<StreamTerminationReason>(&json).unwrap(),
1026            reason
1027        );
1028    }
1029
1030    #[test]
1031    fn a_rate_limit_round_trips_through_serde() {
1032        for retry_after in [None, Some(Duration::from_millis(7_250))] {
1033            let error: UnindexedApiError = ApiError::rate_limited(retry_after);
1034            let json = serde_json::to_string(&error).unwrap();
1035            assert_eq!(
1036                serde_json::from_str::<UnindexedApiError>(&json).unwrap(),
1037                error,
1038                "{json}"
1039            );
1040        }
1041    }
1042
1043    #[test]
1044    fn test_connectivity_error_is_transient() {
1045        assert!(ConnectivityError::Timeout.is_transient());
1046        assert!(ConnectivityError::Socket("connection refused".into()).is_transient());
1047        assert!(ConnectivityError::ExchangeOffline(ExchangeId::BinanceSpot).is_transient());
1048    }
1049
1050    #[test]
1051    fn test_client_error_is_transient_connectivity() {
1052        let err: ClientError = ClientError::Connectivity(ConnectivityError::Timeout);
1053        assert!(err.is_transient());
1054
1055        let err: ClientError = ClientError::Connectivity(ConnectivityError::Socket("err".into()));
1056        assert!(err.is_transient());
1057    }
1058
1059    #[test]
1060    fn test_client_error_is_transient_rate_limit() {
1061        let err: ClientError = ClientError::Api(ApiError::rate_limited(None));
1062        assert!(err.is_transient());
1063    }
1064
1065    #[test]
1066    fn test_client_error_not_transient_api_errors() {
1067        let err: ClientError =
1068            ClientError::Api(ApiError::AssetInvalid(AssetIndex(0), "bad".into()));
1069        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1070
1071        let err: ClientError = ClientError::Api(ApiError::BalanceInsufficient(
1072            Some(AssetIndex(0)),
1073            "low".into(),
1074        ));
1075        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1076
1077        let err: ClientError = ClientError::Api(ApiError::InstrumentInvalid(
1078            InstrumentIndex(0),
1079            "bad".into(),
1080        ));
1081        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1082
1083        let err: ClientError = ClientError::Api(ApiError::OrderRejected("rejected".into()));
1084        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1085
1086        let err: ClientError = ClientError::Api(ApiError::OrderAlreadyCancelled);
1087        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1088
1089        let err: ClientError = ClientError::Api(ApiError::OrderAlreadyFullyFilled);
1090        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1091
1092        let err: ClientError =
1093            ClientError::Api(ApiError::Unauthenticated("invalid signature".into()));
1094        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1095
1096        let err: ClientError =
1097            ClientError::Api(ApiError::RequestRejected("-1127 More than 24 hours".into()));
1098        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1099
1100        let err: ClientError = ClientError::Api(ApiError::BorrowRejected(BorrowReject::new(
1101            BorrowRejectReason::InventoryUnavailable,
1102            Some("-3045".into()),
1103            "-3045 The system doesn't have enough asset now.".into(),
1104        )));
1105        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1106    }
1107
1108    #[test]
1109    fn borrow_rejected_shows_its_reason_and_code() {
1110        let coded: UnindexedApiError = ApiError::BorrowRejected(BorrowReject::new(
1111            BorrowRejectReason::BorrowDisabled,
1112            Some("40310000".into()),
1113            "account is not allowed to short".into(),
1114        ));
1115        assert_eq!(
1116            coded.to_string(),
1117            "borrow rejected: borrow disabled (code 40310000): account is not allowed to short"
1118        );
1119
1120        let uncoded: UnindexedApiError = ApiError::BorrowRejected(BorrowReject::new(
1121            BorrowRejectReason::Other,
1122            None,
1123            "no borrow".into(),
1124        ));
1125        assert_eq!(uncoded.to_string(), "borrow rejected: other: no borrow");
1126
1127        let short: UnindexedApiError = ApiError::BorrowRejected(BorrowReject::new(
1128            BorrowRejectReason::ShortSaleRestricted,
1129            None,
1130            "priced at the bid".into(),
1131        ));
1132        assert_eq!(
1133            short.to_string(),
1134            "borrow rejected: short sale restricted: priced at the bid"
1135        );
1136    }
1137
1138    #[test]
1139    fn borrow_rejected_shows_what_is_available_only_when_known() {
1140        let reject = BorrowReject::new(
1141            BorrowRejectReason::InventoryUnavailable,
1142            None,
1143            "too little to lend".into(),
1144        );
1145        assert_eq!(reject.available, None);
1146
1147        let reject = reject.with_available(dec!(2.5));
1148        assert_eq!(reject.available, Some(dec!(2.5)));
1149        assert_eq!(
1150            reject.to_string(),
1151            "inventory unavailable: too little to lend (2.5 available)"
1152        );
1153    }
1154
1155    #[test]
1156    fn balance_insufficient_names_its_asset_only_when_known() {
1157        let named: UnindexedApiError =
1158            ApiError::BalanceInsufficient(Some(AssetNameExchange::new("BTC")), "low".to_string());
1159        assert_eq!(named.to_string(), "balance insufficient for asset BTC: low");
1160
1161        let unnamed: UnindexedApiError = ApiError::BalanceInsufficient(None, "low".to_string());
1162        assert_eq!(unnamed.to_string(), "balance insufficient: low");
1163    }
1164
1165    #[test]
1166    fn test_client_error_not_transient_task_failed() {
1167        let err: ClientError = ClientError::TaskFailed("task panicked".into());
1168        assert!(!err.is_transient());
1169    }
1170
1171    #[test]
1172    fn test_client_error_not_transient_internal() {
1173        let err: ClientError = ClientError::Internal("unknown error".into());
1174        assert!(!err.is_transient());
1175    }
1176
1177    #[test]
1178    fn test_client_error_not_transient_truncated() {
1179        let err: ClientError = ClientError::Truncated { fills_read: 5_000 };
1180        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1181
1182        let err: ClientError = ClientError::TruncatedSnapshot { limit: 500 };
1183        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1184    }
1185
1186    #[test]
1187    fn test_client_error_is_transient_exchange_offline() {
1188        let err: ClientError =
1189            ClientError::Connectivity(ConnectivityError::ExchangeOffline(ExchangeId::BinanceSpot));
1190        assert!(err.is_transient(), "expected transient for {:?}", err);
1191    }
1192
1193    #[test]
1194    fn test_order_error_is_transient_connectivity() {
1195        let err: UnindexedOrderError = OrderError::Connectivity(ConnectivityError::Timeout);
1196        assert!(err.is_transient(), "expected transient for {:?}", err);
1197
1198        let err: UnindexedOrderError =
1199            OrderError::Connectivity(ConnectivityError::Socket("connection reset".into()));
1200        assert!(err.is_transient(), "expected transient for {:?}", err);
1201
1202        let err: UnindexedOrderError =
1203            OrderError::Connectivity(ConnectivityError::ExchangeOffline(ExchangeId::BinanceSpot));
1204        assert!(err.is_transient(), "expected transient for {:?}", err);
1205    }
1206
1207    #[test]
1208    fn test_order_error_not_placed() {
1209        let not_sent: UnindexedOrderError = OrderError::NotPlaced(NotPlacedReason::NotSent(
1210            ConnectivityError::Socket("connection refused".into()),
1211        ));
1212        assert!(not_sent.is_transient(), "a later send may get through");
1213        assert!(!not_sent.is_outcome_unknown());
1214
1215        let unknown: UnindexedOrderError = OrderError::NotPlaced(NotPlacedReason::UnknownToVenue);
1216        assert!(!unknown.is_transient());
1217        assert!(!unknown.is_outcome_unknown());
1218    }
1219
1220    /// Only a connectivity error leaves an open's outcome unknown, and only as an open's answer
1221    /// does `OrderState` read it so.
1222    #[test]
1223    fn test_order_error_is_outcome_unknown() {
1224        use crate::order::state::{OrderState, UnindexedOrderState};
1225
1226        let timeout: UnindexedOrderError = OrderError::Connectivity(ConnectivityError::Timeout);
1227        assert!(timeout.is_outcome_unknown());
1228        let rejected: UnindexedOrderError =
1229            OrderError::Rejected(ApiError::OrderRejected("no".into()));
1230        assert!(!rejected.is_outcome_unknown());
1231
1232        let state: UnindexedOrderState = OrderState::inactive(timeout);
1233        assert!(state.is_outcome_unknown());
1234        assert!(state.is_failed());
1235        let state: UnindexedOrderState = OrderState::inactive(rejected);
1236        assert!(!state.is_outcome_unknown());
1237    }
1238
1239    #[test]
1240    fn test_order_error_is_transient_rate_limit() {
1241        let err: UnindexedOrderError = OrderError::Rejected(ApiError::rate_limited(None));
1242        assert!(err.is_transient(), "expected transient for {:?}", err);
1243    }
1244
1245    #[test]
1246    fn test_order_error_not_transient_api_errors() {
1247        let err: UnindexedOrderError =
1248            OrderError::Rejected(ApiError::OrderRejected("price out of range".into()));
1249        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1250
1251        let err: UnindexedOrderError = OrderError::Rejected(ApiError::OrderAlreadyCancelled);
1252        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1253
1254        let err: UnindexedOrderError =
1255            OrderError::Rejected(ApiError::BorrowRejected(BorrowReject::new(
1256                BorrowRejectReason::NotShortable,
1257                None,
1258                "asset XYZ cannot be sold short".into(),
1259            )));
1260        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1261
1262        let err: UnindexedOrderError = OrderError::Rejected(ApiError::BalanceInsufficient(
1263            Some(AssetNameExchange::from("BTC")),
1264            "insufficient".into(),
1265        ));
1266        assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1267    }
1268}