Skip to main content

weirdnet_exchange/
error.rs

1//! Errors adapters and helpers return.
2
3use serde::{Deserialize, Serialize};
4
5use crate::order::OrderStatus;
6
7/// Shorthand for results with [`ExchangeError`].
8pub type Result<T, E = ExchangeError> = std::result::Result<T, E>;
9
10/// Why a venue refused an order.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13#[non_exhaustive]
14pub enum RejectReason {
15    InsufficientFunds,
16    BelowMinSize,
17    AboveMaxSize,
18    BelowMinNotional,
19    /// The price or size is not a multiple of the product's increment.
20    BadIncrement,
21    /// A post-only order would have taken liquidity.
22    PostOnlyWouldTake,
23    /// A fill-or-kill order could not fill in full.
24    WouldNotFill,
25    UnknownProduct,
26    /// The client order id was already used for a different order.
27    DuplicateClientId,
28    /// The product is halted, delisted, cancel-only, or limit-only for a market order.
29    TradingDisabled,
30    /// The order type or time in force is not supported by this venue.
31    UnsupportedOrder,
32    /// A reduce-only order would open or grow a position.
33    ReduceOnly,
34    Other,
35}
36
37/// What went wrong talking to a venue, or in a helper.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
39#[serde(rename_all = "snake_case", tag = "kind")]
40#[non_exhaustive]
41pub enum ExchangeError {
42    /// Too many requests; wait `retry_after_ms` when the venue said how long.
43    #[error("rate limited")]
44    RateLimited { retry_after_ms: Option<u64> },
45    /// The venue refused the request.
46    #[error("rejected ({reason:?}): {message}")]
47    Rejected { reason: RejectReason, message: String },
48    /// A timeout or server error. With `outcome_unknown` (an order that may or may not have
49    /// been placed), look the order up by its client id before retrying.
50    #[error("transient failure: {message}")]
51    Transient { message: String, outcome_unknown: bool },
52    /// The credentials were refused.
53    #[error("authentication failed: {message}")]
54    Auth { message: String },
55    /// The venue or product is down for maintenance.
56    #[error("unavailable: {message}")]
57    Unavailable { message: String },
58    /// The adapter or venue does not support this.
59    #[error("unsupported: {message}")]
60    Unsupported { message: String },
61    #[error("not found: {message}")]
62    NotFound { message: String },
63    /// The request or value is not valid.
64    #[error("invalid: {message}")]
65    Invalid { message: String },
66    /// An order book delta did not follow the last sequence number; fetch a new snapshot.
67    #[error("book gap: expected sequence {expected}, got {got}")]
68    BookGap { expected: u64, got: u64 },
69    /// An order event that is not possible in the order's state.
70    #[error("order in state {from:?} cannot take {event}")]
71    InvalidTransition { from: OrderStatus, event: String },
72    /// Credentials for the wrong environment (test credentials for a live adapter).
73    #[error("environment: {message}")]
74    Environment { message: String },
75}
76
77impl ExchangeError {
78    pub fn rejected(reason: RejectReason, message: impl Into<String>) -> Self {
79        Self::Rejected { reason, message: message.into() }
80    }
81
82    pub fn invalid(message: impl Into<String>) -> Self {
83        Self::Invalid { message: message.into() }
84    }
85
86    pub fn not_found(message: impl Into<String>) -> Self {
87        Self::NotFound { message: message.into() }
88    }
89
90    pub fn unsupported(message: impl Into<String>) -> Self {
91        Self::Unsupported { message: message.into() }
92    }
93
94    pub fn transient(message: impl Into<String>, outcome_unknown: bool) -> Self {
95        Self::Transient { message: message.into(), outcome_unknown }
96    }
97
98    /// The same request may succeed later (rate limits, transient failures, maintenance).
99    /// A transient failure with an unknown outcome is retryable only after checking.
100    pub fn is_retryable(&self) -> bool {
101        matches!(self, Self::RateLimited { .. } | Self::Unavailable { .. }) || matches!(self, Self::Transient { outcome_unknown: false, .. })
102    }
103
104    /// The reject reason, if the venue rejected the request.
105    pub fn reject_reason(&self) -> Option<RejectReason> {
106        match self {
107            Self::Rejected { reason, .. } => Some(*reason),
108            _ => None,
109        }
110    }
111}