nautilus-bitmex 0.55.0

BitMEX exchange integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Retry classification for the BitMEX adapter.
//!
//! This module provides an error taxonomy that distinguishes between
//! retryable, non-retryable, and fatal errors, with proper context preservation
//! for debugging and operational monitoring.

use std::time::Duration;

use nautilus_network::http::{HttpClientError, StatusCode};
use thiserror::Error;
use tokio_tungstenite::tungstenite;

use crate::http::error::BitmexBuildError;

/// The main error type for all BitMEX adapter operations.
#[derive(Debug, Error)]
pub enum BitmexError {
    /// Errors that should be retried with backoff.
    #[error("Retryable error: {source}")]
    Retryable {
        #[source]
        source: BitmexRetryableError,
        /// Suggested retry after duration, if provided by the server.
        retry_after: Option<Duration>,
    },

    /// Errors that should not be retried.
    #[error("Non-retryable error: {source}")]
    NonRetryable {
        #[source]
        source: BitmexNonRetryableError,
    },

    /// Fatal errors that require intervention.
    #[error("Fatal error: {source}")]
    Fatal {
        #[source]
        source: BitmexFatalError,
    },

    /// Network transport errors.
    #[error("Network error: {0}")]
    Network(#[from] HttpClientError),

    /// WebSocket specific errors.
    #[error("WebSocket error: {0}")]
    WebSocket(#[from] tungstenite::Error),

    /// JSON serialization/deserialization errors.
    #[error("JSON error: {message}")]
    Json {
        message: String,
        /// The raw JSON that failed to parse, if available.
        raw: Option<String>,
    },

    /// Configuration errors.
    #[error("Configuration error: {0}")]
    Config(String),
}

/// Errors that should be retried with appropriate backoff.
#[derive(Debug, Error)]
pub enum BitmexRetryableError {
    /// Rate limit exceeded (HTTP 429).
    #[error("Rate limit exceeded (remaining: {remaining:?}, reset: {reset_at:?})")]
    RateLimit {
        remaining: Option<u32>,
        reset_at: Option<Duration>,
    },

    /// Service unavailable (HTTP 503).
    #[error("Service temporarily unavailable")]
    ServiceUnavailable,

    /// Gateway timeout (HTTP 504).
    #[error("Gateway timeout")]
    GatewayTimeout,

    /// Server error (HTTP 5xx).
    #[error("Server error (status: {status})")]
    ServerError { status: StatusCode },

    /// Network timeout.
    #[error("Request timed out after {duration:?}")]
    Timeout { duration: Duration },

    /// Temporary network issue.
    #[error("Temporary network error: {message}")]
    TemporaryNetwork { message: String },

    /// WebSocket connection lost.
    #[error("WebSocket connection lost")]
    ConnectionLost,

    /// Order book resync required.
    #[error("Order book resync required for {symbol}")]
    OrderBookResync { symbol: String },
}

/// Errors that should not be retried.
#[derive(Debug, Error)]
pub enum BitmexNonRetryableError {
    /// Bad request (HTTP 400).
    #[error("Bad request: {message}")]
    BadRequest { message: String },

    /// Not found (HTTP 404).
    #[error("Resource not found: {resource}")]
    NotFound { resource: String },

    /// Method not allowed (HTTP 405).
    #[error("Method not allowed: {method}")]
    MethodNotAllowed { method: String },

    /// Validation error.
    #[error("Validation error: {field}: {message}")]
    Validation { field: String, message: String },

    /// Invalid order parameters.
    #[error("Invalid order: {message}")]
    InvalidOrder { message: String },

    /// Insufficient balance.
    #[error("Insufficient balance: {available} < {required}")]
    InsufficientBalance { available: String, required: String },

    /// Symbol not found or invalid.
    #[error("Invalid symbol: {symbol}")]
    InvalidSymbol { symbol: String },

    /// Invalid API request format.
    #[error("Invalid request format: {message}")]
    InvalidRequest { message: String },

    /// Missing required parameter.
    #[error("Missing required parameter: {param}")]
    MissingParameter { param: String },

    /// Order not found.
    #[error("Order not found: {order_id}")]
    OrderNotFound { order_id: String },

    /// Position not found.
    #[error("Position not found: {symbol}")]
    PositionNotFound { symbol: String },
}

/// Fatal errors that require manual intervention.
#[derive(Debug, Error)]
pub enum BitmexFatalError {
    /// Authentication failed (HTTP 401).
    #[error("Authentication failed: {message}")]
    AuthenticationFailed { message: String },

    /// Forbidden (HTTP 403).
    #[error("Forbidden: {message}")]
    Forbidden { message: String },

    /// Account suspended.
    #[error("Account suspended: {reason}")]
    AccountSuspended { reason: String },

    /// Invalid API credentials.
    #[error("Invalid API credentials")]
    InvalidCredentials,

    /// API version no longer supported.
    #[error("API version no longer supported")]
    ApiVersionDeprecated,

    /// Critical invariant violation.
    #[error("Critical invariant violation: {invariant}")]
    InvariantViolation { invariant: String },
}

impl BitmexError {
    /// Creates a new rate limit error from HTTP headers.
    ///
    /// # Parameters
    ///
    /// - `remaining`: X-RateLimit-Remaining header value
    /// - `reset`: X-RateLimit-Reset header value (UNIX timestamp in seconds)
    /// - `retry_after`: Retry-After header value (seconds to wait)
    pub fn from_rate_limit_headers(
        remaining: Option<&str>,
        reset: Option<&str>,
        retry_after: Option<&str>,
    ) -> Self {
        let remaining = remaining.and_then(|s| s.parse().ok());

        // X-RateLimit-Reset is a UNIX timestamp, compute duration from now
        let reset_at = reset.and_then(|s| {
            s.parse::<u64>().ok().and_then(|timestamp| {
                let now = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .ok()?
                    .as_secs();

                if timestamp > now {
                    Some(Duration::from_secs(timestamp - now))
                } else {
                    Some(Duration::from_secs(0))
                }
            })
        });

        // Prefer explicit Retry-After header if present
        let retry_duration = retry_after
            .and_then(|s| s.parse::<u64>().ok().map(Duration::from_secs))
            .or(reset_at);

        Self::Retryable {
            source: BitmexRetryableError::RateLimit {
                remaining,
                reset_at,
            },
            retry_after: retry_duration,
        }
    }

    /// Creates an error from an HTTP status code and optional message.
    pub fn from_http_status(status: StatusCode, message: Option<String>) -> Self {
        match status {
            StatusCode::BAD_REQUEST => Self::NonRetryable {
                source: BitmexNonRetryableError::BadRequest {
                    message: message.unwrap_or_else(|| "Bad request".to_string()),
                },
            },
            StatusCode::UNAUTHORIZED => Self::Fatal {
                source: BitmexFatalError::AuthenticationFailed {
                    message: message.unwrap_or_else(|| "Unauthorized".to_string()),
                },
            },
            StatusCode::FORBIDDEN => Self::Fatal {
                source: BitmexFatalError::Forbidden {
                    message: message.unwrap_or_else(|| "Forbidden".to_string()),
                },
            },
            StatusCode::NOT_FOUND => Self::NonRetryable {
                source: BitmexNonRetryableError::NotFound {
                    resource: message.unwrap_or_else(|| "Resource".to_string()),
                },
            },
            StatusCode::METHOD_NOT_ALLOWED => Self::NonRetryable {
                source: BitmexNonRetryableError::MethodNotAllowed {
                    method: message.unwrap_or_else(|| "Method".to_string()),
                },
            },
            StatusCode::TOO_MANY_REQUESTS => Self::from_rate_limit_headers(None, None, None),
            StatusCode::SERVICE_UNAVAILABLE => Self::Retryable {
                source: BitmexRetryableError::ServiceUnavailable,
                retry_after: None,
            },
            StatusCode::GATEWAY_TIMEOUT => Self::Retryable {
                source: BitmexRetryableError::GatewayTimeout,
                retry_after: None,
            },
            s if s.is_server_error() => Self::Retryable {
                source: BitmexRetryableError::ServerError { status },
                retry_after: None,
            },
            _ => Self::NonRetryable {
                source: BitmexNonRetryableError::InvalidRequest {
                    message: format!("Unexpected status: {status}"),
                },
            },
        }
    }

    /// Checks if this error is retryable.
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        matches!(self, Self::Retryable { .. })
    }

    /// Checks if this error is fatal.
    #[must_use]
    pub fn is_fatal(&self) -> bool {
        matches!(self, Self::Fatal { .. })
    }

    /// Gets the suggested retry duration if available.
    #[must_use]
    pub fn retry_after(&self) -> Option<Duration> {
        match self {
            Self::Retryable { retry_after, .. } => *retry_after,
            _ => None,
        }
    }
}

impl From<serde_json::Error> for BitmexError {
    fn from(error: serde_json::Error) -> Self {
        Self::Json {
            message: error.to_string(),
            raw: None,
        }
    }
}

impl From<BitmexBuildError> for BitmexError {
    fn from(error: BitmexBuildError) -> Self {
        Self::NonRetryable {
            source: BitmexNonRetryableError::Validation {
                field: "parameters".to_string(),
                message: error.to_string(),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    #[rstest]
    fn test_error_classification() {
        let err = BitmexError::from_http_status(StatusCode::TOO_MANY_REQUESTS, None);
        assert!(err.is_retryable());
        assert!(!err.is_fatal());

        let err = BitmexError::from_http_status(StatusCode::UNAUTHORIZED, None);
        assert!(!err.is_retryable());
        assert!(err.is_fatal());

        let err = BitmexError::from_http_status(StatusCode::BAD_REQUEST, None);
        assert!(!err.is_retryable());
        assert!(!err.is_fatal());
    }

    #[rstest]
    fn test_rate_limit_parsing() {
        // Use a timestamp far in the future to ensure retry_after is computed
        let future_timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 60;
        let err = BitmexError::from_rate_limit_headers(
            Some("10"),
            Some(&future_timestamp.to_string()),
            None,
        );
        match err {
            BitmexError::Retryable {
                source: BitmexRetryableError::RateLimit { remaining, .. },
                retry_after,
                ..
            } => {
                assert_eq!(remaining, Some(10));
                assert!(retry_after.is_some());
                let duration = retry_after.unwrap();
                assert!(duration.as_secs() >= 59 && duration.as_secs() <= 61);
            }
            _ => panic!("Expected rate limit error"),
        }
    }

    #[rstest]
    fn test_rate_limit_with_retry_after() {
        let err = BitmexError::from_rate_limit_headers(Some("0"), None, Some("30"));
        match err {
            BitmexError::Retryable {
                source: BitmexRetryableError::RateLimit { remaining, .. },
                retry_after,
                ..
            } => {
                assert_eq!(remaining, Some(0));
                assert_eq!(retry_after, Some(Duration::from_secs(30)));
            }
            _ => panic!("Expected rate limit error"),
        }
    }

    #[rstest]
    fn test_retry_after() {
        let err = BitmexError::Retryable {
            source: BitmexRetryableError::RateLimit {
                remaining: Some(0),
                reset_at: Some(Duration::from_secs(60)),
            },
            retry_after: Some(Duration::from_secs(60)),
        };
        assert_eq!(err.retry_after(), Some(Duration::from_secs(60)));
    }
}