Skip to main content

nautilus_binance/futures/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//! Binance Futures HTTP client for USD-M and COIN-M markets.
17
18use std::{
19    collections::HashMap,
20    num::NonZeroU32,
21    sync::{Arc, LazyLock, Weak},
22    time::Duration,
23};
24
25use ahash::{AHashMap, AHashSet};
26use anyhow::Context;
27use dashmap::DashMap;
28use indexmap::IndexMap;
29use jiff::{SignedDuration, Timestamp};
30use nautilus_common::cache::InstrumentLookupError;
31use nautilus_core::{
32    AtomicMap,
33    datetime::{NANOSECONDS_IN_MILLISECOND, SECONDS_IN_DAY},
34    nanos::UnixNanos,
35    time::AtomicTime,
36};
37use nautilus_model::{
38    data::{Bar, BarType, BookOrder, FundingRateUpdate, TradeTick},
39    enums::{
40        AggregationSource, AggressorSide, BarAggregation, BookType, MarketStatusAction, OrderSide,
41        OrderType, TimeInForce,
42    },
43    events::AccountState,
44    identifiers::{AccountId, ClientOrderId, InstrumentId, TradeId, VenueOrderId},
45    instruments::{Instrument, any::InstrumentAny},
46    orderbook::OrderBook,
47    reports::{FillReport, OrderStatusReport},
48    types::{Currency, Price, Quantity, fixed::FIXED_PRECISION},
49};
50use nautilus_network::{
51    http::{
52        HttpClient, HttpRedirectPolicy, HttpResponse, Method, create_standard_nautilus_headers,
53    },
54    ratelimiter::{RateLimiter, clock::MonotonicClock, quota::Quota},
55    retry::{RetryConfig, RetryError, RetryManager},
56};
57use parking_lot::Mutex;
58use rust_decimal::Decimal;
59use serde::{Deserialize, Serialize, de::DeserializeOwned};
60use ustr::Ustr;
61
62use super::{
63    error::{BinanceFuturesHttpError, BinanceFuturesHttpResult},
64    models::{
65        BatchOrderError, BatchOrderResult, BinanceBookTicker, BinanceCancelAllOrdersResponse,
66        BinanceFundingRate, BinanceFuturesAccountInfo, BinanceFuturesAggTrade,
67        BinanceFuturesAlgoOrder, BinanceFuturesAlgoOrderCancelResponse,
68        BinanceFuturesCoinExchangeInfo, BinanceFuturesCoinSymbol, BinanceFuturesCommissionRate,
69        BinanceFuturesKline, BinanceFuturesMarkPrice, BinanceFuturesOrder,
70        BinanceFuturesTicker24hr, BinanceFuturesTrade, BinanceFuturesUsdExchangeInfo,
71        BinanceFuturesUsdSymbol, BinanceHedgeModeResponse, BinanceLeverageResponse,
72        BinanceOpenInterest, BinanceOpenInterestHistRecord, BinanceOrderBook, BinancePositionRisk,
73        BinancePriceTicker, BinanceServerTime, BinanceUserTrade, ListenKeyResponse,
74    },
75    query::{
76        BatchCancelItem, BatchModifyItem, BatchOrderItem, BinanceAggTradesParams,
77        BinanceAlgoOrderQueryParams, BinanceAllAlgoOrdersParams, BinanceAllOrdersParams,
78        BinanceBookTickerParams, BinanceCancelAllAlgoOrdersParams, BinanceCancelAllOrdersParams,
79        BinanceCancelOrderParams, BinanceCommissionRateParams, BinanceDepthParams,
80        BinanceFundingRateParams, BinanceKlinesParams, BinanceMarkPriceParams,
81        BinanceModifyOrderParams, BinanceNewAlgoOrderParams, BinanceNewOrderParams,
82        BinanceOpenAlgoOrdersParams, BinanceOpenInterestHistParams, BinanceOpenInterestParams,
83        BinanceOpenOrdersParams, BinanceOrderQueryParams, BinancePositionRiskParams,
84        BinanceSetLeverageParams, BinanceSetMarginTypeParams, BinanceTicker24hrParams,
85        BinanceTradesParams, BinanceUserTradesParams, ListenKeyParams,
86    },
87};
88use crate::{
89    book::pacing::{SnapshotAdmission, SnapshotPermit},
90    common::{
91        bar::BinanceBar,
92        consts::{
93            BINANCE_API_KEY_HEADER, BINANCE_DAPI_PATH, BINANCE_DAPI_RATE_LIMITS, BINANCE_FAPI_PATH,
94            BINANCE_FAPI_RATE_LIMITS, BINANCE_INVALID_LISTEN_KEY_CODE,
95            BINANCE_NAUTILUS_FUTURES_BROKER_ID, BINANCE_NO_SUCH_ORDER_CODE,
96            BINANCE_RETRY_AFTER_HEADER, BinanceRateLimitQuota,
97        },
98        credential::SigningCredential,
99        encoder::{encode_broker_id, legacy_client_order_id},
100        enums::{
101            BinanceAlgoType, BinanceEnvironment, BinanceFuturesOrderType, BinancePositionSide,
102            BinancePriceMatch, BinanceProductType, BinanceRateLimitInterval, BinanceRateLimitType,
103            BinanceSide, BinanceTimeInForce, BinanceWorkingType,
104        },
105        http::{
106            BinanceHttpBackoff, BinanceHttpEndpointScope as BinanceFuturesEndpointScope, sha256,
107        },
108        http_weights::request_weight_futures,
109        instruments::BinanceInstrumentSelector,
110        models::BinanceErrorResponse,
111        parse::{
112            parse_coinm_instrument_with_fees, parse_millis, parse_required_price_at_precision,
113            parse_required_quantity_at_precision, parse_usdm_instrument_with_fees,
114            should_warn_on_instrument_parse_error,
115        },
116        symbol::{format_binance_symbol, format_instrument_id},
117        urls::get_http_base_url,
118    },
119    config::BinanceInstrumentProviderConfig,
120    futures::conversions::reduce_only_param,
121};
122
123const ORDER_HISTORY_PAGE_LIMIT: u32 = 1_000;
124
125const BINANCE_GLOBAL_RATE_KEY: &str = "binance:global";
126const BINANCE_ORDERS_RATE_KEY: &str = "binance:orders";
127const BINANCE_FUNDING_RATE_KEY: &str = "binance:funding";
128const BINANCE_OPEN_INTEREST_RATE_KEY: &str = "binance:open-interest";
129
130type BinanceFuturesLimiter = RateLimiter<Ustr, MonotonicClock>;
131type BinanceFuturesRateLimiter = Arc<BinanceFuturesLimiter>;
132type BinanceFuturesRateLimiterRegistry<S> = Mutex<AHashMap<S, Weak<BinanceFuturesLimiter>>>;
133
134#[derive(Clone, PartialEq, Eq, Hash)]
135struct BinanceFuturesRequestScope {
136    endpoint: BinanceFuturesEndpointScope,
137    proxy_url_digest: Option<[u8; 32]>,
138}
139
140#[derive(Clone, Copy, PartialEq, Eq, Hash)]
141struct BinanceFuturesAccountScope([u8; 32]);
142
143#[derive(Clone, PartialEq, Eq, Hash)]
144struct BinanceFuturesOrderScope {
145    endpoint: BinanceFuturesEndpointScope,
146    account: BinanceFuturesAccountScope,
147}
148
149static BINANCE_FUTURES_REQUEST_LIMITERS: LazyLock<
150    BinanceFuturesRateLimiterRegistry<BinanceFuturesRequestScope>,
151> = LazyLock::new(|| Mutex::new(AHashMap::new()));
152
153static BINANCE_FUTURES_ORDER_LIMITERS: LazyLock<
154    BinanceFuturesRateLimiterRegistry<BinanceFuturesOrderScope>,
155> = LazyLock::new(|| Mutex::new(AHashMap::new()));
156
157/// A Binance Futures Algo Service order with optional matching-engine details.
158#[derive(Debug)]
159pub struct BinanceFuturesAlgoOrderQueryResult {
160    /// The original conditional order from the Algo Service.
161    pub algo: BinanceFuturesAlgoOrder,
162    /// The matching-engine order created after the condition triggered, when enrichment succeeds.
163    pub actual: Option<BinanceFuturesOrder>,
164}
165
166#[derive(Debug, Serialize)]
167#[serde(rename_all = "camelCase")]
168struct BatchCancelParams {
169    symbol: String,
170    #[serde(skip_serializing_if = "Option::is_none")]
171    order_id_list: Option<String>,
172    #[serde(skip_serializing_if = "Option::is_none")]
173    orig_client_order_id_list: Option<String>,
174}
175
176/// Raw HTTP client for Binance Futures REST API.
177#[derive(Debug, Clone)]
178pub struct BinanceRawFuturesHttpClient {
179    retry_manager: Arc<RetryManager<BinanceFuturesHttpError>>,
180    client: HttpClient,
181    base_url: String,
182    api_path: &'static str,
183    credential: Option<SigningCredential>,
184    recv_window: Option<u64>,
185    order_rate_keys: Vec<String>,
186    backoff: BinanceHttpBackoff,
187    command_order_quota: Option<bool>,
188}
189
190impl BinanceRawFuturesHttpClient {
191    /// Returns a reference to the underlying HTTP client.
192    #[must_use]
193    pub fn http_client(&self) -> &HttpClient {
194        &self.client
195    }
196
197    /// Returns whether this client has complete signing credentials.
198    #[must_use]
199    pub const fn has_credentials(&self) -> bool {
200        self.credential.is_some()
201    }
202
203    /// Creates a new Binance raw futures HTTP client.
204    ///
205    /// # Errors
206    ///
207    /// Returns an error if credentials are incomplete or the HTTP client fails to build.
208    #[expect(clippy::too_many_arguments)]
209    pub fn new(
210        product_type: BinanceProductType,
211        environment: BinanceEnvironment,
212        api_key: Option<String>,
213        api_secret: Option<String>,
214        base_url_override: Option<String>,
215        recv_window: Option<u64>,
216        timeout_secs: Option<u64>,
217        proxy_url: Option<String>,
218    ) -> BinanceFuturesHttpResult<Self> {
219        let RateLimitConfig {
220            request_quota,
221            order_quotas,
222            order_keys,
223        } = Self::rate_limit_config(product_type);
224
225        let credential = match (api_key, api_secret) {
226            (Some(key), Some(secret)) => Some(SigningCredential::new(key, secret)),
227            (None, None) => None,
228            _ => return Err(BinanceFuturesHttpError::MissingCredentials),
229        };
230
231        let backoff = BinanceHttpBackoff::new(
232            product_type,
233            environment,
234            base_url_override.as_deref(),
235            proxy_url.as_deref(),
236            credential.as_ref(),
237        );
238
239        let account_scope = credential.as_ref().map(Self::account_scope);
240        let rate_limiters = Self::shared_rate_limiters(
241            environment,
242            base_url_override.as_deref(),
243            proxy_url.as_deref(),
244            account_scope,
245            request_quota,
246            order_quotas,
247        );
248        let base_url = base_url_override
249            .unwrap_or_else(|| get_http_base_url(product_type, environment).to_string());
250        let api_path = Self::resolve_api_path(product_type);
251        let headers = Self::default_headers(&credential);
252
253        let client = HttpClient::builder()
254            .redirect_policy(HttpRedirectPolicy::Reject)
255            .headers(headers)
256            .header_keys(vec![
257                BINANCE_API_KEY_HEADER.to_string(),
258                BINANCE_RETRY_AFTER_HEADER.to_string(),
259            ])
260            .maybe_timeout_secs(timeout_secs)
261            .maybe_proxy_url(proxy_url)
262            .rate_limiters(rate_limiters)
263            .build()?;
264
265        Ok(Self {
266            retry_manager: Arc::new(RetryManager::new(crate::common::http::retry_config())),
267            client,
268            base_url,
269            api_path,
270            credential,
271            recv_window,
272            order_rate_keys: order_keys,
273            backoff,
274            command_order_quota: None,
275        })
276    }
277
278    fn shared_rate_limiters(
279        environment: BinanceEnvironment,
280        base_url_override: Option<&str>,
281        proxy_url: Option<&str>,
282        account_scope: Option<BinanceFuturesAccountScope>,
283        request_quota: Quota,
284        order_quotas: Vec<(String, Quota)>,
285    ) -> Vec<BinanceFuturesRateLimiter> {
286        let endpoint = BinanceFuturesEndpointScope::new(
287            BinanceProductType::UsdM,
288            environment,
289            base_url_override,
290        );
291
292        let request_scope = BinanceFuturesRequestScope {
293            endpoint: endpoint.clone(),
294            proxy_url_digest: proxy_url.map(sha256),
295        };
296        let request_limiter = Self::request_rate_limiter(request_scope, request_quota);
297        let mut limiters = vec![request_limiter];
298
299        if let Some(account) = account_scope {
300            let order_scope = BinanceFuturesOrderScope { endpoint, account };
301            limiters.push(Self::order_rate_limiter(order_scope, order_quotas));
302        }
303
304        limiters
305    }
306
307    fn account_scope(credential: &SigningCredential) -> BinanceFuturesAccountScope {
308        BinanceFuturesAccountScope(sha256(credential.api_key()))
309    }
310
311    fn request_rate_limiter(
312        scope: BinanceFuturesRequestScope,
313        quota: Quota,
314    ) -> BinanceFuturesRateLimiter {
315        let mut registry = BINANCE_FUTURES_REQUEST_LIMITERS.lock();
316
317        if let Some(limiter) = registry.get(&scope).and_then(Weak::upgrade) {
318            return limiter;
319        }
320
321        let limiter = Arc::new(RateLimiter::new_with_quota(
322            None,
323            vec![
324                (Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota),
325                (
326                    Ustr::from(BINANCE_FUNDING_RATE_KEY),
327                    Quota::with_period(Duration::from_millis(600))
328                        .expect("non-zero interval")
329                        .allow_burst(NonZeroU32::new(500).expect("non-zero burst")),
330                ),
331                (
332                    Ustr::from(BINANCE_OPEN_INTEREST_RATE_KEY),
333                    Quota::with_period(Duration::from_millis(300))
334                        .expect("non-zero interval")
335                        .allow_burst(NonZeroU32::new(1000).expect("non-zero burst")),
336                ),
337            ],
338        ));
339        registry.insert(scope, Arc::downgrade(&limiter));
340        limiter
341    }
342
343    fn order_rate_limiter(
344        scope: BinanceFuturesOrderScope,
345        quotas: Vec<(String, Quota)>,
346    ) -> BinanceFuturesRateLimiter {
347        let mut registry = BINANCE_FUTURES_ORDER_LIMITERS.lock();
348
349        if let Some(limiter) = registry.get(&scope).and_then(Weak::upgrade) {
350            return limiter;
351        }
352
353        let quotas = quotas
354            .into_iter()
355            .map(|(key, quota)| (Ustr::from(&key), quota))
356            .collect();
357        let limiter = Arc::new(RateLimiter::new_with_quota(None, quotas));
358        registry.insert(scope, Arc::downgrade(&limiter));
359        limiter
360    }
361
362    /// Performs a GET request and deserializes the response body.
363    ///
364    /// # Errors
365    ///
366    /// Returns an error if the request fails or response deserialization fails.
367    pub async fn get<P, T>(
368        &self,
369        path: &str,
370        params: Option<&P>,
371        signed: bool,
372        use_order_quota: bool,
373    ) -> BinanceFuturesHttpResult<T>
374    where
375        P: Serialize + ?Sized,
376        T: DeserializeOwned,
377    {
378        self.request(
379            Method::GET,
380            path,
381            params,
382            signed,
383            use_order_quota,
384            None,
385            None,
386        )
387        .await
388    }
389
390    /// Performs a POST request with optional body and signed query.
391    ///
392    /// # Errors
393    ///
394    /// Returns an error if the request fails or response deserialization fails.
395    pub async fn post<P, T>(
396        &self,
397        path: &str,
398        params: Option<&P>,
399        body: Option<Vec<u8>>,
400        signed: bool,
401        use_order_quota: bool,
402    ) -> BinanceFuturesHttpResult<T>
403    where
404        P: Serialize + ?Sized,
405        T: DeserializeOwned,
406    {
407        self.request(
408            Method::POST,
409            path,
410            params,
411            signed,
412            use_order_quota,
413            body,
414            None,
415        )
416        .await
417    }
418
419    /// Performs a PUT request with signed query.
420    ///
421    /// # Errors
422    ///
423    /// Returns an error if the request fails or response deserialization fails.
424    pub async fn request_put<P, T>(
425        &self,
426        path: &str,
427        params: Option<&P>,
428        signed: bool,
429        use_order_quota: bool,
430    ) -> BinanceFuturesHttpResult<T>
431    where
432        P: Serialize + ?Sized,
433        T: DeserializeOwned,
434    {
435        self.request(
436            Method::PUT,
437            path,
438            params,
439            signed,
440            use_order_quota,
441            None,
442            None,
443        )
444        .await
445    }
446
447    /// Performs a DELETE request with signed query.
448    ///
449    /// # Errors
450    ///
451    /// Returns an error if the request fails or response deserialization fails.
452    pub async fn request_delete<P, T>(
453        &self,
454        path: &str,
455        params: Option<&P>,
456        signed: bool,
457        use_order_quota: bool,
458    ) -> BinanceFuturesHttpResult<T>
459    where
460        P: Serialize + ?Sized,
461        T: DeserializeOwned,
462    {
463        self.request(
464            Method::DELETE,
465            path,
466            params,
467            signed,
468            use_order_quota,
469            None,
470            None,
471        )
472        .await
473    }
474
475    /// Performs a batch POST request with batchOrders parameter.
476    ///
477    /// # Errors
478    ///
479    /// Returns an error if credentials are missing, the request fails, or JSON parsing fails.
480    pub async fn batch_request<T: Serialize>(
481        &self,
482        path: &str,
483        items: &[T],
484        use_order_quota: bool,
485    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
486        self.batch_request_method(Method::POST, path, items, use_order_quota)
487            .await
488    }
489
490    /// Performs a batch DELETE request with batchOrders parameter.
491    ///
492    /// # Errors
493    ///
494    /// Returns an error if credentials are missing, the request fails, or JSON parsing fails.
495    pub async fn batch_request_delete<T: Serialize>(
496        &self,
497        path: &str,
498        items: &[T],
499        use_order_quota: bool,
500    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
501        self.batch_request_method(Method::DELETE, path, items, use_order_quota)
502            .await
503    }
504
505    /// Performs a batch PUT request with batchOrders parameter.
506    ///
507    /// # Errors
508    ///
509    /// Returns an error if credentials are missing, the request fails, or JSON parsing fails.
510    pub async fn batch_request_put<T: Serialize>(
511        &self,
512        path: &str,
513        items: &[T],
514        use_order_quota: bool,
515    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
516        self.batch_request_method(Method::PUT, path, items, use_order_quota)
517            .await
518    }
519
520    async fn batch_request_method<T: Serialize>(
521        &self,
522        method: Method,
523        path: &str,
524        items: &[T],
525        use_order_quota: bool,
526    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
527        let cred = self
528            .credential
529            .as_ref()
530            .ok_or(BinanceFuturesHttpError::MissingCredentials)?;
531
532        let batch_json = serde_json::to_string(items)
533            .map_err(|e| BinanceFuturesHttpError::ValidationError(e.to_string()))?;
534
535        let encoded_batch = Self::percent_encode(&batch_json);
536        let keys = self.rate_limit_keys(&method, path, "", use_order_quota);
537        self.backoff
538            .admit(
539                &self.client,
540                keys,
541                use_order_quota || self.command_order_quota.unwrap_or(false),
542                method == Method::GET && self.command_order_quota.is_none(),
543            )
544            .await
545            .map_err(|()| BinanceFuturesHttpError::RateLimitBlocked)?;
546
547        let timestamp = Timestamp::now().as_millisecond();
548        let mut query = format!("batchOrders={encoded_batch}&timestamp={timestamp}");
549
550        if let Some(recv_window) = self.recv_window {
551            query.push_str(&format!("&recvWindow={recv_window}"));
552        }
553
554        let signature = Self::percent_encode(&cred.sign(&query));
555        query.push_str(&format!("&signature={signature}"));
556
557        let url = self.build_url(path, &query);
558
559        let mut headers = HashMap::new();
560        headers.insert(
561            BINANCE_API_KEY_HEADER.to_string(),
562            cred.api_key().to_string(),
563        );
564
565        let response = self
566            .client
567            .request(
568                method,
569                url,
570                None::<&HashMap<String, Vec<String>>>,
571                Some(headers),
572                None,
573                None,
574                None,
575            )
576            .await?;
577
578        if !response.status.is_success() {
579            return self.parse_error_response(&response);
580        }
581
582        serde_json::from_slice(&response.body)
583            .map_err(|e| BinanceFuturesHttpError::JsonError(e.to_string()))
584    }
585
586    /// Percent-encodes a string for use in URL query parameters.
587    fn percent_encode(input: &str) -> String {
588        let mut result = String::with_capacity(input.len() * 3);
589        for byte in input.bytes() {
590            match byte {
591                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
592                    result.push(byte as char);
593                }
594                _ => {
595                    result.push('%');
596                    result.push_str(&format!("{byte:02X}"));
597                }
598            }
599        }
600        result
601    }
602
603    #[expect(
604        clippy::too_many_arguments,
605        reason = "REST admission carries the snapshot reservation through read retries"
606    )]
607    async fn request<P, T>(
608        &self,
609        method: Method,
610        path: &str,
611        params: Option<&P>,
612        signed: bool,
613        use_order_quota: bool,
614        body: Option<Vec<u8>>,
615        snapshot: Option<&SnapshotAdmission>,
616    ) -> BinanceFuturesHttpResult<T>
617    where
618        P: Serialize + ?Sized,
619        T: DeserializeOwned,
620    {
621        let operation = || {
622            self.request_once(
623                method.clone(),
624                path,
625                params,
626                signed,
627                use_order_quota,
628                body.clone(),
629                snapshot,
630            )
631        };
632
633        if method != Method::GET {
634            return operation().await;
635        }
636
637        self.retry_manager
638            .invocation(
639                path,
640                operation,
641                |e| self.command_order_quota.is_none() && e.is_retryable(),
642                |e| match e {
643                    RetryError::Canceled => {
644                        BinanceFuturesHttpError::Canceled("HTTP requests canceled".to_string())
645                    }
646                    RetryError::OperationTimeout { timeout_ms } => {
647                        BinanceFuturesHttpError::Timeout(format!("Request exceeded {timeout_ms}ms"))
648                    }
649                    RetryError::InvalidConfiguration { message } => {
650                        BinanceFuturesHttpError::ValidationError(message)
651                    }
652                    e @ RetryError::ElapsedBudgetExceeded { .. } => {
653                        BinanceFuturesHttpError::RetryBudgetExceeded(e.to_string())
654                    }
655                },
656            )
657            .retry_delay(&BinanceFuturesHttpError::retry_after)
658            .execute()
659            .await
660    }
661
662    #[expect(
663        clippy::too_many_arguments,
664        reason = "REST admission carries the snapshot reservation through read retries"
665    )]
666    async fn request_once<P, T>(
667        &self,
668        method: Method,
669        path: &str,
670        params: Option<&P>,
671        signed: bool,
672        use_order_quota: bool,
673        body: Option<Vec<u8>>,
674        snapshot: Option<&SnapshotAdmission>,
675    ) -> BinanceFuturesHttpResult<T>
676    where
677        P: Serialize + ?Sized,
678        T: DeserializeOwned,
679    {
680        let mut query = params
681            .map(serde_urlencoded::to_string)
682            .transpose()
683            .map_err(|e| BinanceFuturesHttpError::ValidationError(e.to_string()))?
684            .unwrap_or_default();
685
686        let mut headers = HashMap::new();
687
688        let credential = if signed {
689            Some(
690                self.credential
691                    .as_ref()
692                    .ok_or(BinanceFuturesHttpError::MissingCredentials)?,
693            )
694        } else {
695            None
696        };
697
698        let permit = match snapshot {
699            Some(snapshot) => Some(snapshot.acquire().await),
700            None => None,
701        };
702
703        let keys = self.rate_limit_keys(&method, path, &query, use_order_quota);
704        self.backoff
705            .admit(
706                &self.client,
707                keys,
708                use_order_quota || self.command_order_quota.unwrap_or(false),
709                method == Method::GET && self.command_order_quota.is_none(),
710            )
711            .await
712            .map_err(|()| BinanceFuturesHttpError::RateLimitBlocked)?;
713
714        if let Some(permit) = permit {
715            permit.commit();
716        }
717
718        if let Some(cred) = credential {
719            if !query.is_empty() {
720                query.push('&');
721            }
722
723            let timestamp = Timestamp::now().as_millisecond();
724            query.push_str(&format!("timestamp={timestamp}"));
725
726            if let Some(recv_window) = self.recv_window {
727                query.push_str(&format!("&recvWindow={recv_window}"));
728            }
729
730            // Percent-encode the signature: Ed25519 signatures are base64 and
731            // contain `+`, `/`, `=` which are not URL-safe. HMAC hex is
732            // already safe but percent-encoding it is a no-op.
733            let signature = Self::percent_encode(&cred.sign(&query));
734            query.push_str(&format!("&signature={signature}"));
735            headers.insert(
736                BINANCE_API_KEY_HEADER.to_string(),
737                cred.api_key().to_string(),
738            );
739        }
740
741        let url = self.build_url(path, &query);
742
743        let response = self
744            .client
745            .request(
746                method,
747                url,
748                None::<&HashMap<String, Vec<String>>>,
749                Some(headers),
750                body,
751                None,
752                None,
753            )
754            .await?;
755
756        if !response.status.is_success() {
757            return self.parse_error_response(&response);
758        }
759
760        serde_json::from_slice::<T>(&response.body)
761            .map_err(|e| BinanceFuturesHttpError::JsonError(e.to_string()))
762    }
763
764    fn build_url(&self, path: &str, query: &str) -> String {
765        // Full API paths (e.g., /fapi/v2/account) bypass the default api_path
766        let url_path = if path.starts_with("/fapi/")
767            || path.starts_with("/dapi/")
768            || path.starts_with("/futures/data/")
769        {
770            path.to_string()
771        } else if path.starts_with('/') {
772            format!("{}{}", self.api_path, path)
773        } else {
774            format!("{}/{}", self.api_path, path)
775        };
776
777        let mut url = format!("{}{}", self.base_url, url_path);
778
779        if !query.is_empty() {
780            url.push('?');
781            url.push_str(query);
782        }
783        url
784    }
785
786    fn rate_limit_keys(
787        &self,
788        method: &Method,
789        path: &str,
790        query: &str,
791        use_orders: bool,
792    ) -> Vec<Ustr> {
793        let weight =
794            request_weight_futures(method, path, query, self.api_path == BINANCE_DAPI_PATH);
795        let mut keys = vec![Ustr::from(BINANCE_GLOBAL_RATE_KEY); weight as usize];
796        if use_orders {
797            keys.extend(self.order_rate_keys.iter().map(|key| Ustr::from(key)));
798        }
799
800        if self.api_path == BINANCE_FAPI_PATH {
801            let path = path.trim_start_matches('/');
802            match path.strip_prefix("fapi/v1/").unwrap_or(path) {
803                "fundingRate" | "fundingInfo" => keys.push(Ustr::from(BINANCE_FUNDING_RATE_KEY)),
804                "futures/data/openInterestHist" => {
805                    keys.push(Ustr::from(BINANCE_OPEN_INTEREST_RATE_KEY));
806                }
807                _ => {}
808            }
809        }
810
811        keys
812    }
813
814    fn parse_error_response<T>(&self, response: &HttpResponse) -> BinanceFuturesHttpResult<T> {
815        let status = response.status.as_u16();
816        let body = String::from_utf8_lossy(&response.body).to_string();
817        let retry_after = crate::common::http::retry_after(&response.headers, Timestamp::now());
818        if let Ok(err) = serde_json::from_str::<BinanceErrorResponse>(&body) {
819            self.backoff.observe(status, Some(err.code), retry_after);
820            return Err(BinanceFuturesHttpError::BinanceError {
821                code: err.code,
822                message: err.msg,
823                status,
824                retry_after,
825            });
826        }
827
828        self.backoff.observe(status, None, retry_after);
829        Err(BinanceFuturesHttpError::UnexpectedStatus {
830            status,
831            body,
832            retry_after,
833        })
834    }
835
836    fn default_headers(credential: &Option<SigningCredential>) -> HashMap<String, String> {
837        let mut headers: HashMap<String, String> =
838            create_standard_nautilus_headers().into_iter().collect();
839
840        if let Some(cred) = credential {
841            headers.insert(
842                BINANCE_API_KEY_HEADER.to_string(),
843                cred.api_key().to_string(),
844            );
845        }
846        headers
847    }
848
849    fn resolve_api_path(product_type: BinanceProductType) -> &'static str {
850        match product_type {
851            BinanceProductType::UsdM => BINANCE_FAPI_PATH,
852            BinanceProductType::CoinM => BINANCE_DAPI_PATH,
853            _ => BINANCE_FAPI_PATH, // Default to USD-M
854        }
855    }
856
857    fn rate_limit_config(product_type: BinanceProductType) -> RateLimitConfig {
858        let quotas = match product_type {
859            BinanceProductType::UsdM => BINANCE_FAPI_RATE_LIMITS,
860            BinanceProductType::CoinM => BINANCE_DAPI_RATE_LIMITS,
861            _ => BINANCE_FAPI_RATE_LIMITS,
862        };
863
864        let mut order_quotas = Vec::new();
865        let mut order_keys = Vec::new();
866        let mut request_quota = None;
867
868        for quota in quotas {
869            if let Some(q) = Self::quota_from(quota) {
870                match quota.rate_limit_type {
871                    BinanceRateLimitType::RequestWeight if request_quota.is_none() => {
872                        request_quota = Some(q);
873                    }
874                    BinanceRateLimitType::Orders => {
875                        let key = format!(
876                            "{}:{}:{:?}",
877                            BINANCE_ORDERS_RATE_KEY, quota.interval_num, quota.interval
878                        );
879                        order_keys.push(key.clone());
880                        order_quotas.push((key, q));
881                    }
882                    _ => {}
883                }
884            }
885        }
886
887        let request_quota = request_quota.unwrap_or_else(|| {
888            Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant")
889        });
890
891        RateLimitConfig {
892            request_quota,
893            order_quotas,
894            order_keys,
895        }
896    }
897
898    fn quota_from(quota: &BinanceRateLimitQuota) -> Option<Quota> {
899        let burst = NonZeroU32::new(quota.limit)?;
900        let period = Self::quota_period(quota)?;
901        let replenish_interval_ns = period.as_nanos() / u128::from(quota.limit);
902        let replenish_interval_ns = u64::try_from(replenish_interval_ns).ok()?;
903
904        Quota::with_period(Duration::from_nanos(replenish_interval_ns))
905            .map(|q| q.allow_burst(burst))
906    }
907
908    fn quota_period(quota: &BinanceRateLimitQuota) -> Option<Duration> {
909        match quota.interval {
910            BinanceRateLimitInterval::Second => {
911                Some(Duration::from_secs(u64::from(quota.interval_num)))
912            }
913            BinanceRateLimitInterval::Minute => {
914                Some(Duration::from_secs(60 * u64::from(quota.interval_num)))
915            }
916            BinanceRateLimitInterval::Day => Some(Duration::from_secs(
917                SECONDS_IN_DAY * u64::from(quota.interval_num),
918            )),
919            BinanceRateLimitInterval::Unknown => None,
920        }
921    }
922
923    /// Fetches 24hr ticker statistics.
924    ///
925    /// # Errors
926    ///
927    /// Returns an error if the request fails.
928    pub async fn ticker_24h(
929        &self,
930        params: &BinanceTicker24hrParams,
931    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesTicker24hr>> {
932        self.get("ticker/24hr", Some(params), false, false).await
933    }
934
935    /// Fetches best bid/ask prices.
936    ///
937    /// # Errors
938    ///
939    /// Returns an error if the request fails.
940    pub async fn book_ticker(
941        &self,
942        params: &BinanceBookTickerParams,
943    ) -> BinanceFuturesHttpResult<Vec<BinanceBookTicker>> {
944        self.get("ticker/bookTicker", Some(params), false, false)
945            .await
946    }
947
948    /// Fetches price ticker.
949    ///
950    /// # Errors
951    ///
952    /// Returns an error if the request fails.
953    pub async fn price_ticker(
954        &self,
955        symbol: Option<&str>,
956    ) -> BinanceFuturesHttpResult<Vec<BinancePriceTicker>> {
957        #[derive(Serialize)]
958        struct Params<'a> {
959            #[serde(skip_serializing_if = "Option::is_none")]
960            symbol: Option<&'a str>,
961        }
962        self.get("ticker/price", Some(&Params { symbol }), false, false)
963            .await
964    }
965
966    /// Fetches order book depth.
967    ///
968    /// # Errors
969    ///
970    /// Returns an error if the request fails.
971    pub async fn depth(
972        &self,
973        params: &BinanceDepthParams,
974    ) -> BinanceFuturesHttpResult<BinanceOrderBook> {
975        self.get("depth", Some(params), false, false).await
976    }
977
978    pub(crate) async fn depth_paced(
979        &self,
980        params: &BinanceDepthParams,
981        permit: SnapshotPermit,
982    ) -> BinanceFuturesHttpResult<BinanceOrderBook> {
983        self.request(
984            Method::GET,
985            "depth",
986            Some(params),
987            false,
988            false,
989            None,
990            Some(&SnapshotAdmission::new(permit)),
991        )
992        .await
993    }
994
995    /// Fetches mark price and funding rate.
996    ///
997    /// # Errors
998    ///
999    /// Returns an error if the request fails.
1000    pub async fn mark_price(
1001        &self,
1002        params: &BinanceMarkPriceParams,
1003    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesMarkPrice>> {
1004        let response: MarkPriceResponse =
1005            self.get("premiumIndex", Some(params), false, false).await?;
1006        Ok(response.into())
1007    }
1008
1009    /// Fetches funding rate history.
1010    ///
1011    /// # Errors
1012    ///
1013    /// Returns an error if the request fails.
1014    pub async fn funding_rate(
1015        &self,
1016        params: &BinanceFundingRateParams,
1017    ) -> BinanceFuturesHttpResult<Vec<BinanceFundingRate>> {
1018        self.get("fundingRate", Some(params), false, false).await
1019    }
1020
1021    /// Fetches current open interest for a symbol.
1022    ///
1023    /// # Errors
1024    ///
1025    /// Returns an error if the request fails.
1026    pub async fn open_interest(
1027        &self,
1028        params: &BinanceOpenInterestParams,
1029    ) -> BinanceFuturesHttpResult<BinanceOpenInterest> {
1030        self.get("openInterest", Some(params), false, false).await
1031    }
1032
1033    /// Fetches historical open interest statistics for a symbol or pair.
1034    ///
1035    /// # Errors
1036    ///
1037    /// Returns an error if the request fails.
1038    pub async fn open_interest_hist(
1039        &self,
1040        params: &BinanceOpenInterestHistParams,
1041    ) -> BinanceFuturesHttpResult<Vec<BinanceOpenInterestHistRecord>> {
1042        self.get("/futures/data/openInterestHist", Some(params), false, false)
1043            .await
1044    }
1045
1046    /// Fetches recent public trades for a symbol.
1047    ///
1048    /// # Errors
1049    ///
1050    /// Returns an error if the request fails.
1051    pub async fn trades(
1052        &self,
1053        params: &BinanceTradesParams,
1054    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesTrade>> {
1055        self.get("trades", Some(params), false, false).await
1056    }
1057
1058    /// Fetches aggregate public trades for a symbol.
1059    ///
1060    /// # Errors
1061    ///
1062    /// Returns an error if documented Binance Futures bounds are violated or the request fails.
1063    pub async fn agg_trades(
1064        &self,
1065        params: &BinanceAggTradesParams,
1066    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesAggTrade>> {
1067        if params.limit.is_some_and(|limit| limit > 1000) {
1068            return Err(BinanceFuturesHttpError::ValidationError(
1069                "aggregate trade limit must not exceed 1000".to_string(),
1070            ));
1071        }
1072
1073        if let (Some(start), Some(end)) = (params.start_time, params.end_time) {
1074            if start > end {
1075                return Err(BinanceFuturesHttpError::ValidationError(
1076                    "aggregate trade startTime must not exceed endTime".to_string(),
1077                ));
1078            }
1079            let Some(range) = end.checked_sub(start) else {
1080                return Err(BinanceFuturesHttpError::ValidationError(
1081                    "aggregate trade time range must be less than one hour".to_string(),
1082                ));
1083            };
1084
1085            if range >= 3_600_000 {
1086                return Err(BinanceFuturesHttpError::ValidationError(
1087                    "aggregate trade time range must be less than one hour".to_string(),
1088                ));
1089            }
1090        }
1091
1092        self.get("aggTrades", Some(params), false, false).await
1093    }
1094
1095    /// Fetches kline/candlestick data for a symbol.
1096    ///
1097    /// # Errors
1098    ///
1099    /// Returns an error if the request fails.
1100    pub async fn klines(
1101        &self,
1102        params: &BinanceKlinesParams,
1103    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesKline>> {
1104        self.get("klines", Some(params), false, false).await
1105    }
1106
1107    /// Sets leverage for a symbol.
1108    ///
1109    /// # Errors
1110    ///
1111    /// Returns an error if the request fails.
1112    pub async fn set_leverage(
1113        &self,
1114        params: &BinanceSetLeverageParams,
1115    ) -> BinanceFuturesHttpResult<BinanceLeverageResponse> {
1116        self.post("leverage", Some(params), None, true, false).await
1117    }
1118
1119    /// Sets margin type for a symbol.
1120    ///
1121    /// # Errors
1122    ///
1123    /// Returns an error if the request fails.
1124    pub async fn set_margin_type(
1125        &self,
1126        params: &BinanceSetMarginTypeParams,
1127    ) -> BinanceFuturesHttpResult<serde_json::Value> {
1128        self.post("marginType", Some(params), None, true, false)
1129            .await
1130    }
1131
1132    /// Queries hedge mode (dual side position) setting.
1133    ///
1134    /// # Errors
1135    ///
1136    /// Returns an error if the request fails.
1137    pub async fn query_hedge_mode(&self) -> BinanceFuturesHttpResult<BinanceHedgeModeResponse> {
1138        self.get::<(), _>("positionSide/dual", None, true, false)
1139            .await
1140    }
1141
1142    /// Creates a listen key for user data stream.
1143    ///
1144    /// # Errors
1145    ///
1146    /// Returns an error if the request fails.
1147    pub async fn create_listen_key(&self) -> BinanceFuturesHttpResult<ListenKeyResponse> {
1148        self.post::<(), ListenKeyResponse>("listenKey", None, None, true, false)
1149            .await
1150    }
1151
1152    /// Keeps alive an existing listen key.
1153    ///
1154    /// # Errors
1155    ///
1156    /// Returns an error if the request fails.
1157    pub async fn keepalive_listen_key(&self, listen_key: &str) -> BinanceFuturesHttpResult<()> {
1158        let params = ListenKeyParams {
1159            listen_key: listen_key.into(),
1160        };
1161        let _: serde_json::Value = self
1162            .request_put("listenKey", Some(&params), true, false)
1163            .await?;
1164        Ok(())
1165    }
1166
1167    /// Closes an existing listen key.
1168    ///
1169    /// Succeeds if the venue reports that the key no longer exists.
1170    ///
1171    /// # Errors
1172    ///
1173    /// Returns an error if the request fails.
1174    pub async fn close_listen_key(&self, listen_key: &str) -> BinanceFuturesHttpResult<()> {
1175        let params = ListenKeyParams {
1176            listen_key: listen_key.into(),
1177        };
1178
1179        match self
1180            .request_delete::<_, serde_json::Value>("listenKey", Some(&params), true, false)
1181            .await
1182        {
1183            Ok(_)
1184            | Err(BinanceFuturesHttpError::BinanceError {
1185                code: BINANCE_INVALID_LISTEN_KEY_CODE,
1186                ..
1187            }) => Ok(()),
1188            Err(e) => Err(e),
1189        }
1190    }
1191
1192    /// Fetches account information including balances and positions.
1193    ///
1194    /// # Errors
1195    ///
1196    /// Returns an error if the request fails.
1197    pub async fn query_account(&self) -> BinanceFuturesHttpResult<BinanceFuturesAccountInfo> {
1198        // USD-M uses /fapi/v2/account, COIN-M uses /dapi/v1/account
1199        let path = if self.api_path.starts_with("/fapi") {
1200            "/fapi/v2/account"
1201        } else {
1202            "/dapi/v1/account"
1203        };
1204        self.get::<(), _>(path, None, true, false).await
1205    }
1206
1207    /// Fetches account-specific maker and taker commission rates for one symbol.
1208    ///
1209    /// # Errors
1210    ///
1211    /// Returns an error if credentials are missing or the request fails.
1212    pub async fn commission_rate(
1213        &self,
1214        params: &BinanceCommissionRateParams,
1215    ) -> BinanceFuturesHttpResult<BinanceFuturesCommissionRate> {
1216        self.get("commissionRate", Some(params), true, false).await
1217    }
1218
1219    /// Fetches position risk information.
1220    ///
1221    /// # Errors
1222    ///
1223    /// Returns an error if the request fails.
1224    pub async fn query_positions(
1225        &self,
1226        params: &BinancePositionRiskParams,
1227    ) -> BinanceFuturesHttpResult<Vec<BinancePositionRisk>> {
1228        // USD-M uses /fapi/v2/positionRisk, COIN-M uses /dapi/v1/positionRisk
1229        let path = if self.api_path.starts_with("/fapi") {
1230            "/fapi/v2/positionRisk"
1231        } else {
1232            "/dapi/v1/positionRisk"
1233        };
1234        self.get(path, Some(params), true, false).await
1235    }
1236
1237    /// Fetches user trades for a symbol.
1238    ///
1239    /// # Errors
1240    ///
1241    /// Returns an error if the request fails.
1242    pub async fn query_user_trades(
1243        &self,
1244        params: &BinanceUserTradesParams,
1245    ) -> BinanceFuturesHttpResult<Vec<BinanceUserTrade>> {
1246        self.get("userTrades", Some(params), true, false).await
1247    }
1248
1249    /// Queries a single order by order ID or client order ID.
1250    ///
1251    /// # Errors
1252    ///
1253    /// Returns an error if the request fails.
1254    pub async fn query_order(
1255        &self,
1256        params: &BinanceOrderQueryParams,
1257    ) -> BinanceFuturesHttpResult<BinanceFuturesOrder> {
1258        let Some(legacy) = params
1259            .orig_client_order_id
1260            .as_deref()
1261            .and_then(|id| legacy_client_order_id(id, BINANCE_NAUTILUS_FUTURES_BROKER_ID))
1262        else {
1263            return self.get("order", Some(params), true, false).await;
1264        };
1265
1266        let mut query = params.clone();
1267        if query.order_id.is_some() {
1268            query.orig_client_order_id = None;
1269            return self.get("order", Some(&query), true, false).await;
1270        }
1271
1272        let current: BinanceFuturesHttpResult<BinanceFuturesOrder> =
1273            self.get("order", Some(&query), true, false).await;
1274
1275        if let Err(e) = &current
1276            && !matches!(
1277                e,
1278                BinanceFuturesHttpError::BinanceError {
1279                    code: BINANCE_NO_SUCH_ORDER_CODE,
1280                    ..
1281                }
1282            )
1283        {
1284            return current;
1285        }
1286
1287        query.orig_client_order_id = Some(legacy);
1288        let historical: BinanceFuturesHttpResult<BinanceFuturesOrder> =
1289            self.get("order", Some(&query), true, false).await;
1290
1291        match (current, historical) {
1292            (Ok(current), Ok(historical)) if current.order_id != historical.order_id => {
1293                Err(BinanceFuturesHttpError::ValidationError(
1294                    "Ambiguous historical client order ID".to_string(),
1295                ))
1296            }
1297            (Ok(current), Ok(_)) => Ok(current),
1298            (
1299                Ok(current),
1300                Err(BinanceFuturesHttpError::BinanceError {
1301                    code: BINANCE_NO_SUCH_ORDER_CODE,
1302                    ..
1303                }),
1304            ) => Ok(current),
1305            (Err(_), Ok(historical)) => Ok(historical),
1306            (_, Err(e)) => Err(e),
1307        }
1308    }
1309
1310    pub(crate) async fn resolve_order_identity(
1311        &self,
1312        symbol: &str,
1313        order_id: &mut Option<i64>,
1314        client_order_id: &mut Option<String>,
1315        modify: bool,
1316    ) -> BinanceFuturesHttpResult<()> {
1317        let Some(id) = client_order_id
1318            .as_deref()
1319            .filter(|id| legacy_client_order_id(id, BINANCE_NAUTILUS_FUTURES_BROKER_ID).is_some())
1320        else {
1321            return Ok(());
1322        };
1323
1324        *order_id = Some(
1325            self.resolve_order_id(symbol, *order_id, id, modify && self.modify_order_quota())
1326                .await?,
1327        );
1328        *client_order_id = None;
1329        Ok(())
1330    }
1331
1332    async fn resolve_order_id(
1333        &self,
1334        symbol: &str,
1335        order_id: Option<i64>,
1336        client_order_id: &str,
1337        use_order_quota: bool,
1338    ) -> BinanceFuturesHttpResult<i64> {
1339        if let Some(order_id) = order_id {
1340            return Ok(order_id);
1341        }
1342
1343        self.for_command(use_order_quota)
1344            .query_order(&BinanceOrderQueryParams {
1345                symbol: symbol.to_string(),
1346                order_id: None,
1347                orig_client_order_id: Some(client_order_id.to_string()),
1348                recv_window: None,
1349            })
1350            .await
1351            .map(|order| order.order_id)
1352            .map_err(identity_lookup_error)
1353    }
1354
1355    /// Queries all open orders.
1356    ///
1357    /// # Errors
1358    ///
1359    /// Returns an error if the request fails.
1360    pub async fn query_open_orders(
1361        &self,
1362        params: &BinanceOpenOrdersParams,
1363    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesOrder>> {
1364        self.get("openOrders", Some(params), true, false).await
1365    }
1366
1367    /// Queries all orders (including historical).
1368    ///
1369    /// # Errors
1370    ///
1371    /// Returns an error if the request fails.
1372    pub async fn query_all_orders(
1373        &self,
1374        params: &BinanceAllOrdersParams,
1375    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesOrder>> {
1376        self.get("allOrders", Some(params), true, false).await
1377    }
1378
1379    /// Submits a new order.
1380    ///
1381    /// # Errors
1382    ///
1383    /// Returns an error if the request fails.
1384    pub async fn submit_order(
1385        &self,
1386        params: &BinanceNewOrderParams,
1387    ) -> BinanceFuturesHttpResult<BinanceFuturesOrder> {
1388        self.post("order", Some(params), None, true, true).await
1389    }
1390
1391    /// Submits multiple orders in a single request (up to 5 orders).
1392    ///
1393    /// # Errors
1394    ///
1395    /// Returns an error if the batch exceeds 5 orders or the request fails.
1396    pub async fn submit_order_list(
1397        &self,
1398        orders: &[BatchOrderItem],
1399    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
1400        if orders.is_empty() {
1401            return Ok(Vec::new());
1402        }
1403
1404        if orders.len() > 5 {
1405            return Err(BinanceFuturesHttpError::ValidationError(
1406                "Batch order limit is 5 orders maximum".to_string(),
1407            ));
1408        }
1409
1410        self.batch_request("batchOrders", orders, true).await
1411    }
1412
1413    /// Modifies an existing order (price and quantity only).
1414    ///
1415    /// # Errors
1416    ///
1417    /// Returns an error if the request fails.
1418    pub async fn modify_order(
1419        &self,
1420        params: &BinanceModifyOrderParams,
1421    ) -> BinanceFuturesHttpResult<BinanceFuturesOrder> {
1422        let use_order_quota = self.modify_order_quota();
1423
1424        if let Some(id) = params.orig_client_order_id.as_deref()
1425            && legacy_client_order_id(id, BINANCE_NAUTILUS_FUTURES_BROKER_ID).is_some()
1426        {
1427            let mut resolved = params.clone();
1428            resolved.order_id = Some(
1429                self.resolve_order_id(&params.symbol, params.order_id, id, use_order_quota)
1430                    .await?,
1431            );
1432            resolved.orig_client_order_id = None;
1433            return self
1434                .request_put("order", Some(&resolved), true, use_order_quota)
1435                .await;
1436        }
1437
1438        self.request_put("order", Some(params), true, use_order_quota)
1439            .await
1440    }
1441
1442    /// Modifies multiple orders in a single request (up to 5 orders).
1443    ///
1444    /// # Errors
1445    ///
1446    /// Returns an error if the batch exceeds 5 orders or the request fails.
1447    pub async fn batch_modify_orders(
1448        &self,
1449        modifies: &[BatchModifyItem],
1450    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
1451        let use_order_quota = self.modify_order_quota();
1452
1453        if modifies.is_empty() {
1454            return Ok(Vec::new());
1455        }
1456
1457        if modifies.len() > 5 {
1458            return Err(BinanceFuturesHttpError::ValidationError(
1459                "Batch modify limit is 5 orders maximum".to_string(),
1460            ));
1461        }
1462
1463        if modifies.iter().any(|item| {
1464            item.orig_client_order_id.as_deref().is_some_and(|id| {
1465                legacy_client_order_id(id, BINANCE_NAUTILUS_FUTURES_BROKER_ID).is_some()
1466            })
1467        }) {
1468            let mut resolved = Vec::with_capacity(modifies.len());
1469            let mut results = Vec::with_capacity(modifies.len());
1470            for item in modifies {
1471                let mut item = item.clone();
1472                if let Some(id) = item.orig_client_order_id.as_deref()
1473                    && legacy_client_order_id(id, BINANCE_NAUTILUS_FUTURES_BROKER_ID).is_some()
1474                {
1475                    match self
1476                        .resolve_order_id(&item.symbol, item.order_id, id, use_order_quota)
1477                        .await
1478                    {
1479                        Ok(order_id) => {
1480                            item.order_id = Some(order_id);
1481                            item.orig_client_order_id = None;
1482                        }
1483                        Err(e) => {
1484                            if let Some(error) = missing_order_lookup_error(&e) {
1485                                results.push(Some(BatchOrderResult::Error(error)));
1486                                continue;
1487                            }
1488
1489                            return Err(e);
1490                        }
1491                    }
1492                }
1493
1494                resolved.push(item);
1495                results.push(None);
1496            }
1497
1498            let responses = if resolved.is_empty() {
1499                Vec::new()
1500            } else {
1501                self.batch_request_put("batchOrders", &resolved, use_order_quota)
1502                    .await?
1503            };
1504
1505            return merge_batch_results(results, responses);
1506        }
1507
1508        self.batch_request_put("batchOrders", modifies, use_order_quota)
1509            .await
1510    }
1511
1512    fn modify_order_quota(&self) -> bool {
1513        self.api_path == BINANCE_FAPI_PATH
1514    }
1515
1516    /// Cancels an existing order.
1517    ///
1518    /// # Errors
1519    ///
1520    /// Returns an error if the request fails.
1521    pub async fn cancel_order(
1522        &self,
1523        params: &BinanceCancelOrderParams,
1524    ) -> BinanceFuturesHttpResult<BinanceFuturesOrder> {
1525        if let Some(id) = params.orig_client_order_id.as_deref()
1526            && legacy_client_order_id(id, BINANCE_NAUTILUS_FUTURES_BROKER_ID).is_some()
1527        {
1528            let mut resolved = params.clone();
1529            resolved.order_id = Some(
1530                self.resolve_order_id(&params.symbol, params.order_id, id, false)
1531                    .await?,
1532            );
1533            resolved.orig_client_order_id = None;
1534            return self
1535                .request_delete("order", Some(&resolved), true, false)
1536                .await;
1537        }
1538
1539        self.request_delete("order", Some(params), true, false)
1540            .await
1541    }
1542
1543    /// Cancels all open orders for a symbol.
1544    ///
1545    /// # Errors
1546    ///
1547    /// Returns an error if the request fails.
1548    pub async fn cancel_all_orders(
1549        &self,
1550        params: &BinanceCancelAllOrdersParams,
1551    ) -> BinanceFuturesHttpResult<BinanceCancelAllOrdersResponse> {
1552        self.request_delete("allOpenOrders", Some(params), true, false)
1553            .await
1554    }
1555
1556    /// Cancels multiple orders in a single request (up to 10 orders).
1557    ///
1558    /// # Errors
1559    ///
1560    /// Returns an error if the batch exceeds 10 orders or the request fails.
1561    pub async fn batch_cancel_orders(
1562        &self,
1563        cancels: &[BatchCancelItem],
1564    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
1565        if cancels.is_empty() {
1566            return Ok(Vec::new());
1567        }
1568
1569        if cancels.len() > 10 {
1570            return Err(BinanceFuturesHttpError::ValidationError(
1571                "Batch cancel limit is 10 orders maximum".to_string(),
1572            ));
1573        }
1574
1575        let params = Self::batch_cancel_params(cancels)?;
1576        if cancels.iter().any(|item| {
1577            item.orig_client_order_id.as_deref().is_some_and(|id| {
1578                legacy_client_order_id(id, BINANCE_NAUTILUS_FUTURES_BROKER_ID).is_some()
1579            })
1580        }) {
1581            let mut resolved = Vec::with_capacity(cancels.len());
1582            let mut results = Vec::with_capacity(cancels.len());
1583            for item in cancels {
1584                let order = self
1585                    .for_command(false)
1586                    .query_order(&BinanceOrderQueryParams {
1587                        symbol: item.symbol.clone(),
1588                        order_id: item.order_id,
1589                        orig_client_order_id: item.orig_client_order_id.clone(),
1590                        recv_window: None,
1591                    })
1592                    .await
1593                    .map_err(identity_lookup_error);
1594
1595                match order {
1596                    Ok(order) => {
1597                        resolved.push(BatchCancelItem::by_order_id(
1598                            item.symbol.clone(),
1599                            order.order_id,
1600                        ));
1601                        results.push(None);
1602                    }
1603                    Err(e) => {
1604                        if let Some(error) = missing_order_lookup_error(&e) {
1605                            results.push(Some(BatchOrderResult::Error(error)));
1606                        } else {
1607                            return Err(e);
1608                        }
1609                    }
1610                }
1611            }
1612
1613            let responses = if resolved.is_empty() {
1614                Vec::new()
1615            } else {
1616                let params = Self::batch_cancel_params(&resolved)?;
1617                self.request_delete("batchOrders", Some(&params), true, false)
1618                    .await?
1619            };
1620
1621            return merge_batch_results(results, responses);
1622        }
1623
1624        self.request_delete("batchOrders", Some(&params), true, false)
1625            .await
1626    }
1627
1628    fn batch_cancel_params(
1629        cancels: &[BatchCancelItem],
1630    ) -> BinanceFuturesHttpResult<BatchCancelParams> {
1631        let symbol = cancels[0].symbol.clone();
1632        let mut order_ids = Vec::new();
1633        let mut client_order_ids = Vec::new();
1634
1635        for cancel in cancels {
1636            if cancel.symbol != symbol {
1637                return Err(BinanceFuturesHttpError::ValidationError(
1638                    "Batch cancel orders must use the same symbol".to_string(),
1639                ));
1640            }
1641
1642            if let Some(order_id) = cancel.order_id {
1643                order_ids.push(order_id);
1644            }
1645
1646            if let Some(client_order_id) = &cancel.orig_client_order_id {
1647                client_order_ids.push(client_order_id.clone());
1648            }
1649        }
1650
1651        if order_ids.is_empty() && client_order_ids.is_empty() {
1652            return Err(BinanceFuturesHttpError::ValidationError(
1653                "Batch cancel requires at least one order ID or client order ID".to_string(),
1654            ));
1655        }
1656
1657        if !order_ids.is_empty() && !client_order_ids.is_empty() {
1658            return Err(BinanceFuturesHttpError::ValidationError(
1659                "Batch cancel requires either order IDs or client order IDs, not both".to_string(),
1660            ));
1661        }
1662
1663        let order_id_list = if order_ids.is_empty() {
1664            None
1665        } else {
1666            Some(
1667                serde_json::to_string(&order_ids)
1668                    .map_err(|e| BinanceFuturesHttpError::ValidationError(e.to_string()))?,
1669            )
1670        };
1671        let orig_client_order_id_list = if client_order_ids.is_empty() {
1672            None
1673        } else {
1674            Some(
1675                serde_json::to_string(&client_order_ids)
1676                    .map_err(|e| BinanceFuturesHttpError::ValidationError(e.to_string()))?,
1677            )
1678        };
1679
1680        Ok(BatchCancelParams {
1681            symbol,
1682            order_id_list,
1683            orig_client_order_id_list,
1684        })
1685    }
1686
1687    /// Submits a new algo order (conditional order).
1688    ///
1689    /// Algo orders include STOP_MARKET, STOP (stop-limit), TAKE_PROFIT, TAKE_PROFIT_MARKET,
1690    /// and TRAILING_STOP_MARKET order types.
1691    ///
1692    /// # Errors
1693    ///
1694    /// Returns an error if the request fails.
1695    pub async fn submit_algo_order(
1696        &self,
1697        params: &BinanceNewAlgoOrderParams,
1698    ) -> BinanceFuturesHttpResult<BinanceFuturesAlgoOrder> {
1699        self.post("algoOrder", Some(params), None, true, true).await
1700    }
1701
1702    /// Cancels an algo order.
1703    ///
1704    /// Must provide either `algo_id` or `client_algo_id`.
1705    ///
1706    /// # Errors
1707    ///
1708    /// Returns an error if the request fails.
1709    pub async fn cancel_algo_order(
1710        &self,
1711        params: &BinanceAlgoOrderQueryParams,
1712    ) -> BinanceFuturesHttpResult<BinanceFuturesAlgoOrderCancelResponse> {
1713        if let Some(id) = params.client_algo_id.as_deref()
1714            && legacy_client_order_id(id, BINANCE_NAUTILUS_FUTURES_BROKER_ID).is_some()
1715        {
1716            let mut resolved = params.clone();
1717            if resolved.algo_id.is_none() {
1718                resolved.algo_id = Some(
1719                    self.for_command(false)
1720                        .query_algo_order(params)
1721                        .await
1722                        .map_err(identity_lookup_error)?
1723                        .algo_id,
1724                );
1725            }
1726
1727            resolved.client_algo_id = None;
1728            return self
1729                .request_delete("algoOrder", Some(&resolved), true, false)
1730                .await;
1731        }
1732
1733        self.request_delete("algoOrder", Some(params), true, false)
1734            .await
1735    }
1736
1737    fn for_command(&self, use_order_quota: bool) -> Self {
1738        Self {
1739            command_order_quota: Some(use_order_quota),
1740            ..self.clone()
1741        }
1742    }
1743
1744    /// Queries a single algo order.
1745    ///
1746    /// Must provide either `algo_id` or `client_algo_id`.
1747    ///
1748    /// # Errors
1749    ///
1750    /// Returns an error if the request fails.
1751    pub async fn query_algo_order(
1752        &self,
1753        params: &BinanceAlgoOrderQueryParams,
1754    ) -> BinanceFuturesHttpResult<BinanceFuturesAlgoOrder> {
1755        let Some(legacy) = params
1756            .client_algo_id
1757            .as_deref()
1758            .and_then(|id| legacy_client_order_id(id, BINANCE_NAUTILUS_FUTURES_BROKER_ID))
1759        else {
1760            return self.get("algoOrder", Some(params), true, false).await;
1761        };
1762
1763        let mut query = params.clone();
1764        if query.algo_id.is_some() {
1765            query.client_algo_id = None;
1766            return self.get("algoOrder", Some(&query), true, false).await;
1767        }
1768
1769        let current: BinanceFuturesHttpResult<BinanceFuturesAlgoOrder> =
1770            self.get("algoOrder", Some(&query), true, false).await;
1771
1772        if let Err(e) = &current
1773            && !matches!(
1774                e,
1775                BinanceFuturesHttpError::BinanceError {
1776                    code: BINANCE_NO_SUCH_ORDER_CODE,
1777                    ..
1778                }
1779            )
1780        {
1781            return current;
1782        }
1783
1784        query.client_algo_id = Some(legacy);
1785        let historical: BinanceFuturesHttpResult<BinanceFuturesAlgoOrder> =
1786            self.get("algoOrder", Some(&query), true, false).await;
1787
1788        match (current, historical) {
1789            (Ok(current), Ok(historical)) if current.algo_id != historical.algo_id => {
1790                Err(BinanceFuturesHttpError::ValidationError(
1791                    "Ambiguous historical client algo ID".to_string(),
1792                ))
1793            }
1794            (Ok(current), Ok(_)) => Ok(current),
1795            (
1796                Ok(current),
1797                Err(BinanceFuturesHttpError::BinanceError {
1798                    code: BINANCE_NO_SUCH_ORDER_CODE,
1799                    ..
1800                }),
1801            ) => Ok(current),
1802            (Err(_), Ok(historical)) => Ok(historical),
1803            (_, Err(e)) => Err(e),
1804        }
1805    }
1806
1807    /// Queries all open algo orders.
1808    ///
1809    /// # Errors
1810    ///
1811    /// Returns an error if the request fails.
1812    pub async fn query_open_algo_orders(
1813        &self,
1814        params: &BinanceOpenAlgoOrdersParams,
1815    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesAlgoOrder>> {
1816        self.get("openAlgoOrders", Some(params), true, false).await
1817    }
1818
1819    /// Queries all algo orders including historical (7-day limit).
1820    ///
1821    /// # Errors
1822    ///
1823    /// Returns an error if the request fails.
1824    pub async fn query_all_algo_orders(
1825        &self,
1826        params: &BinanceAllAlgoOrdersParams,
1827    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesAlgoOrder>> {
1828        self.get("allAlgoOrders", Some(params), true, false).await
1829    }
1830
1831    /// Cancels all open algo orders for a symbol.
1832    ///
1833    /// # Errors
1834    ///
1835    /// Returns an error if the request fails.
1836    pub async fn cancel_all_algo_orders(
1837        &self,
1838        params: &BinanceCancelAllAlgoOrdersParams,
1839    ) -> BinanceFuturesHttpResult<BinanceCancelAllOrdersResponse> {
1840        self.request_delete("algoOpenOrders", Some(params), true, false)
1841            .await
1842    }
1843}
1844
1845/// Response wrapper for mark price endpoint.
1846#[derive(Debug, Deserialize)]
1847#[serde(untagged)]
1848enum MarkPriceResponse {
1849    Single(BinanceFuturesMarkPrice),
1850    Multiple(Vec<BinanceFuturesMarkPrice>),
1851}
1852
1853impl From<MarkPriceResponse> for Vec<BinanceFuturesMarkPrice> {
1854    fn from(response: MarkPriceResponse) -> Self {
1855        match response {
1856            MarkPriceResponse::Single(price) => vec![price],
1857            MarkPriceResponse::Multiple(prices) => prices,
1858        }
1859    }
1860}
1861
1862struct RateLimitConfig {
1863    request_quota: Quota,
1864    order_quotas: Vec<(String, Quota)>,
1865    order_keys: Vec<String>,
1866}
1867
1868/// In-memory cache entry for Binance Futures instruments.
1869#[derive(Clone, Debug)]
1870pub enum BinanceFuturesInstrument {
1871    /// USD-M futures symbol.
1872    UsdM(BinanceFuturesUsdSymbol),
1873    /// COIN-M futures symbol.
1874    CoinM(BinanceFuturesCoinSymbol),
1875}
1876
1877impl BinanceFuturesInstrument {
1878    /// Returns the symbol name for the instrument.
1879    #[must_use]
1880    pub const fn symbol(&self) -> Ustr {
1881        match self {
1882            Self::UsdM(s) => s.symbol,
1883            Self::CoinM(s) => s.symbol,
1884        }
1885    }
1886
1887    /// Returns the price precision for the instrument.
1888    #[must_use]
1889    pub const fn price_precision(&self) -> i32 {
1890        match self {
1891            Self::UsdM(s) => s.price_precision,
1892            Self::CoinM(s) => s.price_precision,
1893        }
1894    }
1895
1896    /// Returns the quantity precision for the instrument.
1897    #[must_use]
1898    pub const fn quantity_precision(&self) -> i32 {
1899        match self {
1900            Self::UsdM(s) => s.quantity_precision,
1901            Self::CoinM(s) => s.quantity_precision,
1902        }
1903    }
1904
1905    /// Returns validated price and quantity precision values.
1906    ///
1907    /// # Errors
1908    ///
1909    /// Returns an error if either venue precision is outside the domain type range.
1910    pub fn precisions(&self) -> BinanceFuturesHttpResult<(u8, u8)> {
1911        let price_precision = u8::try_from(self.price_precision()).map_err(|_| {
1912            BinanceFuturesHttpError::ValidationError(format!(
1913                "Invalid Binance Futures price precision {} for {}",
1914                self.price_precision(),
1915                self.symbol()
1916            ))
1917        })?;
1918        let quantity_precision = u8::try_from(self.quantity_precision()).map_err(|_| {
1919            BinanceFuturesHttpError::ValidationError(format!(
1920                "Invalid Binance Futures quantity precision {} for {}",
1921                self.quantity_precision(),
1922                self.symbol()
1923            ))
1924        })?;
1925
1926        if price_precision > FIXED_PRECISION || quantity_precision > FIXED_PRECISION {
1927            return Err(BinanceFuturesHttpError::ValidationError(format!(
1928                "Binance Futures precision exceeds maximum {FIXED_PRECISION} for {}: price={price_precision}, quantity={quantity_precision}",
1929                self.symbol()
1930            )));
1931        }
1932
1933        Ok((price_precision, quantity_precision))
1934    }
1935
1936    /// Returns the Nautilus-formatted instrument ID.
1937    #[must_use]
1938    pub fn id(&self) -> InstrumentId {
1939        match self {
1940            Self::UsdM(s) => format_instrument_id(&s.symbol, BinanceProductType::UsdM),
1941            Self::CoinM(s) => format_instrument_id(&s.symbol, BinanceProductType::CoinM),
1942        }
1943    }
1944
1945    /// Returns the quote currency for the instrument.
1946    #[must_use]
1947    pub fn quote_currency(&self) -> Currency {
1948        let quote_asset = match self {
1949            Self::UsdM(s) => &s.quote_asset,
1950            Self::CoinM(s) => &s.quote_asset,
1951        };
1952        Currency::get_or_create_crypto_with_context(quote_asset.as_str(), Some("futures quote"))
1953    }
1954}
1955
1956/// Binance Futures HTTP client for USD-M and COIN-M perpetuals and delivery contracts.
1957#[derive(Debug, Clone)]
1958pub struct BinanceFuturesHttpClient {
1959    inner: Arc<BinanceRawFuturesHttpClient>,
1960    product_type: BinanceProductType,
1961    clock: &'static AtomicTime,
1962    instruments: Arc<DashMap<Ustr, BinanceFuturesInstrument>>,
1963    instruments_reconciliation: Arc<AtomicMap<InstrumentId, InstrumentAny>>,
1964    instruments_load_lock: Arc<tokio::sync::Mutex<()>>,
1965    treat_expired_as_canceled: bool,
1966}
1967
1968impl BinanceFuturesHttpClient {
1969    /// Creates a new [`BinanceFuturesHttpClient`] instance.
1970    ///
1971    /// # Errors
1972    ///
1973    /// Returns an error if the product type is invalid or HTTP client creation fails.
1974    #[expect(clippy::too_many_arguments)]
1975    pub fn new(
1976        product_type: BinanceProductType,
1977        environment: BinanceEnvironment,
1978        clock: &'static AtomicTime,
1979        api_key: Option<String>,
1980        api_secret: Option<String>,
1981        base_url_override: Option<String>,
1982        recv_window: Option<u64>,
1983        timeout_secs: Option<u64>,
1984        proxy_url: Option<String>,
1985        treat_expired_as_canceled: bool,
1986    ) -> BinanceFuturesHttpResult<Self> {
1987        match product_type {
1988            BinanceProductType::UsdM | BinanceProductType::CoinM => {}
1989            _ => {
1990                return Err(BinanceFuturesHttpError::ValidationError(format!(
1991                    "BinanceFuturesHttpClient requires UsdM or CoinM product type, was {product_type:?}"
1992                )));
1993            }
1994        }
1995
1996        let raw = BinanceRawFuturesHttpClient::new(
1997            product_type,
1998            environment,
1999            api_key,
2000            api_secret,
2001            base_url_override,
2002            recv_window,
2003            timeout_secs,
2004            proxy_url,
2005        )?;
2006
2007        Ok(Self {
2008            inner: Arc::new(raw),
2009            product_type,
2010            clock,
2011            instruments: Arc::new(DashMap::new()),
2012            instruments_reconciliation: Arc::new(AtomicMap::new()),
2013            instruments_load_lock: Arc::new(tokio::sync::Mutex::new(())),
2014            treat_expired_as_canceled,
2015        })
2016    }
2017
2018    pub(crate) fn with_retry_config(mut self, config: RetryConfig) -> Self {
2019        Arc::make_mut(&mut self.inner).retry_manager = Arc::new(RetryManager::new(config));
2020        self
2021    }
2022
2023    /// Returns the product type (UsdM or CoinM).
2024    #[must_use]
2025    pub const fn product_type(&self) -> BinanceProductType {
2026        self.product_type
2027    }
2028
2029    /// Returns a reference to the inner raw HTTP client.
2030    #[must_use]
2031    pub fn inner(&self) -> &BinanceRawFuturesHttpClient {
2032        &self.inner
2033    }
2034
2035    /// Returns a clone of the instruments cache Arc.
2036    #[must_use]
2037    pub fn instruments_cache(&self) -> Arc<DashMap<Ustr, BinanceFuturesInstrument>> {
2038        Arc::clone(&self.instruments)
2039    }
2040
2041    /// Returns the execution-owned parsed instrument for an exact ID.
2042    pub(crate) fn instrument_reconciliation(
2043        &self,
2044        instrument_id: &InstrumentId,
2045    ) -> Option<InstrumentAny> {
2046        self.instruments_reconciliation.get_cloned(instrument_id)
2047    }
2048
2049    pub(crate) fn instrument_ids_reconciliation(&self) -> Vec<InstrumentId> {
2050        self.instruments_reconciliation
2051            .load()
2052            .keys()
2053            .copied()
2054            .collect()
2055    }
2056
2057    /// Returns whether this client has complete signing credentials.
2058    #[must_use]
2059    pub fn has_credentials(&self) -> bool {
2060        self.inner.has_credentials()
2061    }
2062
2063    /// Replaces the raw instrument metadata after a complete catalog fetch.
2064    fn replace_instruments(
2065        &self,
2066        instruments: Vec<(Ustr, BinanceFuturesInstrument)>,
2067    ) -> BinanceFuturesHttpResult<()> {
2068        let mut snapshot = AHashMap::with_capacity(instruments.len());
2069        for (symbol, instrument) in instruments {
2070            instrument.precisions()?;
2071            if instrument.symbol() != symbol {
2072                return Err(BinanceFuturesHttpError::ValidationError(format!(
2073                    "Binance Futures catalog key {symbol} does not match instrument symbol {}",
2074                    instrument.symbol()
2075                )));
2076            }
2077            let expected_id = format_instrument_id(&symbol, self.product_type);
2078            if instrument.id() != expected_id {
2079                return Err(BinanceFuturesHttpError::ValidationError(format!(
2080                    "Binance Futures catalog instrument ID {} does not match expected ID {expected_id}",
2081                    instrument.id()
2082                )));
2083            }
2084
2085            if snapshot.insert(symbol, instrument).is_some() {
2086                return Err(BinanceFuturesHttpError::ValidationError(format!(
2087                    "Duplicate Binance Futures catalog symbol {symbol}"
2088                )));
2089            }
2090        }
2091
2092        let symbols: AHashSet<_> = snapshot.keys().copied().collect();
2093        for (symbol, instrument) in snapshot {
2094            self.instruments.insert(symbol, instrument);
2095        }
2096        self.instruments
2097            .retain(|symbol, _| symbols.contains(symbol));
2098        Ok(())
2099    }
2100
2101    /// Returns server time.
2102    ///
2103    /// # Errors
2104    ///
2105    /// Returns an error if the request fails.
2106    pub async fn server_time(&self) -> BinanceFuturesHttpResult<BinanceServerTime> {
2107        self.inner
2108            .get::<_, BinanceServerTime>("time", None::<&()>, false, false)
2109            .await
2110    }
2111
2112    /// Sets leverage for a symbol.
2113    ///
2114    /// # Errors
2115    ///
2116    /// Returns an error if the request fails.
2117    pub async fn set_leverage(
2118        &self,
2119        params: &BinanceSetLeverageParams,
2120    ) -> BinanceFuturesHttpResult<BinanceLeverageResponse> {
2121        self.inner.set_leverage(params).await
2122    }
2123
2124    /// Sets margin type for a symbol.
2125    ///
2126    /// # Errors
2127    ///
2128    /// Returns an error if the request fails.
2129    pub async fn set_margin_type(
2130        &self,
2131        params: &BinanceSetMarginTypeParams,
2132    ) -> BinanceFuturesHttpResult<serde_json::Value> {
2133        self.inner.set_margin_type(params).await
2134    }
2135
2136    /// Queries hedge mode (dual side position) setting.
2137    ///
2138    /// # Errors
2139    ///
2140    /// Returns an error if the request fails.
2141    pub async fn query_hedge_mode(&self) -> BinanceFuturesHttpResult<BinanceHedgeModeResponse> {
2142        self.inner.query_hedge_mode().await
2143    }
2144
2145    /// Creates a listen key for user data stream.
2146    ///
2147    /// # Errors
2148    ///
2149    /// Returns an error if the request fails.
2150    pub async fn create_listen_key(&self) -> BinanceFuturesHttpResult<ListenKeyResponse> {
2151        self.inner.create_listen_key().await
2152    }
2153
2154    /// Keeps alive an existing listen key.
2155    ///
2156    /// # Errors
2157    ///
2158    /// Returns an error if the request fails.
2159    pub async fn keepalive_listen_key(&self, listen_key: &str) -> BinanceFuturesHttpResult<()> {
2160        self.inner.keepalive_listen_key(listen_key).await
2161    }
2162
2163    /// Closes an existing listen key.
2164    ///
2165    /// # Errors
2166    ///
2167    /// Returns an error if the request fails.
2168    pub async fn close_listen_key(&self, listen_key: &str) -> BinanceFuturesHttpResult<()> {
2169        self.inner.close_listen_key(listen_key).await
2170    }
2171
2172    /// Fetches exchange information and populates the instrument cache.
2173    ///
2174    /// # Errors
2175    ///
2176    /// Returns an error if the request fails or the product type is invalid.
2177    pub async fn exchange_info(&self) -> BinanceFuturesHttpResult<()> {
2178        let _guard = self.instruments_load_lock.lock().await;
2179        let instruments = match self.product_type {
2180            BinanceProductType::UsdM => {
2181                let info: BinanceFuturesUsdExchangeInfo = self
2182                    .inner
2183                    .get("exchangeInfo", None::<&()>, false, false)
2184                    .await?;
2185
2186                info.symbols
2187                    .into_iter()
2188                    .map(|symbol| (symbol.symbol, BinanceFuturesInstrument::UsdM(symbol)))
2189                    .collect()
2190            }
2191            BinanceProductType::CoinM => {
2192                let info: BinanceFuturesCoinExchangeInfo = self
2193                    .inner
2194                    .get("exchangeInfo", None::<&()>, false, false)
2195                    .await?;
2196
2197                info.symbols
2198                    .into_iter()
2199                    .map(|symbol| (symbol.symbol, BinanceFuturesInstrument::CoinM(symbol)))
2200                    .collect()
2201            }
2202            _ => {
2203                return Err(BinanceFuturesHttpError::ValidationError(
2204                    "Invalid product type for futures".to_string(),
2205                ));
2206            }
2207        };
2208
2209        self.replace_instruments(instruments)
2210    }
2211
2212    /// Fetches exchange info and returns the current status of each symbol.
2213    ///
2214    /// Builds a fresh status snapshot from the response without disturbing the
2215    /// shared instruments cache, so a transient failure does not break other
2216    /// HTTP operations that depend on cached precision data.
2217    ///
2218    /// # Errors
2219    ///
2220    /// Returns an error if the request fails or the product type is invalid.
2221    pub async fn request_symbol_statuses(
2222        &self,
2223    ) -> BinanceFuturesHttpResult<AHashMap<Ustr, MarketStatusAction>> {
2224        let mut statuses = AHashMap::new();
2225
2226        match self.product_type {
2227            BinanceProductType::UsdM => {
2228                let info: BinanceFuturesUsdExchangeInfo = self
2229                    .inner
2230                    .get("exchangeInfo", None::<&()>, false, false)
2231                    .await?;
2232
2233                for symbol in &info.symbols {
2234                    statuses.insert(symbol.symbol, MarketStatusAction::from(symbol.status));
2235                }
2236            }
2237            BinanceProductType::CoinM => {
2238                let info: BinanceFuturesCoinExchangeInfo = self
2239                    .inner
2240                    .get("exchangeInfo", None::<&()>, false, false)
2241                    .await?;
2242
2243                for symbol in &info.symbols {
2244                    let action = symbol
2245                        .contract_status
2246                        .map_or(MarketStatusAction::NotAvailableForTrading, Into::into);
2247                    statuses.insert(symbol.symbol, action);
2248                }
2249            }
2250            _ => {
2251                return Err(BinanceFuturesHttpError::ValidationError(
2252                    "Invalid product type for futures".to_string(),
2253                ));
2254            }
2255        }
2256
2257        Ok(statuses)
2258    }
2259
2260    /// Fetches exchange information and returns parsed Nautilus instruments.
2261    ///
2262    /// # Errors
2263    ///
2264    /// Returns an error if the request fails or the product type is invalid.
2265    pub async fn request_instruments(&self) -> BinanceFuturesHttpResult<Vec<InstrumentAny>> {
2266        self.request_instruments_with_config(&BinanceInstrumentProviderConfig::default())
2267            .await
2268    }
2269
2270    /// Fetches, selects, and parses the configured instrument catalog.
2271    ///
2272    /// Non-trading symbols are skipped with a debug log unless explicitly
2273    /// selected via `load_ids` or the `symbols` filter.
2274    ///
2275    /// Account-wide Futures VIP rates provide the fallback when credentials are
2276    /// present. Exact per-symbol commission queries are opt-in.
2277    ///
2278    /// # Errors
2279    ///
2280    /// Returns an error if configuration or the catalog request is invalid.
2281    pub async fn request_instruments_with_config(
2282        &self,
2283        config: &BinanceInstrumentProviderConfig,
2284    ) -> BinanceFuturesHttpResult<Vec<InstrumentAny>> {
2285        let _guard = self.instruments_load_lock.lock().await;
2286        let selector = BinanceInstrumentSelector::new(config, self.product_type)
2287            .map_err(|e| BinanceFuturesHttpError::ValidationError(e.to_string()))?;
2288        let ts_init = self.clock.get_time_ns();
2289        let mut cache = Vec::new();
2290        let mut reconciliation = AHashMap::new();
2291
2292        let instruments = match self.product_type {
2293            BinanceProductType::UsdM => {
2294                let info: BinanceFuturesUsdExchangeInfo = self
2295                    .inner
2296                    .get("exchangeInfo", None::<&()>, false, false)
2297                    .await?;
2298
2299                let mut instruments = Vec::with_capacity(info.symbols.len());
2300
2301                for symbol in info.symbols {
2302                    let instrument_id =
2303                        format_instrument_id(&symbol.symbol, BinanceProductType::UsdM);
2304                    cache.push((
2305                        symbol.symbol,
2306                        BinanceFuturesInstrument::UsdM(symbol.clone()),
2307                    ));
2308
2309                    if !selector.includes(
2310                        instrument_id,
2311                        &symbol.symbol,
2312                        &symbol.base_asset,
2313                        &symbol.quote_asset,
2314                        Some(&symbol.contract_type),
2315                    ) {
2316                        continue;
2317                    }
2318
2319                    match parse_usdm_instrument_with_fees(&symbol, ts_init, ts_init) {
2320                        Ok(instrument) => {
2321                            validate_reconciliation_instrument(
2322                                &mut reconciliation,
2323                                instrument_id,
2324                                &instrument,
2325                            )?;
2326                            instruments.push(instrument);
2327                        }
2328                        Err(e) => {
2329                            log_futures_instrument_parse_error(
2330                                config,
2331                                &selector,
2332                                instrument_id,
2333                                &symbol.symbol,
2334                                &e,
2335                            );
2336                        }
2337                    }
2338                }
2339
2340                log::debug!(
2341                    "Loaded USD-M Futures instruments: count={}",
2342                    instruments.len()
2343                );
2344                instruments
2345            }
2346            BinanceProductType::CoinM => {
2347                let info: BinanceFuturesCoinExchangeInfo = self
2348                    .inner
2349                    .get("exchangeInfo", None::<&()>, false, false)
2350                    .await?;
2351
2352                let mut instruments = Vec::with_capacity(info.symbols.len());
2353                for symbol in info.symbols {
2354                    let instrument_id =
2355                        format_instrument_id(&symbol.symbol, BinanceProductType::CoinM);
2356                    cache.push((
2357                        symbol.symbol,
2358                        BinanceFuturesInstrument::CoinM(symbol.clone()),
2359                    ));
2360
2361                    if !selector.includes(
2362                        instrument_id,
2363                        &symbol.symbol,
2364                        &symbol.base_asset,
2365                        &symbol.quote_asset,
2366                        Some(&symbol.contract_type),
2367                    ) {
2368                        continue;
2369                    }
2370
2371                    match parse_coinm_instrument_with_fees(&symbol, ts_init, ts_init) {
2372                        Ok(instrument) => {
2373                            validate_reconciliation_instrument(
2374                                &mut reconciliation,
2375                                instrument_id,
2376                                &instrument,
2377                            )?;
2378                            instruments.push(instrument);
2379                        }
2380                        Err(e) => {
2381                            log_futures_instrument_parse_error(
2382                                config,
2383                                &selector,
2384                                instrument_id,
2385                                &symbol.symbol,
2386                                &e,
2387                            );
2388                        }
2389                    }
2390                }
2391
2392                log::debug!(
2393                    "Loaded COIN-M Futures instruments: count={}",
2394                    instruments.len()
2395                );
2396                instruments
2397            }
2398            _ => {
2399                return Err(BinanceFuturesHttpError::ValidationError(
2400                    "Invalid product type for futures".to_string(),
2401                ));
2402            }
2403        };
2404
2405        self.replace_instruments(cache)?;
2406        self.instruments_reconciliation.store(reconciliation);
2407        Ok(instruments)
2408    }
2409
2410    /// Fetches 24hr ticker statistics.
2411    ///
2412    /// # Errors
2413    ///
2414    /// Returns an error if the request fails.
2415    pub async fn ticker_24h(
2416        &self,
2417        params: &BinanceTicker24hrParams,
2418    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesTicker24hr>> {
2419        self.inner.ticker_24h(params).await
2420    }
2421
2422    /// Fetches best bid/ask prices.
2423    ///
2424    /// # Errors
2425    ///
2426    /// Returns an error if the request fails.
2427    pub async fn book_ticker(
2428        &self,
2429        params: &BinanceBookTickerParams,
2430    ) -> BinanceFuturesHttpResult<Vec<BinanceBookTicker>> {
2431        self.inner.book_ticker(params).await
2432    }
2433
2434    /// Fetches price ticker.
2435    ///
2436    /// # Errors
2437    ///
2438    /// Returns an error if the request fails.
2439    pub async fn price_ticker(
2440        &self,
2441        symbol: Option<&str>,
2442    ) -> BinanceFuturesHttpResult<Vec<BinancePriceTicker>> {
2443        self.inner.price_ticker(symbol).await
2444    }
2445
2446    /// Fetches order book depth.
2447    ///
2448    /// # Errors
2449    ///
2450    /// Returns an error if the request fails.
2451    pub async fn depth(
2452        &self,
2453        params: &BinanceDepthParams,
2454    ) -> BinanceFuturesHttpResult<BinanceOrderBook> {
2455        self.inner.depth(params).await
2456    }
2457
2458    /// Fetches mark price and funding rate.
2459    ///
2460    /// # Errors
2461    ///
2462    /// Returns an error if the request fails.
2463    pub async fn mark_price(
2464        &self,
2465        params: &BinanceMarkPriceParams,
2466    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesMarkPrice>> {
2467        self.inner.mark_price(params).await
2468    }
2469
2470    /// Fetches funding rate history.
2471    ///
2472    /// # Errors
2473    ///
2474    /// Returns an error if the request fails.
2475    pub async fn funding_rate(
2476        &self,
2477        params: &BinanceFundingRateParams,
2478    ) -> BinanceFuturesHttpResult<Vec<BinanceFundingRate>> {
2479        self.inner.funding_rate(params).await
2480    }
2481
2482    /// Fetches current open interest for a symbol.
2483    ///
2484    /// # Errors
2485    ///
2486    /// Returns an error if the request fails.
2487    pub async fn open_interest(
2488        &self,
2489        params: &BinanceOpenInterestParams,
2490    ) -> BinanceFuturesHttpResult<BinanceOpenInterest> {
2491        self.inner.open_interest(params).await
2492    }
2493
2494    /// Fetches historical open interest statistics for a symbol or pair.
2495    ///
2496    /// # Errors
2497    ///
2498    /// Returns an error if the request fails.
2499    pub async fn open_interest_hist(
2500        &self,
2501        params: &BinanceOpenInterestHistParams,
2502    ) -> BinanceFuturesHttpResult<Vec<BinanceOpenInterestHistRecord>> {
2503        self.inner.open_interest_hist(params).await
2504    }
2505
2506    /// Queries a single order by order ID or client order ID.
2507    ///
2508    /// # Errors
2509    ///
2510    /// Returns an error if the request fails.
2511    pub async fn query_order(
2512        &self,
2513        params: &BinanceOrderQueryParams,
2514    ) -> BinanceFuturesHttpResult<BinanceFuturesOrder> {
2515        self.inner.query_order(params).await
2516    }
2517
2518    /// Queries all open orders.
2519    ///
2520    /// # Errors
2521    ///
2522    /// Returns an error if the request fails.
2523    pub async fn query_open_orders(
2524        &self,
2525        params: &BinanceOpenOrdersParams,
2526    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesOrder>> {
2527        self.inner.query_open_orders(params).await
2528    }
2529
2530    /// Queries all orders (including historical).
2531    ///
2532    /// # Errors
2533    ///
2534    /// Returns an error if the request fails.
2535    pub async fn query_all_orders(
2536        &self,
2537        params: &BinanceAllOrdersParams,
2538    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesOrder>> {
2539        self.inner.query_all_orders(params).await
2540    }
2541
2542    pub(crate) async fn query_order_history(
2543        &self,
2544        instrument_id: InstrumentId,
2545        start: UnixNanos,
2546        end: UnixNanos,
2547    ) -> anyhow::Result<(
2548        IndexMap<i64, BinanceFuturesOrder>,
2549        IndexMap<i64, BinanceFuturesAlgoOrder>,
2550    )> {
2551        const MAX_INTERVAL_MS: i64 = 7 * SECONDS_IN_DAY as i64 * 1_000;
2552
2553        let symbol = format_binance_symbol(&instrument_id);
2554        let end_ms = end.as_i64() / NANOSECONDS_IN_MILLISECOND as i64;
2555        let mut window_start = start.as_i64() / NANOSECONDS_IN_MILLISECOND as i64;
2556        let mut orders = IndexMap::new();
2557        let mut algo_orders = IndexMap::new();
2558
2559        while window_start <= end_ms {
2560            let window_end = window_start.saturating_add(MAX_INTERVAL_MS - 1).min(end_ms);
2561            let page = self
2562                .query_order_history_window(&symbol, window_start, window_end)
2563                .await?;
2564            orders.extend(page.into_iter().map(|order| (order.order_id, order)));
2565
2566            if self.product_type == BinanceProductType::UsdM {
2567                let page = self
2568                    .query_algo_history_window(&symbol, window_start, window_end)
2569                    .await?;
2570                algo_orders.extend(page.into_iter().map(|order| (order.algo_id, order)));
2571            }
2572
2573            window_start = window_end + 1;
2574        }
2575
2576        Ok((orders, algo_orders))
2577    }
2578
2579    async fn query_order_history_window(
2580        &self,
2581        symbol: &str,
2582        start: i64,
2583        end: i64,
2584    ) -> anyhow::Result<Vec<BinanceFuturesOrder>> {
2585        let mut orders = Vec::new();
2586        let mut order_id = None;
2587
2588        loop {
2589            let params = BinanceAllOrdersParams {
2590                symbol: symbol.to_string(),
2591                order_id,
2592                start_time: order_id.is_none().then_some(start),
2593                end_time: order_id.is_none().then_some(end),
2594                limit: Some(ORDER_HISTORY_PAGE_LIMIT),
2595                recv_window: None,
2596            };
2597
2598            let page = self.query_all_orders(&params).await?;
2599            let page_len = page.len();
2600
2601            let Some(last_id) = page.iter().map(|order| order.order_id).max() else {
2602                break;
2603            };
2604
2605            let past_end = page
2606                .iter()
2607                .any(|order| order.time.is_some_and(|time| time > end));
2608            orders.extend(
2609                page.into_iter()
2610                    .filter(|order| order.time.is_none_or(|time| time <= end)),
2611            );
2612
2613            if page_len < ORDER_HISTORY_PAGE_LIMIT as usize || past_end {
2614                break;
2615            }
2616
2617            let next_id = last_id
2618                .checked_add(1)
2619                .context("Binance Futures order ID overflow during pagination")?;
2620            anyhow::ensure!(
2621                next_id > order_id.unwrap_or_default(),
2622                "Binance Futures order history pagination made no progress"
2623            );
2624            order_id = Some(next_id);
2625        }
2626
2627        Ok(orders)
2628    }
2629
2630    async fn query_algo_history_window(
2631        &self,
2632        symbol: &str,
2633        start: i64,
2634        end: i64,
2635    ) -> anyhow::Result<Vec<BinanceFuturesAlgoOrder>> {
2636        let mut orders = Vec::new();
2637        let mut algo_id = None;
2638
2639        loop {
2640            let params = BinanceAllAlgoOrdersParams {
2641                symbol: symbol.to_string(),
2642                algo_id,
2643                start_time: algo_id.is_none().then_some(start),
2644                end_time: algo_id.is_none().then_some(end),
2645                page: None,
2646                limit: Some(ORDER_HISTORY_PAGE_LIMIT),
2647                recv_window: None,
2648            };
2649
2650            let page = self.inner.query_all_algo_orders(&params).await?;
2651            let page_len = page.len();
2652
2653            let Some(last_id) = page.iter().map(|order| order.algo_id).max() else {
2654                break;
2655            };
2656
2657            let past_end = page
2658                .iter()
2659                .any(|order| order.create_time.is_some_and(|time| time > end));
2660            orders.extend(
2661                page.into_iter()
2662                    .filter(|order| order.create_time.is_none_or(|time| time <= end)),
2663            );
2664
2665            if page_len < ORDER_HISTORY_PAGE_LIMIT as usize || past_end {
2666                break;
2667            }
2668
2669            let next_id = last_id
2670                .checked_add(1)
2671                .context("Binance Futures algo ID overflow during pagination")?;
2672            anyhow::ensure!(
2673                next_id > algo_id.unwrap_or_default(),
2674                "Binance Futures algo history pagination made no progress"
2675            );
2676            algo_id = Some(next_id);
2677        }
2678
2679        Ok(orders)
2680    }
2681
2682    /// Fetches account information including balances and positions.
2683    ///
2684    /// # Errors
2685    ///
2686    /// Returns an error if the request fails.
2687    pub async fn query_account(&self) -> BinanceFuturesHttpResult<BinanceFuturesAccountInfo> {
2688        self.inner.query_account().await
2689    }
2690
2691    /// Fetches position risk information.
2692    ///
2693    /// # Errors
2694    ///
2695    /// Returns an error if the request fails.
2696    pub async fn query_positions(
2697        &self,
2698        params: &BinancePositionRiskParams,
2699    ) -> BinanceFuturesHttpResult<Vec<BinancePositionRisk>> {
2700        self.inner.query_positions(params).await
2701    }
2702
2703    /// Fetches user trades for a symbol.
2704    ///
2705    /// # Errors
2706    ///
2707    /// Returns an error if the request fails.
2708    pub async fn query_user_trades(
2709        &self,
2710        params: &BinanceUserTradesParams,
2711    ) -> BinanceFuturesHttpResult<Vec<BinanceUserTrade>> {
2712        self.inner.query_user_trades(params).await
2713    }
2714
2715    /// Submits a new order.
2716    ///
2717    /// # Errors
2718    ///
2719    /// Returns an error if:
2720    /// - The instrument is not cached.
2721    /// - The order type or time-in-force is unsupported.
2722    /// - Stop orders are submitted without a trigger price.
2723    /// - The request fails.
2724    #[expect(clippy::too_many_arguments)]
2725    pub async fn submit_order(
2726        &self,
2727        account_id: AccountId,
2728        instrument_id: InstrumentId,
2729        client_order_id: ClientOrderId,
2730        order_side: OrderSide,
2731        order_type: OrderType,
2732        quantity: Quantity,
2733        time_in_force: TimeInForce,
2734        price: Option<Price>,
2735        trigger_price: Option<Price>,
2736        reduce_only: bool,
2737        post_only: bool,
2738        rpi: bool,
2739        position_side: Option<BinancePositionSide>,
2740        price_match: Option<BinancePriceMatch>,
2741        good_till_date: Option<i64>,
2742    ) -> anyhow::Result<OrderStatusReport> {
2743        let (symbol, price_precision, size_precision) =
2744            self.cached_precisions_by_id(instrument_id)?;
2745
2746        let binance_side = BinanceSide::try_from(order_side)?;
2747        let binance_order_type = order_type_to_binance_futures(order_type)?;
2748        let binance_tif = if rpi {
2749            BinanceTimeInForce::Rpi
2750        } else if post_only {
2751            BinanceTimeInForce::Gtx
2752        } else {
2753            BinanceTimeInForce::try_from(time_in_force)?
2754        };
2755
2756        let requires_trigger_price = matches!(
2757            order_type,
2758            OrderType::StopMarket
2759                | OrderType::StopLimit
2760                | OrderType::TrailingStopMarket
2761                | OrderType::MarketIfTouched
2762                | OrderType::LimitIfTouched
2763        );
2764
2765        if requires_trigger_price && trigger_price.is_none() {
2766            anyhow::bail!("Order type {order_type:?} requires a trigger price");
2767        }
2768
2769        // MARKET and STOP_MARKET orders don't accept timeInForce
2770        let requires_time_in_force = matches!(
2771            order_type,
2772            OrderType::Limit | OrderType::StopLimit | OrderType::LimitIfTouched
2773        );
2774
2775        let qty_str = quantity.to_string();
2776        let price_str = if price_match.is_some() {
2777            None
2778        } else {
2779            price.map(|p| p.to_string())
2780        };
2781        let stop_price_str = trigger_price.map(|p| p.to_string());
2782        let client_id_str = encode_broker_id(&client_order_id, BINANCE_NAUTILUS_FUTURES_BROKER_ID);
2783
2784        let params = BinanceNewOrderParams {
2785            symbol,
2786            side: binance_side,
2787            order_type: binance_order_type,
2788            time_in_force: if requires_time_in_force {
2789                Some(binance_tif)
2790            } else {
2791                None
2792            },
2793            quantity: Some(qty_str),
2794            price: price_str,
2795            new_client_order_id: Some(client_id_str),
2796            stop_price: stop_price_str,
2797            reduce_only: reduce_only_param(reduce_only, position_side),
2798            position_side,
2799            close_position: None,
2800            activation_price: None,
2801            callback_rate: None,
2802            working_type: None,
2803            price_protect: None,
2804            new_order_resp_type: None,
2805            good_till_date,
2806            recv_window: None,
2807            price_match,
2808            self_trade_prevention_mode: None,
2809        };
2810
2811        let order = self.inner.submit_order(&params).await?;
2812        let ts_init = self.clock.get_time_ns();
2813        order.to_order_status_report(
2814            account_id,
2815            instrument_id,
2816            price_precision,
2817            size_precision,
2818            self.treat_expired_as_canceled,
2819            ts_init,
2820        )
2821    }
2822
2823    /// Submits an algo order (conditional order) to the Binance Algo Service.
2824    ///
2825    /// As of 2025-12-09, Binance migrated conditional order types to the Algo Service API.
2826    /// This method handles StopMarket, StopLimit, MarketIfTouched, LimitIfTouched,
2827    /// and TrailingStopMarket orders.
2828    ///
2829    /// # Errors
2830    ///
2831    /// Returns an error if:
2832    /// - The order type requires a trigger price but none is provided.
2833    /// - The instrument is not cached.
2834    /// - The request fails.
2835    #[expect(clippy::too_many_arguments)]
2836    pub async fn submit_algo_order(
2837        &self,
2838        account_id: AccountId,
2839        instrument_id: InstrumentId,
2840        client_order_id: ClientOrderId,
2841        order_side: OrderSide,
2842        order_type: OrderType,
2843        quantity: Quantity,
2844        time_in_force: TimeInForce,
2845        price: Option<Price>,
2846        trigger_price: Option<Price>,
2847        reduce_only: bool,
2848        close_position: bool,
2849        position_side: Option<BinancePositionSide>,
2850        activation_price: Option<Price>,
2851        callback_rate: Option<String>,
2852        working_type: Option<BinanceWorkingType>,
2853        good_till_date: Option<i64>,
2854    ) -> anyhow::Result<OrderStatusReport> {
2855        let (symbol, price_precision, size_precision) =
2856            self.cached_precisions_by_id(instrument_id)?;
2857
2858        let binance_side = BinanceSide::try_from(order_side)?;
2859        let binance_order_type = order_type_to_binance_futures(order_type)?;
2860        let binance_tif = BinanceTimeInForce::try_from(time_in_force)?;
2861
2862        let requires_trigger_price = matches!(
2863            order_type,
2864            OrderType::StopMarket
2865                | OrderType::StopLimit
2866                | OrderType::MarketIfTouched
2867                | OrderType::LimitIfTouched
2868        );
2869        anyhow::ensure!(
2870            !requires_trigger_price || trigger_price.is_some(),
2871            "Algo order type {order_type:?} requires a trigger price"
2872        );
2873
2874        // Limit orders require time in force
2875        let requires_time_in_force =
2876            matches!(order_type, OrderType::StopLimit | OrderType::LimitIfTouched);
2877
2878        let price_str = price.map(|p| p.to_string());
2879        let trigger_price_str = if matches!(order_type, OrderType::TrailingStopMarket) {
2880            None
2881        } else {
2882            trigger_price.map(|p| p.to_string())
2883        };
2884        let reduce_only = reduce_only_param(reduce_only, position_side);
2885        let client_id_str = encode_broker_id(&client_order_id, BINANCE_NAUTILUS_FUTURES_BROKER_ID);
2886
2887        // closePosition is mutually exclusive with quantity and reduceOnly
2888        let params = if close_position {
2889            BinanceNewAlgoOrderParams {
2890                symbol,
2891                side: binance_side,
2892                order_type: binance_order_type,
2893                algo_type: BinanceAlgoType::Conditional,
2894                position_side,
2895                quantity: None,
2896                price: price_str,
2897                trigger_price: trigger_price_str,
2898                time_in_force: if requires_time_in_force {
2899                    Some(binance_tif)
2900                } else {
2901                    None
2902                },
2903                working_type,
2904                close_position: Some(true),
2905                price_protect: None,
2906                reduce_only: None,
2907                activation_price: activation_price.map(|p| p.to_string()),
2908                callback_rate,
2909                client_algo_id: Some(client_id_str),
2910                good_till_date,
2911                recv_window: None,
2912            }
2913        } else {
2914            let qty_str = quantity.to_string();
2915            BinanceNewAlgoOrderParams {
2916                symbol,
2917                side: binance_side,
2918                order_type: binance_order_type,
2919                algo_type: BinanceAlgoType::Conditional,
2920                position_side,
2921                quantity: Some(qty_str),
2922                price: price_str,
2923                trigger_price: trigger_price_str,
2924                time_in_force: if requires_time_in_force {
2925                    Some(binance_tif)
2926                } else {
2927                    None
2928                },
2929                working_type,
2930                close_position: None,
2931                price_protect: None,
2932                reduce_only,
2933                activation_price: activation_price.map(|p| p.to_string()),
2934                callback_rate,
2935                client_algo_id: Some(client_id_str),
2936                good_till_date,
2937                recv_window: None,
2938            }
2939        };
2940
2941        let order = self.inner.submit_algo_order(&params).await?;
2942        let ts_init = self.clock.get_time_ns();
2943        order.to_order_status_report(
2944            account_id,
2945            instrument_id,
2946            price_precision,
2947            size_precision,
2948            ts_init,
2949        )
2950    }
2951
2952    /// Submits multiple orders in a single request (up to 5 orders).
2953    ///
2954    /// Each order in the batch is processed independently. The response contains
2955    /// the result for each order, which can be either a success or an error.
2956    ///
2957    /// # Errors
2958    ///
2959    /// Returns an error if the batch exceeds 5 orders or the request fails.
2960    pub async fn submit_order_list(
2961        &self,
2962        orders: &[BatchOrderItem],
2963    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
2964        self.inner.submit_order_list(orders).await
2965    }
2966
2967    /// Modifies an existing order (price and quantity only).
2968    ///
2969    /// Either `venue_order_id` or `client_order_id` must be provided.
2970    ///
2971    /// # Errors
2972    ///
2973    /// Returns an error if:
2974    /// - Neither venue_order_id nor client_order_id is provided.
2975    /// - The instrument is not cached.
2976    /// - The request fails.
2977    #[expect(clippy::too_many_arguments)]
2978    pub async fn modify_order(
2979        &self,
2980        account_id: AccountId,
2981        instrument_id: InstrumentId,
2982        venue_order_id: Option<VenueOrderId>,
2983        client_order_id: Option<ClientOrderId>,
2984        order_side: OrderSide,
2985        quantity: Quantity,
2986        price: Price,
2987    ) -> anyhow::Result<OrderStatusReport> {
2988        anyhow::ensure!(
2989            venue_order_id.is_some() || client_order_id.is_some(),
2990            "Either venue_order_id or client_order_id must be provided"
2991        );
2992
2993        let (symbol, price_precision, size_precision) =
2994            self.cached_precisions_by_id(instrument_id)?;
2995
2996        let binance_side = BinanceSide::try_from(order_side)?;
2997
2998        let order_id = venue_order_id
2999            .map(|id| id.inner().parse::<i64>())
3000            .transpose()
3001            .map_err(|_| anyhow::anyhow!("Invalid venue order ID"))?;
3002
3003        let params = BinanceModifyOrderParams {
3004            symbol,
3005            order_id,
3006            orig_client_order_id: client_order_id
3007                .map(|id| encode_broker_id(&id, BINANCE_NAUTILUS_FUTURES_BROKER_ID)),
3008            side: binance_side,
3009            quantity: quantity.to_string(),
3010            price: price.to_string(),
3011            recv_window: None,
3012        };
3013
3014        let order = self.inner.modify_order(&params).await?;
3015        let ts_init = self.clock.get_time_ns();
3016        order.to_order_status_report(
3017            account_id,
3018            instrument_id,
3019            price_precision,
3020            size_precision,
3021            self.treat_expired_as_canceled,
3022            ts_init,
3023        )
3024    }
3025
3026    /// Modifies multiple orders in a single request (up to 5 orders).
3027    ///
3028    /// Each modify in the batch is processed independently. The response contains
3029    /// the result for each modify, which can be either a success or an error.
3030    ///
3031    /// # Errors
3032    ///
3033    /// Returns an error if the batch exceeds 5 orders or the request fails.
3034    pub async fn batch_modify_orders(
3035        &self,
3036        modifies: &[BatchModifyItem],
3037    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
3038        self.inner.batch_modify_orders(modifies).await
3039    }
3040
3041    /// Cancels an order by venue order ID or client order ID.
3042    ///
3043    /// Either `venue_order_id` or `client_order_id` must be provided.
3044    ///
3045    /// # Errors
3046    ///
3047    /// Returns an error if:
3048    /// - Neither venue_order_id nor client_order_id is provided.
3049    /// - The request fails.
3050    pub async fn cancel_order(
3051        &self,
3052        instrument_id: InstrumentId,
3053        venue_order_id: Option<VenueOrderId>,
3054        client_order_id: Option<ClientOrderId>,
3055    ) -> anyhow::Result<VenueOrderId> {
3056        anyhow::ensure!(
3057            venue_order_id.is_some() || client_order_id.is_some(),
3058            "Either venue_order_id or client_order_id must be provided"
3059        );
3060
3061        let symbol = format_binance_symbol(&instrument_id);
3062
3063        let order_id = match venue_order_id {
3064            Some(venue_order_id) => match venue_order_id.inner().parse::<i64>() {
3065                Ok(order_id) => Some(order_id),
3066                Err(e) if client_order_id.is_some() => {
3067                    log::warn!(
3068                        "Unable to parse venue_order_id {venue_order_id} for cancel, canceling by client_order_id: {e}"
3069                    );
3070                    None
3071                }
3072                Err(e) => anyhow::bail!("Invalid venue order ID: {e}"),
3073            },
3074            None => None,
3075        };
3076
3077        let params = BinanceCancelOrderParams {
3078            symbol,
3079            order_id,
3080            orig_client_order_id: client_order_id
3081                .map(|id| encode_broker_id(&id, BINANCE_NAUTILUS_FUTURES_BROKER_ID)),
3082            recv_window: None,
3083        };
3084
3085        let order = self.inner.cancel_order(&params).await?;
3086        Ok(VenueOrderId::new(order.order_id.to_string()))
3087    }
3088
3089    /// Cancels an algo order (conditional order) via the Binance Algo Service.
3090    ///
3091    /// Use the `client_algo_id` which corresponds to the `client_order_id` used
3092    /// when submitting the algo order.
3093    ///
3094    /// # Errors
3095    ///
3096    /// Returns an error if the request fails.
3097    pub async fn cancel_algo_order(&self, client_order_id: ClientOrderId) -> anyhow::Result<()> {
3098        let params = BinanceAlgoOrderQueryParams {
3099            algo_id: None,
3100            client_algo_id: Some(encode_broker_id(
3101                &client_order_id,
3102                BINANCE_NAUTILUS_FUTURES_BROKER_ID,
3103            )),
3104            recv_window: None,
3105        };
3106
3107        let response = self.inner.cancel_algo_order(&params).await?;
3108        let code = response.code.parse::<i64>()?;
3109        if code == 200 {
3110            Ok(())
3111        } else {
3112            Err(BinanceFuturesHttpError::BinanceError {
3113                code,
3114                message: response.msg,
3115                status: 200,
3116                retry_after: None,
3117            }
3118            .into())
3119        }
3120    }
3121
3122    /// Cancels all open orders for a symbol.
3123    ///
3124    /// # Errors
3125    ///
3126    /// Returns an error if the request fails.
3127    pub async fn cancel_all_orders(
3128        &self,
3129        instrument_id: InstrumentId,
3130    ) -> anyhow::Result<Vec<VenueOrderId>> {
3131        let symbol = format_binance_symbol(&instrument_id);
3132
3133        let params = BinanceCancelAllOrdersParams {
3134            symbol,
3135            recv_window: None,
3136        };
3137
3138        let response = self.inner.cancel_all_orders(&params).await?;
3139        if response.code == 200 {
3140            Ok(vec![])
3141        } else {
3142            anyhow::bail!("Cancel all orders failed: {}", response.msg);
3143        }
3144    }
3145
3146    /// Cancels all open algo orders for a symbol.
3147    ///
3148    /// # Errors
3149    ///
3150    /// Returns an error if the request fails.
3151    pub async fn cancel_all_algo_orders(&self, instrument_id: InstrumentId) -> anyhow::Result<()> {
3152        let symbol = format_binance_symbol(&instrument_id);
3153
3154        let params = BinanceCancelAllAlgoOrdersParams {
3155            symbol,
3156            recv_window: None,
3157        };
3158
3159        let response = self.inner.cancel_all_algo_orders(&params).await?;
3160        if response.code == 200 {
3161            Ok(())
3162        } else {
3163            anyhow::bail!("Cancel all algo orders failed: {}", response.msg);
3164        }
3165    }
3166
3167    /// Cancels multiple orders in a single request (up to 10 orders).
3168    ///
3169    /// Each cancel in the batch is processed independently. The response contains
3170    /// the result for each cancel, which can be either a success or an error.
3171    ///
3172    /// # Errors
3173    ///
3174    /// Returns an error if the batch exceeds 10 orders or the request fails.
3175    pub async fn batch_cancel_orders(
3176        &self,
3177        cancels: &[BatchCancelItem],
3178    ) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
3179        self.inner.batch_cancel_orders(cancels).await
3180    }
3181
3182    /// Queries open algo orders (conditional orders).
3183    ///
3184    /// Returns all open algo orders, optionally filtered by symbol.
3185    ///
3186    /// # Errors
3187    ///
3188    /// Returns an error if the request fails.
3189    pub async fn query_open_algo_orders(
3190        &self,
3191        instrument_id: Option<InstrumentId>,
3192    ) -> BinanceFuturesHttpResult<Vec<BinanceFuturesAlgoOrder>> {
3193        let symbol = instrument_id.map(|id| format_binance_symbol(&id));
3194
3195        let params = BinanceOpenAlgoOrdersParams {
3196            symbol,
3197            recv_window: None,
3198        };
3199
3200        self.inner.query_open_algo_orders(&params).await
3201    }
3202
3203    /// Queries a single algo order by client_order_id.
3204    ///
3205    /// # Errors
3206    ///
3207    /// Returns an error if the request fails.
3208    pub async fn query_algo_order(
3209        &self,
3210        client_order_id: ClientOrderId,
3211    ) -> BinanceFuturesHttpResult<BinanceFuturesAlgoOrder> {
3212        let params = BinanceAlgoOrderQueryParams {
3213            algo_id: None,
3214            client_algo_id: Some(encode_broker_id(
3215                &client_order_id,
3216                BINANCE_NAUTILUS_FUTURES_BROKER_ID,
3217            )),
3218            recv_window: None,
3219        };
3220
3221        self.inner.query_algo_order(&params).await
3222    }
3223
3224    /// Queries a single algo order by venue order ID.
3225    ///
3226    /// # Errors
3227    ///
3228    /// Returns an error if the venue order ID is not numeric or the request fails.
3229    pub async fn query_algo_order_by_venue_order_id(
3230        &self,
3231        venue_order_id: VenueOrderId,
3232    ) -> BinanceFuturesHttpResult<BinanceFuturesAlgoOrder> {
3233        let algo_id = venue_order_id
3234            .inner()
3235            .parse::<i64>()
3236            .map_err(|e| BinanceFuturesHttpError::ValidationError(e.to_string()))?;
3237        let params = BinanceAlgoOrderQueryParams {
3238            algo_id: Some(algo_id),
3239            client_algo_id: None,
3240            recv_window: None,
3241        };
3242
3243        self.inner.query_algo_order(&params).await
3244    }
3245
3246    async fn query_historical_algo_order_by_venue_order_id(
3247        &self,
3248        instrument_id: InstrumentId,
3249        venue_order_id: VenueOrderId,
3250    ) -> BinanceFuturesHttpResult<Option<BinanceFuturesAlgoOrder>> {
3251        let algo_id = venue_order_id
3252            .inner()
3253            .parse::<i64>()
3254            .map_err(|e| BinanceFuturesHttpError::ValidationError(e.to_string()))?;
3255        let symbol = format_binance_symbol(&instrument_id);
3256        let params = BinanceAllAlgoOrdersParams {
3257            symbol,
3258            algo_id: Some(algo_id),
3259            start_time: None,
3260            end_time: None,
3261            page: None,
3262            limit: Some(1),
3263            recv_window: None,
3264        };
3265        let order = self
3266            .inner
3267            .query_all_algo_orders(&params)
3268            .await?
3269            .into_iter()
3270            .next()
3271            .filter(|order| order.algo_id == algo_id);
3272
3273        Ok(order)
3274    }
3275
3276    /// Queries an algo order by venue ID, falling back to recent history when needed.
3277    ///
3278    /// Uses the client order ID only when no venue order ID is available.
3279    /// Matching-engine details are best-effort; remote enrichment failures fall back to the
3280    /// Algo Service execution fields.
3281    ///
3282    /// # Errors
3283    ///
3284    /// Returns an error if an ID is invalid, the Algo Service request fails, or matching-engine
3285    /// enrichment fails because of a local configuration or validation error.
3286    pub async fn query_algo_order_with_history(
3287        &self,
3288        instrument_id: InstrumentId,
3289        client_order_id: Option<ClientOrderId>,
3290        algo_venue_order_id: Option<VenueOrderId>,
3291    ) -> BinanceFuturesHttpResult<Option<BinanceFuturesAlgoOrderQueryResult>> {
3292        let order = if let Some(venue_order_id) = algo_venue_order_id {
3293            match self
3294                .query_algo_order_by_venue_order_id(venue_order_id)
3295                .await
3296            {
3297                Ok(order) => Some(order),
3298                Err(BinanceFuturesHttpError::BinanceError {
3299                    code: BINANCE_NO_SUCH_ORDER_CODE,
3300                    ..
3301                }) => {
3302                    self.query_historical_algo_order_by_venue_order_id(
3303                        instrument_id,
3304                        venue_order_id,
3305                    )
3306                    .await?
3307                }
3308                Err(e) => return Err(e),
3309            }
3310        } else {
3311            let Some(client_order_id) = client_order_id else {
3312                return Ok(None);
3313            };
3314
3315            match self.query_algo_order(client_order_id).await {
3316                Ok(order) => Some(order),
3317                Err(BinanceFuturesHttpError::BinanceError {
3318                    code: BINANCE_NO_SUCH_ORDER_CODE,
3319                    ..
3320                }) => None,
3321                Err(e) => return Err(e),
3322            }
3323        };
3324
3325        let Some(order) = order else {
3326            return Ok(None);
3327        };
3328
3329        let actual = if let Some(actual_order_id) = order
3330            .actual_order_id
3331            .as_deref()
3332            .filter(|id| !id.is_empty())
3333            .map(str::parse::<i64>)
3334            .transpose()
3335            .map_err(|e| BinanceFuturesHttpError::ValidationError(e.to_string()))?
3336        {
3337            self.query_algo_order_actual(instrument_id, actual_order_id)
3338                .await?
3339        } else {
3340            None
3341        };
3342
3343        Ok(Some(BinanceFuturesAlgoOrderQueryResult {
3344            algo: order,
3345            actual,
3346        }))
3347    }
3348
3349    pub(crate) async fn query_algo_order_actual(
3350        &self,
3351        instrument_id: InstrumentId,
3352        actual_order_id: i64,
3353    ) -> BinanceFuturesHttpResult<Option<BinanceFuturesOrder>> {
3354        let params = BinanceOrderQueryParams {
3355            symbol: format_binance_symbol(&instrument_id),
3356            order_id: Some(actual_order_id),
3357            orig_client_order_id: None,
3358            recv_window: None,
3359        };
3360
3361        let actual = match self.inner.query_order(&params).await {
3362            Ok(actual) => Some(actual),
3363            Err(
3364                e @ (BinanceFuturesHttpError::MissingCredentials
3365                | BinanceFuturesHttpError::ValidationError(_)),
3366            ) => return Err(e),
3367            Err(e) => {
3368                log::warn!(
3369                    "Failed to enrich algo order with matching-engine order \
3370                     {actual_order_id}: {e}; falling back to Algo Service execution fields"
3371                );
3372                None
3373            }
3374        };
3375
3376        Ok(actual)
3377    }
3378
3379    /// Requests the current account state.
3380    ///
3381    /// # Errors
3382    ///
3383    /// Returns an error if the request fails or parsing fails.
3384    pub async fn request_account_state(
3385        &self,
3386        account_id: AccountId,
3387    ) -> anyhow::Result<AccountState> {
3388        let ts_init = UnixNanos::default();
3389        let account_info = self.inner.query_account().await?;
3390        account_info.to_account_state(account_id, ts_init)
3391    }
3392
3393    /// Requests a single order status report.
3394    ///
3395    /// Either `venue_order_id` or `client_order_id` must be provided.
3396    ///
3397    /// # Errors
3398    ///
3399    /// Returns an error if the request fails or parsing fails.
3400    pub async fn request_order_status_report(
3401        &self,
3402        account_id: AccountId,
3403        instrument_id: InstrumentId,
3404        venue_order_id: Option<VenueOrderId>,
3405        client_order_id: Option<ClientOrderId>,
3406    ) -> anyhow::Result<OrderStatusReport> {
3407        anyhow::ensure!(
3408            venue_order_id.is_some() || client_order_id.is_some(),
3409            "Either venue_order_id or client_order_id must be provided"
3410        );
3411
3412        let (symbol, price_precision, size_precision) =
3413            self.cached_precisions_by_id(instrument_id)?;
3414
3415        let order_id = venue_order_id
3416            .map(|id| id.inner().parse::<i64>())
3417            .transpose()
3418            .map_err(|_| anyhow::anyhow!("Invalid venue order ID"))?;
3419
3420        let orig_client_order_id =
3421            client_order_id.map(|id| encode_broker_id(&id, BINANCE_NAUTILUS_FUTURES_BROKER_ID));
3422
3423        let params = BinanceOrderQueryParams {
3424            symbol,
3425            order_id,
3426            orig_client_order_id,
3427            recv_window: None,
3428        };
3429
3430        let order = self.inner.query_order(&params).await?;
3431        let ts_init = self.clock.get_time_ns();
3432        order.to_order_status_report(
3433            account_id,
3434            instrument_id,
3435            price_precision,
3436            size_precision,
3437            self.treat_expired_as_canceled,
3438            ts_init,
3439        )
3440    }
3441
3442    /// Requests order status reports for open orders.
3443    ///
3444    /// If `instrument_id` is None, returns all open orders.
3445    ///
3446    /// # Errors
3447    ///
3448    /// Returns an error if the request fails or parsing fails.
3449    pub async fn request_order_status_reports(
3450        &self,
3451        account_id: AccountId,
3452        instrument_id: Option<InstrumentId>,
3453        open_only: bool,
3454    ) -> anyhow::Result<Vec<OrderStatusReport>> {
3455        let symbol = instrument_id.map(|id| format_binance_symbol(&id));
3456
3457        let orders = if open_only {
3458            let params = BinanceOpenOrdersParams {
3459                symbol: symbol.clone(),
3460                recv_window: None,
3461            };
3462            self.inner.query_open_orders(&params).await?
3463        } else {
3464            // For historical orders, symbol is required
3465            let symbol = symbol.ok_or_else(|| {
3466                anyhow::anyhow!("instrument_id is required for historical orders")
3467            })?;
3468            let params = BinanceAllOrdersParams {
3469                symbol,
3470                order_id: None,
3471                start_time: None,
3472                end_time: None,
3473                limit: None,
3474                recv_window: None,
3475            };
3476            self.inner.query_all_orders(&params).await?
3477        };
3478
3479        let ts_init = self.clock.get_time_ns();
3480        let mut reports = Vec::with_capacity(orders.len());
3481
3482        for order in orders {
3483            let order_instrument_id = instrument_id
3484                .unwrap_or_else(|| format_instrument_id(&order.symbol, self.product_type));
3485            let (_, price_precision, size_precision) =
3486                self.cached_precisions_by_id(order_instrument_id)?;
3487
3488            match order.to_order_status_report(
3489                account_id,
3490                order_instrument_id,
3491                price_precision,
3492                size_precision,
3493                self.treat_expired_as_canceled,
3494                ts_init,
3495            ) {
3496                Ok(report) => reports.push(report),
3497                Err(e) => {
3498                    log::warn!("Failed to parse order status report: {e}");
3499                }
3500            }
3501        }
3502
3503        Ok(reports)
3504    }
3505
3506    /// Requests fill reports for a symbol.
3507    ///
3508    /// # Errors
3509    ///
3510    /// Returns an error if the request fails or parsing fails.
3511    #[expect(clippy::too_many_arguments)]
3512    pub async fn request_fill_reports(
3513        &self,
3514        account_id: AccountId,
3515        instrument_id: InstrumentId,
3516        venue_order_id: Option<VenueOrderId>,
3517        start: Option<i64>,
3518        end: Option<i64>,
3519        limit: Option<u32>,
3520        bnfcr_currency: Currency,
3521    ) -> anyhow::Result<Vec<FillReport>> {
3522        let (symbol, price_precision, size_precision) =
3523            self.cached_precisions_by_id(instrument_id)?;
3524
3525        let order_id = venue_order_id
3526            .map(|id| id.inner().parse::<i64>())
3527            .transpose()
3528            .map_err(|_| anyhow::anyhow!("Invalid venue order ID"))?;
3529
3530        let params = BinanceUserTradesParams {
3531            symbol,
3532            order_id,
3533            start_time: start,
3534            end_time: end,
3535            from_id: None,
3536            limit,
3537            recv_window: None,
3538        };
3539
3540        let trades = self.inner.query_user_trades(&params).await?;
3541
3542        let ts_init = self.clock.get_time_ns();
3543        let mut reports = Vec::with_capacity(trades.len());
3544
3545        for trade in trades {
3546            match trade.to_fill_report(
3547                account_id,
3548                instrument_id,
3549                price_precision,
3550                size_precision,
3551                bnfcr_currency,
3552                ts_init,
3553            ) {
3554                Ok(report) => reports.push(report),
3555                Err(e) => {
3556                    log::warn!("Failed to parse fill report: {e}");
3557                }
3558            }
3559        }
3560
3561        Ok(reports)
3562    }
3563
3564    /// Requests recent public trades for an instrument.
3565    ///
3566    /// # Errors
3567    ///
3568    /// Returns an error if the request fails, instrument is not cached, or parsing fails.
3569    pub async fn request_trades(
3570        &self,
3571        instrument_id: InstrumentId,
3572        limit: Option<u32>,
3573    ) -> anyhow::Result<Vec<TradeTick>> {
3574        let (symbol, price_precision, size_precision) =
3575            self.cached_precisions_by_id(instrument_id)?;
3576
3577        let params = BinanceTradesParams { symbol, limit };
3578
3579        let trades = self.inner.trades(&params).await?;
3580        let ts_init = UnixNanos::default();
3581
3582        let mut result = Vec::with_capacity(trades.len());
3583        for trade in trades {
3584            let tick = parse_futures_trade_tick(
3585                &trade,
3586                instrument_id,
3587                price_precision,
3588                size_precision,
3589                ts_init,
3590            )?;
3591            result.push(tick);
3592        }
3593
3594        Ok(result)
3595    }
3596
3597    /// Requests bounded aggregate public trades for an instrument.
3598    ///
3599    /// # Errors
3600    ///
3601    /// Returns an error if a supplied time bound is invalid or parsing fails.
3602    pub async fn request_agg_trades(
3603        &self,
3604        instrument_id: InstrumentId,
3605        start: Option<Timestamp>,
3606        end: Option<Timestamp>,
3607        limit: Option<u32>,
3608    ) -> anyhow::Result<Vec<TradeTick>> {
3609        let cutoff = self.clock.get_time_ns().to_datetime_utc() - SignedDuration::from_hours(48);
3610        anyhow::ensure!(
3611            start.as_ref().is_none_or(|value| value >= &cutoff)
3612                && end.as_ref().is_none_or(|value| value >= &cutoff),
3613            "Binance Futures aggregate trade history is limited to the past 48 hours"
3614        );
3615        let (symbol, price_precision, size_precision) =
3616            self.cached_precisions_by_id(instrument_id)?;
3617        let params = BinanceAggTradesParams {
3618            symbol,
3619            from_id: None,
3620            start_time: start.map(|value| value.as_millisecond()),
3621            end_time: end.map(|value| value.as_millisecond()),
3622            limit,
3623        };
3624        let trades = self.inner.agg_trades(&params).await?;
3625        trades
3626            .iter()
3627            .map(|trade| {
3628                let ts_init = parse_millis(trade.time, "Futures aggregate trade time")?;
3629                parse_futures_agg_trade_tick(
3630                    trade,
3631                    instrument_id,
3632                    price_precision,
3633                    size_precision,
3634                    ts_init,
3635                )
3636            })
3637            .collect()
3638    }
3639
3640    /// Requests bar (kline/candlestick) data for an instrument.
3641    ///
3642    /// # Errors
3643    ///
3644    /// Returns an error if the bar type is not supported, instrument is not cached,
3645    /// or the request fails.
3646    pub async fn request_binance_bars(
3647        &self,
3648        bar_type: BarType,
3649        start: Option<Timestamp>,
3650        end: Option<Timestamp>,
3651        limit: Option<u32>,
3652    ) -> anyhow::Result<Vec<BinanceBar>> {
3653        anyhow::ensure!(
3654            bar_type.aggregation_source() == AggregationSource::External,
3655            "Only EXTERNAL aggregation is supported"
3656        );
3657
3658        let spec = bar_type.spec();
3659        let step = spec.step.get();
3660        let interval = match spec.aggregation {
3661            BarAggregation::Second => {
3662                anyhow::bail!("Binance Futures does not support second-level kline intervals")
3663            }
3664            BarAggregation::Minute => format!("{step}m"),
3665            BarAggregation::Hour => format!("{step}h"),
3666            BarAggregation::Day => format!("{step}d"),
3667            BarAggregation::Week => format!("{step}w"),
3668            BarAggregation::Month => format!("{step}M"),
3669            a => anyhow::bail!("Binance Futures does not support {a:?} aggregation"),
3670        };
3671
3672        let instrument_id = bar_type.instrument_id();
3673        let (symbol, price_precision, size_precision) =
3674            self.cached_precisions_by_id(instrument_id)?;
3675
3676        let params = BinanceKlinesParams {
3677            symbol,
3678            interval,
3679            start_time: start.map(|dt| dt.as_millisecond()),
3680            end_time: end.map(|dt| dt.as_millisecond()),
3681            limit,
3682        };
3683
3684        let klines = self.inner.klines(&params).await?;
3685        let now = self.clock.get_time_ns();
3686
3687        let mut result = Vec::with_capacity(klines.len());
3688        for kline in klines {
3689            let ts_init = parse_millis(kline.close_time, "Futures kline close time")?;
3690            let bar = parse_futures_kline_binance_bar(
3691                &kline,
3692                bar_type,
3693                price_precision,
3694                size_precision,
3695                ts_init,
3696            )?;
3697
3698            if bar.ts_event < now {
3699                result.push(bar);
3700            }
3701        }
3702
3703        Ok(result)
3704    }
3705
3706    /// Requests core bars for an instrument.
3707    ///
3708    /// # Errors
3709    ///
3710    /// Returns an error if the bar type is unsupported or the request fails.
3711    pub async fn request_bars(
3712        &self,
3713        bar_type: BarType,
3714        start: Option<Timestamp>,
3715        end: Option<Timestamp>,
3716        limit: Option<u32>,
3717    ) -> anyhow::Result<Vec<Bar>> {
3718        Ok(self
3719            .request_binance_bars(bar_type, start, end, limit)
3720            .await?
3721            .into_iter()
3722            .map(|bar| bar.bar())
3723            .collect())
3724    }
3725
3726    /// Requests an explicit L2 order-book snapshot.
3727    ///
3728    /// # Errors
3729    ///
3730    /// Returns an error if the depth is invalid, the instrument is missing, the request fails, or a
3731    /// level is invalid.
3732    pub async fn request_book_snapshot(
3733        &self,
3734        instrument_id: InstrumentId,
3735        depth: Option<u32>,
3736    ) -> anyhow::Result<OrderBook> {
3737        self.request_book_snapshot_with_permit(instrument_id, depth, None)
3738            .await
3739    }
3740
3741    pub(crate) async fn request_book_snapshot_with_permit(
3742        &self,
3743        instrument_id: InstrumentId,
3744        depth: Option<u32>,
3745        permit: Option<SnapshotPermit>,
3746    ) -> anyhow::Result<OrderBook> {
3747        if depth.is_some_and(|value| !crate::common::consts::BINANCE_BOOK_DEPTHS.contains(&value)) {
3748            anyhow::bail!(
3749                "invalid Binance Futures order-book depth; valid values are {:?}",
3750                crate::common::consts::BINANCE_BOOK_DEPTHS
3751            );
3752        }
3753        let (symbol, price_precision, size_precision) =
3754            self.cached_precisions_by_id(instrument_id)?;
3755        let params = BinanceDepthParams {
3756            symbol,
3757            limit: depth,
3758        };
3759
3760        let snapshot = match permit {
3761            Some(permit) => self.inner.depth_paced(&params, permit).await?,
3762            None => self.inner.depth(&params).await?,
3763        };
3764
3765        let ts_event = self.clock.get_time_ns();
3766        let sequence = u64::try_from(snapshot.last_update_id)
3767            .map_err(|_| anyhow::anyhow!("invalid negative order-book update ID"))?;
3768        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
3769        for (index, level) in snapshot.bids.iter().enumerate() {
3770            let order = BookOrder::new(
3771                OrderSide::Buy,
3772                parse_required_price_at_precision(&level.0, price_precision, "bid price")?,
3773                parse_required_quantity_at_precision(&level.1, size_precision, "bid quantity")?,
3774                index as u64,
3775            );
3776            book.add(order, 0, sequence, ts_event);
3777        }
3778        let bid_count = snapshot.bids.len();
3779        for (index, level) in snapshot.asks.iter().enumerate() {
3780            let order = BookOrder::new(
3781                OrderSide::Sell,
3782                parse_required_price_at_precision(&level.0, price_precision, "ask price")?,
3783                parse_required_quantity_at_precision(&level.1, size_precision, "ask quantity")?,
3784                (bid_count + index) as u64,
3785            );
3786            book.add(order, 0, sequence, ts_event);
3787        }
3788        Ok(book)
3789    }
3790
3791    fn cached_precisions_by_id(
3792        &self,
3793        instrument_id: InstrumentId,
3794    ) -> anyhow::Result<(String, u8, u8)> {
3795        let symbol = format_binance_symbol(&instrument_id);
3796        let instrument = self.instrument_metadata(instrument_id)?;
3797        let (price_precision, size_precision) = instrument.precisions()?;
3798
3799        Ok((symbol, price_precision, size_precision))
3800    }
3801
3802    pub(crate) fn instrument_metadata(
3803        &self,
3804        instrument_id: InstrumentId,
3805    ) -> anyhow::Result<BinanceFuturesInstrument> {
3806        let symbol = format_binance_symbol(&instrument_id);
3807        let instrument = self
3808            .instruments
3809            .get(&Ustr::from(symbol.as_str()))
3810            .map(|instrument| instrument.value().clone())
3811            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
3812        if instrument.id() != instrument_id {
3813            return Err(InstrumentLookupError::not_found(instrument_id).into());
3814        }
3815
3816        Ok(instrument)
3817    }
3818
3819    /// Requests historical funding rates for an instrument.
3820    ///
3821    /// # Errors
3822    ///
3823    /// Returns an error if the request fails or parsing fails.
3824    pub async fn request_funding_rates(
3825        &self,
3826        instrument_id: InstrumentId,
3827        start: Option<Timestamp>,
3828        end: Option<Timestamp>,
3829        limit: Option<u32>,
3830    ) -> anyhow::Result<Vec<FundingRateUpdate>> {
3831        let params = BinanceFundingRateParams {
3832            symbol: Some(format_binance_symbol(&instrument_id)),
3833            start_time: start.map(|dt| dt.as_millisecond()),
3834            end_time: end.map(|dt| dt.as_millisecond()),
3835            limit,
3836        };
3837
3838        let rates = self.inner.funding_rate(&params).await?;
3839        let mut result = Vec::with_capacity(rates.len());
3840        for rate in rates {
3841            result.push(parse_futures_funding_rate_update(&rate, instrument_id)?);
3842        }
3843
3844        Ok(result)
3845    }
3846}
3847
3848fn identity_lookup_error(error: BinanceFuturesHttpError) -> BinanceFuturesHttpError {
3849    match error {
3850        BinanceFuturesHttpError::RateLimitBlocked => error,
3851        _ => BinanceFuturesHttpError::IdentityLookup(Box::new(error)),
3852    }
3853}
3854
3855fn missing_order_lookup_error(error: &BinanceFuturesHttpError) -> Option<BatchOrderError> {
3856    let BinanceFuturesHttpError::IdentityLookup(source) = error else {
3857        return None;
3858    };
3859
3860    match source.as_ref() {
3861        BinanceFuturesHttpError::BinanceError {
3862            code: BINANCE_NO_SUCH_ORDER_CODE,
3863            message,
3864            ..
3865        } => Some(BatchOrderError {
3866            code: BINANCE_NO_SUCH_ORDER_CODE,
3867            msg: message.clone(),
3868            not_sent: true,
3869        }),
3870        _ => None,
3871    }
3872}
3873
3874fn merge_batch_results(
3875    results: Vec<Option<BatchOrderResult>>,
3876    responses: Vec<BatchOrderResult>,
3877) -> BinanceFuturesHttpResult<Vec<BatchOrderResult>> {
3878    if results.iter().filter(|result| result.is_none()).count() != responses.len() {
3879        return Err(BinanceFuturesHttpError::JsonError(
3880            "Batch response length does not match submitted orders".to_string(),
3881        ));
3882    }
3883
3884    let mut responses = responses.into_iter();
3885    Ok(results
3886        .into_iter()
3887        .filter_map(|result| result.or_else(|| responses.next()))
3888        .collect())
3889}
3890
3891fn parse_futures_trade_tick(
3892    trade: &BinanceFuturesTrade,
3893    instrument_id: InstrumentId,
3894    price_precision: u8,
3895    size_precision: u8,
3896    ts_init: UnixNanos,
3897) -> anyhow::Result<TradeTick> {
3898    let price = parse_required_price_at_precision(&trade.price, price_precision, "trade.price")
3899        .map_err(|e| anyhow::anyhow!("invalid Futures trade id {}: {e}", trade.id))?;
3900    let size = parse_required_quantity_at_precision(&trade.qty, size_precision, "trade.qty")
3901        .map_err(|e| anyhow::anyhow!("invalid Futures trade id {}: {e}", trade.id))?;
3902    let ts_event = parse_millis(trade.time, "Futures trade time")?;
3903
3904    let aggressor_side = if trade.is_buyer_maker {
3905        AggressorSide::Sell
3906    } else {
3907        AggressorSide::Buy
3908    };
3909
3910    Ok(TradeTick::new(
3911        instrument_id,
3912        price,
3913        size,
3914        aggressor_side,
3915        TradeId::new(trade.id.to_string()),
3916        ts_event,
3917        ts_init,
3918    ))
3919}
3920
3921fn parse_futures_agg_trade_tick(
3922    trade: &BinanceFuturesAggTrade,
3923    instrument_id: InstrumentId,
3924    price_precision: u8,
3925    size_precision: u8,
3926    ts_init: UnixNanos,
3927) -> anyhow::Result<TradeTick> {
3928    let trade = BinanceFuturesTrade {
3929        id: trade.id,
3930        price: trade.price.clone(),
3931        qty: trade.qty.clone(),
3932        quote_qty: String::new(),
3933        time: trade.time,
3934        is_buyer_maker: trade.is_buyer_maker,
3935    };
3936    parse_futures_trade_tick(
3937        &trade,
3938        instrument_id,
3939        price_precision,
3940        size_precision,
3941        ts_init,
3942    )
3943}
3944
3945fn parse_futures_kline_binance_bar(
3946    kline: &BinanceFuturesKline,
3947    bar_type: BarType,
3948    price_precision: u8,
3949    size_precision: u8,
3950    ts_init: UnixNanos,
3951) -> anyhow::Result<BinanceBar> {
3952    let open = parse_required_price_at_precision(&kline.open, price_precision, "kline.open")
3953        .map_err(|e| anyhow::anyhow!("invalid Futures kline {}: {e}", kline.open_time))?;
3954    let high = parse_required_price_at_precision(&kline.high, price_precision, "kline.high")
3955        .map_err(|e| anyhow::anyhow!("invalid Futures kline {}: {e}", kline.open_time))?;
3956    let low = parse_required_price_at_precision(&kline.low, price_precision, "kline.low")
3957        .map_err(|e| anyhow::anyhow!("invalid Futures kline {}: {e}", kline.open_time))?;
3958    let close = parse_required_price_at_precision(&kline.close, price_precision, "kline.close")
3959        .map_err(|e| anyhow::anyhow!("invalid Futures kline {}: {e}", kline.open_time))?;
3960    let volume =
3961        parse_required_quantity_at_precision(&kline.volume, size_precision, "kline.volume")
3962            .map_err(|e| anyhow::anyhow!("invalid Futures kline {}: {e}", kline.open_time))?;
3963    let ts_event = parse_millis(kline.close_time, "Futures kline close time")?;
3964
3965    let quote_volume = kline.quote_volume.parse::<Decimal>().map_err(|e| {
3966        anyhow::anyhow!(
3967            "invalid Futures kline {} quote volume: {e}",
3968            kline.open_time
3969        )
3970    })?;
3971    let taker_buy_base_volume = kline
3972        .taker_buy_base_volume
3973        .parse::<Decimal>()
3974        .map_err(|e| {
3975            anyhow::anyhow!(
3976                "invalid Futures kline {} taker buy base volume: {e}",
3977                kline.open_time
3978            )
3979        })?;
3980    let taker_buy_quote_volume = kline
3981        .taker_buy_quote_volume
3982        .parse::<Decimal>()
3983        .map_err(|e| {
3984            anyhow::anyhow!(
3985                "invalid Futures kline {} taker buy quote volume: {e}",
3986                kline.open_time
3987            )
3988        })?;
3989    let count = u64::try_from(kline.num_trades).map_err(|_| {
3990        anyhow::anyhow!(
3991            "invalid Futures kline {} negative trade count",
3992            kline.open_time
3993        )
3994    })?;
3995
3996    Ok(BinanceBar::new(
3997        bar_type,
3998        open,
3999        high,
4000        low,
4001        close,
4002        volume,
4003        quote_volume,
4004        count,
4005        taker_buy_base_volume,
4006        taker_buy_quote_volume,
4007        ts_event,
4008        ts_init,
4009    ))
4010}
4011
4012fn parse_futures_funding_rate_update(
4013    rate: &BinanceFundingRate,
4014    instrument_id: InstrumentId,
4015) -> anyhow::Result<FundingRateUpdate> {
4016    let funding_rate = rate.funding_rate.parse::<Decimal>().map_err(|e| {
4017        anyhow::anyhow!("invalid Futures funding rate at {}: {e}", rate.funding_time)
4018    })?;
4019
4020    let ts_event = parse_millis(rate.funding_time, "Futures funding time")?;
4021    Ok(FundingRateUpdate::new(
4022        instrument_id,
4023        funding_rate,
4024        None, // Funding interval is not provided by the history endpoint
4025        None, // Next funding time is not provided by the history endpoint
4026        ts_event,
4027        ts_event,
4028    ))
4029}
4030
4031fn validate_reconciliation_instrument(
4032    instruments: &mut AHashMap<InstrumentId, InstrumentAny>,
4033    expected_id: InstrumentId,
4034    instrument: &InstrumentAny,
4035) -> BinanceFuturesHttpResult<()> {
4036    let parsed_id = instrument.id();
4037    if parsed_id != expected_id {
4038        return Err(BinanceFuturesHttpError::ValidationError(format!(
4039            "Parsed Binance Futures instrument ID {parsed_id} does not match expected ID {expected_id}"
4040        )));
4041    }
4042
4043    if instruments.insert(parsed_id, instrument.clone()).is_some() {
4044        return Err(BinanceFuturesHttpError::ValidationError(format!(
4045            "Duplicate parsed Binance Futures instrument ID {parsed_id}"
4046        )));
4047    }
4048
4049    Ok(())
4050}
4051
4052fn log_futures_instrument_parse_error(
4053    config: &BinanceInstrumentProviderConfig,
4054    selector: &BinanceInstrumentSelector,
4055    instrument_id: InstrumentId,
4056    symbol: &str,
4057    error: &anyhow::Error,
4058) {
4059    let explicit = selector.is_explicit(instrument_id, symbol);
4060    if should_warn_on_instrument_parse_error(config.log_warnings, explicit, error) {
4061        log::warn!("Skipping Binance Futures instrument {symbol}: {error}");
4062    } else {
4063        log::debug!("Skipping Binance Futures instrument {symbol}: {error}");
4064    }
4065}
4066
4067/// Checks if an order type requires the Binance Algo Service API.
4068///
4069/// As of 2025-12-09, Binance migrated conditional order types to the Algo Service API.
4070/// The traditional `/fapi/v1/order` endpoint returns error `-4120` for these types.
4071#[must_use]
4072pub fn is_algo_order_type(order_type: OrderType) -> bool {
4073    matches!(
4074        order_type,
4075        OrderType::StopMarket
4076            | OrderType::StopLimit
4077            | OrderType::MarketIfTouched
4078            | OrderType::LimitIfTouched
4079            | OrderType::TrailingStopMarket
4080    )
4081}
4082
4083/// Converts a Nautilus order type to a Binance Futures order type.
4084pub(crate) fn order_type_to_binance_futures(
4085    order_type: OrderType,
4086) -> anyhow::Result<BinanceFuturesOrderType> {
4087    match order_type {
4088        OrderType::Market => Ok(BinanceFuturesOrderType::Market),
4089        OrderType::Limit => Ok(BinanceFuturesOrderType::Limit),
4090        OrderType::StopMarket => Ok(BinanceFuturesOrderType::StopMarket),
4091        OrderType::StopLimit => Ok(BinanceFuturesOrderType::Stop),
4092        OrderType::MarketIfTouched => Ok(BinanceFuturesOrderType::TakeProfitMarket),
4093        OrderType::LimitIfTouched => Ok(BinanceFuturesOrderType::TakeProfit),
4094        OrderType::TrailingStopMarket => Ok(BinanceFuturesOrderType::TrailingStopMarket),
4095        _ => anyhow::bail!("Unsupported order type for Binance Futures: {order_type:?}"),
4096    }
4097}
4098
4099#[cfg(test)]
4100mod tests {
4101    use std::sync::atomic::{AtomicUsize, Ordering};
4102
4103    use axum::{Router, http::Method, response::IntoResponse, routing::any};
4104    use nautilus_core::time::get_atomic_clock_realtime;
4105    use nautilus_live::execution::failure::CommandFailure;
4106    use nautilus_model::enums::OrderStatus;
4107    use nautilus_network::http::{HttpStatus, StatusCode};
4108    use nautilus_testkit::http::assert_http_redirect_rejected;
4109    use rstest::rstest;
4110    use tokio_util::bytes::Bytes;
4111
4112    use super::*;
4113    use crate::common::{enums::BinanceTradingStatus, failure::classify_futures_http_failure};
4114
4115    #[rstest]
4116    #[case::usd_regular(
4117        BinanceProductType::UsdM,
4118        false,
4119        "BTCUSDT-PERP.BINANCE",
4120        "BTCUSDT",
4121        "/fapi/v1/"
4122    )]
4123    #[case::usd_algo(
4124        BinanceProductType::UsdM,
4125        true,
4126        "BTCUSDT-PERP.BINANCE",
4127        "BTCUSDT",
4128        "/fapi/v1/"
4129    )]
4130    #[case::coin_regular(
4131        BinanceProductType::CoinM,
4132        false,
4133        "BTCUSD_PERP.BINANCE",
4134        "BTCUSD_PERP",
4135        "/dapi/v1/"
4136    )]
4137    #[tokio::test]
4138    async fn test_order_history_pages_with_fixed_cutoff(
4139        #[case] product: BinanceProductType,
4140        #[case] page_algo: bool,
4141        #[case] instrument: &str,
4142        #[case] symbol: &str,
4143        #[case] prefix: &str,
4144    ) {
4145        let captured = Arc::new(parking_lot::Mutex::new(Vec::new()));
4146        let app = Router::new()
4147            .fallback(any(order_history_response))
4148            .with_state((page_algo, captured.clone()));
4149
4150        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4151        let url = format!("http://{}", listener.local_addr().unwrap());
4152
4153        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4154        let client = BinanceFuturesHttpClient::new(
4155            product,
4156            BinanceEnvironment::Live,
4157            get_atomic_clock_realtime(),
4158            Some("key".into()),
4159            Some("secret".into()),
4160            Some(url),
4161            None,
4162            Some(1),
4163            None,
4164            false,
4165        )
4166        .unwrap();
4167
4168        let (orders, algos) = client
4169            .query_order_history(
4170                InstrumentId::from(instrument),
4171                10_000_000.into(),
4172                20_000_000.into(),
4173            )
4174            .await
4175            .unwrap();
4176        let instrument_id = InstrumentId::from(instrument);
4177
4178        let report = orders[&8_886_774]
4179            .to_order_status_report(
4180                "BINANCE-001".into(),
4181                instrument_id,
4182                2,
4183                if product == BinanceProductType::CoinM {
4184                    0
4185                } else {
4186                    3
4187                },
4188                false,
4189                20_000_000.into(),
4190            )
4191            .unwrap();
4192
4193        let qty = if product == BinanceProductType::CoinM {
4194            Quantity::from("1")
4195        } else {
4196            Quantity::from("0.001")
4197        };
4198
4199        let requests = captured.lock();
4200
4201        let paged_endpoint = if page_algo {
4202            "allAlgoOrders"
4203        } else {
4204            "allOrders"
4205        };
4206
4207        let pages: Vec<_> = requests
4208            .iter()
4209            .filter(|(path, _)| path.ends_with(paged_endpoint))
4210            .collect();
4211
4212        let cursor = if page_algo { "algoId" } else { "orderId" };
4213
4214        assert_eq!(report.instrument_id, instrument_id);
4215        assert_eq!(report.venue_order_id, VenueOrderId::from("8886774"));
4216        assert_eq!(
4217            report.client_order_id,
4218            Some(ClientOrderId::from("testOrder123"))
4219        );
4220        assert_eq!(report.order_status, OrderStatus::Filled);
4221        assert_eq!(report.quantity, qty);
4222        assert_eq!(report.filled_qty, qty);
4223        assert_eq!(report.avg_px, Some(rust_decimal_macros::dec!(50000)));
4224        assert_eq!(orders.len(), if page_algo { 1 } else { 1_001 });
4225        assert_eq!(orders[&8_886_774].symbol.as_str(), symbol);
4226        assert_eq!(orders[&8_886_774].order_id, 8_886_774);
4227        assert_eq!(
4228            algos.len(),
4229            if product == BinanceProductType::CoinM {
4230                0
4231            } else if page_algo {
4232                1_001
4233            } else {
4234                1
4235            }
4236        );
4237        assert_eq!(pages.len(), 2);
4238        assert!(!pages[0].1.contains_key(cursor));
4239        assert_eq!(pages[1].1[cursor], "1001");
4240
4241        for (path, query) in requests.iter() {
4242            assert!(path.starts_with(prefix));
4243            assert_eq!(query["symbol"], symbol);
4244
4245            if query.contains_key("algoId") || query.contains_key("orderId") {
4246                assert!(!query.contains_key("startTime"));
4247                assert!(!query.contains_key("endTime"));
4248            } else {
4249                assert_eq!(query["startTime"], "10");
4250                assert_eq!(query["endTime"], "20");
4251            }
4252
4253            assert_eq!(query["limit"], "1000");
4254            assert!(!query.contains_key("page"));
4255        }
4256
4257        if product == BinanceProductType::CoinM {
4258            assert_eq!(requests.len(), 2);
4259        } else {
4260            assert_eq!(requests.len(), 3);
4261            assert_eq!(algos[&8_886_774].symbol.as_str(), symbol);
4262        }
4263
4264        server.abort();
4265    }
4266
4267    #[rstest]
4268    #[case::usd(BinanceProductType::UsdM, "/fapi/v1/", "BTCUSDT-PERP.BINANCE")]
4269    #[case::coin(BinanceProductType::CoinM, "/dapi/v1/", "BTCUSD_PERP.BINANCE")]
4270    #[tokio::test]
4271    async fn test_order_history_windows_are_contiguous(
4272        #[case] product: BinanceProductType,
4273        #[case] prefix: &str,
4274        #[case] instrument: &str,
4275    ) {
4276        let captured = HistoryRequests::default();
4277
4278        let app = Router::new()
4279            .fallback(any(
4280                |axum::extract::State(requests): axum::extract::State<HistoryRequests>,
4281                 uri: axum::http::Uri,
4282                 axum::extract::Query(query): axum::extract::Query<
4283                    std::collections::HashMap<String, String>,
4284                >| async move {
4285                    requests.lock().push((uri.path().to_string(), query));
4286                    axum::Json(serde_json::json!([]))
4287                },
4288            ))
4289            .with_state(captured.clone());
4290
4291        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4292        let url = format!("http://{}", listener.local_addr().unwrap());
4293
4294        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4295        let client = BinanceFuturesHttpClient::new(
4296            product,
4297            BinanceEnvironment::Live,
4298            get_atomic_clock_realtime(),
4299            Some("key".into()),
4300            Some("secret".into()),
4301            Some(url),
4302            None,
4303            Some(1),
4304            None,
4305            false,
4306        )
4307        .unwrap();
4308
4309        let (orders, algos) = client
4310            .query_order_history(
4311                InstrumentId::from(instrument),
4312                10_000_000.into(),
4313                1_209_600_133_000_000.into(),
4314            )
4315            .await
4316            .unwrap();
4317        let requests = captured.lock();
4318
4319        let endpoints = if product == BinanceProductType::UsdM {
4320            vec!["allOrders", "allAlgoOrders"]
4321        } else {
4322            vec!["allOrders"]
4323        };
4324
4325        let windows = [
4326            (10, 604_800_009),
4327            (604_800_010, 1_209_600_009),
4328            (1_209_600_010, 1_209_600_133),
4329        ];
4330
4331        assert!(orders.is_empty());
4332        assert!(algos.is_empty());
4333        assert_eq!(requests.len(), windows.len() * endpoints.len());
4334
4335        for ((path, query), ((start, end), endpoint)) in requests.iter().zip(
4336            windows
4337                .iter()
4338                .flat_map(|window| endpoints.iter().map(move |endpoint| (window, endpoint))),
4339        ) {
4340            assert_eq!(path, &format!("{prefix}{endpoint}"));
4341            assert_eq!(query["startTime"], start.to_string());
4342            assert_eq!(query["endTime"], end.to_string());
4343            assert_eq!(query["limit"], "1000");
4344            assert!(!query.contains_key("orderId"));
4345            assert!(!query.contains_key("algoId"));
4346        }
4347
4348        server.abort();
4349    }
4350
4351    type HistoryRequests =
4352        Arc<parking_lot::Mutex<Vec<(String, std::collections::HashMap<String, String>)>>>;
4353
4354    async fn order_history_response(
4355        axum::extract::State((page_algo, requests)): axum::extract::State<(bool, HistoryRequests)>,
4356        uri: axum::http::Uri,
4357        axum::extract::Query(query): axum::extract::Query<
4358            std::collections::HashMap<String, String>,
4359        >,
4360    ) -> axum::response::Response {
4361        let algo = uri.path().ends_with("allAlgoOrders");
4362
4363        let (cursor, mut template) = if algo {
4364            let rows: Vec<serde_json::Value> = serde_json::from_str(include_str!(
4365                "../../../test_data/futures/http_json/open_algo_orders.json"
4366            ))
4367            .unwrap();
4368            ("algoId", rows[0].clone())
4369        } else {
4370            let row = serde_json::from_str(include_str!(
4371                "../../../test_data/futures/http_json/order_response.json"
4372            ))
4373            .unwrap();
4374            ("orderId", row)
4375        };
4376
4377        let first_page = !query.contains_key(cursor);
4378        if !first_page && (query.contains_key("startTime") || query.contains_key("endTime")) {
4379            return (axum::http::StatusCode::BAD_REQUEST, axum::Json(serde_json::json!({"code": -1106, "msg": "Cursor cannot accompany time bounds"}))).into_response();
4380        }
4381
4382        requests
4383            .lock()
4384            .push((uri.path().to_string(), query.clone()));
4385
4386        let qty = if query["symbol"] == "BTCUSD_PERP" {
4387            "1"
4388        } else {
4389            "0.001"
4390        };
4391
4392        template["symbol"] = serde_json::json!(query["symbol"]);
4393        template["status"] = serde_json::json!("FILLED");
4394        template["origQty"] = serde_json::json!(qty);
4395        template["executedQty"] = serde_json::json!(qty);
4396        template["avgPrice"] = serde_json::json!("50000.00");
4397
4398        let ids: Vec<_> = if algo == page_algo && first_page {
4399            (1..=1_000).collect()
4400        } else {
4401            vec![8_886_774, 8_886_775]
4402        };
4403
4404        let rows: Vec<_> = ids
4405            .into_iter()
4406            .map(|value| {
4407                let mut row = template.clone();
4408                row[cursor] = serde_json::json!(value);
4409
4410                let timestamp = if value == 8_886_775 { 21 } else { 15 };
4411                row["time"] = serde_json::json!(timestamp);
4412                row["createTime"] = serde_json::json!(timestamp);
4413                row["updateTime"] = serde_json::json!(timestamp);
4414                row
4415            })
4416            .collect();
4417
4418        axum::Json(rows).into_response()
4419    }
4420
4421    #[rstest]
4422    #[case::usd_m(BinanceProductType::UsdM)]
4423    #[case::coin_m(BinanceProductType::CoinM)]
4424    #[tokio::test]
4425    async fn test_weighted_zero_ip_order_keeps_order_quota(#[case] product: BinanceProductType) {
4426        let requests = Arc::new(AtomicUsize::new(0));
4427        let captured = requests.clone();
4428        let response = include_str!("../../../test_data/futures/http_json/order_response.json");
4429
4430        let app = Router::new().fallback(any(move || {
4431            let captured = captured.clone();
4432            async move {
4433                captured.fetch_add(1, Ordering::Relaxed);
4434                response
4435            }
4436        }));
4437
4438        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4439        let url = format!("http://{}", listener.local_addr().unwrap());
4440
4441        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4442        let mut client = BinanceRawFuturesHttpClient::new(
4443            product,
4444            BinanceEnvironment::Live,
4445            Some("key".into()),
4446            Some("secret".into()),
4447            Some(url),
4448            None,
4449            None,
4450            None,
4451        )
4452        .unwrap();
4453        let quota = Quota::with_period(Duration::from_secs(3600)).unwrap();
4454        let mut quotas = vec![(Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota)];
4455        quotas.extend(
4456            client
4457                .order_rate_keys
4458                .iter()
4459                .map(|key| (Ustr::from(key), quota)),
4460        );
4461        let limiter = Arc::new(RateLimiter::new_with_quota(None, quotas));
4462        client.client = HttpClient::builder()
4463            .rate_limiters(vec![limiter.clone()])
4464            .build()
4465            .unwrap();
4466        assert_eq!(
4467            limiter.check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY)),
4468            Ok(())
4469        );
4470
4471        let first = client
4472            .post::<(), serde_json::Value>("order", None, None, true, true)
4473            .await;
4474        let blocked = client
4475            .post::<(), serde_json::Value>("order", None, None, true, true)
4476            .await;
4477        let orders_exhausted = client
4478            .order_rate_keys
4479            .iter()
4480            .all(|key| limiter.check_key(&Ustr::from(key)).is_err());
4481        server.abort();
4482
4483        assert_eq!(
4484            first.unwrap(),
4485            serde_json::from_str::<serde_json::Value>(response).unwrap()
4486        );
4487        assert!(matches!(
4488            blocked,
4489            Err(BinanceFuturesHttpError::RateLimitBlocked)
4490        ));
4491        assert!(orders_exhausted);
4492        assert_eq!(requests.load(Ordering::Relaxed), 1);
4493    }
4494
4495    #[rstest]
4496    #[case::usd_m(BinanceProductType::UsdM)]
4497    #[case::coin_m(BinanceProductType::CoinM)]
4498    #[tokio::test]
4499    async fn test_weighted_batch_keeps_single_order_quota(#[case] product: BinanceProductType) {
4500        let response = include_str!("../../../test_data/futures/http_json/order_response.json");
4501        let batch_response = format!("[{response}]");
4502        let app = Router::new().fallback(any(move || {
4503            let response = batch_response.clone();
4504            async move { response }
4505        }));
4506
4507        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4508        let url = format!("http://{}", listener.local_addr().unwrap());
4509
4510        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4511        let mut client = BinanceRawFuturesHttpClient::new(
4512            product,
4513            BinanceEnvironment::Live,
4514            Some("key".into()),
4515            Some("secret".into()),
4516            Some(url),
4517            None,
4518            None,
4519            None,
4520        )
4521        .unwrap();
4522        let quota = Quota::with_period(Duration::from_secs(3600)).unwrap();
4523        let mut quotas = vec![(
4524            Ustr::from(BINANCE_GLOBAL_RATE_KEY),
4525            quota.allow_burst(NonZeroU32::new(5).unwrap()),
4526        )];
4527        quotas.extend(
4528            client
4529                .order_rate_keys
4530                .iter()
4531                .map(|key| (Ustr::from(key), quota)),
4532        );
4533        let limiter = Arc::new(RateLimiter::new_with_quota(None, quotas));
4534        client.client = HttpClient::builder()
4535            .rate_limiters(vec![limiter.clone()])
4536            .build()
4537            .unwrap();
4538
4539        let result = client
4540            .batch_request("batchOrders", &[()], true)
4541            .await
4542            .unwrap();
4543        let ip_exhausted = limiter
4544            .check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY))
4545            .is_err();
4546        let orders_exhausted = client
4547            .order_rate_keys
4548            .iter()
4549            .all(|key| limiter.check_key(&Ustr::from(key)).is_err());
4550        server.abort();
4551
4552        assert_eq!(result.len(), 1);
4553
4554        let BatchOrderResult::Success(order) = &result[0] else {
4555            panic!("Expected a successful batch response");
4556        };
4557
4558        let expected: BinanceFuturesOrder = serde_json::from_str(response).unwrap();
4559        assert_eq!(
4560            serde_json::to_value(order).unwrap(),
4561            serde_json::to_value(expected).unwrap()
4562        );
4563        assert!(ip_exhausted);
4564        assert!(orders_exhausted);
4565    }
4566
4567    #[rstest]
4568    #[case("fundingRate", BINANCE_FUNDING_RATE_KEY)]
4569    #[case("fundingInfo", BINANCE_FUNDING_RATE_KEY)]
4570    #[case("/fapi/v1/fundingRate", BINANCE_FUNDING_RATE_KEY)]
4571    #[case("/futures/data/openInterestHist", BINANCE_OPEN_INTEREST_RATE_KEY)]
4572    #[tokio::test]
4573    async fn test_weighted_zero_ip_reads_enforce_private_quota(
4574        #[case] path: &str,
4575        #[case] key: &str,
4576    ) {
4577        let mut client = BinanceRawFuturesHttpClient::new(
4578            BinanceProductType::UsdM,
4579            BinanceEnvironment::Live,
4580            None,
4581            None,
4582            Some("http://127.0.0.1:1".into()),
4583            None,
4584            None,
4585            None,
4586        )
4587        .unwrap()
4588        .for_command(false);
4589        let quota = Quota::with_period(Duration::from_secs(3600)).unwrap();
4590
4591        let limiter = Arc::new(RateLimiter::new_with_quota(
4592            None,
4593            vec![
4594                (Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota),
4595                (Ustr::from(key), quota),
4596            ],
4597        ));
4598        client.client = HttpClient::builder()
4599            .rate_limiters(vec![limiter.clone()])
4600            .build()
4601            .unwrap();
4602        assert_eq!(limiter.check_key(&Ustr::from(key)), Ok(()));
4603
4604        let result = client
4605            .get::<(), serde_json::Value>(path, None, false, false)
4606            .await;
4607        let ip_available = limiter.check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY));
4608
4609        assert!(matches!(
4610            result,
4611            Err(BinanceFuturesHttpError::RateLimitBlocked)
4612        ));
4613        assert_eq!(ip_available, Ok(()));
4614        assert_eq!(
4615            client.rate_limit_keys(&Method::GET, path, "", false),
4616            vec![Ustr::from(key)]
4617        );
4618    }
4619
4620    #[tokio::test]
4621    async fn test_weighted_concurrent_clients_share_atomic_quota() {
4622        let requests = Arc::new(AtomicUsize::new(0));
4623        let captured = requests.clone();
4624        let response = include_str!("../../../test_data/spot/http_json/server_time_response.json");
4625
4626        let app = Router::new().fallback(any(move || {
4627            let captured = captured.clone();
4628            async move {
4629                captured.fetch_add(1, Ordering::Relaxed);
4630                response
4631            }
4632        }));
4633
4634        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4635        let url = format!("http://{}", listener.local_addr().unwrap());
4636
4637        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4638        let quota = Quota::with_period(Duration::from_secs(3600))
4639            .unwrap()
4640            .allow_burst(NonZeroU32::new(30).unwrap());
4641
4642        let scope = BinanceFuturesRequestScope {
4643            endpoint: BinanceFuturesEndpointScope::new(
4644                BinanceProductType::UsdM,
4645                BinanceEnvironment::Live,
4646                Some(&url),
4647            ),
4648            proxy_url_digest: None,
4649        };
4650
4651        let limiter = BinanceRawFuturesHttpClient::request_rate_limiter(scope, quota);
4652        let client = BinanceRawFuturesHttpClient::new(
4653            BinanceProductType::UsdM,
4654            BinanceEnvironment::Live,
4655            Some("key".into()),
4656            Some("secret".into()),
4657            Some(url.clone()),
4658            None,
4659            None,
4660            None,
4661        )
4662        .unwrap()
4663        .for_command(false);
4664        let other = BinanceRawFuturesHttpClient::new(
4665            BinanceProductType::CoinM,
4666            BinanceEnvironment::Live,
4667            None,
4668            None,
4669            Some(url.clone()),
4670            None,
4671            None,
4672            None,
4673        )
4674        .unwrap()
4675        .for_command(false);
4676
4677        let (first, second) = tokio::join!(
4678            async {
4679                client
4680                    .get::<(), serde_json::Value>("aggTrades", None, false, false)
4681                    .await
4682            },
4683            async {
4684                other
4685                    .get::<(), serde_json::Value>("aggTrades", None, false, false)
4686                    .await
4687            }
4688        );
4689        let successes = usize::from(first.is_ok()) + usize::from(second.is_ok());
4690        let blocked = usize::from(matches!(
4691            first,
4692            Err(BinanceFuturesHttpError::RateLimitBlocked)
4693        )) + usize::from(matches!(
4694            second,
4695            Err(BinanceFuturesHttpError::RateLimitBlocked)
4696        ));
4697        let mut remaining = 0;
4698        while limiter
4699            .check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY))
4700            .is_ok()
4701        {
4702            remaining += 1;
4703        }
4704
4705        server.abort();
4706
4707        assert_eq!(successes, 1);
4708        assert_eq!(blocked, 1);
4709        assert_eq!(remaining, 10);
4710        assert_eq!(requests.load(Ordering::Relaxed), 1);
4711    }
4712
4713    #[tokio::test]
4714    async fn test_weighted_history_pages_consume_each_page() {
4715        let cursors = Arc::new(Mutex::new(Vec::new()));
4716        let captured = cursors.clone();
4717        let response = include_str!("../../../test_data/spot/http_json/server_time_response.json");
4718
4719        let app = Router::new().fallback(any(move |uri: axum::http::Uri| {
4720            let captured = captured.clone();
4721            async move {
4722                let query: AHashMap<String, String> =
4723                    serde_urlencoded::from_str(uri.query().unwrap()).unwrap();
4724                captured.lock().push(query["fromId"].clone());
4725                response
4726            }
4727        }));
4728
4729        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4730        let url = format!("http://{}", listener.local_addr().unwrap());
4731
4732        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4733        let quota = Quota::with_period(Duration::from_secs(3600))
4734            .unwrap()
4735            .allow_burst(NonZeroU32::new(10).unwrap());
4736
4737        let limiter = Arc::new(RateLimiter::new_with_quota(
4738            None,
4739            vec![(Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota)],
4740        ));
4741        let mut client = BinanceRawFuturesHttpClient::new(
4742            BinanceProductType::UsdM,
4743            BinanceEnvironment::Live,
4744            Some("key".into()),
4745            Some("secret".into()),
4746            Some(url.clone()),
4747            None,
4748            None,
4749            None,
4750        )
4751        .unwrap()
4752        .for_command(false);
4753        client.client = HttpClient::builder()
4754            .rate_limiters(vec![limiter.clone()])
4755            .build()
4756            .unwrap();
4757        let mut responses = Vec::new();
4758
4759        for from_id in [1, 101] {
4760            let params = [
4761                ("symbol", "BTCUSDT".to_string()),
4762                ("fromId", from_id.to_string()),
4763            ];
4764            responses.push(
4765                client
4766                    .get::<_, serde_json::Value>("userTrades", Some(&params), true, false)
4767                    .await
4768                    .unwrap(),
4769            );
4770        }
4771
4772        let exhausted = limiter
4773            .check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY))
4774            .is_err();
4775        server.abort();
4776
4777        assert_eq!(
4778            responses,
4779            vec![serde_json::from_str::<serde_json::Value>(response).unwrap(); 2]
4780        );
4781        assert_eq!(*cursors.lock(), ["1", "101"]);
4782        assert!(exhausted);
4783    }
4784
4785    #[rstest]
4786    #[case("time", 1)]
4787    #[case("aggTrades", 20)]
4788    #[tokio::test]
4789    async fn test_weighted_request_consumes_endpoint_cost(#[case] path: &str, #[case] weight: u32) {
4790        let requests = Arc::new(AtomicUsize::new(0));
4791        let captured = requests.clone();
4792        let response = include_str!("../../../test_data/spot/http_json/server_time_response.json");
4793
4794        let app = Router::new().fallback(any(move || {
4795            let captured = captured.clone();
4796            async move {
4797                captured.fetch_add(1, Ordering::Relaxed);
4798                response
4799            }
4800        }));
4801
4802        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4803        let url = format!("http://{}", listener.local_addr().unwrap());
4804
4805        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4806        let quota = Quota::with_period(Duration::from_secs(3600))
4807            .unwrap()
4808            .allow_burst(NonZeroU32::new(weight).unwrap());
4809
4810        let limiter = Arc::new(RateLimiter::new_with_quota(
4811            None,
4812            vec![(Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota)],
4813        ));
4814        let mut client = BinanceRawFuturesHttpClient::new(
4815            BinanceProductType::UsdM,
4816            BinanceEnvironment::Live,
4817            None,
4818            None,
4819            Some(url),
4820            None,
4821            None,
4822            None,
4823        )
4824        .unwrap()
4825        .for_command(false);
4826        client.client = HttpClient::builder()
4827            .rate_limiters(vec![limiter.clone()])
4828            .build()
4829            .unwrap();
4830
4831        let first = client
4832            .get::<(), serde_json::Value>(path, None, false, false)
4833            .await;
4834        let blocked = client
4835            .get::<(), serde_json::Value>("time", None, false, false)
4836            .await;
4837        let exhausted = limiter
4838            .check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY))
4839            .is_err();
4840        server.abort();
4841
4842        assert_eq!(
4843            first.unwrap(),
4844            serde_json::from_str::<serde_json::Value>(response).unwrap()
4845        );
4846        assert!(matches!(
4847            blocked,
4848            Err(BinanceFuturesHttpError::RateLimitBlocked)
4849        ));
4850        assert!(exhausted);
4851        assert_eq!(requests.load(Ordering::Relaxed), 1);
4852    }
4853
4854    #[tokio::test]
4855    async fn test_weighted_read_retry_consumes_each_attempt() {
4856        let requests = Arc::new(AtomicUsize::new(0));
4857        let captured = requests.clone();
4858        let response = include_str!("../../../test_data/spot/http_json/server_time_response.json");
4859
4860        let app = Router::new().fallback(any(move || {
4861            let captured = captured.clone();
4862            async move {
4863                if captured.fetch_add(1, Ordering::Relaxed) == 0 {
4864                    (StatusCode::SERVICE_UNAVAILABLE, "retry").into_response()
4865                } else {
4866                    (StatusCode::OK, response).into_response()
4867                }
4868            }
4869        }));
4870
4871        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4872        let url = format!("http://{}", listener.local_addr().unwrap());
4873
4874        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4875        let quota = Quota::with_period(Duration::from_secs(3600))
4876            .unwrap()
4877            .allow_burst(NonZeroU32::new(40).unwrap());
4878
4879        let limiter = Arc::new(RateLimiter::new_with_quota(
4880            None,
4881            vec![(Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota)],
4882        ));
4883        let mut client = BinanceRawFuturesHttpClient::new(
4884            BinanceProductType::UsdM,
4885            BinanceEnvironment::Live,
4886            None,
4887            None,
4888            Some(url),
4889            None,
4890            None,
4891            None,
4892        )
4893        .unwrap();
4894        client.client = HttpClient::builder()
4895            .rate_limiters(vec![limiter.clone()])
4896            .build()
4897            .unwrap();
4898
4899        client.retry_manager = Arc::new(RetryManager::new(RetryConfig {
4900            max_retries: 1,
4901            initial_delay_ms: 1,
4902            max_delay_ms: 1,
4903            jitter_ms: 0,
4904            ..crate::common::http::retry_config()
4905        }));
4906
4907        let path = "aggTrades";
4908        let result = client
4909            .get::<(), serde_json::Value>(path, None, false, false)
4910            .await;
4911        let exhausted = limiter
4912            .check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY))
4913            .is_err();
4914        server.abort();
4915
4916        assert_eq!(
4917            result.unwrap(),
4918            serde_json::from_str::<serde_json::Value>(response).unwrap()
4919        );
4920        assert_eq!(requests.load(Ordering::Relaxed), 2);
4921        assert!(exhausted);
4922    }
4923
4924    #[rstest]
4925    #[case::usd_m(BinanceProductType::UsdM)]
4926    #[case::coin_m(BinanceProductType::CoinM)]
4927    #[tokio::test]
4928    async fn test_cancel_bypasses_exhausted_order_bucket(#[case] product: BinanceProductType) {
4929        let requests = Arc::new(Mutex::new(Vec::new()));
4930        let captured = requests.clone();
4931        let app = Router::new().fallback(any(move |method: Method| {
4932            let captured = captured.clone();
4933            async move {
4934                captured.lock().push(method.clone());
4935
4936                let body = if method == Method::DELETE {
4937                    let mut order: serde_json::Value = serde_json::from_str(include_str!(
4938                        "../../../test_data/futures/http_json/order_response.json"
4939                    ))
4940                    .unwrap();
4941                    order["status"] = serde_json::json!("CANCELED");
4942                    order.to_string()
4943                } else {
4944                    "{}".into()
4945                };
4946
4947                (StatusCode::OK, body).into_response()
4948            }
4949        }));
4950
4951        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4952        let url = format!("http://{}", listener.local_addr().unwrap());
4953
4954        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4955        let mut client = BinanceRawFuturesHttpClient::new(
4956            product,
4957            BinanceEnvironment::Live,
4958            Some("key".into()),
4959            Some("secret".into()),
4960            Some(url),
4961            None,
4962            None,
4963            None,
4964        )
4965        .unwrap();
4966        client.client = HttpClient::builder()
4967            .keyed_quotas(
4968                client
4969                    .order_rate_keys
4970                    .iter()
4971                    .map(|key| {
4972                        (
4973                            key.clone(),
4974                            Quota::per_minute(std::num::NonZeroU32::MIN)
4975                                .allow_burst(std::num::NonZeroU32::MIN),
4976                        )
4977                    })
4978                    .collect(),
4979            )
4980            .build()
4981            .unwrap();
4982
4983        let first = client
4984            .post::<(), serde_json::Value>("order", None, None, true, true)
4985            .await;
4986        let blocked = client
4987            .post::<(), serde_json::Value>("order", None, None, true, true)
4988            .await;
4989
4990        let cancel = tokio::time::timeout(Duration::from_millis(250), async {
4991            client
4992                .cancel_order(&BinanceCancelOrderParams {
4993                    symbol: "BTCUSDT".into(),
4994                    order_id: Some(12345678),
4995                    orig_client_order_id: None,
4996                    recv_window: None,
4997                })
4998                .await
4999        })
5000        .await
5001        .unwrap();
5002
5003        server.abort();
5004
5005        assert!(first.is_ok());
5006        assert!(matches!(
5007            blocked,
5008            Err(BinanceFuturesHttpError::RateLimitBlocked)
5009        ));
5010        assert_eq!(cancel.unwrap().order_id, 12345678);
5011        assert_eq!(*requests.lock(), [Method::POST, Method::DELETE]);
5012    }
5013
5014    #[tokio::test]
5015    async fn test_authenticated_client_rejects_redirects() {
5016        let client = BinanceRawFuturesHttpClient::new(
5017            BinanceProductType::UsdM,
5018            BinanceEnvironment::Testnet,
5019            Some("key".into()),
5020            Some("secret".into()),
5021            None,
5022            None,
5023            Some(3),
5024            None,
5025        )
5026        .unwrap()
5027        .client;
5028        assert_http_redirect_rejected(|url| async move {
5029            client
5030                .get(url, None, None, Some(3), None)
5031                .await
5032                .unwrap()
5033                .status
5034                .as_u16()
5035        })
5036        .await;
5037    }
5038
5039    #[rstest]
5040    fn test_rate_limit_config_usdm_has_request_weight_and_orders() {
5041        let config = BinanceRawFuturesHttpClient::rate_limit_config(BinanceProductType::UsdM);
5042
5043        assert_eq!(config.request_quota.burst_size().get(), 2_400);
5044        assert_eq!(config.order_keys.len(), 2);
5045        assert!(
5046            config
5047                .order_keys
5048                .iter()
5049                .any(|key| key == "binance:orders:10:Second")
5050        );
5051        assert!(
5052            config
5053                .order_keys
5054                .iter()
5055                .any(|key| key == "binance:orders:1:Minute")
5056        );
5057
5058        let ten_second_quota = config
5059            .order_quotas
5060            .iter()
5061            .find(|(key, _)| key == "binance:orders:10:Second")
5062            .map(|(_, quota)| quota)
5063            .expect("USD-M 10-second order quota");
5064        assert_eq!(ten_second_quota.burst_size().get(), 300);
5065        assert_eq!(
5066            ten_second_quota.replenish_interval(),
5067            Duration::from_nanos(33_333_333)
5068        );
5069    }
5070
5071    #[rstest]
5072    fn test_rate_limit_config_coinm_has_request_weight_and_orders() {
5073        let config = BinanceRawFuturesHttpClient::rate_limit_config(BinanceProductType::CoinM);
5074
5075        assert_eq!(config.request_quota.burst_size().get(), 2_400);
5076        assert_eq!(config.order_keys.len(), 2);
5077        assert!(
5078            config
5079                .order_keys
5080                .iter()
5081                .any(|key| key == "binance:orders:10:Second")
5082        );
5083        assert!(
5084            config
5085                .order_keys
5086                .iter()
5087                .any(|key| key == "binance:orders:1:Minute")
5088        );
5089
5090        let ten_second_quota = config
5091            .order_quotas
5092            .iter()
5093            .find(|(key, _)| key == "binance:orders:10:Second")
5094            .map(|(_, quota)| quota)
5095            .expect("COIN-M 10-second order quota");
5096        let minute_quota = config
5097            .order_quotas
5098            .iter()
5099            .find(|(key, _)| key == "binance:orders:1:Minute")
5100            .map(|(_, quota)| quota)
5101            .expect("COIN-M one-minute order quota");
5102
5103        assert_eq!(ten_second_quota.burst_size().get(), 300);
5104        assert_eq!(minute_quota.burst_size().get(), 1_200);
5105    }
5106
5107    #[rstest]
5108    fn test_rate_limiters_share_usdm_and_coinm_scopes() {
5109        let account = Some(BinanceFuturesAccountScope([1; 32]));
5110        let usdm_config = BinanceRawFuturesHttpClient::rate_limit_config(BinanceProductType::UsdM);
5111        let coinm_config =
5112            BinanceRawFuturesHttpClient::rate_limit_config(BinanceProductType::CoinM);
5113
5114        let usdm = BinanceRawFuturesHttpClient::shared_rate_limiters(
5115            BinanceEnvironment::Live,
5116            None,
5117            None,
5118            account,
5119            usdm_config.request_quota,
5120            usdm_config.order_quotas,
5121        );
5122        let coinm = BinanceRawFuturesHttpClient::shared_rate_limiters(
5123            BinanceEnvironment::Live,
5124            Some(get_http_base_url(
5125                BinanceProductType::CoinM,
5126                BinanceEnvironment::Live,
5127            )),
5128            None,
5129            account,
5130            coinm_config.request_quota,
5131            coinm_config.order_quotas,
5132        );
5133        let public = create_test_rate_limiters(BinanceEnvironment::Live, None, None, None);
5134
5135        assert_eq!(usdm.len(), 2);
5136        assert_eq!(coinm.len(), 2);
5137        assert_eq!(public.len(), 1);
5138        assert!(Arc::ptr_eq(&usdm[0], &coinm[0]));
5139        assert!(Arc::ptr_eq(&usdm[0], &public[0]));
5140        assert!(Arc::ptr_eq(&usdm[1], &coinm[1]));
5141    }
5142
5143    #[rstest]
5144    fn test_rate_limiters_isolate_unrelated_scopes() {
5145        let account_a = Some(BinanceFuturesAccountScope([2; 32]));
5146        let account_b = Some(BinanceFuturesAccountScope([3; 32]));
5147
5148        let live_direct =
5149            create_test_rate_limiters(BinanceEnvironment::Live, None, None, account_a);
5150        let testnet_direct =
5151            create_test_rate_limiters(BinanceEnvironment::Testnet, None, None, account_a);
5152        let demo_direct =
5153            create_test_rate_limiters(BinanceEnvironment::Demo, None, None, account_a);
5154        let custom_a = create_test_rate_limiters(
5155            BinanceEnvironment::Live,
5156            Some("http://127.0.0.1:41001"),
5157            None,
5158            account_a,
5159        );
5160        let custom_b = create_test_rate_limiters(
5161            BinanceEnvironment::Live,
5162            Some("http://127.0.0.1:41002"),
5163            None,
5164            account_a,
5165        );
5166        let proxy_a = create_test_rate_limiters(
5167            BinanceEnvironment::Live,
5168            None,
5169            Some("http://127.0.0.1:42001"),
5170            account_a,
5171        );
5172        let proxy_b = create_test_rate_limiters(
5173            BinanceEnvironment::Live,
5174            None,
5175            Some("http://127.0.0.1:42002"),
5176            account_a,
5177        );
5178        let other_account =
5179            create_test_rate_limiters(BinanceEnvironment::Live, None, None, account_b);
5180
5181        assert!(!Arc::ptr_eq(&live_direct[0], &testnet_direct[0]));
5182        assert!(!Arc::ptr_eq(&live_direct[0], &demo_direct[0]));
5183        assert!(!Arc::ptr_eq(&live_direct[0], &custom_a[0]));
5184        assert!(!Arc::ptr_eq(&custom_a[0], &custom_b[0]));
5185        assert!(!Arc::ptr_eq(&proxy_a[0], &proxy_b[0]));
5186        assert!(Arc::ptr_eq(&proxy_a[1], &proxy_b[1]));
5187        assert!(Arc::ptr_eq(&live_direct[0], &other_account[0]));
5188        assert!(!Arc::ptr_eq(&live_direct[1], &other_account[1]));
5189    }
5190
5191    fn create_test_rate_limiters(
5192        environment: BinanceEnvironment,
5193        base_url_override: Option<&str>,
5194        proxy_url: Option<&str>,
5195        account_scope: Option<BinanceFuturesAccountScope>,
5196    ) -> Vec<BinanceFuturesRateLimiter> {
5197        let config = BinanceRawFuturesHttpClient::rate_limit_config(BinanceProductType::UsdM);
5198        BinanceRawFuturesHttpClient::shared_rate_limiters(
5199            environment,
5200            base_url_override,
5201            proxy_url,
5202            account_scope,
5203            config.request_quota,
5204            config.order_quotas,
5205        )
5206    }
5207
5208    #[rstest]
5209    fn test_rate_limit_keys_usdm_include_order_buckets() {
5210        let client = BinanceRawFuturesHttpClient::new(
5211            BinanceProductType::UsdM,
5212            BinanceEnvironment::Live,
5213            None,
5214            None,
5215            None,
5216            None,
5217            None,
5218            None,
5219        )
5220        .unwrap();
5221
5222        assert_eq!(
5223            client.rate_limit_keys(&Method::GET, "time", "", false),
5224            vec![Ustr::from(BINANCE_GLOBAL_RATE_KEY)]
5225        );
5226        assert_eq!(
5227            client.rate_limit_keys(&Method::DELETE, "order", "", true),
5228            vec![
5229                Ustr::from(BINANCE_GLOBAL_RATE_KEY),
5230                Ustr::from("binance:orders:10:Second"),
5231                Ustr::from("binance:orders:1:Minute"),
5232            ]
5233        );
5234    }
5235
5236    #[rstest]
5237    fn test_quota_from_unknown_interval_returns_none() {
5238        let quota = BinanceRateLimitQuota {
5239            rate_limit_type: BinanceRateLimitType::Orders,
5240            interval: BinanceRateLimitInterval::Unknown,
5241            interval_num: 1,
5242            limit: 10,
5243        };
5244
5245        assert!(BinanceRawFuturesHttpClient::quota_from(&quota).is_none());
5246    }
5247
5248    #[rstest]
5249    fn test_create_client_rejects_spot_product_type() {
5250        let result = BinanceFuturesHttpClient::new(
5251            BinanceProductType::Spot,
5252            BinanceEnvironment::Live,
5253            get_atomic_clock_realtime(),
5254            None,
5255            None,
5256            None,
5257            None,
5258            None,
5259            None,
5260            false,
5261        );
5262
5263        result.unwrap_err();
5264    }
5265
5266    #[rstest]
5267    fn test_parse_futures_trade_tick_rejects_invalid_price() {
5268        let trade = BinanceFuturesTrade {
5269            id: 100,
5270            price: "not-a-number".to_string(),
5271            qty: "0.001".to_string(),
5272            quote_qty: "50.00".to_string(),
5273            time: 1_625_474_304_000,
5274            is_buyer_maker: false,
5275        };
5276
5277        let result = parse_futures_trade_tick(
5278            &trade,
5279            InstrumentId::from("BTCUSDT-PERP.BINANCE"),
5280            2,
5281            3,
5282            UnixNanos::from(1_000_000_000u64),
5283        );
5284
5285        let error = result.unwrap_err().to_string();
5286        assert!(error.contains("trade.price"));
5287        assert!(error.contains("100"));
5288    }
5289
5290    #[rstest]
5291    fn test_parse_futures_kline_bar_rejects_invalid_volume() {
5292        let kline = BinanceFuturesKline {
5293            open_time: 1_625_474_304_000,
5294            open: "50000.00".to_string(),
5295            high: "51000.00".to_string(),
5296            low: "49000.00".to_string(),
5297            close: "50500.00".to_string(),
5298            volume: "not-a-number".to_string(),
5299            close_time: 1_625_474_364_000,
5300            quote_volume: "631250.00".to_string(),
5301            num_trades: 100,
5302            taker_buy_base_volume: "6.2".to_string(),
5303            taker_buy_quote_volume: "313100.00".to_string(),
5304        };
5305
5306        let result = parse_futures_kline_binance_bar(
5307            &kline,
5308            BarType::from("BTCUSDT-PERP.BINANCE-1-MINUTE-LAST-EXTERNAL"),
5309            2,
5310            3,
5311            UnixNanos::from(1_000_000_000u64),
5312        );
5313
5314        let error = result.unwrap_err().to_string();
5315        assert!(error.contains("kline.volume"));
5316        assert!(error.contains("1625474304000"));
5317    }
5318
5319    #[rstest]
5320    #[case::limit(
5321        BinanceAggTradesParams {
5322            symbol: "BTCUSDT".to_string(),
5323            from_id: None,
5324            start_time: None,
5325            end_time: None,
5326            limit: Some(1001),
5327        },
5328        "Validation error: aggregate trade limit must not exceed 1000"
5329    )]
5330    #[case::order(
5331        BinanceAggTradesParams {
5332            symbol: "BTCUSDT".to_string(),
5333            from_id: None,
5334            start_time: Some(2000),
5335            end_time: Some(1000),
5336            limit: Some(1000),
5337        },
5338        "Validation error: aggregate trade startTime must not exceed endTime"
5339    )]
5340    #[case::range(
5341        BinanceAggTradesParams {
5342            symbol: "BTCUSDT".to_string(),
5343            from_id: None,
5344            start_time: Some(1000),
5345            end_time: Some(3_601_000),
5346            limit: Some(1000),
5347        },
5348        "Validation error: aggregate trade time range must be less than one hour"
5349    )]
5350    #[case::overflow(
5351        BinanceAggTradesParams {
5352            symbol: "BTCUSDT".to_string(),
5353            from_id: None,
5354            start_time: Some(i64::MIN),
5355            end_time: Some(i64::MAX),
5356            limit: Some(1000),
5357        },
5358        "Validation error: aggregate trade time range must be less than one hour"
5359    )]
5360    #[tokio::test]
5361    async fn test_agg_trades_rejects_invalid_bounds(
5362        #[case] params: BinanceAggTradesParams,
5363        #[case] expected: &str,
5364    ) {
5365        let error = create_test_raw_client()
5366            .agg_trades(&params)
5367            .await
5368            .unwrap_err();
5369
5370        assert_eq!(error.to_string(), expected);
5371    }
5372
5373    #[rstest]
5374    #[case::at_cutoff(0, false)]
5375    #[case::before_cutoff(-1, true)]
5376    #[case::after_cutoff(1, false)]
5377    #[tokio::test]
5378    async fn test_request_agg_trades_48_hour_boundary(
5379        #[case] offset_ms: i64,
5380        #[case] rejected: bool,
5381        #[values(BinanceProductType::UsdM, BinanceProductType::CoinM)]
5382        product_type: BinanceProductType,
5383        #[values((true, false), (false, true), (true, true))] bounds: (bool, bool),
5384    ) {
5385        let (include_start, include_end) = bounds;
5386        let now = UnixNanos::from_millis(1_800_000_000_000);
5387        let clock = Box::leak(Box::new(AtomicTime::new(false, now)));
5388        let client = BinanceFuturesHttpClient::new(
5389            product_type,
5390            BinanceEnvironment::Testnet,
5391            clock,
5392            None,
5393            None,
5394            Some("http://127.0.0.1:1".to_string()),
5395            None,
5396            Some(1),
5397            None,
5398            false,
5399        )
5400        .unwrap();
5401        let start = now.to_datetime_utc() - SignedDuration::from_hours(48)
5402            + SignedDuration::from_millis(offset_ms);
5403        let end = start + SignedDuration::from_mins(30);
5404
5405        let instrument_id = InstrumentId::from(match product_type {
5406            BinanceProductType::UsdM => "BTCUSDT-PERP.BINANCE",
5407            BinanceProductType::CoinM => "BTCUSD_PERP.BINANCE",
5408            _ => unreachable!(),
5409        });
5410
5411        let end = if include_start { end } else { start };
5412
5413        let error = client
5414            .request_agg_trades(
5415                instrument_id,
5416                include_start.then_some(start),
5417                include_end.then_some(end),
5418                Some(1000),
5419            )
5420            .await
5421            .unwrap_err();
5422
5423        let expected = if rejected {
5424            "Binance Futures aggregate trade history is limited to the past 48 hours".to_string()
5425        } else {
5426            InstrumentLookupError::not_found(instrument_id).to_string()
5427        };
5428
5429        assert_eq!(error.to_string(), expected);
5430    }
5431
5432    fn create_test_raw_client() -> BinanceRawFuturesHttpClient {
5433        BinanceRawFuturesHttpClient::new(
5434            BinanceProductType::UsdM,
5435            BinanceEnvironment::Live,
5436            None,
5437            None,
5438            None,
5439            None,
5440            None,
5441            None,
5442        )
5443        .expect("Failed to create test client")
5444    }
5445
5446    fn create_test_client() -> BinanceFuturesHttpClient {
5447        BinanceFuturesHttpClient::new(
5448            BinanceProductType::UsdM,
5449            BinanceEnvironment::Live,
5450            get_atomic_clock_realtime(),
5451            None,
5452            None,
5453            Some("http://127.0.0.1:1".to_string()),
5454            None,
5455            Some(1),
5456            None,
5457            false,
5458        )
5459        .expect("Failed to create test client")
5460    }
5461
5462    fn test_usdm_symbol() -> BinanceFuturesUsdSymbol {
5463        BinanceFuturesUsdSymbol {
5464            symbol: Ustr::from("BTCUSDT"),
5465            pair: Ustr::from("BTCUSDT"),
5466            contract_type: "PERPETUAL".to_string(),
5467            delivery_date: 4_133_404_800_000,
5468            onboard_date: 1_569_398_400_000,
5469            status: BinanceTradingStatus::Trading,
5470            maint_margin_percent: "2.5000".to_string(),
5471            required_margin_percent: "5.0000".to_string(),
5472            base_asset: Ustr::from("BTC"),
5473            quote_asset: Ustr::from("USDT"),
5474            margin_asset: Ustr::from("USDT"),
5475            price_precision: 2,
5476            quantity_precision: 3,
5477            base_asset_precision: 8,
5478            quote_precision: 8,
5479            underlying_type: None,
5480            underlying_sub_type: Vec::new(),
5481            settle_plan: None,
5482            trigger_protect: None,
5483            liquidation_fee: None,
5484            market_take_bound: None,
5485            order_types: Vec::new(),
5486            time_in_force: Vec::new(),
5487            filters: Vec::new(),
5488        }
5489    }
5490
5491    #[rstest]
5492    fn test_cached_precisions_by_id_returns_symbol_and_precisions() {
5493        let client = create_test_client();
5494        client.instruments_cache().insert(
5495            Ustr::from("BTCUSDT"),
5496            BinanceFuturesInstrument::UsdM(test_usdm_symbol()),
5497        );
5498
5499        let (symbol, price_precision, size_precision) = client
5500            .cached_precisions_by_id(InstrumentId::from("BTCUSDT-PERP.BINANCE"))
5501            .unwrap();
5502
5503        assert_eq!(symbol, "BTCUSDT");
5504        assert_eq!(price_precision, 2);
5505        assert_eq!(size_precision, 3);
5506    }
5507
5508    #[rstest]
5509    fn test_cached_precisions_by_id_rejects_spot_alias() {
5510        let client = create_test_client();
5511        client.instruments_cache().insert(
5512            Ustr::from("BTCUSDT"),
5513            BinanceFuturesInstrument::UsdM(test_usdm_symbol()),
5514        );
5515
5516        let error = client
5517            .cached_precisions_by_id(InstrumentId::from("BTCUSDT.BINANCE"))
5518            .unwrap_err();
5519
5520        assert_eq!(
5521            error.to_string(),
5522            InstrumentLookupError::not_found(InstrumentId::from("BTCUSDT.BINANCE")).to_string()
5523        );
5524    }
5525
5526    #[rstest]
5527    fn test_invalid_precision_preserves_previous_raw_snapshot() {
5528        let client = create_test_client();
5529        let valid = test_usdm_symbol();
5530        client
5531            .replace_instruments(vec![(
5532                valid.symbol,
5533                BinanceFuturesInstrument::UsdM(valid.clone()),
5534            )])
5535            .unwrap();
5536        let mut invalid = valid;
5537        invalid.price_precision = i32::from(FIXED_PRECISION) + 1;
5538
5539        let error = client
5540            .replace_instruments(vec![(
5541                invalid.symbol,
5542                BinanceFuturesInstrument::UsdM(invalid),
5543            )])
5544            .unwrap_err();
5545        let retained = client
5546            .instruments_cache()
5547            .get(&Ustr::from("BTCUSDT"))
5548            .map(|instrument| instrument.value().clone())
5549            .unwrap();
5550
5551        assert!(error.to_string().contains("precision exceeds maximum"));
5552        assert_eq!(retained.precisions().unwrap(), (2, 3));
5553    }
5554
5555    #[rstest]
5556    #[tokio::test]
5557    async fn test_submit_algo_order_stop_market_requires_trigger_price() {
5558        let client = create_test_client();
5559        client.instruments_cache().insert(
5560            Ustr::from("BTCUSDT"),
5561            BinanceFuturesInstrument::UsdM(test_usdm_symbol()),
5562        );
5563
5564        let result = client
5565            .submit_algo_order(
5566                AccountId::from("BINANCE-001"),
5567                InstrumentId::from("BTCUSDT-PERP.BINANCE"),
5568                ClientOrderId::new("missing-trigger-test-001"),
5569                OrderSide::Sell,
5570                OrderType::StopMarket,
5571                Quantity::from("0.001"),
5572                TimeInForce::Gtc,
5573                None,
5574                None,
5575                false,
5576                false,
5577                None,
5578                None,
5579                None,
5580                None,
5581                None,
5582            )
5583            .await;
5584
5585        let error = result.unwrap_err().to_string();
5586        assert_eq!(error, "Algo order type StopMarket requires a trigger price");
5587    }
5588
5589    #[rstest]
5590    fn test_batch_cancel_params_builds_order_id_list() {
5591        let items = vec![
5592            BatchCancelItem::by_order_id("BTCUSDT", 123),
5593            BatchCancelItem::by_order_id("BTCUSDT", 456),
5594        ];
5595
5596        let params = BinanceRawFuturesHttpClient::batch_cancel_params(&items).unwrap();
5597
5598        assert_eq!(params.symbol, "BTCUSDT");
5599        assert_eq!(params.order_id_list.as_deref(), Some("[123,456]"));
5600        assert_eq!(params.orig_client_order_id_list, None);
5601    }
5602
5603    #[rstest]
5604    fn test_batch_cancel_params_builds_client_order_id_list() {
5605        let items = vec![
5606            BatchCancelItem::by_client_order_id("BTCUSDT", "first-order"),
5607            BatchCancelItem::by_client_order_id("BTCUSDT", "second-order"),
5608        ];
5609
5610        let params = BinanceRawFuturesHttpClient::batch_cancel_params(&items).unwrap();
5611
5612        assert_eq!(params.symbol, "BTCUSDT");
5613        assert_eq!(params.order_id_list, None);
5614        assert_eq!(
5615            params.orig_client_order_id_list.as_deref(),
5616            Some("[\"first-order\",\"second-order\"]"),
5617        );
5618    }
5619
5620    #[rstest]
5621    fn test_batch_cancel_params_rejects_mixed_symbols() {
5622        let items = vec![
5623            BatchCancelItem::by_order_id("BTCUSDT", 123),
5624            BatchCancelItem::by_order_id("ETHUSDT", 456),
5625        ];
5626
5627        let result = BinanceRawFuturesHttpClient::batch_cancel_params(&items);
5628
5629        assert_validation_error(result, "same symbol");
5630    }
5631
5632    #[rstest]
5633    fn test_batch_cancel_params_rejects_mixed_id_types() {
5634        let items = vec![
5635            BatchCancelItem::by_order_id("BTCUSDT", 123),
5636            BatchCancelItem::by_client_order_id("BTCUSDT", "client-order"),
5637        ];
5638
5639        let result = BinanceRawFuturesHttpClient::batch_cancel_params(&items);
5640
5641        assert_validation_error(result, "not both");
5642    }
5643
5644    #[rstest]
5645    fn test_batch_cancel_params_rejects_items_without_ids() {
5646        let items = vec![BatchCancelItem {
5647            symbol: "BTCUSDT".to_string(),
5648            order_id: None,
5649            orig_client_order_id: None,
5650        }];
5651
5652        let result = BinanceRawFuturesHttpClient::batch_cancel_params(&items);
5653
5654        assert_validation_error(result, "at least one order ID or client order ID");
5655    }
5656
5657    #[rstest]
5658    #[tokio::test]
5659    async fn test_batch_cancel_orders_rejects_more_than_ten_items() {
5660        let client = create_test_raw_client();
5661        let items = (0..11)
5662            .map(|order_id| BatchCancelItem::by_order_id("BTCUSDT", order_id))
5663            .collect::<Vec<_>>();
5664
5665        let result = client.batch_cancel_orders(&items).await;
5666
5667        match result {
5668            Err(BinanceFuturesHttpError::ValidationError(message)) => {
5669                assert!(message.contains("10 orders maximum"));
5670            }
5671            other => panic!("Expected ValidationError, was {other:?}"),
5672        }
5673    }
5674
5675    #[rstest]
5676    fn test_batch_response_length_mismatch_has_unknown_outcome() {
5677        let error = merge_batch_results(vec![None], Vec::new()).unwrap_err();
5678
5679        assert_eq!(
5680            classify_futures_http_failure(&error),
5681            CommandFailure::Ambiguous(
5682                "JSON error: Batch response length does not match submitted orders".to_string()
5683            ),
5684        );
5685    }
5686
5687    fn assert_validation_error(
5688        result: BinanceFuturesHttpResult<BatchCancelParams>,
5689        expected_message: &str,
5690    ) {
5691        match result {
5692            Err(BinanceFuturesHttpError::ValidationError(message)) => {
5693                assert!(message.contains(expected_message));
5694            }
5695            other => panic!("Expected ValidationError, was {other:?}"),
5696        }
5697    }
5698
5699    #[rstest]
5700    fn test_parse_error_response_binance_error() {
5701        let client = create_test_raw_client();
5702        let response = HttpResponse {
5703            status: HttpStatus::new(StatusCode::BAD_REQUEST),
5704            headers: HashMap::new(),
5705            body: Bytes::from(r#"{"code":-1121,"msg":"Invalid symbol."}"#),
5706        };
5707
5708        let result: BinanceFuturesHttpResult<()> = client.parse_error_response(&response);
5709
5710        match result {
5711            Err(BinanceFuturesHttpError::BinanceError {
5712                code,
5713                message,
5714                status,
5715                retry_after,
5716            }) => {
5717                assert_eq!(code, -1121);
5718                assert_eq!(message, "Invalid symbol.");
5719                assert_eq!(status, 400);
5720                assert_eq!(retry_after, None);
5721            }
5722            other => panic!("Expected BinanceError, was {other:?}"),
5723        }
5724    }
5725}