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. Other
396 /// clients report such refusals as [`OrderRejected`](Self::OrderRejected) until their venue's
397 /// wording is confirmed.
398 ///
399 /// Not transient — the same request fails identically until the venue's lending changes.
400 #[error("borrow rejected: {0}")]
401 BorrowRejected(BorrowReject),
402}
403
404impl<AssetKey, InstrumentKey> ApiError<AssetKey, InstrumentKey> {
405 /// A [`RateLimit`](Self::RateLimit) refusal, with the venue's minimum wait when it sent one.
406 pub fn rate_limited(retry_after: Option<Duration>) -> Self {
407 Self::RateLimit { retry_after }
408 }
409
410 /// The venue's minimum wait before a retry: `Some` only for a
411 /// [`RateLimit`](Self::RateLimit) whose venue sent a hint the client could read.
412 pub fn retry_after(&self) -> Option<Duration> {
413 match self {
414 Self::RateLimit { retry_after } => *retry_after,
415 _ => None,
416 }
417 }
418}
419
420/// Formats a [`RateLimit`](ApiError::RateLimit)'s hint for its message: nothing when there is
421/// none.
422struct RetryAfter(Option<Duration>);
423
424impl fmt::Display for RetryAfter {
425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426 match self.0 {
427 Some(retry_after) => write!(f, "; retry after {retry_after:?}"),
428 None => Ok(()),
429 }
430 }
431}
432
433/// Why a venue refused to lend for an order, as carried by [`ApiError::BorrowRejected`].
434#[non_exhaustive]
435#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
436pub struct BorrowReject {
437 /// The kind of refusal.
438 pub reason: BorrowRejectReason,
439 /// The venue's own code for the refusal, where it gave one (e.g. `-3045` on Binance,
440 /// `40310000` on Alpaca).
441 ///
442 /// For diagnostics only, not a stable contract: match on [`reason`](Self::reason) instead. A
443 /// venue may reuse a code for several refusals, as Alpaca's generic `40310000` is.
444 pub venue_code: Option<String>,
445 /// The venue's message. It may itself carry the code, as Binance's does.
446 pub message: String,
447 /// How much the venue could still have lent, in the units the order was sized in, where
448 /// known: the most a smaller order could have sold short. Set by the simulated venue; no live
449 /// client reports it yet.
450 pub available: Option<Decimal>,
451}
452
453impl BorrowReject {
454 /// A refusal for `reason`, with the venue's code where it gave one, and its message.
455 pub fn new(reason: BorrowRejectReason, venue_code: Option<String>, message: String) -> Self {
456 Self {
457 reason,
458 venue_code,
459 message,
460 available: None,
461 }
462 }
463
464 /// With how much the venue could still have lent.
465 #[must_use]
466 pub fn with_available(mut self, available: Decimal) -> Self {
467 self.available = Some(available);
468 self
469 }
470}
471
472impl fmt::Display for BorrowReject {
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 let Self {
475 reason,
476 venue_code,
477 message,
478 available,
479 } = self;
480 write!(f, "{reason}")?;
481 if let Some(code) = venue_code {
482 write!(f, " (code {code})")?;
483 }
484 write!(f, ": {message}")?;
485 if let Some(available) = available {
486 write!(f, " ({available} available)")?;
487 }
488 Ok(())
489 }
490}
491
492/// The kind of borrow refusal carried by a [`BorrowReject`].
493#[non_exhaustive]
494#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
495pub enum BorrowRejectReason {
496 /// The instrument cannot be sold short at all, whoever asks (e.g. Alpaca's "asset X cannot be
497 /// sold short").
498 NotShortable,
499 /// Borrowing is barred for this account, or for this asset on this account (e.g. Binance
500 /// `-3008`, `-3012` and `-3014`, Alpaca's "account is not allowed to short").
501 BorrowDisabled,
502 /// The venue has too little of the asset to lend right now (e.g. Binance `-3045`). It may
503 /// lend again later.
504 InventoryUnavailable,
505 /// The borrow would exceed what the account may borrow (e.g. Binance `-3006`).
506 BorrowLimitExceeded,
507 /// A short-sale restriction is in effect, such as the SEC's Rule 201 circuit breaker after a
508 /// 10% fall, and the order would sell short at or below the best bid. A short sale priced
509 /// above the bid may still be accepted.
510 ShortSaleRestricted,
511 /// A borrow refusal of a kind not listed here. The [`BorrowReject`] message says which.
512 Other,
513}
514
515impl fmt::Display for BorrowRejectReason {
516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517 f.write_str(match self {
518 Self::NotShortable => "not shortable",
519 Self::BorrowDisabled => "borrow disabled",
520 Self::InventoryUnavailable => "inventory unavailable",
521 Self::BorrowLimitExceeded => "borrow limit exceeded",
522 Self::ShortSaleRestricted => "short sale restricted",
523 Self::Other => "other",
524 })
525 }
526}
527
528/// Represents all errors that can be generated when cancelling or opening orders.
529///
530/// This is a subset of [`ClientError`] for order-specific operations. Use
531/// [`is_transient()`](Self::is_transient) to determine retry eligibility.
532#[non_exhaustive]
533#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
534pub enum OrderError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
535 /// Connectivity-based error (timeout, socket failure, exchange offline), or a venue failure
536 /// that leaves the order's status unknown.
537 ///
538 /// Transient — retry with backoff. See [`ConnectivityError`] for details. The order may or
539 /// may not have reached the matching engine, so before resubmitting an open request,
540 /// reconcile its state (open orders, fills); a blind retry can place it twice.
541 #[error("connectivity: {0}")]
542 Connectivity(#[from] ConnectivityError),
543
544 /// API-based error (rate limit, invalid instrument, order rejected, etc.).
545 ///
546 /// Retry semantics depend on the specific [`ApiError`] variant. Only
547 /// [`ApiError::RateLimit`] is transient; other variants are not.
548 #[error("order rejected: {0}")]
549 Rejected(#[from] ApiError<AssetKey, InstrumentKey>),
550
551 /// The order type is not supported by this connector, or the venue refused it as a type it
552 /// does not take for this account or instrument.
553 ///
554 /// Non-transient — place a different order type. A connector usually returns this without
555 /// sending the request (e.g., trailing stop orders on a connector that only supports
556 /// market/limit); when the venue's own refusal says so, it can also come back after the round
557 /// trip.
558 #[error("unsupported order type: {0}")]
559 UnsupportedOrderType(String),
560
561 /// A quantity or price in the request has more precision than the venue accepts, so the
562 /// client refused it without sending it.
563 ///
564 /// Non-transient — change the request. A client that refuses this way never rounds a value
565 /// itself, because rounding would place a different order than the one requested; it
566 /// documents how to read the venue's precision so the caller can round first.
567 #[error("invalid precision: {0}")]
568 InvalidPrecision(PrecisionViolation),
569
570 /// A value in the request is outside the range the venue accepts for the instrument, so the
571 /// client refused it without sending it.
572 ///
573 /// Non-transient — change the request. Unlike [`InvalidPrecision`](Self::InvalidPrecision),
574 /// which says a value is badly formed, this says a well-formed value is too small or too
575 /// large: below a minimum price, quantity or notional, or above a maximum. The error carries
576 /// the limit that was broken, so the caller can resize the order. A client checks only the
577 /// rules it has loaded (see [`OrderRules`](crate::rules::OrderRules)); a request that passes
578 /// can still be rejected by the venue.
579 #[error("out of bounds: {0}")]
580 OutOfBounds(BoundsViolation),
581
582 /// The request names a [`MarginEffect`] this client cannot honour, so it refused the order
583 /// without sending it.
584 ///
585 /// Non-transient — drop the effect (`RequestOpen::margin_effect` of `None` takes the client's
586 /// default) or send the order to a client that honours it. A client refuses rather than
587 /// ignores an effect it cannot honour, because placing the order without it would borrow, or
588 /// not repay, against the caller's intent. Which effects a client honours is on its type: a
589 /// spot or cash account takes only [`NoSideEffect`](MarginEffect::NoSideEffect), a venue
590 /// with account-level margin takes none.
591 #[error("unsupported margin effect: {0:?}")]
592 UnsupportedMarginEffect(MarginEffect),
593}
594
595/// A value in an order request with more precision than the venue accepts, or that is not
596/// positive.
597///
598/// Carried by [`OrderError::InvalidPrecision`].
599#[non_exhaustive]
600#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
601pub struct PrecisionViolation {
602 /// Which value of the request broke the rule.
603 pub field: OrderField,
604 /// The value as requested.
605 pub value: Decimal,
606 /// The rule it broke.
607 pub limit: PrecisionLimit,
608}
609
610impl PrecisionViolation {
611 /// The request's `field`, of `value`, breaks `limit`.
612 pub fn new(field: OrderField, value: Decimal, limit: PrecisionLimit) -> Self {
613 Self {
614 field,
615 value,
616 limit,
617 }
618 }
619}
620
621impl fmt::Display for PrecisionViolation {
622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623 let Self {
624 field,
625 value,
626 limit,
627 } = self;
628 write!(f, "{field} {value} ")?;
629 match limit {
630 PrecisionLimit::DecimalPlaces { max } => {
631 write!(f, "has more than {max} decimal places")
632 }
633 PrecisionLimit::SignificantFigures { max } => {
634 write!(
635 f,
636 "is not an integer and has more than {max} significant figures"
637 )
638 }
639 PrecisionLimit::NotRepresentable => {
640 write!(f, "cannot be sent exactly in the venue's number format")
641 }
642 PrecisionLimit::NotPositive => write!(f, "is not positive"),
643 PrecisionLimit::NotOnGrid { step } => {
644 write!(f, "is not a multiple of {step}")
645 }
646 }
647 }
648}
649
650/// A value in an order request that is below a venue minimum or above a venue maximum.
651///
652/// Carried by [`OrderError::OutOfBounds`].
653#[non_exhaustive]
654#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
655pub struct BoundsViolation {
656 /// Which value of the request broke the bound.
657 pub field: OrderField,
658 /// Whether `value` is below the minimum or above the maximum.
659 pub bound: Bound,
660 /// The limit `value` broke.
661 pub limit: Decimal,
662 /// The value as requested. For [`OrderField::Notional`] it is the price times the quantity.
663 pub value: Decimal,
664}
665
666impl BoundsViolation {
667 /// The request's `field`, of `value`, is beyond the `bound` at `limit`.
668 pub fn new(field: OrderField, bound: Bound, limit: Decimal, value: Decimal) -> Self {
669 Self {
670 field,
671 bound,
672 limit,
673 value,
674 }
675 }
676}
677
678impl fmt::Display for BoundsViolation {
679 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
680 let Self {
681 field,
682 bound,
683 limit,
684 value,
685 } = self;
686 let (relation, name) = match bound {
687 Bound::Min => ("below", "minimum"),
688 Bound::Max => ("above", "maximum"),
689 };
690 write!(f, "{field} {value} is {relation} the {name} {limit}")
691 }
692}
693
694/// Which end of a range a [`BoundsViolation`] broke.
695#[non_exhaustive]
696#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
697pub enum Bound {
698 /// The value is below the minimum.
699 Min,
700 /// The value is above the maximum.
701 Max,
702}
703
704/// A value of an order request, as named by a [`PrecisionViolation`] or [`BoundsViolation`].
705#[non_exhaustive]
706#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
707pub enum OrderField {
708 /// The order's quantity.
709 Quantity,
710 /// The order's limit price.
711 Price,
712 /// The price that triggers a stop or take-profit order.
713 TriggerPrice,
714 /// A trailing order's offset.
715 TrailingOffset,
716 /// The order's price times its quantity, in the quote asset. Never a request field of its
717 /// own: only a [`BoundsViolation`] names it.
718 Notional,
719}
720
721impl fmt::Display for OrderField {
722 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723 f.write_str(match self {
724 Self::Quantity => "quantity",
725 Self::Price => "price",
726 Self::TriggerPrice => "trigger price",
727 Self::TrailingOffset => "trailing offset",
728 Self::Notional => "notional",
729 })
730 }
731}
732
733/// A venue's precision rule, as broken by a [`PrecisionViolation`].
734#[non_exhaustive]
735#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
736pub enum PrecisionLimit {
737 /// The value may have at most `max` decimal places.
738 DecimalPlaces {
739 /// The most decimal places allowed.
740 max: u32,
741 },
742 /// The value may have at most `max` significant figures, unless it is an integer.
743 SignificantFigures {
744 /// The most significant figures allowed.
745 max: u32,
746 },
747 /// The value cannot be sent exactly: the venue's client library converts it to a number
748 /// format that would change it.
749 NotRepresentable,
750 /// The value is zero or negative. A quantity, price or trailing offset must be positive.
751 NotPositive,
752 /// The value is not a whole multiple of `step`: a price must sit on the instrument's tick
753 /// grid and a quantity on its lot grid, counted from zero.
754 NotOnGrid {
755 /// The grid's step: the tick size for a price, the lot step for a quantity.
756 step: Decimal,
757 },
758}
759
760impl<AssetKey, InstrumentKey> OrderError<AssetKey, InstrumentKey> {
761 /// Returns `true` if this error is likely transient and the operation
762 /// may succeed if retried after a suitable backoff.
763 ///
764 /// # Transient errors
765 /// - [`Connectivity`](Self::Connectivity) errors (timeout, socket, offline)
766 /// - [`Rejected(ApiError::RateLimit)`](ApiError::RateLimit), though not before its
767 /// `retry_after`
768 ///
769 /// # Non-transient errors
770 /// - Other [`Rejected`](Self::Rejected) errors (invalid instrument, insufficient balance,
771 /// refused borrow, etc.)
772 /// - [`UnsupportedOrderType`](Self::UnsupportedOrderType),
773 /// [`InvalidPrecision`](Self::InvalidPrecision),
774 /// [`OutOfBounds`](Self::OutOfBounds) and
775 /// [`UnsupportedMarginEffect`](Self::UnsupportedMarginEffect)
776 pub fn is_transient(&self) -> bool {
777 match self {
778 Self::Connectivity(e) => e.is_transient(),
779 Self::Rejected(ApiError::RateLimit { .. }) => true,
780 Self::Rejected(_) => false,
781 Self::UnsupportedOrderType(_)
782 | Self::InvalidPrecision(_)
783 | Self::OutOfBounds(_)
784 | Self::UnsupportedMarginEffect(_) => false,
785 }
786 }
787}
788
789/// Why an account event stream ended.
790///
791/// Delivered in-band as the payload of
792/// [`AccountEventKind::StreamTerminated`](crate::AccountEventKind::StreamTerminated) so that
793/// stream death is a programmatic signal on the account feed rather than a log-only event. A
794/// consumer can react (re-sync via REST, re-establish the stream, halt trading) according to its
795/// own policy — the library reports *why* the stream ended without prescribing the response.
796///
797/// # Only in-band-deliverable terminations are represented
798///
799/// Every variant here is a termination the library can actually deliver to a consumer that is
800/// still listening. A consumer-initiated drop is deliberately **not** a variant: by the time a
801/// stream task observes the drop, the receiving half of the channel is already gone, so a
802/// `StreamTerminated` send would be a guaranteed no-op. `StreamTerminated` therefore always means
803/// "the stream died while you were still listening".
804///
805/// `#[non_exhaustive]` so venues may distinguish further termination causes in future without a
806/// breaking change (e.g. a venue able to signal a graceful shutdown over a still-open channel).
807#[non_exhaustive]
808#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
809pub enum StreamTerminationReason {
810 /// A venue with built-in reconnection exhausted its retry budget and gave up.
811 ///
812 /// Emitted by venues that reconnect internally (e.g. Binance spot/margin, Alpaca) once the
813 /// final attempt fails. Each client documents its budget. `last_error` is the most recent
814 /// underlying failure; `attempts` is the number of reconnects tried before surrendering. The
815 /// stream will not recover on its own — the consumer must re-establish it.
816 #[error("reconnect budget exhausted after {attempts} attempts: {last_error}")]
817 ReconnectBudgetExhausted {
818 /// Number of reconnect attempts made before giving up.
819 attempts: u32,
820 /// The most recent underlying error that triggered surrender.
821 last_error: String,
822 },
823
824 /// The stream ended on an unrecoverable error with no automatic recovery.
825 ///
826 /// Emitted by venues without library-managed reconnection — e.g. IBKR (the underlying
827 /// subscription errored and the client does not retry), Hyperliquid (the SDK closed the
828 /// subscription's channel; its own reconnection never gives up), or the mock exchange (its
829 /// broadcast stream lagged past the buffer). The consumer is responsible for any
830 /// re-establishment.
831 #[error("unrecoverable stream error: {0}")]
832 Error(String),
833
834 /// The venue is refusing this client for exceeding its rate limits, for longer than the
835 /// stream waits through in place.
836 ///
837 /// Emitted by venues that reconnect internally (Binance spot/margin) when a reconnect faces a
838 /// rate-limit cooldown, or a ban, with more than a few seconds left. The stream ends at once
839 /// rather than spend its reconnect budget against a venue that refuses every attempt, and
840 /// reconnects that would lengthen a ban. `retry_after` is how long the cooldown had left: the
841 /// earliest the consumer should re-establish the stream. Opening it sooner fails with
842 /// [`ApiError::RateLimit`], unsent.
843 ///
844 /// Nothing that happens on the account until the stream is re-established reaches the
845 /// consumer through this stream, as after any other termination: re-sync from the new
846 /// stream's snapshot, and read fills of the gap with a trades query. An
847 /// `ExecutionManager` re-opens the stream itself, no sooner than `retry_after`, and reports
848 /// each refused attempt as a `ReinitFailed` carrying the time left.
849 #[error("rate-limited by the venue; retry after {retry_after:?}")]
850 RateLimited {
851 /// How long the venue's cooldown had left when the stream ended.
852 retry_after: Duration,
853 },
854}
855
856/// Type alias for an [`AccountStreamInitError`] that is keyed on [`AssetNameExchange`] and
857/// [`InstrumentNameExchange`] (yet to be indexed).
858pub type UnindexedAccountStreamInitError =
859 AccountStreamInitError<AssetNameExchange, InstrumentNameExchange>;
860
861/// Why an attempt to initialise an account stream, its snapshot and its updates, failed.
862#[non_exhaustive]
863#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
864pub enum AccountStreamInitError<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
865 /// The [`ExecutionClient`](crate::client::ExecutionClient) failed to fetch the account
866 /// snapshot or to open the account stream. See [`ClientError::is_transient`].
867 #[error("{0}")]
868 Client(#[from] ClientError<AssetKey, InstrumentKey>),
869
870 /// The account snapshot named an exchange, asset or instrument that is not indexed. This does
871 /// not resolve on retry while the venue keeps reporting it.
872 #[error("IndexError: {0}")]
873 Index(#[from] IndexError),
874}
875
876impl<AssetKey, InstrumentKey> AccountStreamInitError<AssetKey, InstrumentKey> {
877 /// The venue's minimum wait before the next attempt: `Some` only for a client's
878 /// [`Api::RateLimit`](ApiError::RateLimit) whose venue sent a hint the client could read. See
879 /// [`ClientError::retry_after`].
880 pub fn retry_after(&self) -> Option<Duration> {
881 match self {
882 Self::Client(error) => error.retry_after(),
883 Self::Index(_) => None,
884 }
885 }
886}
887
888/// A failed attempt to re-initialise an account stream after it ended.
889///
890/// Delivered in-band as the payload of
891/// [`AccountEventKind::ReinitFailed`](crate::AccountEventKind::ReinitFailed), once per failed
892/// attempt. Attempts continue with backoff; giving up is the consumer's decision.
893#[non_exhaustive]
894#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, Constructor)]
895pub struct AccountReinitFailure<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
896 /// Consecutive failed attempts since the stream last initialised, starting at 1.
897 pub attempt: u32,
898 /// Why this attempt failed.
899 pub error: AccountStreamInitError<AssetKey, InstrumentKey>,
900}
901
902/// Represents errors related to exchange, asset and instrument identifier key lookups.
903#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Error)]
904pub enum KeyError {
905 /// Indicates an [`ExchangeId`] was encountered that was not indexed, so does not have a
906 /// corresponding `ExchangeIndex`.
907 #[error("ExchangeId: {0}")]
908 ExchangeId(String),
909
910 /// Indicates an [`AssetNameExchange`] was encountered that was not indexed, so does not have a
911 /// corresponding [`AssetIndex`].
912 #[error("AssetKey: {0}")]
913 AssetKey(String),
914
915 /// Indicates an [`InstrumentNameExchange`] was encountered that was no indexed, so does
916 /// not have a corresponding [`InstrumentIndex`].
917 #[error("InstrumentKey: {0}")]
918 InstrumentKey(String),
919}
920
921#[cfg(test)]
922#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
923mod tests {
924 use super::*;
925 use rust_decimal_macros::dec;
926
927 #[test]
928 fn a_rate_limit_carries_and_shows_the_venues_wait() {
929 let hinted: UnindexedApiError = ApiError::rate_limited(Some(Duration::from_secs(7)));
930 assert_eq!(hinted.retry_after(), Some(Duration::from_secs(7)));
931 assert_eq!(hinted.to_string(), "rate limit exceeded; retry after 7s");
932 assert!(UnindexedClientError::Api(hinted.clone()).is_transient());
933 assert!(UnindexedOrderError::Rejected(hinted).is_transient());
934
935 let unhinted: UnindexedApiError = ApiError::rate_limited(None);
936 assert_eq!(unhinted.retry_after(), None);
937 assert_eq!(unhinted.to_string(), "rate limit exceeded");
938
939 let other: UnindexedApiError = ApiError::Unauthenticated("bad key".to_string());
940 assert_eq!(other.retry_after(), None);
941 }
942
943 #[test]
944 fn a_client_or_init_error_reads_the_wait_of_its_rate_limit() {
945 let wait = Some(Duration::from_secs(7));
946 let hinted = UnindexedClientError::Api(ApiError::rate_limited(wait));
947 assert_eq!(hinted.retry_after(), wait);
948 assert_eq!(
949 UnindexedAccountStreamInitError::Client(hinted).retry_after(),
950 wait
951 );
952
953 let unhinted = UnindexedClientError::Api(ApiError::rate_limited(None));
954 assert_eq!(unhinted.retry_after(), None);
955 let socket = UnindexedClientError::Connectivity(ConnectivityError::Timeout);
956 assert_eq!(socket.retry_after(), None);
957 assert_eq!(
958 UnindexedAccountStreamInitError::Client(socket).retry_after(),
959 None
960 );
961 }
962
963 #[test]
964 fn a_rate_limited_termination_shows_and_round_trips_its_wait() {
965 let reason = StreamTerminationReason::RateLimited {
966 retry_after: Duration::from_secs(120),
967 };
968 assert_eq!(
969 reason.to_string(),
970 "rate-limited by the venue; retry after 120s"
971 );
972 let json = serde_json::to_string(&reason).unwrap();
973 assert_eq!(
974 serde_json::from_str::<StreamTerminationReason>(&json).unwrap(),
975 reason
976 );
977 }
978
979 #[test]
980 fn a_rate_limit_round_trips_through_serde() {
981 for retry_after in [None, Some(Duration::from_millis(7_250))] {
982 let error: UnindexedApiError = ApiError::rate_limited(retry_after);
983 let json = serde_json::to_string(&error).unwrap();
984 assert_eq!(
985 serde_json::from_str::<UnindexedApiError>(&json).unwrap(),
986 error,
987 "{json}"
988 );
989 }
990 }
991
992 #[test]
993 fn test_connectivity_error_is_transient() {
994 assert!(ConnectivityError::Timeout.is_transient());
995 assert!(ConnectivityError::Socket("connection refused".into()).is_transient());
996 assert!(ConnectivityError::ExchangeOffline(ExchangeId::BinanceSpot).is_transient());
997 }
998
999 #[test]
1000 fn test_client_error_is_transient_connectivity() {
1001 let err: ClientError = ClientError::Connectivity(ConnectivityError::Timeout);
1002 assert!(err.is_transient());
1003
1004 let err: ClientError = ClientError::Connectivity(ConnectivityError::Socket("err".into()));
1005 assert!(err.is_transient());
1006 }
1007
1008 #[test]
1009 fn test_client_error_is_transient_rate_limit() {
1010 let err: ClientError = ClientError::Api(ApiError::rate_limited(None));
1011 assert!(err.is_transient());
1012 }
1013
1014 #[test]
1015 fn test_client_error_not_transient_api_errors() {
1016 let err: ClientError =
1017 ClientError::Api(ApiError::AssetInvalid(AssetIndex(0), "bad".into()));
1018 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1019
1020 let err: ClientError = ClientError::Api(ApiError::BalanceInsufficient(
1021 Some(AssetIndex(0)),
1022 "low".into(),
1023 ));
1024 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1025
1026 let err: ClientError = ClientError::Api(ApiError::InstrumentInvalid(
1027 InstrumentIndex(0),
1028 "bad".into(),
1029 ));
1030 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1031
1032 let err: ClientError = ClientError::Api(ApiError::OrderRejected("rejected".into()));
1033 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1034
1035 let err: ClientError = ClientError::Api(ApiError::OrderAlreadyCancelled);
1036 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1037
1038 let err: ClientError = ClientError::Api(ApiError::OrderAlreadyFullyFilled);
1039 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1040
1041 let err: ClientError =
1042 ClientError::Api(ApiError::Unauthenticated("invalid signature".into()));
1043 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1044
1045 let err: ClientError =
1046 ClientError::Api(ApiError::RequestRejected("-1127 More than 24 hours".into()));
1047 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1048
1049 let err: ClientError = ClientError::Api(ApiError::BorrowRejected(BorrowReject::new(
1050 BorrowRejectReason::InventoryUnavailable,
1051 Some("-3045".into()),
1052 "-3045 The system doesn't have enough asset now.".into(),
1053 )));
1054 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1055 }
1056
1057 #[test]
1058 fn borrow_rejected_shows_its_reason_and_code() {
1059 let coded: UnindexedApiError = ApiError::BorrowRejected(BorrowReject::new(
1060 BorrowRejectReason::BorrowDisabled,
1061 Some("40310000".into()),
1062 "account is not allowed to short".into(),
1063 ));
1064 assert_eq!(
1065 coded.to_string(),
1066 "borrow rejected: borrow disabled (code 40310000): account is not allowed to short"
1067 );
1068
1069 let uncoded: UnindexedApiError = ApiError::BorrowRejected(BorrowReject::new(
1070 BorrowRejectReason::Other,
1071 None,
1072 "no borrow".into(),
1073 ));
1074 assert_eq!(uncoded.to_string(), "borrow rejected: other: no borrow");
1075
1076 let short: UnindexedApiError = ApiError::BorrowRejected(BorrowReject::new(
1077 BorrowRejectReason::ShortSaleRestricted,
1078 None,
1079 "priced at the bid".into(),
1080 ));
1081 assert_eq!(
1082 short.to_string(),
1083 "borrow rejected: short sale restricted: priced at the bid"
1084 );
1085 }
1086
1087 #[test]
1088 fn borrow_rejected_shows_what_is_available_only_when_known() {
1089 let reject = BorrowReject::new(
1090 BorrowRejectReason::InventoryUnavailable,
1091 None,
1092 "too little to lend".into(),
1093 );
1094 assert_eq!(reject.available, None);
1095
1096 let reject = reject.with_available(dec!(2.5));
1097 assert_eq!(reject.available, Some(dec!(2.5)));
1098 assert_eq!(
1099 reject.to_string(),
1100 "inventory unavailable: too little to lend (2.5 available)"
1101 );
1102 }
1103
1104 #[test]
1105 fn balance_insufficient_names_its_asset_only_when_known() {
1106 let named: UnindexedApiError =
1107 ApiError::BalanceInsufficient(Some(AssetNameExchange::new("BTC")), "low".to_string());
1108 assert_eq!(named.to_string(), "balance insufficient for asset BTC: low");
1109
1110 let unnamed: UnindexedApiError = ApiError::BalanceInsufficient(None, "low".to_string());
1111 assert_eq!(unnamed.to_string(), "balance insufficient: low");
1112 }
1113
1114 #[test]
1115 fn test_client_error_not_transient_task_failed() {
1116 let err: ClientError = ClientError::TaskFailed("task panicked".into());
1117 assert!(!err.is_transient());
1118 }
1119
1120 #[test]
1121 fn test_client_error_not_transient_internal() {
1122 let err: ClientError = ClientError::Internal("unknown error".into());
1123 assert!(!err.is_transient());
1124 }
1125
1126 #[test]
1127 fn test_client_error_not_transient_truncated() {
1128 let err: ClientError = ClientError::Truncated { fills_read: 5_000 };
1129 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1130
1131 let err: ClientError = ClientError::TruncatedSnapshot { limit: 500 };
1132 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1133 }
1134
1135 #[test]
1136 fn test_client_error_is_transient_exchange_offline() {
1137 let err: ClientError =
1138 ClientError::Connectivity(ConnectivityError::ExchangeOffline(ExchangeId::BinanceSpot));
1139 assert!(err.is_transient(), "expected transient for {:?}", err);
1140 }
1141
1142 #[test]
1143 fn test_order_error_is_transient_connectivity() {
1144 let err: UnindexedOrderError = OrderError::Connectivity(ConnectivityError::Timeout);
1145 assert!(err.is_transient(), "expected transient for {:?}", err);
1146
1147 let err: UnindexedOrderError =
1148 OrderError::Connectivity(ConnectivityError::Socket("connection reset".into()));
1149 assert!(err.is_transient(), "expected transient for {:?}", err);
1150
1151 let err: UnindexedOrderError =
1152 OrderError::Connectivity(ConnectivityError::ExchangeOffline(ExchangeId::BinanceSpot));
1153 assert!(err.is_transient(), "expected transient for {:?}", err);
1154 }
1155
1156 #[test]
1157 fn test_order_error_is_transient_rate_limit() {
1158 let err: UnindexedOrderError = OrderError::Rejected(ApiError::rate_limited(None));
1159 assert!(err.is_transient(), "expected transient for {:?}", err);
1160 }
1161
1162 #[test]
1163 fn test_order_error_not_transient_api_errors() {
1164 let err: UnindexedOrderError =
1165 OrderError::Rejected(ApiError::OrderRejected("price out of range".into()));
1166 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1167
1168 let err: UnindexedOrderError = OrderError::Rejected(ApiError::OrderAlreadyCancelled);
1169 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1170
1171 let err: UnindexedOrderError =
1172 OrderError::Rejected(ApiError::BorrowRejected(BorrowReject::new(
1173 BorrowRejectReason::NotShortable,
1174 None,
1175 "asset XYZ cannot be sold short".into(),
1176 )));
1177 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1178
1179 let err: UnindexedOrderError = OrderError::Rejected(ApiError::BalanceInsufficient(
1180 Some(AssetNameExchange::from("BTC")),
1181 "insufficient".into(),
1182 ));
1183 assert!(!err.is_transient(), "expected non-transient for {:?}", err);
1184 }
1185}