Skip to main content

nautilus_architect_ax/http/
client.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Provides the HTTP client integration for the Ax REST API.
17
18use std::{
19    collections::{HashMap, HashSet},
20    fmt::Debug,
21    num::NonZeroU32,
22    sync::{
23        Arc, LazyLock,
24        atomic::{AtomicBool, Ordering},
25    },
26    time::Duration,
27};
28
29use ahash::AHashMap;
30use anyhow::Context;
31use http::Method;
32use jiff::{Timestamp, civil::Date};
33use nautilus_core::{
34    AtomicMap, AtomicTime, UUID4, nanos::UnixNanos, string::secret::SecretString,
35    time::get_atomic_clock_realtime,
36};
37use nautilus_model::{
38    data::{Bar, BookOrder, FundingRateUpdate, TradeTick},
39    enums::{BookType, OrderSide, OrderStatus, OrderType, TimeInForce},
40    events::AccountState,
41    fees::MakerTakerFeeRates,
42    identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
43    instruments::{Instrument, any::InstrumentAny},
44    orderbook::OrderBook,
45    reports::{FillReport, OrderStatusReport, PositionStatusReport},
46    types::{Price, Quantity},
47};
48use nautilus_network::{
49    backoff::ExponentialBackoff,
50    http::{HttpClient, HttpRedirectPolicy, create_standard_nautilus_headers},
51    ratelimiter::quota::Quota,
52    retry::{RetryConfig, RetryError, RetryManager},
53};
54use parking_lot::RwLock;
55use rust_decimal::Decimal;
56use serde::{Serialize, de::DeserializeOwned};
57use tokio_util::sync::CancellationToken;
58use ustr::Ustr;
59
60use super::{
61    error::{AxErrorResponse, AxHttpError},
62    models::{
63        AuthenticateApiKeyRequest, AxAuthenticateResponse, AxBalancesResponse, AxBookResponse,
64        AxCancelAllOrdersResponse, AxCancelOrderResponse, AxCandle, AxCandleResponse,
65        AxCandlesResponse, AxFillsResponse, AxFundingRatesResponse, AxFundingSlotsResponse,
66        AxInitialMarginRequirementResponse, AxInstrument, AxInstrumentsResponse,
67        AxOpenOrdersResponse, AxOrderDetail, AxOrderRejectReason, AxOrderStatusQueryResponse,
68        AxOrdersResponse, AxPlaceOrderResponse, AxPositionsResponse,
69        AxPreviewAggressiveLimitOrderResponse, AxReplaceOrderResponse, AxRiskSnapshotResponse,
70        AxTicker, AxTickerResponse, AxTickersResponse, AxTradesResponse, AxTransactionsResponse,
71        AxWhoAmI, CancelAllOrdersRequest, CancelOrderRequest, PlaceOrderRequest,
72        PreviewAggressiveLimitOrderRequest, ReplaceOrderRequest,
73    },
74    parse::{
75        parse_account_state, parse_bar, parse_fill_report, parse_funding_rate, parse_instrument,
76        parse_order_detail_status_report, parse_order_status, parse_order_status_report,
77        parse_position_status_report, parse_trade_tick, update_order_report_timestamps,
78    },
79    query::{
80        GetBookParams, GetCandleParams, GetCandlesParams, GetFillsParams, GetFundingRatesParams,
81        GetFundingSlotsParams, GetInstrumentParams, GetOpenOrdersParams, GetOrderStatusParams,
82        GetOrdersParams, GetTickerParams, GetTickersParams, GetTradesParams, GetTransactionsParams,
83    },
84};
85use crate::common::{
86    consts::{
87        AX_FILLS_MAX_LOOKBACK_DAYS, AX_HTTP_SANDBOX_URL, AX_HTTP_URL, AX_ORDERS_SANDBOX_URL,
88        AX_ORDERS_URL,
89    },
90    credential::Credential,
91    enums::{AxCandleWidth, AxInstrumentState},
92    parse::{ax_timestamp_stn_to_unix_nanos, cid_to_client_order_id, client_order_id_to_cid},
93};
94
95/// Default Ax REST API rate limit.
96///
97/// Conservative default of 10 requests per second.
98pub static AX_REST_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
99    Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant")
100});
101
102const AX_GLOBAL_RATE_KEY: &str = "architect:global";
103
104/// Raw HTTP client for low-level AX Exchange API operations.
105///
106/// This client handles request/response operations with the AX Exchange API,
107/// returning venue-specific response types. It does not parse to Nautilus domain types.
108/// Order-management operations require `orders_base_url` when `base_url` is a custom endpoint.
109pub struct AxRawHttpClient {
110    base_url: String,
111    orders_base_url: Option<String>,
112    client: HttpClient,
113    credential: Option<Credential>,
114    session_token: RwLock<Option<SecretString>>,
115    retry_manager: RetryManager<AxHttpError>,
116    cancellation_token: RwLock<CancellationToken>,
117}
118
119impl Default for AxRawHttpClient {
120    fn default() -> Self {
121        Self::new(None, None, 60, 3, 1000, 10_000, None)
122            .expect("Failed to create default AxRawHttpClient")
123    }
124}
125
126impl Debug for AxRawHttpClient {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        let has_session_token = self.session_token.read().is_some();
129        f.debug_struct(stringify!(AxRawHttpClient))
130            .field("base_url", &self.base_url)
131            .field("orders_base_url", &self.orders_base_url)
132            .field("has_credentials", &self.credential.is_some())
133            .field("has_session_token", &has_session_token)
134            .finish()
135    }
136}
137
138impl AxRawHttpClient {
139    /// Returns the base URL for this client.
140    #[must_use]
141    pub fn base_url(&self) -> &str {
142        &self.base_url
143    }
144
145    fn orders_base_url(&self) -> Result<&str, AxHttpError> {
146        self.orders_base_url.as_deref().ok_or_else(|| {
147            AxHttpError::ValidationError(
148                "Orders base URL is required for order-management operations with a custom API base URL"
149                    .to_string(),
150            )
151        })
152    }
153
154    /// Returns a masked version of the API key for logging purposes.
155    #[must_use]
156    pub fn api_key_masked(&self) -> String {
157        self.credential
158            .as_ref()
159            .map_or_else(|| "None".to_string(), |c| c.masked_api_key())
160    }
161
162    /// Cancel all pending HTTP requests.
163    pub fn cancel_all_requests(&self) {
164        self.cancellation_token.read().cancel();
165    }
166
167    /// Replaces the cancelled token so new requests can proceed after reconnect.
168    pub fn reset_cancellation_token(&self) {
169        *self.cancellation_token.write() = CancellationToken::new();
170    }
171
172    /// Get a clone of the current cancellation token.
173    pub fn cancellation_token(&self) -> CancellationToken {
174        self.cancellation_token.read().clone()
175    }
176
177    /// Creates a new [`AxRawHttpClient`] using the default Ax HTTP URL.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error if the retry manager cannot be created.
182    pub fn new(
183        base_url: Option<String>,
184        orders_base_url: Option<String>,
185        timeout_secs: u64,
186        max_retries: u32,
187        retry_delay_ms: u64,
188        retry_delay_max_ms: u64,
189        proxy_url: Option<String>,
190    ) -> Result<Self, AxHttpError> {
191        let retry_config = retry_config(
192            timeout_secs,
193            max_retries,
194            retry_delay_ms,
195            retry_delay_max_ms,
196        )?;
197        let retry_manager = RetryManager::new(retry_config);
198        let (base_url, orders_base_url) = resolve_base_urls(base_url, orders_base_url);
199
200        Ok(Self {
201            base_url,
202            orders_base_url,
203            client: HttpClient::builder()
204                .redirect_policy(HttpRedirectPolicy::Reject)
205                .headers(Self::default_headers())
206                .keyed_quotas(Self::rate_limiter_quotas())
207                .default_quota(*AX_REST_QUOTA)
208                .timeout_secs(timeout_secs)
209                .maybe_proxy_url(proxy_url)
210                .build()
211                .map_err(|e| {
212                    AxHttpError::NetworkError(format!("Failed to create HTTP client: {e}"))
213                })?,
214            credential: None,
215            session_token: RwLock::new(None),
216            retry_manager,
217            cancellation_token: RwLock::new(CancellationToken::new()),
218        })
219    }
220
221    /// Creates a new [`AxRawHttpClient`] configured with credentials.
222    ///
223    /// # Errors
224    ///
225    /// Returns an error if the HTTP client cannot be created.
226    #[expect(clippy::too_many_arguments)]
227    pub fn with_credentials(
228        api_key: String,
229        api_secret: String,
230        base_url: Option<String>,
231        orders_base_url: Option<String>,
232        timeout_secs: u64,
233        max_retries: u32,
234        retry_delay_ms: u64,
235        retry_delay_max_ms: u64,
236        proxy_url: Option<String>,
237    ) -> Result<Self, AxHttpError> {
238        let retry_config = retry_config(
239            timeout_secs,
240            max_retries,
241            retry_delay_ms,
242            retry_delay_max_ms,
243        )?;
244        let retry_manager = RetryManager::new(retry_config);
245        let (base_url, orders_base_url) = resolve_base_urls(base_url, orders_base_url);
246
247        Ok(Self {
248            base_url,
249            orders_base_url,
250            client: HttpClient::builder()
251                .redirect_policy(HttpRedirectPolicy::Reject)
252                .headers(Self::default_headers())
253                .keyed_quotas(Self::rate_limiter_quotas())
254                .default_quota(*AX_REST_QUOTA)
255                .timeout_secs(timeout_secs)
256                .maybe_proxy_url(proxy_url)
257                .build()
258                .map_err(|e| {
259                    AxHttpError::NetworkError(format!("Failed to create HTTP client: {e}"))
260                })?,
261            credential: Some(Credential::new(api_key, api_secret)),
262            session_token: RwLock::new(None),
263            retry_manager,
264            cancellation_token: RwLock::new(CancellationToken::new()),
265        })
266    }
267
268    /// Sets the session token for authenticated requests.
269    ///
270    /// The session token is obtained through the login flow and used for bearer token authentication.
271    pub fn set_session_token(&self, token: SecretString) {
272        *self.session_token.write() = Some(token);
273    }
274
275    fn default_headers() -> HashMap<String, String> {
276        let mut headers: HashMap<String, String> =
277            create_standard_nautilus_headers().into_iter().collect();
278        headers.insert("Accept".to_string(), "application/json".to_string());
279        headers
280    }
281
282    fn rate_limiter_quotas() -> Vec<(String, Quota)> {
283        vec![(AX_GLOBAL_RATE_KEY.to_string(), *AX_REST_QUOTA)]
284    }
285
286    fn rate_limit_keys(endpoint: &str) -> Vec<String> {
287        let normalized = endpoint.split('?').next().unwrap_or(endpoint);
288        let route = format!("architect:{normalized}");
289
290        vec![AX_GLOBAL_RATE_KEY.to_string(), route]
291    }
292
293    fn auth_headers(&self) -> Result<HashMap<String, String>, AxHttpError> {
294        let guard = self.session_token.read();
295        let session_token = guard.as_ref().ok_or(AxHttpError::MissingSessionToken)?;
296
297        let mut headers = HashMap::new();
298        headers.insert(
299            "Authorization".to_string(),
300            format!("Bearer {}", session_token.expose_secret()),
301        );
302
303        Ok(headers)
304    }
305
306    async fn send_request<T: DeserializeOwned, P: Serialize>(
307        &self,
308        method: Method,
309        endpoint: &str,
310        params: Option<&P>,
311        body: Option<Vec<u8>>,
312        authenticate: bool,
313    ) -> Result<T, AxHttpError> {
314        self.send_request_to_url(&self.base_url, method, endpoint, params, body, authenticate)
315            .await
316    }
317
318    async fn send_request_to_url<T: DeserializeOwned, P: Serialize>(
319        &self,
320        base_url: &str,
321        method: Method,
322        endpoint: &str,
323        params: Option<&P>,
324        body: Option<Vec<u8>>,
325        authenticate: bool,
326    ) -> Result<T, AxHttpError> {
327        let endpoint = endpoint.to_string();
328        let url = format!("{base_url}{endpoint}");
329
330        let params_str = if method == Method::GET || method == Method::DELETE {
331            params
332                .map(serde_urlencoded::to_string)
333                .transpose()
334                .map_err(|e| AxHttpError::JsonError(format!("Failed to serialize params: {e}")))?
335        } else {
336            None
337        };
338
339        let operation = || {
340            let url = url.clone();
341            let method = method.clone();
342            let endpoint = endpoint.clone();
343            let params_str = params_str.clone();
344            let body = body.clone();
345
346            async move {
347                let mut headers = Self::default_headers();
348
349                if authenticate {
350                    let auth_headers = self.auth_headers()?;
351                    headers.extend(auth_headers);
352                }
353
354                if body.is_some() {
355                    headers.insert("Content-Type".to_string(), "application/json".to_string());
356                }
357
358                let full_url = if let Some(ref query) = params_str {
359                    if query.is_empty() {
360                        url
361                    } else {
362                        format!("{url}?{query}")
363                    }
364                } else {
365                    url
366                };
367
368                let rate_limit_keys = Self::rate_limit_keys(&endpoint);
369
370                let response = self
371                    .client
372                    .request(
373                        method,
374                        full_url,
375                        None,
376                        Some(headers),
377                        body,
378                        None,
379                        Some(rate_limit_keys),
380                    )
381                    .await?;
382
383                let status = response.status;
384                let response_body = String::from_utf8_lossy(&response.body).to_string();
385
386                if !status.is_success() {
387                    return Err(AxHttpError::UnexpectedStatus {
388                        status: status.as_u16(),
389                        body: response_body,
390                    });
391                }
392
393                serde_json::from_str(&response_body).map_err(|e| {
394                    AxHttpError::JsonError(format!(
395                        "Failed to deserialize response: {e}\nBody: {response_body}"
396                    ))
397                })
398            }
399        };
400
401        // Only retry idempotent methods to avoid duplicate orders/cancels
402        let is_idempotent = matches!(method, Method::GET | Method::HEAD | Method::OPTIONS);
403        let should_retry = |error: &AxHttpError| -> bool { is_idempotent && error.is_retryable() };
404
405        let create_error = |error: RetryError| -> AxHttpError {
406            match error {
407                RetryError::Canceled => {
408                    AxHttpError::Canceled("Adapter disconnecting or shutting down".to_string())
409                }
410                error => AxHttpError::NetworkError(error.to_string()),
411            }
412        };
413
414        let cancel_token = self.cancellation_token.read().clone();
415
416        self.retry_manager
417            .invocation(endpoint.as_str(), operation, should_retry, create_error)
418            .cancellation_token(&cancel_token)
419            .execute()
420            .await
421    }
422
423    /// Fetches the current authenticated user information.
424    ///
425    /// # Endpoint
426    /// `GET /whoami`
427    ///
428    /// # Errors
429    ///
430    /// Returns an error if the request fails or the response cannot be parsed.
431    pub async fn get_whoami(&self) -> Result<AxWhoAmI, AxHttpError> {
432        self.send_request::<AxWhoAmI, ()>(Method::GET, "/whoami", None, None, true)
433            .await
434    }
435
436    /// Fetches all available instruments.
437    ///
438    /// # Endpoint
439    /// `GET /instruments`
440    ///
441    /// # Errors
442    ///
443    /// Returns an error if the request fails or the response cannot be parsed.
444    pub async fn get_instruments(&self) -> Result<AxInstrumentsResponse, AxHttpError> {
445        self.send_request::<AxInstrumentsResponse, ()>(
446            Method::GET,
447            "/instruments",
448            None,
449            None,
450            false,
451        )
452        .await
453    }
454
455    /// Fetches all account balances for the authenticated user.
456    ///
457    /// # Endpoint
458    /// `GET /balances`
459    ///
460    /// # Errors
461    ///
462    /// Returns an error if the request fails or the response cannot be parsed.
463    pub async fn get_balances(&self) -> Result<AxBalancesResponse, AxHttpError> {
464        self.send_request::<AxBalancesResponse, ()>(Method::GET, "/balances", None, None, true)
465            .await
466    }
467
468    /// Fetches all open positions for the authenticated user.
469    ///
470    /// # Endpoint
471    /// `GET /positions`
472    ///
473    /// # Errors
474    ///
475    /// Returns an error if the request fails or the response cannot be parsed.
476    pub async fn get_positions(&self) -> Result<AxPositionsResponse, AxHttpError> {
477        self.send_request::<AxPositionsResponse, ()>(Method::GET, "/positions", None, None, true)
478            .await
479    }
480
481    /// Fetches all tickers.
482    ///
483    /// # Endpoint
484    /// `GET /tickers`
485    ///
486    /// # Errors
487    ///
488    /// Returns an error if the request fails or the response cannot be parsed.
489    pub async fn get_tickers(&self) -> Result<AxTickersResponse, AxHttpError> {
490        self.send_request::<AxTickersResponse, ()>(Method::GET, "/tickers", None, None, true)
491            .await
492    }
493
494    /// Fetches tickers with optional pagination and sorting.
495    ///
496    /// # Endpoint
497    /// `GET /tickers`
498    ///
499    /// # Errors
500    ///
501    /// Returns an error if the request fails or the response cannot be parsed.
502    pub async fn get_tickers_with_params(
503        &self,
504        params: &GetTickersParams,
505    ) -> Result<AxTickersResponse, AxHttpError> {
506        self.send_request::<AxTickersResponse, _>(Method::GET, "/tickers", Some(params), None, true)
507            .await
508    }
509
510    /// Fetches a single ticker by symbol.
511    ///
512    /// # Endpoint
513    /// `GET /ticker?symbol=<symbol>`
514    ///
515    /// # Errors
516    ///
517    /// Returns an error if the request fails or the response cannot be parsed.
518    pub async fn get_ticker(&self, symbol: Ustr) -> Result<AxTicker, AxHttpError> {
519        let params = GetTickerParams::new(symbol);
520        self.send_request::<AxTickerResponse, _>(Method::GET, "/ticker", Some(&params), None, true)
521            .await
522            .map(|response| response.ticker)
523    }
524
525    /// Fetches a single instrument by symbol.
526    ///
527    /// # Endpoint
528    /// `GET /instrument?symbol=<symbol>`
529    ///
530    /// # Errors
531    ///
532    /// Returns an error if the request fails or the response cannot be parsed.
533    pub async fn get_instrument(&self, symbol: Ustr) -> Result<AxInstrument, AxHttpError> {
534        let params = GetInstrumentParams::new(symbol);
535        self.send_request::<AxInstrument, _>(Method::GET, "/instrument", Some(&params), None, false)
536            .await
537    }
538
539    /// Authenticates using API key and secret to obtain a session token.
540    ///
541    /// # Endpoint
542    /// `POST /authenticate`
543    ///
544    /// # Errors
545    ///
546    /// Returns an error if the request fails or the response cannot be parsed.
547    pub async fn authenticate(
548        &self,
549        api_key: &str,
550        api_secret: &str,
551        expiration_seconds: i32,
552    ) -> Result<AxAuthenticateResponse, AxHttpError> {
553        let request = AuthenticateApiKeyRequest::new(api_key, api_secret, expiration_seconds);
554
555        let body = serde_json::to_vec(&request)
556            .map_err(|e| AxHttpError::JsonError(format!("Failed to serialize request: {e}")))?;
557
558        self.send_request::<AxAuthenticateResponse, ()>(
559            Method::POST,
560            "/authenticate",
561            None,
562            Some(body),
563            false,
564        )
565        .await
566    }
567
568    /// Authenticates using stored credentials or environment variables.
569    ///
570    /// # Credential Resolution
571    ///
572    /// Credentials are resolved in the following order:
573    /// 1. Stored credentials (from `with_credentials` constructor)
574    /// 2. Environment variables (`AX_API_KEY` and `AX_API_SECRET`)
575    ///
576    /// # Errors
577    ///
578    /// Returns an error if:
579    /// - No credentials are available from either source.
580    /// - The HTTP request fails.
581    /// - The credentials are invalid.
582    pub async fn authenticate_auto(
583        &self,
584        expiration_seconds: i32,
585    ) -> Result<AxAuthenticateResponse, AxHttpError> {
586        let (api_key, api_secret) = self
587            .resolve_credentials()
588            .ok_or(AxHttpError::MissingCredentials)?;
589
590        self.authenticate(
591            api_key.expose_secret(),
592            api_secret.expose_secret(),
593            expiration_seconds,
594        )
595        .await
596    }
597
598    fn resolve_credentials(&self) -> Option<(SecretString, SecretString)> {
599        if let Some(cred) = &self.credential {
600            return Some((
601                SecretString::from(cred.api_key()),
602                SecretString::from(cred.api_secret()),
603            ));
604        }
605
606        let cred = Credential::resolve(None, None)?;
607        Some((
608            SecretString::from(cred.api_key()),
609            SecretString::from(cred.api_secret()),
610        ))
611    }
612
613    /// Places a new order.
614    ///
615    /// # Endpoint
616    /// `POST /place-order` (orders base URL)
617    ///
618    /// # Errors
619    ///
620    /// Returns an error if the request fails or the response cannot be parsed.
621    pub async fn place_order(
622        &self,
623        request: &PlaceOrderRequest,
624    ) -> Result<AxPlaceOrderResponse, AxHttpError> {
625        let body = serde_json::to_vec(request)
626            .map_err(|e| AxHttpError::JsonError(format!("Failed to serialize request: {e}")))?;
627        self.send_request_to_url::<AxPlaceOrderResponse, ()>(
628            self.orders_base_url()?,
629            Method::POST,
630            "/place-order",
631            None,
632            Some(body),
633            true,
634        )
635        .await
636    }
637
638    /// Cancels an existing order.
639    ///
640    /// # Endpoint
641    /// `POST /cancel-order` (orders base URL)
642    ///
643    /// # Errors
644    ///
645    /// Returns an error if the request fails or the response cannot be parsed.
646    pub async fn cancel_order(&self, order_id: &str) -> Result<AxCancelOrderResponse, AxHttpError> {
647        let request = CancelOrderRequest::new(order_id);
648        let body = serde_json::to_vec(&request)
649            .map_err(|e| AxHttpError::JsonError(format!("Failed to serialize request: {e}")))?;
650        self.send_request_to_url::<AxCancelOrderResponse, ()>(
651            self.orders_base_url()?,
652            Method::POST,
653            "/cancel-order",
654            None,
655            Some(body),
656            true,
657        )
658        .await
659    }
660
661    /// Replaces (amends) an existing order.
662    ///
663    /// The exchange cancels the original order and creates a new one with the
664    /// updated fields. Unspecified optional fields inherit from the original.
665    ///
666    /// # Endpoint
667    /// `POST /replace-order` (orders base URL)
668    ///
669    /// # Errors
670    ///
671    /// Returns an error if the request fails or the response cannot be parsed.
672    pub async fn replace_order(
673        &self,
674        request: &ReplaceOrderRequest,
675    ) -> Result<AxReplaceOrderResponse, AxHttpError> {
676        let body = serde_json::to_vec(request)
677            .map_err(|e| AxHttpError::JsonError(format!("Failed to serialize request: {e}")))?;
678        self.send_request_to_url::<AxReplaceOrderResponse, ()>(
679            self.orders_base_url()?,
680            Method::POST,
681            "/replace-order",
682            None,
683            Some(body),
684            true,
685        )
686        .await
687    }
688
689    /// Cancels all open orders, optionally filtered by account or symbol.
690    ///
691    /// # Endpoint
692    /// `POST /cancel-all-orders` (orders base URL)
693    ///
694    /// # Errors
695    ///
696    /// Returns an error if the request fails or the response cannot be parsed.
697    pub async fn cancel_all_orders(
698        &self,
699        request: &CancelAllOrdersRequest,
700    ) -> Result<AxCancelAllOrdersResponse, AxHttpError> {
701        let body = serde_json::to_vec(request)
702            .map_err(|e| AxHttpError::JsonError(format!("Failed to serialize request: {e}")))?;
703        self.send_request_to_url::<AxCancelAllOrdersResponse, ()>(
704            self.orders_base_url()?,
705            Method::POST,
706            "/cancel-all-orders",
707            None,
708            Some(body),
709            true,
710        )
711        .await
712    }
713
714    /// Fetches all open orders.
715    ///
716    /// # Endpoint
717    /// `GET /open-orders` (orders base URL)
718    ///
719    /// # Errors
720    ///
721    /// Returns an error if the request fails or the response cannot be parsed.
722    pub async fn get_open_orders(&self) -> Result<AxOpenOrdersResponse, AxHttpError> {
723        self.get_open_orders_page(&GetOpenOrdersParams::new()).await
724    }
725
726    /// Fetches one page of open orders.
727    ///
728    /// # Errors
729    ///
730    /// Returns an error if the request fails or the response cannot be parsed.
731    pub async fn get_open_orders_page(
732        &self,
733        params: &GetOpenOrdersParams,
734    ) -> Result<AxOpenOrdersResponse, AxHttpError> {
735        self.send_request_to_url::<AxOpenOrdersResponse, _>(
736            self.orders_base_url()?,
737            Method::GET,
738            "/open-orders",
739            Some(params),
740            None,
741            true,
742        )
743        .await
744    }
745
746    /// Fetches the default page of fills/trades.
747    ///
748    /// # Endpoint
749    /// `GET /fills`
750    ///
751    /// # Errors
752    ///
753    /// Returns an error if the request fails or the response cannot be parsed.
754    pub async fn get_fills(
755        &self,
756        start_timestamp_ns: i64,
757        end_timestamp_ns: i64,
758    ) -> Result<AxFillsResponse, AxHttpError> {
759        let params = GetFillsParams::new(start_timestamp_ns, end_timestamp_ns);
760        self.get_fills_page(&params).await
761    }
762
763    /// Fetches one page of fills/trades.
764    ///
765    /// # Errors
766    ///
767    /// Returns an error if the request fails or the response cannot be parsed.
768    pub async fn get_fills_page(
769        &self,
770        params: &GetFillsParams,
771    ) -> Result<AxFillsResponse, AxHttpError> {
772        self.send_request::<AxFillsResponse, _>(Method::GET, "/fills", Some(params), None, true)
773            .await
774    }
775
776    /// Fetches historical candles.
777    ///
778    /// # Endpoint
779    /// `GET /candles`
780    ///
781    /// # Errors
782    ///
783    /// Returns an error if the request fails or the response cannot be parsed.
784    pub async fn get_candles(
785        &self,
786        symbol: Ustr,
787        start_timestamp_ns: i64,
788        end_timestamp_ns: i64,
789        candle_width: AxCandleWidth,
790    ) -> Result<AxCandlesResponse, AxHttpError> {
791        let params =
792            GetCandlesParams::new(symbol, start_timestamp_ns, end_timestamp_ns, candle_width);
793        self.send_request::<AxCandlesResponse, _>(
794            Method::GET,
795            "/candles",
796            Some(&params),
797            None,
798            true,
799        )
800        .await
801    }
802
803    /// Fetches the current (incomplete) candle.
804    ///
805    /// # Endpoint
806    /// `GET /candles/current`
807    ///
808    /// # Errors
809    ///
810    /// Returns an error if the request fails or the response cannot be parsed.
811    pub async fn get_current_candle(
812        &self,
813        symbol: Ustr,
814        candle_width: AxCandleWidth,
815    ) -> Result<AxCandle, AxHttpError> {
816        let params = GetCandleParams::new(symbol, candle_width);
817        let response = self
818            .send_request::<AxCandleResponse, _>(
819                Method::GET,
820                "/candles/current",
821                Some(&params),
822                None,
823                true,
824            )
825            .await?;
826        Ok(response.candle)
827    }
828
829    /// Fetches the last completed candle.
830    ///
831    /// # Endpoint
832    /// `GET /candles/last`
833    ///
834    /// # Errors
835    ///
836    /// Returns an error if the request fails or the response cannot be parsed.
837    pub async fn get_last_candle(
838        &self,
839        symbol: Ustr,
840        candle_width: AxCandleWidth,
841    ) -> Result<AxCandle, AxHttpError> {
842        let params = GetCandleParams::new(symbol, candle_width);
843        let response = self
844            .send_request::<AxCandleResponse, _>(
845                Method::GET,
846                "/candles/last",
847                Some(&params),
848                None,
849                true,
850            )
851            .await?;
852        Ok(response.candle)
853    }
854
855    /// Fetches the default page of funding rates for a symbol.
856    ///
857    /// # Endpoint
858    /// `GET /funding-rates`
859    ///
860    /// # Errors
861    ///
862    /// Returns an error if the request fails or the response cannot be parsed.
863    pub async fn get_funding_rates(
864        &self,
865        symbol: Ustr,
866        start_timestamp_ns: i64,
867        end_timestamp_ns: i64,
868    ) -> Result<AxFundingRatesResponse, AxHttpError> {
869        let params = GetFundingRatesParams::new(symbol, start_timestamp_ns, end_timestamp_ns);
870        self.get_funding_rates_page(&params).await
871    }
872
873    /// Fetches one page of funding rates for a symbol.
874    ///
875    /// # Errors
876    ///
877    /// Returns an error if the request fails or the response cannot be parsed.
878    pub async fn get_funding_rates_page(
879        &self,
880        params: &GetFundingRatesParams,
881    ) -> Result<AxFundingRatesResponse, AxHttpError> {
882        self.send_request::<AxFundingRatesResponse, _>(
883            Method::GET,
884            "/funding-rates",
885            Some(params),
886            None,
887            true,
888        )
889        .await
890    }
891
892    /// Fetches the funding-slot schedule for a symbol on a trading day.
893    ///
894    /// # Endpoint
895    /// `GET /funding-slots`
896    ///
897    /// # Errors
898    ///
899    /// Returns an error if the request fails or the response cannot be parsed.
900    pub async fn get_funding_slots(
901        &self,
902        params: &GetFundingSlotsParams,
903    ) -> Result<AxFundingSlotsResponse, AxHttpError> {
904        self.send_request::<AxFundingSlotsResponse, _>(
905            Method::GET,
906            "/funding-slots",
907            Some(params),
908            None,
909            true,
910        )
911        .await
912    }
913
914    /// Fetches the current risk snapshot.
915    ///
916    /// # Endpoint
917    /// `GET /risk-snapshot`
918    ///
919    /// # Errors
920    ///
921    /// Returns an error if the request fails or the response cannot be parsed.
922    pub async fn get_risk_snapshot(&self) -> Result<AxRiskSnapshotResponse, AxHttpError> {
923        self.send_request::<AxRiskSnapshotResponse, ()>(
924            Method::GET,
925            "/risk-snapshot",
926            None,
927            None,
928            true,
929        )
930        .await
931    }
932
933    /// Previews an aggressive limit order to get the "take through" price.
934    ///
935    /// This endpoint calculates the price needed to sweep the order book for a given
936    /// quantity, which is used to simulate market orders on AX (which only supports
937    /// limit orders natively).
938    ///
939    /// # Endpoint
940    /// `POST /preview-aggressive-limit-order`
941    ///
942    /// # Errors
943    ///
944    /// Returns an error if the request fails or the response cannot be parsed.
945    pub async fn preview_aggressive_limit_order(
946        &self,
947        request: &PreviewAggressiveLimitOrderRequest,
948    ) -> Result<AxPreviewAggressiveLimitOrderResponse, AxHttpError> {
949        let body = serde_json::to_vec(request)
950            .map_err(|e| AxHttpError::JsonError(format!("Failed to serialize request: {e}")))?;
951        self.send_request::<AxPreviewAggressiveLimitOrderResponse, ()>(
952            Method::POST,
953            "/preview-aggressive-limit-order",
954            None,
955            Some(body),
956            true,
957        )
958        .await
959    }
960
961    /// Fetches the default page of transactions filtered by type.
962    ///
963    /// # Endpoint
964    /// `GET /transactions`
965    ///
966    /// # Errors
967    ///
968    /// Returns an error if the request fails or the response cannot be parsed.
969    pub async fn get_transactions(
970        &self,
971        transaction_types: Vec<Ustr>,
972        start_timestamp_ns: i64,
973        end_timestamp_ns: i64,
974    ) -> Result<AxTransactionsResponse, AxHttpError> {
975        let params =
976            GetTransactionsParams::new(transaction_types, start_timestamp_ns, end_timestamp_ns);
977        self.get_transactions_page(&params).await
978    }
979
980    /// Fetches one page of transactions.
981    ///
982    /// # Errors
983    ///
984    /// Returns an error if the request fails or the response cannot be parsed.
985    pub async fn get_transactions_page(
986        &self,
987        params: &GetTransactionsParams,
988    ) -> Result<AxTransactionsResponse, AxHttpError> {
989        self.send_request::<AxTransactionsResponse, _>(
990            Method::GET,
991            "/transactions",
992            Some(params),
993            None,
994            true,
995        )
996        .await
997    }
998
999    /// Fetches recent trades for a symbol.
1000    ///
1001    /// # Endpoint
1002    /// `GET /trades`
1003    ///
1004    /// # Errors
1005    ///
1006    /// Returns an error if the request fails or the response cannot be parsed.
1007    pub async fn get_trades(
1008        &self,
1009        symbol: Ustr,
1010        limit: Option<i32>,
1011    ) -> Result<AxTradesResponse, AxHttpError> {
1012        let params = GetTradesParams::new(symbol, limit);
1013        self.send_request::<AxTradesResponse, _>(Method::GET, "/trades", Some(&params), None, true)
1014            .await
1015    }
1016
1017    /// Fetches an order book snapshot for a symbol.
1018    ///
1019    /// # Endpoint
1020    /// `GET /book`
1021    ///
1022    /// # Errors
1023    ///
1024    /// Returns an error if the request fails or the response cannot be parsed.
1025    pub async fn get_book(
1026        &self,
1027        symbol: Ustr,
1028        level: Option<i32>,
1029    ) -> Result<AxBookResponse, AxHttpError> {
1030        let params = GetBookParams::new(symbol, level);
1031        // The AX sandbox requires authentication for `/book` despite the public schema
1032        self.send_request::<AxBookResponse, _>(Method::GET, "/book", Some(&params), None, true)
1033            .await
1034    }
1035
1036    /// Fetches the status of a single order by order ID.
1037    ///
1038    /// # Endpoint
1039    /// `GET /order-status` (orders base URL)
1040    ///
1041    /// # Errors
1042    ///
1043    /// Returns an error if the request fails or the response cannot be parsed.
1044    pub async fn get_order_status_by_id(
1045        &self,
1046        order_id: &str,
1047    ) -> Result<AxOrderStatusQueryResponse, AxHttpError> {
1048        let params = GetOrderStatusParams::by_order_id(order_id);
1049        self.send_request_to_url::<AxOrderStatusQueryResponse, _>(
1050            self.orders_base_url()?,
1051            Method::GET,
1052            "/order-status",
1053            Some(&params),
1054            None,
1055            true,
1056        )
1057        .await
1058    }
1059
1060    /// Fetches the status of a single order by client order ID.
1061    ///
1062    /// # Endpoint
1063    /// `GET /order-status` (orders base URL)
1064    ///
1065    /// # Errors
1066    ///
1067    /// Returns an error if the request fails or the response cannot be parsed.
1068    pub async fn get_order_status_by_cid(
1069        &self,
1070        client_order_id: u64,
1071    ) -> Result<AxOrderStatusQueryResponse, AxHttpError> {
1072        let params = GetOrderStatusParams::by_client_order_id(client_order_id);
1073        self.send_request_to_url::<AxOrderStatusQueryResponse, _>(
1074            self.orders_base_url()?,
1075            Method::GET,
1076            "/order-status",
1077            Some(&params),
1078            None,
1079            true,
1080        )
1081        .await
1082    }
1083
1084    /// Fetches historical orders with optional filters.
1085    ///
1086    /// # Endpoint
1087    /// `GET /orders` (orders base URL)
1088    ///
1089    /// # Errors
1090    ///
1091    /// Returns an error if the request fails or the response cannot be parsed.
1092    pub async fn get_orders(
1093        &self,
1094        params: &GetOrdersParams,
1095    ) -> Result<AxOrdersResponse, AxHttpError> {
1096        self.send_request_to_url::<AxOrdersResponse, _>(
1097            self.orders_base_url()?,
1098            Method::GET,
1099            "/orders",
1100            Some(params),
1101            None,
1102            true,
1103        )
1104        .await
1105    }
1106
1107    /// Checks the initial margin requirement for a proposed order.
1108    ///
1109    /// # Endpoint
1110    /// `POST /initial-margin-requirement` (orders base URL)
1111    ///
1112    /// # Errors
1113    ///
1114    /// Returns an error if the request fails or the response cannot be parsed.
1115    pub async fn check_initial_margin(
1116        &self,
1117        request: &PlaceOrderRequest,
1118    ) -> Result<AxInitialMarginRequirementResponse, AxHttpError> {
1119        let body = serde_json::to_vec(request)
1120            .map_err(|e| AxHttpError::JsonError(format!("Failed to serialize request: {e}")))?;
1121        self.send_request_to_url::<AxInitialMarginRequirementResponse, ()>(
1122            self.orders_base_url()?,
1123            Method::POST,
1124            "/initial-margin-requirement",
1125            None,
1126            Some(body),
1127            true,
1128        )
1129        .await
1130    }
1131}
1132
1133fn retry_config(
1134    timeout_secs: u64,
1135    max_retries: u32,
1136    retry_delay_ms: u64,
1137    retry_delay_max_ms: u64,
1138) -> Result<RetryConfig, AxHttpError> {
1139    if timeout_secs == 0 {
1140        return Err(AxHttpError::ValidationError(
1141            "HTTP timeout must be non-zero".to_string(),
1142        ));
1143    }
1144
1145    let operation_timeout_ms = timeout_secs.checked_mul(1_000).ok_or_else(|| {
1146        AxHttpError::ValidationError("HTTP timeout in milliseconds exceeds u64::MAX".to_string())
1147    })?;
1148
1149    ExponentialBackoff::new(
1150        Duration::from_millis(retry_delay_ms),
1151        Duration::from_millis(retry_delay_max_ms),
1152        2.0,
1153        1_000,
1154        false,
1155    )
1156    .map_err(|e| AxHttpError::ValidationError(format!("Invalid retry configuration: {e}")))?;
1157
1158    Ok(RetryConfig {
1159        max_retries,
1160        initial_delay_ms: retry_delay_ms,
1161        max_delay_ms: retry_delay_max_ms,
1162        backoff_factor: 2.0,
1163        jitter_ms: 1_000,
1164        operation_timeout_ms: Some(operation_timeout_ms),
1165        immediate_first: false,
1166        max_elapsed_ms: None,
1167    })
1168}
1169
1170fn resolve_base_urls(
1171    base_url: Option<String>,
1172    orders_base_url: Option<String>,
1173) -> (String, Option<String>) {
1174    let base_url = base_url.map_or_else(|| AX_HTTP_URL.to_string(), normalize_base_url);
1175
1176    let orders_base_url = match orders_base_url {
1177        Some(url) => Some(normalize_base_url(url)),
1178        None => match base_url.as_str() {
1179            AX_HTTP_URL => Some(AX_ORDERS_URL.to_string()),
1180            AX_HTTP_SANDBOX_URL => Some(AX_ORDERS_SANDBOX_URL.to_string()),
1181            _ => None,
1182        },
1183    };
1184
1185    (base_url, orders_base_url)
1186}
1187
1188fn normalize_base_url(url: String) -> String {
1189    let normalized = url.trim_end_matches('/');
1190    if normalized.ends_with(':') {
1191        return url;
1192    }
1193
1194    normalized.to_string()
1195}
1196
1197/// High-level HTTP client for the Ax REST API.
1198///
1199/// This client wraps the underlying [`AxRawHttpClient`] to provide a convenient
1200/// interface for Python bindings and instrument caching.
1201#[derive(Debug)]
1202#[cfg_attr(
1203    feature = "python",
1204    pyo3::pyclass(module = "nautilus_trader.adapters.architect_ax", from_py_object)
1205)]
1206#[cfg_attr(
1207    feature = "python",
1208    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.architect_ax")
1209)]
1210pub struct AxHttpClient {
1211    pub(crate) inner: Arc<AxRawHttpClient>,
1212    pub(crate) instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
1213    pub(crate) account_fee_rates: Arc<AtomicMap<Option<Ustr>, MakerTakerFeeRates>>,
1214    clock: &'static AtomicTime,
1215    cache_initialized: Arc<AtomicBool>,
1216}
1217
1218impl Clone for AxHttpClient {
1219    fn clone(&self) -> Self {
1220        Self {
1221            inner: self.inner.clone(),
1222            instruments_cache: self.instruments_cache.clone(),
1223            account_fee_rates: self.account_fee_rates.clone(),
1224            clock: self.clock,
1225            cache_initialized: self.cache_initialized.clone(),
1226        }
1227    }
1228}
1229
1230impl Default for AxHttpClient {
1231    fn default() -> Self {
1232        Self::new(None, None, 60, 3, 1000, 10_000, None)
1233            .expect("Failed to create default AxHttpClient")
1234    }
1235}
1236
1237impl AxHttpClient {
1238    /// Creates a new [`AxHttpClient`] using the default Ax HTTP URL.
1239    ///
1240    /// # Errors
1241    ///
1242    /// Returns an error if the retry manager cannot be created.
1243    pub fn new(
1244        base_url: Option<String>,
1245        orders_base_url: Option<String>,
1246        timeout_secs: u64,
1247        max_retries: u32,
1248        retry_delay_ms: u64,
1249        retry_delay_max_ms: u64,
1250        proxy_url: Option<String>,
1251    ) -> Result<Self, AxHttpError> {
1252        Ok(Self {
1253            inner: Arc::new(AxRawHttpClient::new(
1254                base_url,
1255                orders_base_url,
1256                timeout_secs,
1257                max_retries,
1258                retry_delay_ms,
1259                retry_delay_max_ms,
1260                proxy_url,
1261            )?),
1262            instruments_cache: Arc::new(AtomicMap::new()),
1263            account_fee_rates: Arc::new(AtomicMap::new()),
1264            clock: get_atomic_clock_realtime(),
1265            cache_initialized: Arc::new(AtomicBool::new(false)),
1266        })
1267    }
1268
1269    /// Creates a new [`AxHttpClient`] configured with credentials.
1270    ///
1271    /// # Errors
1272    ///
1273    /// Returns an error if the HTTP client cannot be created.
1274    #[expect(clippy::too_many_arguments)]
1275    pub fn with_credentials(
1276        api_key: String,
1277        api_secret: String,
1278        base_url: Option<String>,
1279        orders_base_url: Option<String>,
1280        timeout_secs: u64,
1281        max_retries: u32,
1282        retry_delay_ms: u64,
1283        retry_delay_max_ms: u64,
1284        proxy_url: Option<String>,
1285    ) -> Result<Self, AxHttpError> {
1286        Ok(Self {
1287            inner: Arc::new(AxRawHttpClient::with_credentials(
1288                api_key,
1289                api_secret,
1290                base_url,
1291                orders_base_url,
1292                timeout_secs,
1293                max_retries,
1294                retry_delay_ms,
1295                retry_delay_max_ms,
1296                proxy_url,
1297            )?),
1298            instruments_cache: Arc::new(AtomicMap::new()),
1299            account_fee_rates: Arc::new(AtomicMap::new()),
1300            clock: get_atomic_clock_realtime(),
1301            cache_initialized: Arc::new(AtomicBool::new(false)),
1302        })
1303    }
1304
1305    /// Returns the base URL for this client.
1306    #[must_use]
1307    pub fn base_url(&self) -> &str {
1308        self.inner.base_url()
1309    }
1310
1311    /// Returns a masked version of the API key for logging purposes.
1312    #[must_use]
1313    pub fn api_key_masked(&self) -> String {
1314        self.inner.api_key_masked()
1315    }
1316
1317    /// Cancel all pending HTTP requests.
1318    pub fn cancel_all_requests(&self) {
1319        self.inner.cancel_all_requests();
1320    }
1321
1322    /// Replaces the cancelled token so new requests can proceed after reconnect.
1323    pub fn reset_cancellation_token(&self) {
1324        self.inner.reset_cancellation_token();
1325    }
1326
1327    /// Sets the session token for authenticated requests.
1328    ///
1329    /// The session token is obtained through the login flow and used for bearer token authentication.
1330    pub fn set_session_token(&self, token: SecretString) {
1331        self.inner.set_session_token(token);
1332    }
1333
1334    /// Generates a timestamp for initialization.
1335    fn generate_ts_init(&self) -> UnixNanos {
1336        self.clock.get_time_ns()
1337    }
1338
1339    /// Checks if the client is initialized.
1340    ///
1341    /// The client is considered initialized if any instruments have been cached from the venue.
1342    #[must_use]
1343    pub fn is_initialized(&self) -> bool {
1344        self.cache_initialized.load(Ordering::Acquire)
1345    }
1346
1347    /// Returns a snapshot of all instrument symbols currently held in the internal cache.
1348    #[must_use]
1349    pub fn get_cached_symbols(&self) -> Vec<String> {
1350        self.instruments_cache
1351            .load()
1352            .keys()
1353            .map(|k| k.to_string())
1354            .collect()
1355    }
1356
1357    /// Caches multiple instruments.
1358    ///
1359    /// Any existing instruments with the same symbols will be replaced.
1360    pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
1361        self.instruments_cache.rcu(|m| {
1362            for inst in instruments {
1363                m.insert(inst.raw_symbol().inner(), inst.clone());
1364            }
1365        });
1366        self.cache_initialized.store(true, Ordering::Release);
1367    }
1368
1369    /// Caches a single instrument.
1370    ///
1371    /// Any existing instrument with the same symbol will be replaced.
1372    pub fn cache_instrument(&self, instrument: InstrumentAny) {
1373        self.instruments_cache
1374            .insert(instrument.raw_symbol().inner(), instrument);
1375        self.cache_initialized.store(true, Ordering::Release);
1376    }
1377
1378    /// Authenticates with Ax using API credentials.
1379    ///
1380    /// On success, the session token is automatically stored for subsequent authenticated requests.
1381    ///
1382    /// # Errors
1383    ///
1384    /// Returns an error if the HTTP request fails or credentials are invalid.
1385    pub async fn authenticate(
1386        &self,
1387        api_key: &str,
1388        api_secret: &str,
1389        expiration_seconds: i32,
1390    ) -> Result<SecretString, AxHttpError> {
1391        let resp = self
1392            .inner
1393            .authenticate(api_key, api_secret, expiration_seconds)
1394            .await?;
1395        let token = resp.into_token();
1396        self.inner.set_session_token(token.clone());
1397        Ok(token)
1398    }
1399
1400    /// Authenticates using stored credentials or environment variables.
1401    ///
1402    /// # Credential Resolution
1403    ///
1404    /// Credentials are resolved in the following order:
1405    /// 1. Stored credentials (from `with_credentials` constructor)
1406    /// 2. Environment variables (`AX_API_KEY` and `AX_API_SECRET`)
1407    ///
1408    /// On success, the session token is automatically stored for subsequent authenticated requests.
1409    ///
1410    /// # Errors
1411    ///
1412    /// Returns an error if:
1413    /// - No credentials are available from either source.
1414    /// - The HTTP request fails.
1415    /// - The credentials are invalid.
1416    pub async fn authenticate_auto(
1417        &self,
1418        expiration_seconds: i32,
1419    ) -> Result<SecretString, AxHttpError> {
1420        let resp = self.inner.authenticate_auto(expiration_seconds).await?;
1421        let token = resp.into_token();
1422        self.inner.set_session_token(token.clone());
1423        Ok(token)
1424    }
1425
1426    /// Gets an instrument from the cache by symbol.
1427    pub fn get_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
1428        self.instruments_cache.get_cloned(symbol)
1429    }
1430
1431    /// Resolves the maker and taker fee rates for the account behind the current credentials.
1432    ///
1433    /// AX reports fee rates per account rather than per user, and returns the accounts the
1434    /// credentials can act on. The first entry's rates are returned and serve as the default
1435    /// for fill payloads without an account identifier. Each successful call replaces the
1436    /// cached rates for every listed account that supplies both maker and taker rates.
1437    /// Instruments do not carry these rates.
1438    ///
1439    /// Requires an authenticated client.
1440    ///
1441    /// # Errors
1442    ///
1443    /// Returns an error if the request fails, the response carries no accounts, or the selected
1444    /// account supplies no fee rates. An absent rate is not treated as zero, because a zero rate
1445    /// is itself valid and a silent zero would outlive the response that caused it.
1446    pub async fn request_account_fees(&self) -> anyhow::Result<(Decimal, Decimal)> {
1447        let whoami = self
1448            .inner
1449            .get_whoami()
1450            .await
1451            .map_err(|e| anyhow::anyhow!(e))
1452            .context("failed to request AX whoami")?;
1453
1454        let Some(account) = whoami.accounts.first() else {
1455            anyhow::bail!("AX whoami returned no accounts to resolve fees from");
1456        };
1457
1458        if whoami.accounts.len() > 1 {
1459            log::warn!(
1460                "AX credentials cover {} accounts, using {} as the fallback for fills without an account ID",
1461                whoami.accounts.len(),
1462                account.id,
1463            );
1464        }
1465
1466        let (Some(maker_fee), Some(taker_fee)) = (account.maker_fee, account.taker_fee) else {
1467            anyhow::bail!("AX whoami account {} supplied no fee rates", account.id);
1468        };
1469
1470        let fees = (maker_fee, taker_fee);
1471        let mut rates = AHashMap::new();
1472        rates.insert(None, MakerTakerFeeRates::new(maker_fee, taker_fee));
1473
1474        for account in &whoami.accounts {
1475            if let (Some(maker), Some(taker)) = (account.maker_fee, account.taker_fee) {
1476                rates.insert(Some(account.id), MakerTakerFeeRates::new(maker, taker));
1477            }
1478        }
1479
1480        self.account_fee_rates.store(rates);
1481
1482        Ok(fees)
1483    }
1484
1485    /// Requests all instruments from Ax.
1486    ///
1487    /// # Errors
1488    ///
1489    /// Returns an error if the HTTP request fails or instrument parsing fails.
1490    pub async fn request_instruments(&self) -> anyhow::Result<Vec<InstrumentAny>> {
1491        let resp = self
1492            .inner
1493            .get_instruments()
1494            .await
1495            .map_err(|e| anyhow::anyhow!(e))?;
1496
1497        let ts_init = self.generate_ts_init();
1498
1499        let mut instruments: Vec<InstrumentAny> = Vec::new();
1500        for inst in &resp.instruments {
1501            if inst.state == AxInstrumentState::Delisted {
1502                log::debug!("Skipping delisted instrument: {}", inst.symbol);
1503                continue;
1504            }
1505
1506            // Skip test instruments (not real tradable products)
1507            if inst.symbol.starts_with("TEST") {
1508                log::debug!("Skipping test instrument: {}", inst.symbol);
1509                continue;
1510            }
1511
1512            match parse_instrument(inst, ts_init, ts_init) {
1513                Ok(instrument) => instruments.push(instrument),
1514                Err(e) => {
1515                    log::warn!("Failed to parse instrument {}: {e}", inst.symbol);
1516                }
1517            }
1518        }
1519
1520        Ok(instruments)
1521    }
1522
1523    /// Requests a single instrument from Ax by symbol.
1524    ///
1525    /// # Errors
1526    ///
1527    /// Returns an error if the HTTP request fails or instrument parsing fails.
1528    pub async fn request_instrument(&self, symbol: Ustr) -> anyhow::Result<InstrumentAny> {
1529        let resp = self
1530            .inner
1531            .get_instrument(symbol)
1532            .await
1533            .map_err(|e| anyhow::anyhow!(e))?;
1534
1535        let ts_init = self.generate_ts_init();
1536
1537        parse_instrument(&resp, ts_init, ts_init)
1538    }
1539
1540    /// Requests an order book snapshot from Ax and builds a Nautilus [`OrderBook`].
1541    ///
1542    /// Requires the instrument to be cached.
1543    ///
1544    /// # Errors
1545    ///
1546    /// Returns an error if:
1547    /// - The instrument is not found in the cache.
1548    /// - The HTTP request fails.
1549    pub async fn request_book_snapshot(
1550        &self,
1551        symbol: Ustr,
1552        depth: Option<usize>,
1553    ) -> anyhow::Result<OrderBook> {
1554        let instrument = self
1555            .get_instrument(&symbol)
1556            .ok_or_else(|| anyhow::anyhow!("Instrument {symbol} not found in cache"))?;
1557
1558        let resp = self
1559            .inner
1560            .get_book(symbol, Some(2))
1561            .await
1562            .map_err(|e| anyhow::anyhow!(e))?;
1563
1564        let instrument_id = instrument.id();
1565        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
1566
1567        let price_precision = instrument.price_precision();
1568        let size_precision = instrument.size_precision();
1569        let ts_event = ax_timestamp_stn_to_unix_nanos(resp.book.ts, resp.book.tn)?;
1570
1571        for (i, level) in resp.book.b.iter().enumerate() {
1572            if depth.is_some_and(|d| i >= d) {
1573                break;
1574            }
1575            let price = Price::from_decimal_dp(level.p, price_precision).with_context(|| {
1576                format!(
1577                    "Failed to convert AX book bid price {} for {symbol}",
1578                    level.p
1579                )
1580            })?;
1581            let size = Quantity::new(level.q as f64, size_precision);
1582            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
1583            book.add(order, 0, i as u64, ts_event);
1584        }
1585
1586        let bids_len = resp.book.b.len();
1587        for (i, level) in resp.book.a.iter().enumerate() {
1588            if depth.is_some_and(|d| i >= d) {
1589                break;
1590            }
1591            let price = Price::from_decimal_dp(level.p, price_precision).with_context(|| {
1592                format!(
1593                    "Failed to convert AX book ask price {} for {symbol}",
1594                    level.p
1595                )
1596            })?;
1597            let size = Quantity::new(level.q as f64, size_precision);
1598            let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
1599            book.add(order, 0, (bids_len + i) as u64, ts_event);
1600        }
1601
1602        Ok(book)
1603    }
1604
1605    /// Requests recent trades from Ax and parses them to Nautilus [`TradeTick`].
1606    ///
1607    /// The AX trades endpoint does not accept time range parameters, so
1608    /// `start` and `end` are applied as client-side filters after fetching.
1609    ///
1610    /// Requires the instrument to be cached.
1611    ///
1612    /// # Errors
1613    ///
1614    /// Returns an error if:
1615    /// - The instrument is not found in the cache.
1616    /// - The HTTP request fails.
1617    /// - Trade parsing fails.
1618    pub async fn request_trade_ticks(
1619        &self,
1620        symbol: Ustr,
1621        limit: Option<i32>,
1622        start: Option<UnixNanos>,
1623        end: Option<UnixNanos>,
1624    ) -> anyhow::Result<Vec<TradeTick>> {
1625        let instrument = self
1626            .get_instrument(&symbol)
1627            .ok_or_else(|| anyhow::anyhow!("Instrument {symbol} not found in cache"))?;
1628
1629        let resp = self
1630            .inner
1631            .get_trades(symbol, limit)
1632            .await
1633            .map_err(|e| anyhow::anyhow!(e))?;
1634
1635        let ts_init = self.generate_ts_init();
1636        let mut ticks = Vec::with_capacity(resp.trades.len());
1637
1638        for trade in &resp.trades {
1639            match parse_trade_tick(trade, &instrument, ts_init) {
1640                Ok(tick) => {
1641                    if start.is_some_and(|s| tick.ts_event < s) {
1642                        continue;
1643                    }
1644
1645                    if end.is_some_and(|e| tick.ts_event > e) {
1646                        continue;
1647                    }
1648                    ticks.push(tick);
1649                }
1650                Err(e) => {
1651                    log::warn!("Failed to parse trade for {symbol}: {e}");
1652                }
1653            }
1654        }
1655
1656        Ok(ticks)
1657    }
1658
1659    /// Requests historical bars from Ax and parses them to Nautilus Bar types.
1660    ///
1661    /// Requires the instrument to be cached (call `request_instruments` first).
1662    ///
1663    /// # Errors
1664    ///
1665    /// Returns an error if:
1666    /// - The instrument is not found in the cache.
1667    /// - The HTTP request fails.
1668    /// - Bar parsing fails.
1669    pub async fn request_bars(
1670        &self,
1671        symbol: Ustr,
1672        start: Option<Timestamp>,
1673        end: Option<Timestamp>,
1674        width: AxCandleWidth,
1675    ) -> anyhow::Result<Vec<Bar>> {
1676        let instrument = self
1677            .get_instrument(&symbol)
1678            .ok_or_else(|| anyhow::anyhow!("Instrument {symbol} not found in cache"))?;
1679
1680        let start_ns = start
1681            .and_then(|dt| i64::try_from(dt.as_nanosecond()).ok())
1682            .unwrap_or(0);
1683        let end_ns = end
1684            .and_then(|dt| i64::try_from(dt.as_nanosecond()).ok())
1685            .unwrap_or_else(|| self.generate_ts_init().as_i64());
1686        let resp = self
1687            .inner
1688            .get_candles(symbol, start_ns, end_ns, width)
1689            .await
1690            .map_err(|e| anyhow::anyhow!(e))?;
1691
1692        let ts_init = self.generate_ts_init();
1693        let mut bars = Vec::with_capacity(resp.candles.len());
1694
1695        for candle in &resp.candles {
1696            match parse_bar(candle, &instrument, ts_init) {
1697                Ok(bar) => bars.push(bar),
1698                Err(e) => {
1699                    log::warn!("Failed to parse bar for {symbol}: {e}");
1700                }
1701            }
1702        }
1703
1704        Ok(bars)
1705    }
1706
1707    /// Requests funding rates from Ax and parses them to Nautilus types.
1708    ///
1709    /// Traverses the provider's cursor chain. This is a best-effort historical
1710    /// read, not an atomic snapshot if AX corrects rows during the traversal.
1711    ///
1712    /// # Errors
1713    ///
1714    /// Returns an error if the HTTP request fails.
1715    pub async fn request_funding_rates(
1716        &self,
1717        instrument_id: InstrumentId,
1718        start: Option<Timestamp>,
1719        end: Option<Timestamp>,
1720    ) -> Result<Vec<FundingRateUpdate>, AxHttpError> {
1721        const PAGE_SIZE: i32 = 100;
1722
1723        let symbol = instrument_id.symbol.inner();
1724        let start_ns = start
1725            .and_then(|dt| i64::try_from(dt.as_nanosecond()).ok())
1726            .unwrap_or(0);
1727        let end_ns = end
1728            .and_then(|dt| i64::try_from(dt.as_nanosecond()).ok())
1729            .unwrap_or_else(|| self.generate_ts_init().as_i64());
1730        let mut params = GetFundingRatesParams::new(symbol, start_ns, end_ns);
1731        params.limit = Some(PAGE_SIZE);
1732        params.sort_ts = Some("desc".to_string());
1733
1734        let mut funding_rates = Vec::new();
1735        let mut seen_rows = HashSet::new();
1736        let mut seen_cursors = HashSet::new();
1737        let mut expected_total = None;
1738
1739        loop {
1740            let response = self.inner.get_funding_rates_page(&params).await?;
1741            let page_len = response.funding_rates.len();
1742
1743            if page_len > PAGE_SIZE as usize {
1744                return Err(format!(
1745                    "AX funding-rates page length {page_len} exceeds requested limit {PAGE_SIZE}"
1746                )
1747                .into());
1748            }
1749
1750            if let Some(limit) = response.limit {
1751                if !(0..=PAGE_SIZE).contains(&limit) {
1752                    return Err(format!(
1753                        "AX funding-rates applied limit must be between 0 and {PAGE_SIZE}, was {limit}"
1754                    )
1755                    .into());
1756                }
1757
1758                if page_len > limit as usize {
1759                    return Err(format!(
1760                        "AX funding-rates page length {page_len} exceeds applied limit {limit}"
1761                    )
1762                    .into());
1763                }
1764            }
1765
1766            if let Some(total_count) = response.total_count {
1767                if total_count < 0 {
1768                    return Err(format!(
1769                        "AX funding-rates total_count must be non-negative, was {total_count}"
1770                    )
1771                    .into());
1772                }
1773
1774                if let Some(expected) = expected_total {
1775                    if total_count != expected {
1776                        return Err(format!(
1777                            "AX funding-rates total_count changed during pagination: expected {expected}, was {total_count}"
1778                        )
1779                        .into());
1780                    }
1781                } else {
1782                    expected_total = Some(total_count);
1783                }
1784            }
1785
1786            for rate in response.funding_rates {
1787                let identity = (
1788                    rate.symbol,
1789                    rate.timestamp_ns,
1790                    rate.funding_rate,
1791                    rate.funding_amount,
1792                    rate.benchmark_price,
1793                    rate.settlement_price,
1794                );
1795
1796                if !seen_rows.insert(identity) {
1797                    return Err(format!(
1798                        "AX funding-rates pagination returned an exact duplicate row for {} at {}",
1799                        rate.symbol, rate.timestamp_ns
1800                    )
1801                    .into());
1802                }
1803                funding_rates.push(rate);
1804            }
1805
1806            if let Some(total_count) = expected_total
1807                && funding_rates.len() as i64 > total_count
1808            {
1809                return Err(format!(
1810                    "AX funding-rates pagination returned more unique rows ({}) than total_count {total_count}",
1811                    funding_rates.len()
1812                )
1813                .into());
1814            }
1815
1816            match response.next_cursor {
1817                Some(next_cursor) => {
1818                    if next_cursor.is_empty() {
1819                        return Err("AX funding-rates returned an empty next_cursor"
1820                            .to_string()
1821                            .into());
1822                    }
1823
1824                    if page_len == 0 {
1825                        return Err("AX funding-rates returned an empty page with a next_cursor"
1826                            .to_string()
1827                            .into());
1828                    }
1829
1830                    if !seen_cursors.insert(next_cursor.clone()) {
1831                        return Err(format!(
1832                            "AX funding-rates pagination repeated cursor {next_cursor:?}"
1833                        )
1834                        .into());
1835                    }
1836                    params.cursor = Some(next_cursor);
1837                }
1838                None => break,
1839            }
1840        }
1841
1842        if let Some(total_count) = expected_total
1843            && funding_rates.len() as i64 != total_count
1844        {
1845            return Err(format!(
1846                "AX funding-rates pagination returned {} unique rows, expected {total_count}",
1847                funding_rates.len()
1848            )
1849            .into());
1850        }
1851
1852        let ts_init = self.generate_ts_init();
1853        let updates = funding_rates
1854            .iter()
1855            .map(|r| parse_funding_rate(r, instrument_id, ts_init))
1856            .collect::<anyhow::Result<Vec<_>>>()
1857            .map_err(|e| AxHttpError::from(e.to_string()))?;
1858
1859        Ok(updates)
1860    }
1861
1862    /// Requests the funding-slot schedule for a symbol on a trading day.
1863    ///
1864    /// AX returns a single response covering the whole trading day, so there
1865    /// is no pagination. The schedule has no Nautilus domain equivalent, so
1866    /// the venue response is returned verbatim.
1867    ///
1868    /// # Errors
1869    ///
1870    /// Returns an error if the HTTP request fails or the response cannot be parsed.
1871    pub async fn request_funding_slots(
1872        &self,
1873        instrument_id: InstrumentId,
1874        date: Option<Date>,
1875    ) -> Result<AxFundingSlotsResponse, AxHttpError> {
1876        let symbol = instrument_id.symbol.inner();
1877        let mut params = GetFundingSlotsParams::new(symbol);
1878
1879        if let Some(date) = date {
1880            params.date = Some(date.strftime("%Y-%m-%d").to_string());
1881        }
1882
1883        self.inner.get_funding_slots(&params).await
1884    }
1885
1886    /// Requests account state from Ax and parses to a Nautilus [`AccountState`].
1887    ///
1888    /// # Errors
1889    ///
1890    /// Returns an error if the HTTP request fails or parsing fails.
1891    pub async fn request_account_state(
1892        &self,
1893        account_id: AccountId,
1894    ) -> anyhow::Result<AccountState> {
1895        // Time-bound the snapshot so a hung /risk-snapshot cannot stall connect
1896        const RISK_SNAPSHOT_TIMEOUT_SECS: u64 = 10;
1897
1898        let (balances, risk) = tokio::join!(
1899            self.inner.get_balances(),
1900            tokio::time::timeout(
1901                Duration::from_secs(RISK_SNAPSHOT_TIMEOUT_SECS),
1902                self.inner.get_risk_snapshot(),
1903            ),
1904        );
1905
1906        let response = balances.map_err(|e| anyhow::anyhow!(e))?;
1907
1908        let risk = match risk {
1909            Ok(Ok(snapshot)) => Some(snapshot.risk_snapshot),
1910            Ok(Err(e)) => {
1911                log::warn!(
1912                    "AX risk snapshot unavailable, account state reports zero locked margin: {e}"
1913                );
1914                None
1915            }
1916            Err(_) => {
1917                log::warn!(
1918                    "AX risk snapshot timed out after {RISK_SNAPSHOT_TIMEOUT_SECS}s, \
1919                     account state reports zero locked margin"
1920                );
1921                None
1922            }
1923        };
1924
1925        let ts_init = self.generate_ts_init();
1926        parse_account_state(&response, risk.as_ref(), account_id, ts_init, ts_init)
1927    }
1928
1929    /// Checks the initial margin requirement for a proposed order.
1930    ///
1931    /// # Errors
1932    ///
1933    /// Returns an error if the HTTP request fails.
1934    pub async fn check_initial_margin(
1935        &self,
1936        request: &PlaceOrderRequest,
1937    ) -> anyhow::Result<Decimal> {
1938        let resp = self
1939            .inner
1940            .check_initial_margin(request)
1941            .await
1942            .map_err(|e| anyhow::anyhow!(e))?;
1943        Ok(resp.im)
1944    }
1945
1946    /// Queries a single order by venue order ID or client order ID using the
1947    /// dedicated `/order-status` endpoint, which works for any order state.
1948    ///
1949    /// The caller must supply `order_side`, `order_type`, and `time_in_force`
1950    /// because the endpoint does not return these fields.
1951    /// Canceled, expired, and rejected orders with no remaining quantity use `/orders`
1952    /// to recover their original quantity.
1953    ///
1954    /// # Errors
1955    ///
1956    /// Returns an error if:
1957    /// - Neither `venue_order_id` nor `client_order_id` is provided.
1958    /// - The HTTP request fails.
1959    /// - The original quantity is unavailable in order history.
1960    #[expect(clippy::too_many_arguments)]
1961    pub async fn request_order_status(
1962        &self,
1963        account_id: AccountId,
1964        instrument_id: InstrumentId,
1965        client_order_id: Option<ClientOrderId>,
1966        venue_order_id: Option<VenueOrderId>,
1967        order_side: Option<OrderSide>,
1968        order_type: OrderType,
1969        time_in_force: TimeInForce,
1970    ) -> anyhow::Result<OrderStatusReport> {
1971        let resp = if let Some(ref voi) = venue_order_id {
1972            self.inner.get_order_status_by_id(voi.as_str()).await
1973        } else if let Some(ref coid) = client_order_id {
1974            let cid = client_order_id_to_cid(coid);
1975            self.inner.get_order_status_by_cid(cid).await
1976        } else {
1977            anyhow::bail!("Either venue_order_id or client_order_id must be provided")
1978        }
1979        .map_err(|e| anyhow::anyhow!(e))?;
1980
1981        let detail = resp.status;
1982        let size_precision = self
1983            .get_instrument(&detail.symbol)
1984            .map_or(0, |i| i.size_precision());
1985
1986        let voi = VenueOrderId::new(&detail.order_id);
1987        let order_status = parse_order_status(detail.state, time_in_force)?;
1988        let filled = detail.filled_quantity.unwrap_or(0);
1989        let remaining = detail.remaining_quantity.unwrap_or(0);
1990
1991        let total = if remaining == 0
1992            && matches!(
1993                order_status,
1994                OrderStatus::Canceled | OrderStatus::Expired | OrderStatus::Rejected
1995            ) {
1996            let response = self
1997                .inner
1998                .get_orders(&GetOrdersParams {
1999                    order_id: Some(detail.order_id.clone()),
2000                    limit: Some(1),
2001                    ..Default::default()
2002                })
2003                .await?;
2004
2005            let order = response
2006                .orders
2007                .iter()
2008                .find(|order| order.oid == detail.order_id)
2009                .with_context(|| {
2010                    format!(
2011                        "AX order {} original quantity unavailable in history",
2012                        detail.order_id
2013                    )
2014                })?;
2015
2016            Decimal::from(order.q)
2017        } else {
2018            Decimal::from(filled) + Decimal::from(remaining)
2019        };
2020
2021        let quantity = Quantity::from_decimal_dp(total, size_precision)?;
2022        let filled_qty = Quantity::from_decimal_dp(Decimal::from(filled), size_precision)?;
2023        let ts_init = self.generate_ts_init();
2024
2025        let resolved_coid = client_order_id.or_else(|| detail.clord_id.map(cid_to_client_order_id));
2026
2027        let mut report = OrderStatusReport::new(
2028            account_id,
2029            instrument_id,
2030            resolved_coid,
2031            voi,
2032            order_side,
2033            order_type,
2034            time_in_force,
2035            order_status,
2036            quantity,
2037            filled_qty,
2038            ts_init,
2039            ts_init,
2040            ts_init,
2041            Some(UUID4::new()),
2042        );
2043
2044        if let Some(reason) =
2045            AxOrderRejectReason::reason_str(detail.reject_reason, detail.reject_message.as_deref())
2046        {
2047            report = report.with_cancel_reason(reason);
2048        }
2049
2050        Ok(report)
2051    }
2052
2053    pub(crate) async fn request_order_report<F>(
2054        &self,
2055        account_id: AccountId,
2056        client_order_id: Option<ClientOrderId>,
2057        venue_order_id: Option<VenueOrderId>,
2058        cid_resolver: Option<F>,
2059    ) -> anyhow::Result<Option<OrderStatusReport>>
2060    where
2061        F: Fn(u64) -> Option<ClientOrderId>,
2062    {
2063        let response = if let Some(order_id) = venue_order_id {
2064            self.inner.get_order_status_by_id(order_id.as_str()).await
2065        } else if let Some(client_order_id) = client_order_id {
2066            let cid = client_order_id_to_cid(&client_order_id);
2067            self.inner.get_order_status_by_cid(cid).await
2068        } else {
2069            anyhow::bail!("Either venue_order_id or client_order_id must be provided")
2070        };
2071
2072        let status = match response {
2073            Ok(response) => response.status,
2074            Err(AxHttpError::UnexpectedStatus { status: 404, body })
2075                if serde_json::from_str::<AxErrorResponse>(&body).is_ok_and(|response| {
2076                    response.error.as_deref() == Some("no matching orders")
2077                }) =>
2078            {
2079                return Ok(None);
2080            }
2081            Err(e) => return Err(e.into()),
2082        };
2083
2084        let params = GetOrdersParams {
2085            order_id: Some(status.order_id.clone()),
2086            ..Default::default()
2087        };
2088
2089        let orders = self.request_order_details(params).await?;
2090        let order = orders
2091            .iter()
2092            .find(|order| order.oid == status.order_id)
2093            .context("AX order status exists but its complete history record is unavailable")?;
2094        let instrument = self.resolve_report_instrument(order.s).await?;
2095        let ts_init = self.generate_ts_init();
2096        let mut report = parse_order_detail_status_report(
2097            order,
2098            account_id,
2099            &instrument,
2100            ts_init,
2101            cid_resolver.as_ref(),
2102        )?;
2103
2104        if let Some(client_order_id) = client_order_id {
2105            report.client_order_id = Some(client_order_id);
2106        }
2107
2108        if report.order_status.is_closed() && !report.filled_qty.is_zero() {
2109            let fills = self.request_fill_reports(account_id, None, None).await?;
2110            update_order_report_timestamps(std::slice::from_mut(&mut report), &fills);
2111        }
2112
2113        Ok(Some(report))
2114    }
2115
2116    /// Requests open orders from Ax and parses them to Nautilus [`OrderStatusReport`].
2117    ///
2118    /// Missing instruments are requested from Ax and cached before parsing order details.
2119    ///
2120    /// The `cid_resolver` parameter is an optional function that resolves a `cid` (u64)
2121    /// to a `ClientOrderId`. This is needed for correlating orders submitted via WebSocket.
2122    ///
2123    /// # Errors
2124    ///
2125    /// Returns an error if:
2126    /// - The HTTP request fails.
2127    /// - An order's instrument cannot be fetched or parsed.
2128    /// - An order cannot be mapped to a complete status report.
2129    pub async fn request_order_status_reports<F>(
2130        &self,
2131        account_id: AccountId,
2132        cid_resolver: Option<F>,
2133    ) -> anyhow::Result<Vec<OrderStatusReport>>
2134    where
2135        F: Fn(u64) -> Option<ClientOrderId>,
2136    {
2137        const PAGE_SIZE: i32 = 100;
2138
2139        let mut orders = Vec::new();
2140        let mut seen_order_ids = HashSet::new();
2141        let mut offset = 0_i64;
2142        let mut expected_total = None;
2143
2144        loop {
2145            let request_offset = i32::try_from(offset)
2146                .context("AX open-orders offset exceeds the documented int32 range")?;
2147            let params = GetOpenOrdersParams {
2148                account_id: None,
2149                limit: Some(PAGE_SIZE),
2150                offset: Some(request_offset),
2151                sort_ts: Some("desc".to_string()),
2152            };
2153            let response = self
2154                .inner
2155                .get_open_orders_page(&params)
2156                .await
2157                .map_err(|e| anyhow::anyhow!(e))?;
2158
2159            anyhow::ensure!(
2160                response.total_count >= 0,
2161                "AX open-orders total_count must be non-negative, was {}",
2162                response.total_count
2163            );
2164            anyhow::ensure!(
2165                response.limit >= 0 && response.limit <= PAGE_SIZE,
2166                "AX open-orders applied limit must be between 0 and {PAGE_SIZE}, was {}",
2167                response.limit
2168            );
2169            anyhow::ensure!(
2170                i64::from(response.offset) == offset,
2171                "AX open-orders response offset mismatch: requested {offset}, was {}",
2172                response.offset
2173            );
2174
2175            let total_count = *expected_total.get_or_insert(response.total_count);
2176            anyhow::ensure!(
2177                response.total_count == total_count,
2178                "AX open-orders total_count changed during pagination: expected {total_count}, was {}",
2179                response.total_count
2180            );
2181
2182            let page_len = i64::try_from(response.orders.len())
2183                .context("AX open-orders page length exceeds i64")?;
2184            anyhow::ensure!(
2185                page_len <= i64::from(response.limit),
2186                "AX open-orders page length {page_len} exceeds applied limit {}",
2187                response.limit
2188            );
2189            let next_offset = offset
2190                .checked_add(page_len)
2191                .context("AX open-orders offset overflow")?;
2192            anyhow::ensure!(
2193                next_offset <= total_count,
2194                "AX open-orders page exceeds total_count: next offset {next_offset}, total {total_count}"
2195            );
2196
2197            if total_count == 0 {
2198                anyhow::ensure!(
2199                    response.orders.is_empty(),
2200                    "AX open-orders returned rows with total_count zero"
2201                );
2202                break;
2203            }
2204
2205            anyhow::ensure!(
2206                !response.orders.is_empty(),
2207                "AX open-orders returned an empty page before offset {offset} reached total {total_count}"
2208            );
2209
2210            for order in response.orders {
2211                anyhow::ensure!(
2212                    seen_order_ids.insert(order.oid.clone()),
2213                    "AX open-orders pagination returned duplicate order ID {}",
2214                    order.oid
2215                );
2216                orders.push(order);
2217            }
2218
2219            if next_offset == total_count {
2220                break;
2221            }
2222
2223            offset = next_offset;
2224        }
2225
2226        anyhow::ensure!(
2227            i64::try_from(orders.len()).context("AX open-orders result length exceeds i64")?
2228                == expected_total.unwrap_or_default(),
2229            "AX open-orders pagination did not return the advertised number of unique orders"
2230        );
2231
2232        let ts_init = self.generate_ts_init();
2233        let mut reports = Vec::with_capacity(orders.len());
2234
2235        for order in &orders {
2236            let instrument = self.resolve_report_instrument(order.s).await?;
2237
2238            let report = parse_order_status_report(
2239                order,
2240                account_id,
2241                &instrument,
2242                ts_init,
2243                cid_resolver.as_ref(),
2244            )
2245            .with_context(|| format!("failed to parse AX order {}", order.oid))?;
2246            reports.push(report);
2247        }
2248
2249        Ok(reports)
2250    }
2251
2252    /// Requests historical orders from Ax and parses them to Nautilus
2253    /// [`OrderStatusReport`].
2254    ///
2255    /// Closed orders with fills trigger a `/fills` request in the same window to set
2256    /// a lower bound for `ts_last`. The fill window is capped at seven days; without
2257    /// a matching fill, creation time remains because `/orders` has no terminal timestamp.
2258    ///
2259    /// Missing instruments are requested from Ax and cached before parsing orders or fills.
2260    ///
2261    /// The `cid_resolver` parameter is an optional function that resolves a `cid` (u64)
2262    /// to a `ClientOrderId`. This is needed for correlating orders submitted via WebSocket.
2263    ///
2264    /// # Errors
2265    ///
2266    /// Returns an error if:
2267    /// - The HTTP request or pagination contract fails.
2268    /// - An order or fill's instrument cannot be fetched or parsed.
2269    /// - An order or fill cannot be mapped to a complete report.
2270    /// - A `start` or `end` timestamp exceeds `i64::MAX` nanoseconds.
2271    pub async fn request_historical_order_status_reports<F>(
2272        &self,
2273        account_id: AccountId,
2274        start: Option<UnixNanos>,
2275        end: Option<UnixNanos>,
2276        cid_resolver: Option<F>,
2277    ) -> anyhow::Result<Vec<OrderStatusReport>>
2278    where
2279        F: Fn(u64) -> Option<ClientOrderId>,
2280    {
2281        let mut reports = self
2282            .request_order_history(account_id, start, end, cid_resolver)
2283            .await?;
2284
2285        if reports
2286            .iter()
2287            .any(|report| report.order_status.is_closed() && !report.filled_qty.is_zero())
2288        {
2289            let fills = self.request_fill_reports(account_id, start, end).await?;
2290            update_order_report_timestamps(&mut reports, &fills);
2291        }
2292
2293        Ok(reports)
2294    }
2295
2296    pub(crate) async fn request_order_history<F>(
2297        &self,
2298        account_id: AccountId,
2299        start: Option<UnixNanos>,
2300        end: Option<UnixNanos>,
2301        cid_resolver: Option<F>,
2302    ) -> anyhow::Result<Vec<OrderStatusReport>>
2303    where
2304        F: Fn(u64) -> Option<ClientOrderId>,
2305    {
2306        let params = GetOrdersParams {
2307            start_timestamp_ns: start
2308                .map(|timestamp| i64::try_from(timestamp.as_u64()))
2309                .transpose()
2310                .context("start timestamp exceeds the signed nanosecond range")?,
2311            end_timestamp_ns: end
2312                .map(|timestamp| i64::try_from(timestamp.as_u64()))
2313                .transpose()
2314                .context("end timestamp exceeds the signed nanosecond range")?,
2315            ..Default::default()
2316        };
2317
2318        let orders = self.request_order_details(params).await?;
2319
2320        let ts_init = self.generate_ts_init();
2321        let mut reports = Vec::with_capacity(orders.len());
2322
2323        for order in &orders {
2324            let instrument = self.resolve_report_instrument(order.s).await?;
2325
2326            let report = parse_order_detail_status_report(
2327                order,
2328                account_id,
2329                &instrument,
2330                ts_init,
2331                cid_resolver.as_ref(),
2332            )
2333            .with_context(|| format!("failed to parse AX order {}", order.oid))?;
2334            reports.push(report);
2335        }
2336
2337        Ok(reports)
2338    }
2339
2340    async fn request_order_details(
2341        &self,
2342        mut params: GetOrdersParams,
2343    ) -> anyhow::Result<Vec<AxOrderDetail>> {
2344        const PAGE_SIZE: i32 = 100;
2345        params.limit = Some(PAGE_SIZE);
2346        let mut orders = Vec::new();
2347        let mut seen_cursors = HashSet::new();
2348        let mut seen_order_ids = HashSet::new();
2349        let mut expected_total = None;
2350
2351        loop {
2352            let response = self
2353                .inner
2354                .get_orders(&params)
2355                .await
2356                .map_err(|e| anyhow::anyhow!(e))?;
2357
2358            let page_len = response.orders.len();
2359            anyhow::ensure!(
2360                page_len <= PAGE_SIZE as usize,
2361                "AX orders page length {page_len} exceeds requested limit {PAGE_SIZE}"
2362            );
2363
2364            if let Some(limit) = response.limit {
2365                anyhow::ensure!(
2366                    (0..=PAGE_SIZE).contains(&limit),
2367                    "AX orders applied limit must be between 0 and {PAGE_SIZE}, was {limit}"
2368                );
2369                anyhow::ensure!(
2370                    page_len <= limit as usize,
2371                    "AX orders page length {page_len} exceeds applied limit {limit}"
2372                );
2373            }
2374
2375            if let Some(total_count) = response.total_count {
2376                anyhow::ensure!(
2377                    total_count >= 0,
2378                    "AX orders total_count must be non-negative, was {total_count}"
2379                );
2380
2381                if let Some(expected) = expected_total {
2382                    anyhow::ensure!(
2383                        total_count == expected,
2384                        "AX orders total_count changed during pagination: expected {expected}, was {total_count}"
2385                    );
2386                } else {
2387                    expected_total = Some(total_count);
2388                }
2389            }
2390
2391            for order in response.orders {
2392                anyhow::ensure!(
2393                    seen_order_ids.insert(order.oid.clone()),
2394                    "AX orders pagination returned duplicate order ID {}",
2395                    order.oid
2396                );
2397                orders.push(order);
2398            }
2399
2400            if let Some(total_count) = expected_total {
2401                anyhow::ensure!(
2402                    orders.len() as i64 <= total_count,
2403                    "AX orders pagination returned more unique rows ({}) than total_count {total_count}",
2404                    orders.len()
2405                );
2406            }
2407
2408            match response.next_cursor {
2409                Some(next_cursor) => {
2410                    anyhow::ensure!(
2411                        !next_cursor.is_empty(),
2412                        "AX orders returned an empty next_cursor"
2413                    );
2414                    anyhow::ensure!(
2415                        page_len > 0,
2416                        "AX orders returned an empty page with a next_cursor"
2417                    );
2418                    anyhow::ensure!(
2419                        seen_cursors.insert(next_cursor.clone()),
2420                        "AX orders pagination repeated cursor {next_cursor:?}"
2421                    );
2422                    params.cursor = Some(next_cursor);
2423                }
2424                None => break,
2425            }
2426        }
2427
2428        if let Some(total_count) = expected_total {
2429            anyhow::ensure!(
2430                orders.len() as i64 == total_count,
2431                "AX orders pagination returned {} unique rows, expected {total_count}",
2432                orders.len()
2433            );
2434        }
2435
2436        Ok(orders)
2437    }
2438
2439    /// Requests fills from Ax and parses them to Nautilus [`FillReport`].
2440    ///
2441    /// Missing instruments are requested from Ax and cached before parsing fill details.
2442    /// Traverses the provider's cursor chain. This is a best-effort historical
2443    /// read, not an atomic snapshot if AX corrects rows during the traversal.
2444    ///
2445    /// # Errors
2446    ///
2447    /// Returns an error if:
2448    /// - The HTTP request fails.
2449    /// - A fill's instrument cannot be fetched or parsed.
2450    /// - Fill parsing fails.
2451    /// - A `start` or `end` timestamp exceeds `i64::MAX` nanoseconds.
2452    pub async fn request_fill_reports(
2453        &self,
2454        account_id: AccountId,
2455        start: Option<UnixNanos>,
2456        end: Option<UnixNanos>,
2457    ) -> anyhow::Result<Vec<FillReport>> {
2458        const PAGE_SIZE: i32 = 100;
2459
2460        // The AX `/fills` endpoint requires a bounded time range and caps the span at 7 days
2461        let max_span_ns = AX_FILLS_MAX_LOOKBACK_DAYS * 24 * 60 * 60 * 1_000_000_000;
2462        let end_ns = i64::try_from(end.unwrap_or_else(|| self.generate_ts_init()).as_u64())
2463            .context("end timestamp exceeds the signed nanosecond range")?;
2464        let floor_ns = end_ns - max_span_ns;
2465        let start_ns = start
2466            .map(|timestamp| i64::try_from(timestamp.as_u64()))
2467            .transpose()
2468            .context("start timestamp exceeds the signed nanosecond range")?
2469            .unwrap_or(floor_ns)
2470            .max(floor_ns);
2471        let mut params = GetFillsParams::new(start_ns, end_ns);
2472        params.limit = Some(PAGE_SIZE);
2473        params.sort_ts = Some("desc".to_string());
2474
2475        let mut fills = Vec::new();
2476        let mut seen_trade_ids = HashSet::new();
2477        let mut seen_cursors = HashSet::new();
2478        let mut expected_total = None;
2479
2480        loop {
2481            let response = self
2482                .inner
2483                .get_fills_page(&params)
2484                .await
2485                .map_err(|e| anyhow::anyhow!(e))?;
2486            let page_len = response.fills.len();
2487
2488            anyhow::ensure!(
2489                page_len <= PAGE_SIZE as usize,
2490                "AX fills page length {page_len} exceeds requested limit {PAGE_SIZE}"
2491            );
2492
2493            if let Some(limit) = response.limit {
2494                anyhow::ensure!(
2495                    (0..=PAGE_SIZE).contains(&limit),
2496                    "AX fills applied limit must be between 0 and {PAGE_SIZE}, was {limit}"
2497                );
2498                anyhow::ensure!(
2499                    page_len <= limit as usize,
2500                    "AX fills page length {page_len} exceeds applied limit {limit}"
2501                );
2502            }
2503
2504            if let Some(total_count) = response.total_count {
2505                anyhow::ensure!(
2506                    total_count >= 0,
2507                    "AX fills total_count must be non-negative, was {total_count}"
2508                );
2509
2510                if let Some(expected) = expected_total {
2511                    anyhow::ensure!(
2512                        total_count == expected,
2513                        "AX fills total_count changed during pagination: expected {expected}, was {total_count}"
2514                    );
2515                } else {
2516                    expected_total = Some(total_count);
2517                }
2518            }
2519
2520            for fill in response.fills {
2521                anyhow::ensure!(
2522                    seen_trade_ids.insert(fill.trade_id.clone()),
2523                    "AX fills pagination returned duplicate trade ID {}",
2524                    fill.trade_id
2525                );
2526                fills.push(fill);
2527            }
2528
2529            if let Some(total_count) = expected_total {
2530                anyhow::ensure!(
2531                    fills.len() as i64 <= total_count,
2532                    "AX fills pagination returned more unique rows ({}) than total_count {total_count}",
2533                    fills.len()
2534                );
2535            }
2536
2537            match response.next_cursor {
2538                Some(next_cursor) => {
2539                    anyhow::ensure!(
2540                        !next_cursor.is_empty(),
2541                        "AX fills returned an empty next_cursor"
2542                    );
2543                    anyhow::ensure!(
2544                        page_len > 0,
2545                        "AX fills returned an empty page with a next_cursor"
2546                    );
2547                    anyhow::ensure!(
2548                        seen_cursors.insert(next_cursor.clone()),
2549                        "AX fills pagination repeated cursor {next_cursor:?}"
2550                    );
2551                    params.cursor = Some(next_cursor);
2552                }
2553                None => break,
2554            }
2555        }
2556
2557        if let Some(total_count) = expected_total {
2558            anyhow::ensure!(
2559                fills.len() as i64 == total_count,
2560                "AX fills pagination returned {} unique rows, expected {total_count}",
2561                fills.len()
2562            );
2563        }
2564
2565        let ts_init = self.generate_ts_init();
2566        let mut reports = Vec::with_capacity(fills.len());
2567
2568        for fill in &fills {
2569            let instrument = self.resolve_report_instrument(fill.symbol).await?;
2570            let report = parse_fill_report(fill, account_id, &instrument, ts_init)
2571                .with_context(|| format!("Failed to parse AX fill {}", fill.trade_id))?;
2572            reports.push(report);
2573        }
2574
2575        Ok(reports)
2576    }
2577
2578    /// Requests positions from Ax and parses them to Nautilus [`PositionStatusReport`].
2579    ///
2580    /// Missing instruments are requested from Ax and cached before parsing position details.
2581    ///
2582    /// # Errors
2583    ///
2584    /// Returns an error if:
2585    /// - The HTTP request fails.
2586    /// - A position's instrument cannot be fetched or parsed.
2587    /// - A position cannot be parsed.
2588    pub async fn request_position_reports(
2589        &self,
2590        account_id: AccountId,
2591    ) -> anyhow::Result<Vec<PositionStatusReport>> {
2592        let response = self
2593            .inner
2594            .get_positions()
2595            .await
2596            .map_err(|e| anyhow::anyhow!(e))?;
2597
2598        let ts_init = self.generate_ts_init();
2599        let mut reports = Vec::with_capacity(response.positions.len());
2600
2601        for position in &response.positions {
2602            let instrument = self.resolve_report_instrument(position.symbol).await?;
2603
2604            let report = parse_position_status_report(position, account_id, &instrument, ts_init)
2605                .with_context(|| {
2606                format!("failed to parse AX position for {}", position.symbol)
2607            })?;
2608
2609            reports.push(report);
2610        }
2611
2612        Ok(reports)
2613    }
2614
2615    async fn resolve_report_instrument(&self, symbol: Ustr) -> anyhow::Result<InstrumentAny> {
2616        if let Some(instrument) = self.get_instrument(&symbol) {
2617            return Ok(instrument);
2618        }
2619
2620        let instrument = self.request_instrument(symbol).await.map_err(|e| {
2621            anyhow::anyhow!("Failed to resolve AX instrument {symbol} via GET /instrument: {e}")
2622        })?;
2623        self.cache_instrument(instrument.clone());
2624        Ok(instrument)
2625    }
2626
2627    /// Cancels all open orders for an instrument.
2628    ///
2629    /// # Errors
2630    ///
2631    /// Returns an error if the request fails.
2632    pub async fn cancel_all_orders(&self, instrument_id: InstrumentId) -> Result<(), AxHttpError> {
2633        let request = CancelAllOrdersRequest::new().with_symbol(instrument_id.symbol.inner());
2634        self.inner.cancel_all_orders(&request).await?;
2635        Ok(())
2636    }
2637}
2638
2639#[cfg(test)]
2640mod tests {
2641    use rstest::rstest;
2642
2643    use super::*;
2644    use crate::common::enums::{AxOrderSide, AxTimeInForce};
2645
2646    #[derive(Clone, Copy, Debug)]
2647    enum OrderOperation {
2648        Place,
2649        Cancel,
2650        Replace,
2651        CancelAll,
2652        OpenOrders,
2653        OrderStatusById,
2654        OrderStatusByCid,
2655        Orders,
2656        InitialMargin,
2657    }
2658
2659    fn custom_api_client() -> AxRawHttpClient {
2660        AxRawHttpClient::new(
2661            Some("http://mock".to_string()),
2662            None,
2663            60,
2664            3,
2665            1_000,
2666            10_000,
2667            None,
2668        )
2669        .unwrap()
2670    }
2671
2672    #[rstest]
2673    #[case::production_defaults(None, None, AX_HTTP_URL, Some(AX_ORDERS_URL))]
2674    #[case::sandbox_default_orders(
2675        Some(AX_HTTP_SANDBOX_URL),
2676        None,
2677        AX_HTTP_SANDBOX_URL,
2678        Some(AX_ORDERS_SANDBOX_URL)
2679    )]
2680    #[case::sandbox_trailing_slash(
2681        Some("https://gateway.sandbox.architect.exchange/api/"),
2682        None,
2683        AX_HTTP_SANDBOX_URL,
2684        Some(AX_ORDERS_SANDBOX_URL)
2685    )]
2686    #[case::custom_without_orders(Some("http://mock/"), None, "http://mock", None)]
2687    #[case::explicit_orders(
2688        Some("http://mock/"),
2689        Some("http://orders/"),
2690        "http://mock",
2691        Some("http://orders")
2692    )]
2693    fn test_resolve_base_urls(
2694        #[case] base_url: Option<&str>,
2695        #[case] orders_base_url: Option<&str>,
2696        #[case] expected_base: &str,
2697        #[case] expected_orders: Option<&str>,
2698    ) {
2699        let (base, orders) = resolve_base_urls(
2700            base_url.map(str::to_string),
2701            orders_base_url.map(str::to_string),
2702        );
2703
2704        assert_eq!(base, expected_base);
2705        assert_eq!(orders.as_deref(), expected_orders);
2706    }
2707
2708    #[rstest]
2709    fn test_custom_base_url_without_orders_url_rejects_order_route() {
2710        let client = custom_api_client();
2711
2712        let error = client.orders_base_url().unwrap_err();
2713
2714        assert!(matches!(error, AxHttpError::ValidationError(_)));
2715    }
2716
2717    #[rstest]
2718    #[case::place(OrderOperation::Place)]
2719    #[case::cancel(OrderOperation::Cancel)]
2720    #[case::replace(OrderOperation::Replace)]
2721    #[case::cancel_all(OrderOperation::CancelAll)]
2722    #[case::open_orders(OrderOperation::OpenOrders)]
2723    #[case::order_status_by_id(OrderOperation::OrderStatusById)]
2724    #[case::order_status_by_cid(OrderOperation::OrderStatusByCid)]
2725    #[case::orders(OrderOperation::Orders)]
2726    #[case::initial_margin(OrderOperation::InitialMargin)]
2727    #[tokio::test]
2728    async fn test_order_operations_require_orders_url_for_custom_api_url(
2729        #[case] operation: OrderOperation,
2730    ) {
2731        let client = custom_api_client();
2732
2733        let place_request = PlaceOrderRequest::new(
2734            AxOrderSide::Buy,
2735            Decimal::from(100),
2736            1,
2737            Ustr::from("XAU-PERP"),
2738            AxTimeInForce::Gtc,
2739            false,
2740        );
2741
2742        let result = match operation {
2743            OrderOperation::Place => client.place_order(&place_request).await.map(|_| ()),
2744            OrderOperation::Cancel => client.cancel_order("OID-1").await.map(|_| ()),
2745            OrderOperation::Replace => client
2746                .replace_order(&ReplaceOrderRequest::new("OID-1"))
2747                .await
2748                .map(|_| ()),
2749            OrderOperation::CancelAll => client
2750                .cancel_all_orders(&CancelAllOrdersRequest::new())
2751                .await
2752                .map(|_| ()),
2753            OrderOperation::OpenOrders => client.get_open_orders().await.map(|_| ()),
2754            OrderOperation::OrderStatusById => {
2755                client.get_order_status_by_id("OID-1").await.map(|_| ())
2756            }
2757            OrderOperation::OrderStatusByCid => {
2758                client.get_order_status_by_cid(123).await.map(|_| ())
2759            }
2760            OrderOperation::Orders => client
2761                .get_orders(&GetOrdersParams::default())
2762                .await
2763                .map(|_| ()),
2764            OrderOperation::InitialMargin => client
2765                .check_initial_margin(&place_request)
2766                .await
2767                .map(|_| ()),
2768        };
2769
2770        let error = result.unwrap_err();
2771        match error {
2772            AxHttpError::ValidationError(message) => assert_eq!(
2773                message,
2774                "Orders base URL is required for order-management operations with a custom API base URL"
2775            ),
2776            other => panic!("Expected validation error, was {other}"),
2777        }
2778    }
2779
2780    #[rstest]
2781    #[case::new(false)]
2782    #[case::with_credentials(true)]
2783    fn test_raw_http_constructors_reject_invalid_timing(#[case] with_credentials: bool) {
2784        let result = if with_credentials {
2785            AxRawHttpClient::with_credentials(
2786                "key".to_string(),
2787                "secret".to_string(),
2788                None,
2789                None,
2790                0,
2791                3,
2792                1_000,
2793                10_000,
2794                None,
2795            )
2796        } else {
2797            AxRawHttpClient::new(None, None, 0, 3, 1_000, 10_000, None)
2798        };
2799
2800        assert!(matches!(
2801            result.unwrap_err(),
2802            AxHttpError::ValidationError(_)
2803        ));
2804    }
2805
2806    #[rstest]
2807    fn test_low_level_http_accepts_socks_proxy() {
2808        let result = AxRawHttpClient::new(
2809            None,
2810            None,
2811            60,
2812            3,
2813            1_000,
2814            10_000,
2815            Some("socks5://127.0.0.1:1080".to_string()),
2816        );
2817
2818        assert!(result.is_ok());
2819    }
2820
2821    #[rstest]
2822    fn test_retry_config_uses_configured_timeout_without_hidden_elapsed_cap() {
2823        let config = retry_config(120, 4, 2_000, 8_000).unwrap();
2824
2825        assert_eq!(config.max_retries, 4);
2826        assert_eq!(config.initial_delay_ms, 2_000);
2827        assert_eq!(config.max_delay_ms, 8_000);
2828        assert_eq!(config.backoff_factor, 2.0);
2829        assert_eq!(config.jitter_ms, 1_000);
2830        assert_eq!(config.operation_timeout_ms, Some(120_000));
2831        assert!(!config.immediate_first);
2832        assert_eq!(config.max_elapsed_ms, None);
2833    }
2834
2835    #[rstest]
2836    #[case::zero_timeout(0, 3, 1_000, 10_000)]
2837    #[case::timeout_overflow(u64::MAX, 3, 1_000, 10_000)]
2838    #[case::zero_initial_delay(60, 3, 0, 10_000)]
2839    #[case::zero_initial_delay_without_retries(60, 0, 0, 10_000)]
2840    #[case::reversed_delays(60, 3, 10_001, 10_000)]
2841    fn test_retry_config_rejects_invalid_timing(
2842        #[case] timeout_secs: u64,
2843        #[case] max_retries: u32,
2844        #[case] retry_delay_ms: u64,
2845        #[case] retry_delay_max_ms: u64,
2846    ) {
2847        let error = retry_config(
2848            timeout_secs,
2849            max_retries,
2850            retry_delay_ms,
2851            retry_delay_max_ms,
2852        )
2853        .unwrap_err();
2854
2855        assert!(matches!(error, AxHttpError::ValidationError(_)));
2856    }
2857}