1use 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
95pub 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
104pub 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 #[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 #[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 pub fn cancel_all_requests(&self) {
164 self.cancellation_token.read().cancel();
165 }
166
167 pub fn reset_cancellation_token(&self) {
169 *self.cancellation_token.write() = CancellationToken::new();
170 }
171
172 pub fn cancellation_token(&self) -> CancellationToken {
174 self.cancellation_token.read().clone()
175 }
176
177 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 #[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 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 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 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 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 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 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 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 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 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(¶ms), None, true)
521 .await
522 .map(|response| response.ticker)
523 }
524
525 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(¶ms), None, false)
536 .await
537 }
538
539 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 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 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 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 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 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 pub async fn get_open_orders(&self) -> Result<AxOpenOrdersResponse, AxHttpError> {
723 self.get_open_orders_page(&GetOpenOrdersParams::new()).await
724 }
725
726 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 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(¶ms).await
761 }
762
763 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 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(¶ms),
797 None,
798 true,
799 )
800 .await
801 }
802
803 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(¶ms),
822 None,
823 true,
824 )
825 .await?;
826 Ok(response.candle)
827 }
828
829 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(¶ms),
848 None,
849 true,
850 )
851 .await?;
852 Ok(response.candle)
853 }
854
855 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(¶ms).await
871 }
872
873 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 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 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 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 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(¶ms).await
978 }
979
980 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 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(¶ms), None, true)
1014 .await
1015 }
1016
1017 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 self.send_request::<AxBookResponse, _>(Method::GET, "/book", Some(¶ms), None, true)
1033 .await
1034 }
1035
1036 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(¶ms),
1054 None,
1055 true,
1056 )
1057 .await
1058 }
1059
1060 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(¶ms),
1078 None,
1079 true,
1080 )
1081 .await
1082 }
1083
1084 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 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#[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 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 #[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 #[must_use]
1307 pub fn base_url(&self) -> &str {
1308 self.inner.base_url()
1309 }
1310
1311 #[must_use]
1313 pub fn api_key_masked(&self) -> String {
1314 self.inner.api_key_masked()
1315 }
1316
1317 pub fn cancel_all_requests(&self) {
1319 self.inner.cancel_all_requests();
1320 }
1321
1322 pub fn reset_cancellation_token(&self) {
1324 self.inner.reset_cancellation_token();
1325 }
1326
1327 pub fn set_session_token(&self, token: SecretString) {
1331 self.inner.set_session_token(token);
1332 }
1333
1334 fn generate_ts_init(&self) -> UnixNanos {
1336 self.clock.get_time_ns()
1337 }
1338
1339 #[must_use]
1343 pub fn is_initialized(&self) -> bool {
1344 self.cache_initialized.load(Ordering::Acquire)
1345 }
1346
1347 #[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 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 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 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 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 pub fn get_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
1428 self.instruments_cache.get_cloned(symbol)
1429 }
1430
1431 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 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 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 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 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 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 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 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(¶ms).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 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(¶ms).await
1884 }
1885
1886 pub async fn request_account_state(
1892 &self,
1893 account_id: AccountId,
1894 ) -> anyhow::Result<AccountState> {
1895 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 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 #[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 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(¶ms)
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 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(¶ms)
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 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 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(¶ms)
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 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 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}