use serde::{Deserialize, Serialize};
use crate::order::OrderStatus;
pub type Result<T, E = ExchangeError> = std::result::Result<T, E>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RejectReason {
InsufficientFunds,
BelowMinSize,
AboveMaxSize,
BelowMinNotional,
BadIncrement,
PostOnlyWouldTake,
WouldNotFill,
UnknownProduct,
DuplicateClientId,
TradingDisabled,
UnsupportedOrder,
ReduceOnly,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[serde(rename_all = "snake_case", tag = "kind")]
#[non_exhaustive]
pub enum ExchangeError {
#[error("rate limited")]
RateLimited { retry_after_ms: Option<u64> },
#[error("rejected ({reason:?}): {message}")]
Rejected { reason: RejectReason, message: String },
#[error("transient failure: {message}")]
Transient { message: String, outcome_unknown: bool },
#[error("authentication failed: {message}")]
Auth { message: String },
#[error("unavailable: {message}")]
Unavailable { message: String },
#[error("unsupported: {message}")]
Unsupported { message: String },
#[error("not found: {message}")]
NotFound { message: String },
#[error("invalid: {message}")]
Invalid { message: String },
#[error("book gap: expected sequence {expected}, got {got}")]
BookGap { expected: u64, got: u64 },
#[error("order in state {from:?} cannot take {event}")]
InvalidTransition { from: OrderStatus, event: String },
#[error("environment: {message}")]
Environment { message: String },
}
impl ExchangeError {
pub fn rejected(reason: RejectReason, message: impl Into<String>) -> Self {
Self::Rejected { reason, message: message.into() }
}
pub fn invalid(message: impl Into<String>) -> Self {
Self::Invalid { message: message.into() }
}
pub fn not_found(message: impl Into<String>) -> Self {
Self::NotFound { message: message.into() }
}
pub fn unsupported(message: impl Into<String>) -> Self {
Self::Unsupported { message: message.into() }
}
pub fn transient(message: impl Into<String>, outcome_unknown: bool) -> Self {
Self::Transient { message: message.into(), outcome_unknown }
}
pub fn is_retryable(&self) -> bool {
matches!(self, Self::RateLimited { .. } | Self::Unavailable { .. }) || matches!(self, Self::Transient { outcome_unknown: false, .. })
}
pub fn reject_reason(&self) -> Option<RejectReason> {
match self {
Self::Rejected { reason, .. } => Some(*reason),
_ => None,
}
}
}