Skip to main content

nautilus_binance/spot/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 Spot HTTP client with SBE encoding.
17//!
18//! This client communicates with Binance Spot REST API using SBE (Simple Binary
19//! Encoding) for all request/response payloads, providing microsecond timestamp
20//! precision and reduced latency compared to JSON.
21//!
22//! ## Architecture
23//!
24//! Two-layer client pattern:
25//! - [`BinanceRawSpotHttpClient`]: Low-level API methods returning raw bytes.
26//! - [`BinanceSpotHttpClient`]: High-level methods with SBE decoding.
27//!
28//! ## SBE Headers
29//!
30//! All requests include:
31//! - `Accept: application/sbe`
32//! - `X-MBX-SBE: 3:5` (schema ID:version)
33
34use std::{collections::HashMap, fmt::Debug, num::NonZeroU32, sync::Arc};
35
36use ahash::AHashMap;
37use anyhow::Context;
38use indexmap::{IndexMap, map::Entry};
39use jiff::Timestamp;
40use nautilus_common::cache::InstrumentLookupError;
41use nautilus_core::{
42    collections::AtomicMap,
43    datetime::{NANOSECONDS_IN_MICROSECOND, NANOSECONDS_IN_MILLISECOND, SECONDS_IN_DAY},
44    hex,
45    nanos::UnixNanos,
46    time::AtomicTime,
47};
48use nautilus_model::{
49    data::{Bar, BarType, BookOrder, TradeTick},
50    enums::{
51        AggregationSource, BarAggregation, BookType, MarketStatusAction, OrderSide, OrderType,
52        TimeInForce,
53    },
54    events::AccountState,
55    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, VenueOrderId},
56    instruments::{Instrument, any::InstrumentAny},
57    orderbook::OrderBook,
58    reports::{FillReport, OrderStatusReport},
59    types::{Price, Quantity},
60};
61use nautilus_network::{
62    http::{
63        HttpClient, HttpRedirectPolicy, HttpResponse, Method, create_standard_nautilus_headers,
64    },
65    ratelimiter::quota::Quota,
66    retry::{RetryConfig, RetryError, RetryManager},
67};
68use rust_decimal::Decimal;
69use serde::{Deserialize, Serialize};
70use serde_json::Value;
71use ustr::Ustr;
72
73use super::{
74    error::{BinanceSpotHttpError, BinanceSpotHttpResult},
75    models::{
76        AvgPrice, BatchCancelResult, BatchOrderResult, BinanceAccountCommission,
77        BinanceAccountInfo, BinanceAccountRatesJson, BinanceAccountTrade, BinanceAggTrade,
78        BinanceAggTrades, BinanceBalance, BinanceCancelOpenOrdersResponse,
79        BinanceCancelOrderListResponse, BinanceCancelOrderResponse, BinanceDepth,
80        BinanceExchangeInfoJson, BinanceKline, BinanceKlines, BinanceNewOrderResponse,
81        BinanceOrderFill, BinanceOrderResponse, BinancePriceLevel, BinanceTrade, BinanceTrades,
82        BookTicker, ListenKeyResponse, NewOcoOrderListResponse, OrderListOrder, Ticker24hr,
83        TickerPrice, TradeFee,
84    },
85    parse,
86    query::{
87        AccountCommissionParams, AccountInfoParams, AccountTradesParams, AggTradesParams,
88        AllOrdersParams, AvgPriceParams, BatchCancelItem, BatchOrderItem, CancelOpenOrdersParams,
89        CancelOrderParams, CancelReplaceOrderParams, DepthParams, KlinesParams, ListenKeyParams,
90        NewOcoOrderListParams, NewOrderParams, OpenOrdersParams, QueryOrderParams, TickerParams,
91        TradeFeeParams, TradesParams,
92    },
93};
94use crate::{
95    book::pacing::{SnapshotAdmission, SnapshotPermit},
96    common::{
97        consts::{
98            BINANCE_API_KEY_HEADER, BINANCE_NAUTILUS_SPOT_BROKER_ID, BINANCE_NO_SUCH_ORDER_CODE,
99            BINANCE_RETRY_AFTER_HEADER, BINANCE_SPOT_RATE_LIMITS, BINANCE_VENUE,
100            BinanceRateLimitQuota,
101        },
102        credential::SigningCredential,
103        encoder::{decode_client_order_id, encode_broker_id, legacy_client_order_id},
104        enums::{
105            BinanceEnvironment, BinanceOrderStatus, BinanceProductType, BinanceRateLimitInterval,
106            BinanceRateLimitType, BinanceSelfTradePreventionMode, BinanceSide, BinanceTimeInForce,
107        },
108        http::BinanceHttpBackoff,
109        http_weights::request_weight_spot,
110        instruments::BinanceInstrumentSelector,
111        models::BinanceErrorResponse,
112        parse::{
113            get_currency, parse_fill_report_sbe, parse_klines_to_binance_bars,
114            parse_new_order_response_sbe, parse_order_status_report_sbe,
115            parse_spot_instrument_json_with_fees, parse_spot_instrument_sbe_with_fees,
116            parse_spot_trades_sbe, should_warn_on_instrument_parse_error,
117        },
118        symbol::format_instrument_id,
119        urls::get_http_base_url,
120    },
121    config::BinanceInstrumentProviderConfig,
122    spot::{
123        enums::{
124            BinanceCancelReplaceMode, BinanceOrderResponseType, BinanceSpotOrderType,
125            order_type_to_binance_spot, time_in_force_to_binance_spot,
126        },
127        sbe::{
128            generated::symbol_status::SymbolStatus,
129            spot::{
130                ReadBuf, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION,
131                contingency_type::ContingencyType as SbeContingencyType,
132                error_response_codec::{self, ErrorResponseDecoder},
133                list_order_status::ListOrderStatus as SbeListOrderStatus,
134                list_status_type::ListStatusType as SbeListStatusType,
135                message_header_codec::MessageHeaderDecoder,
136                order_side::OrderSide as SbeOrderSide,
137                order_status::OrderStatus as SbeOrderStatus,
138                order_type::OrderType as SbeOrderType,
139                self_trade_prevention_mode::SelfTradePreventionMode as SbeSelfTradePreventionMode,
140                time_in_force::TimeInForce as SbeTimeInForce,
141            },
142        },
143    },
144};
145
146/// SBE schema header value (`X-MBX-SBE`) sent on Spot API requests.
147///
148/// Requests the current `3:5` schema. The decoder accepts any version within schema ID `3`
149/// (see `parse::MessageHeader::validate`), so compatible responses continue to decode.
150pub const SBE_SCHEMA_HEADER: &str = "3:5";
151
152use crate::common::consts::{
153    BINANCE_SAPI_PATH as SAPI_PATH, BINANCE_SPOT_API_PATH as SPOT_API_PATH,
154};
155
156/// Global rate limit key.
157const BINANCE_GLOBAL_RATE_KEY: &str = "binance:spot:global";
158
159/// Orders rate limit key prefix.
160const BINANCE_ORDERS_RATE_KEY: &str = "binance:spot:orders";
161
162struct RateLimitConfig {
163    default_quota: Option<Quota>,
164    keyed_quotas: Vec<(String, Quota)>,
165    order_keys: Vec<String>,
166}
167
168#[derive(Debug, Deserialize)]
169#[serde(rename_all = "camelCase")]
170struct SpotAccountJson {
171    #[serde(default)]
172    maker_commission: i64,
173    #[serde(default)]
174    taker_commission: i64,
175    #[serde(default)]
176    buyer_commission: i64,
177    #[serde(default)]
178    seller_commission: i64,
179    #[serde(default)]
180    commission_rates: Option<SpotCommissionRatesJson>,
181    can_trade: bool,
182    can_withdraw: bool,
183    can_deposit: bool,
184    #[serde(default)]
185    require_self_trade_prevention: bool,
186    #[serde(default)]
187    prevent_sor: bool,
188    update_time: i64,
189    account_type: String,
190    balances: Vec<SpotBalanceJson>,
191}
192
193#[derive(Debug, Deserialize)]
194struct SpotCommissionRatesJson {
195    maker: String,
196    taker: String,
197    buyer: String,
198    seller: String,
199}
200
201#[derive(Debug, Deserialize)]
202struct SpotBalanceJson {
203    asset: String,
204    free: String,
205    locked: String,
206}
207
208#[derive(Debug, Deserialize)]
209#[serde(rename_all = "camelCase")]
210struct SpotOrderJson {
211    symbol: String,
212    order_id: i64,
213    #[serde(default)]
214    order_list_id: Option<i64>,
215    client_order_id: String,
216    #[serde(default)]
217    orig_client_order_id: String,
218    #[serde(default)]
219    transact_time: i64,
220    #[serde(default)]
221    price: String,
222    #[serde(default)]
223    orig_qty: String,
224    #[serde(default)]
225    executed_qty: String,
226    #[serde(default, rename = "cummulativeQuoteQty")]
227    cummulative_quote_qty: String,
228    status: BinanceOrderStatus,
229    time_in_force: BinanceTimeInForce,
230    #[serde(rename = "type")]
231    order_type: BinanceSpotOrderType,
232    side: BinanceSide,
233    #[serde(default)]
234    stop_price: String,
235    #[serde(default)]
236    iceberg_qty: String,
237    #[serde(default)]
238    time: i64,
239    #[serde(default)]
240    update_time: i64,
241    #[serde(default)]
242    is_working: bool,
243    #[serde(default)]
244    working_time: Option<i64>,
245    #[serde(default)]
246    orig_quote_order_qty: String,
247    #[serde(default)]
248    self_trade_prevention_mode: Option<BinanceSelfTradePreventionMode>,
249    #[serde(default)]
250    fills: Vec<SpotOrderFillJson>,
251}
252
253#[derive(Debug, Deserialize)]
254#[serde(rename_all = "camelCase")]
255struct SpotCancelOrderListJson {
256    order_list_id: i64,
257    contingency_type: String,
258    list_status_type: String,
259    list_order_status: String,
260    list_client_order_id: String,
261    transaction_time: i64,
262    symbol: String,
263    orders: Vec<OrderListOrder>,
264    order_reports: Vec<SpotOrderJson>,
265}
266
267#[derive(Debug, Deserialize)]
268#[serde(rename_all = "camelCase")]
269struct SpotCancelReplaceJson {
270    new_order_response: SpotOrderJson,
271}
272
273#[derive(Debug, Deserialize)]
274#[serde(rename_all = "camelCase")]
275struct SpotOrderFillJson {
276    price: String,
277    qty: String,
278    commission: String,
279    commission_asset: String,
280    #[serde(default)]
281    trade_id: Option<i64>,
282}
283
284#[derive(Debug, Deserialize)]
285#[serde(rename_all = "camelCase")]
286struct SpotAccountTradeJson {
287    symbol: String,
288    id: i64,
289    order_id: i64,
290    #[serde(default)]
291    order_list_id: Option<i64>,
292    price: String,
293    qty: String,
294    quote_qty: String,
295    commission: String,
296    commission_asset: String,
297    time: i64,
298    is_buyer: bool,
299    is_maker: bool,
300    is_best_match: bool,
301}
302
303#[derive(Debug, Deserialize)]
304#[serde(rename_all = "camelCase")]
305struct SpotDepthJson {
306    last_update_id: i64,
307    bids: Vec<[String; 2]>,
308    asks: Vec<[String; 2]>,
309}
310
311#[derive(Debug, Deserialize)]
312#[serde(rename_all = "camelCase")]
313struct SpotTradeJson {
314    id: i64,
315    price: String,
316    qty: String,
317    quote_qty: String,
318    time: i64,
319    is_buyer_maker: bool,
320    is_best_match: bool,
321}
322
323#[derive(Debug, Deserialize)]
324struct SpotAggTradeJson {
325    #[serde(rename = "a")]
326    id: i64,
327    #[serde(rename = "p")]
328    price: String,
329    #[serde(rename = "q")]
330    qty: String,
331    #[serde(rename = "f")]
332    first_trade_id: i64,
333    #[serde(rename = "l")]
334    last_trade_id: i64,
335    #[serde(rename = "T")]
336    time: i64,
337    #[serde(rename = "m")]
338    is_buyer_maker: bool,
339    #[serde(rename = "M")]
340    is_best_match: bool,
341}
342
343type SpotKlineJson = (
344    i64,
345    String,
346    String,
347    String,
348    String,
349    String,
350    i64,
351    String,
352    i64,
353    String,
354    String,
355    String,
356);
357
358/// Low-level HTTP client for Binance Spot REST API with SBE encoding.
359///
360/// Handles:
361/// - Base URL resolution by environment.
362/// - Optional HMAC SHA256 signing for private endpoints.
363/// - Rate limiting using Spot API quotas.
364/// - SBE decoding to Binance-specific response types.
365///
366/// Methods are named to match Binance API endpoints and return
367/// venue-specific types (decoded from SBE).
368#[derive(Debug, Clone)]
369pub struct BinanceRawSpotHttpClient {
370    retry_manager: Arc<RetryManager<BinanceSpotHttpError>>,
371    client: HttpClient,
372    base_url: String,
373    credential: Option<SigningCredential>,
374    recv_window: Option<u64>,
375    order_rate_keys: Vec<String>,
376    json_responses: bool,
377    backoff: BinanceHttpBackoff,
378    command_order_quota: Option<bool>,
379}
380
381impl BinanceRawSpotHttpClient {
382    /// Returns whether signed requests can be made.
383    #[must_use]
384    pub fn has_credentials(&self) -> bool {
385        self.credential.is_some()
386    }
387
388    /// Creates a new Binance Spot raw HTTP client.
389    ///
390    /// # Errors
391    ///
392    /// Returns an error if the underlying [`HttpClient`] fails to build.
393    pub fn new(
394        environment: BinanceEnvironment,
395        api_key: Option<String>,
396        api_secret: Option<String>,
397        base_url_override: Option<String>,
398        recv_window: Option<u64>,
399        timeout_secs: Option<u64>,
400        proxy_url: Option<String>,
401    ) -> BinanceSpotHttpResult<Self> {
402        Self::new_with_json_responses(
403            environment,
404            api_key,
405            api_secret,
406            base_url_override,
407            recv_window,
408            timeout_secs,
409            proxy_url,
410            false,
411        )
412    }
413
414    /// Creates a raw Spot client with JSON responses instead of Global SBE responses.
415    ///
416    /// # Errors
417    ///
418    /// Returns an error if the underlying [`HttpClient`] fails to build.
419    #[expect(clippy::too_many_arguments)]
420    pub fn new_with_json_responses(
421        environment: BinanceEnvironment,
422        api_key: Option<String>,
423        api_secret: Option<String>,
424        base_url_override: Option<String>,
425        recv_window: Option<u64>,
426        timeout_secs: Option<u64>,
427        proxy_url: Option<String>,
428        json_responses: bool,
429    ) -> BinanceSpotHttpResult<Self> {
430        let RateLimitConfig {
431            default_quota,
432            keyed_quotas,
433            order_keys,
434        } = Self::rate_limit_config();
435
436        let credential = match (api_key, api_secret) {
437            (Some(key), Some(secret)) => Some(SigningCredential::new(key, secret)),
438            (None, None) => None,
439            _ => return Err(BinanceSpotHttpError::MissingCredentials),
440        };
441
442        let backoff = BinanceHttpBackoff::new(
443            BinanceProductType::Spot,
444            environment,
445            base_url_override.as_deref(),
446            proxy_url.as_deref(),
447            credential.as_ref(),
448        );
449
450        let base_url = base_url_override.unwrap_or_else(|| {
451            get_http_base_url(BinanceProductType::Spot, environment).to_string()
452        });
453
454        let headers = Self::default_headers(&credential, json_responses);
455
456        let client = HttpClient::builder()
457            .redirect_policy(HttpRedirectPolicy::Reject)
458            .headers(headers)
459            .header_keys(vec![
460                BINANCE_API_KEY_HEADER.to_string(),
461                BINANCE_RETRY_AFTER_HEADER.to_string(),
462            ])
463            .keyed_quotas(keyed_quotas)
464            .maybe_default_quota(default_quota)
465            .maybe_timeout_secs(timeout_secs)
466            .maybe_proxy_url(proxy_url)
467            .build()?;
468
469        Ok(Self {
470            retry_manager: Arc::new(RetryManager::new(crate::common::http::retry_config())),
471            client,
472            base_url,
473            credential,
474            recv_window,
475            order_rate_keys: order_keys,
476            json_responses,
477            backoff,
478            command_order_quota: None,
479        })
480    }
481
482    /// Returns the SBE schema ID.
483    #[must_use]
484    pub const fn schema_id() -> u16 {
485        SBE_SCHEMA_ID
486    }
487
488    /// Returns the SBE schema version.
489    #[must_use]
490    pub const fn schema_version() -> u16 {
491        SBE_SCHEMA_VERSION
492    }
493
494    /// Performs a GET request and returns raw response bytes.
495    ///
496    /// # Errors
497    ///
498    /// Returns an error if the request fails.
499    pub async fn get<P>(&self, path: &str, params: Option<&P>) -> BinanceSpotHttpResult<Vec<u8>>
500    where
501        P: Serialize + ?Sized,
502    {
503        self.request(Method::GET, path, params, false, false).await
504    }
505
506    /// Performs a signed GET request and returns raw response bytes.
507    ///
508    /// # Errors
509    ///
510    /// Returns an error if credentials are missing or the request fails.
511    pub async fn get_signed<P>(
512        &self,
513        path: &str,
514        params: Option<&P>,
515    ) -> BinanceSpotHttpResult<Vec<u8>>
516    where
517        P: Serialize + ?Sized,
518    {
519        self.request(Method::GET, path, params, true, false).await
520    }
521
522    /// Performs a signed GET request and requests a JSON response.
523    ///
524    /// # Errors
525    ///
526    /// Returns an error if credentials are missing or the request fails.
527    pub async fn get_signed_json<P>(
528        &self,
529        path: &str,
530        params: Option<&P>,
531    ) -> BinanceSpotHttpResult<Vec<u8>>
532    where
533        P: Serialize + ?Sized,
534    {
535        self.request_with_extra_headers(
536            Method::GET,
537            path,
538            params,
539            true,
540            false,
541            Some(HashMap::from([(
542                "Accept".to_string(),
543                "application/json".to_string(),
544            )])),
545            None,
546        )
547        .await
548    }
549
550    /// Performs a signed POST request and returns raw response bytes.
551    ///
552    /// # Errors
553    ///
554    /// Returns an error if credentials are missing or the request fails.
555    pub async fn post_signed<P>(
556        &self,
557        path: &str,
558        params: Option<&P>,
559    ) -> BinanceSpotHttpResult<Vec<u8>>
560    where
561        P: Serialize + ?Sized,
562    {
563        self.request(Method::POST, path, params, true, true).await
564    }
565
566    /// Performs a signed POST request and requests a JSON response.
567    ///
568    /// # Errors
569    ///
570    /// Returns an error if credentials are missing or the request fails.
571    pub async fn post_signed_json<P>(
572        &self,
573        path: &str,
574        params: Option<&P>,
575    ) -> BinanceSpotHttpResult<Vec<u8>>
576    where
577        P: Serialize + ?Sized,
578    {
579        self.request_with_extra_headers(
580            Method::POST,
581            path,
582            params,
583            true,
584            true,
585            Some(HashMap::from([(
586                "Accept".to_string(),
587                "application/json".to_string(),
588            )])),
589            None,
590        )
591        .await
592    }
593
594    /// Performs a signed DELETE request and returns raw response bytes.
595    ///
596    /// # Errors
597    ///
598    /// Returns an error if credentials are missing or the request fails.
599    pub async fn delete_signed<P>(
600        &self,
601        path: &str,
602        params: Option<&P>,
603    ) -> BinanceSpotHttpResult<Vec<u8>>
604    where
605        P: Serialize + ?Sized,
606    {
607        self.request(Method::DELETE, path, params, true, false)
608            .await
609    }
610
611    /// Performs a signed DELETE request and requests a JSON response.
612    ///
613    /// # Errors
614    ///
615    /// Returns an error if credentials are missing or the request fails.
616    pub async fn delete_signed_json<P>(
617        &self,
618        path: &str,
619        params: Option<&P>,
620    ) -> BinanceSpotHttpResult<Vec<u8>>
621    where
622        P: Serialize + ?Sized,
623    {
624        self.request_with_extra_headers(
625            Method::DELETE,
626            path,
627            params,
628            true,
629            false,
630            Some(HashMap::from([(
631                "Accept".to_string(),
632                "application/json".to_string(),
633            )])),
634            None,
635        )
636        .await
637    }
638
639    async fn request<P>(
640        &self,
641        method: Method,
642        path: &str,
643        params: Option<&P>,
644        signed: bool,
645        use_order_quota: bool,
646    ) -> BinanceSpotHttpResult<Vec<u8>>
647    where
648        P: Serialize + ?Sized,
649    {
650        self.request_with_extra_headers(method, path, params, signed, use_order_quota, None, None)
651            .await
652    }
653
654    #[expect(
655        clippy::too_many_arguments,
656        reason = "REST admission carries the snapshot reservation through read retries"
657    )]
658    async fn request_with_extra_headers<P>(
659        &self,
660        method: Method,
661        path: &str,
662        params: Option<&P>,
663        signed: bool,
664        use_order_quota: bool,
665        extra_headers: Option<HashMap<String, String>>,
666        snapshot: Option<&SnapshotAdmission>,
667    ) -> BinanceSpotHttpResult<Vec<u8>>
668    where
669        P: Serialize + ?Sized,
670    {
671        let operation = || {
672            self.request_with_extra_headers_once(
673                method.clone(),
674                path,
675                params,
676                signed,
677                use_order_quota,
678                extra_headers.clone(),
679                snapshot,
680            )
681        };
682
683        if method != Method::GET {
684            return operation().await;
685        }
686
687        self.retry_manager
688            .invocation(
689                path,
690                operation,
691                |e| self.command_order_quota.is_none() && e.is_retryable(),
692                |e| match e {
693                    RetryError::Canceled => {
694                        BinanceSpotHttpError::Canceled("HTTP requests canceled".to_string())
695                    }
696                    RetryError::OperationTimeout { timeout_ms } => {
697                        BinanceSpotHttpError::Timeout(format!("Request exceeded {timeout_ms}ms"))
698                    }
699                    RetryError::InvalidConfiguration { message } => {
700                        BinanceSpotHttpError::ValidationError(message)
701                    }
702                    e @ RetryError::ElapsedBudgetExceeded { .. } => {
703                        BinanceSpotHttpError::RetryBudgetExceeded(e.to_string())
704                    }
705                },
706            )
707            .retry_delay(&BinanceSpotHttpError::retry_after)
708            .execute()
709            .await
710    }
711
712    #[expect(
713        clippy::too_many_arguments,
714        reason = "REST admission carries the snapshot reservation through read retries"
715    )]
716    async fn request_with_extra_headers_once<P>(
717        &self,
718        method: Method,
719        path: &str,
720        params: Option<&P>,
721        signed: bool,
722        use_order_quota: bool,
723        extra_headers: Option<HashMap<String, String>>,
724        snapshot: Option<&SnapshotAdmission>,
725    ) -> BinanceSpotHttpResult<Vec<u8>>
726    where
727        P: Serialize + ?Sized,
728    {
729        let mut query = params
730            .map(serde_urlencoded::to_string)
731            .transpose()
732            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?
733            .unwrap_or_default();
734
735        let mut headers = extra_headers.unwrap_or_default();
736
737        let credential = if signed {
738            Some(
739                self.credential
740                    .as_ref()
741                    .ok_or(BinanceSpotHttpError::MissingCredentials)?,
742            )
743        } else {
744            None
745        };
746
747        let permit = match snapshot {
748            Some(snapshot) => Some(snapshot.acquire().await),
749            None => None,
750        };
751
752        let keys = self.rate_limit_keys(&method, path, &query, use_order_quota);
753        self.backoff
754            .admit(
755                &self.client,
756                keys,
757                use_order_quota || self.command_order_quota.unwrap_or(false),
758                method == Method::GET && self.command_order_quota.is_none(),
759            )
760            .await
761            .map_err(|()| BinanceSpotHttpError::RateLimitBlocked)?;
762
763        if let Some(permit) = permit {
764            permit.commit();
765        }
766
767        if let Some(cred) = credential {
768            if !query.is_empty() {
769                query.push('&');
770            }
771
772            let timestamp = Timestamp::now().as_millisecond();
773            query.push_str(&format!("timestamp={timestamp}"));
774
775            if let Some(recv_window) = self.recv_window {
776                query.push_str(&format!("&recvWindow={recv_window}"));
777            }
778
779            let signature = Self::percent_encode(&cred.sign(&query));
780            query.push_str(&format!("&signature={signature}"));
781            headers.insert(
782                BINANCE_API_KEY_HEADER.to_string(),
783                cred.api_key().to_string(),
784            );
785        }
786
787        let url = self.build_url(path, &query);
788
789        let response = self
790            .client
791            .request(
792                method,
793                url,
794                None::<&HashMap<String, Vec<String>>>,
795                Some(headers),
796                None,
797                None,
798                None,
799            )
800            .await?;
801
802        if !response.status.is_success() {
803            return self.parse_error_response(&response);
804        }
805
806        Ok(response.body.to_vec())
807    }
808
809    fn build_url(&self, path: &str, query: &str) -> String {
810        let normalized_path = if path.starts_with('/') {
811            path.to_string()
812        } else {
813            format!("/{path}")
814        };
815
816        let mut url = if normalized_path.starts_with(&format!("{SAPI_PATH}/")) {
817            format!("{}{normalized_path}", self.base_url)
818        } else {
819            format!("{}{}{}", self.base_url, SPOT_API_PATH, normalized_path)
820        };
821
822        if !query.is_empty() {
823            url.push('?');
824            url.push_str(query);
825        }
826        url
827    }
828
829    fn rate_limit_keys(
830        &self,
831        method: &Method,
832        path: &str,
833        query: &str,
834        use_orders: bool,
835    ) -> Vec<Ustr> {
836        let weight = request_weight_spot(method, path, query);
837        let mut keys = vec![Ustr::from(BINANCE_GLOBAL_RATE_KEY); weight as usize];
838        if use_orders {
839            keys.extend(self.order_rate_keys.iter().map(|key| Ustr::from(key)));
840        }
841
842        keys
843    }
844
845    fn parse_error_response<T>(&self, response: &HttpResponse) -> BinanceSpotHttpResult<T> {
846        let status = response.status.as_u16();
847        let body = &response.body;
848        let retry_after = crate::common::http::retry_after(&response.headers, Timestamp::now());
849
850        // Binance may return JSON errors even when SBE was requested
851        if let Ok(body_str) = std::str::from_utf8(body)
852            && let Ok(err) = serde_json::from_str::<BinanceErrorResponse>(body_str)
853        {
854            self.backoff.observe(status, Some(err.code), retry_after);
855            return Err(BinanceSpotHttpError::BinanceError {
856                code: err.code,
857                message: err.msg,
858                status,
859                retry_after,
860            });
861        }
862
863        // Try to decode SBE error response
864        if let Some((code, message)) = Self::try_decode_sbe_error(body) {
865            self.backoff
866                .observe(status, Some(i64::from(code)), retry_after);
867            return Err(BinanceSpotHttpError::BinanceError {
868                code: code.into(),
869                message,
870                status,
871                retry_after,
872            });
873        }
874
875        self.backoff.observe(status, None, retry_after);
876        Err(BinanceSpotHttpError::UnexpectedStatus {
877            status,
878            body: hex::encode(body),
879            retry_after,
880        })
881    }
882
883    /// Attempts to decode an SBE error response.
884    ///
885    /// Returns Some((code, message)) if successfully decoded, None otherwise.
886    fn try_decode_sbe_error(body: &[u8]) -> Option<(i16, String)> {
887        const HEADER_LEN: usize = 8;
888        if body.len() < HEADER_LEN + error_response_codec::SBE_BLOCK_LENGTH as usize {
889            return None;
890        }
891
892        let buf = ReadBuf::new(body);
893
894        // Decode message header
895        let header = MessageHeaderDecoder::default().wrap(buf, 0);
896        if header.template_id() != error_response_codec::SBE_TEMPLATE_ID {
897            return None;
898        }
899
900        // Decode error response
901        let mut decoder = ErrorResponseDecoder::default().header(header, 0);
902        let code = decoder.code();
903
904        // Decode the message string (VAR_DATA with 2-byte length prefix)
905        let msg_coords = decoder.msg_decoder();
906        let msg_bytes = decoder.msg_slice(msg_coords);
907        let message = String::from_utf8_lossy(msg_bytes).into_owned();
908
909        Some((code, message))
910    }
911
912    fn default_headers(
913        credential: &Option<SigningCredential>,
914        json_responses: bool,
915    ) -> HashMap<String, String> {
916        let mut headers: HashMap<String, String> =
917            create_standard_nautilus_headers().into_iter().collect();
918
919        if json_responses {
920            headers.insert("Accept".to_string(), "application/json".to_string());
921        } else {
922            headers.insert("Accept".to_string(), "application/sbe".to_string());
923            headers.insert("X-MBX-SBE".to_string(), SBE_SCHEMA_HEADER.to_string());
924        }
925
926        if let Some(cred) = credential {
927            headers.insert(
928                BINANCE_API_KEY_HEADER.to_string(),
929                cred.api_key().to_string(),
930            );
931        }
932        headers
933    }
934
935    fn rate_limit_config() -> RateLimitConfig {
936        let quotas = BINANCE_SPOT_RATE_LIMITS;
937        let mut keyed = Vec::new();
938        let mut order_keys = Vec::new();
939        let mut default = None;
940
941        for quota in quotas {
942            if let Some(q) = Self::quota_from(quota) {
943                match quota.rate_limit_type {
944                    BinanceRateLimitType::RequestWeight if default.is_none() => {
945                        default = Some(q);
946                    }
947                    BinanceRateLimitType::Orders => {
948                        let key = format!("{}:{:?}", BINANCE_ORDERS_RATE_KEY, quota.interval);
949                        order_keys.push(key.clone());
950                        keyed.push((key, q));
951                    }
952                    _ => {}
953                }
954            }
955        }
956
957        let default_quota = default.unwrap_or_else(|| {
958            Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant")
959        });
960
961        keyed.push((BINANCE_GLOBAL_RATE_KEY.to_string(), default_quota));
962
963        RateLimitConfig {
964            default_quota: Some(default_quota),
965            keyed_quotas: keyed,
966            order_keys,
967        }
968    }
969
970    fn quota_from(quota: &BinanceRateLimitQuota) -> Option<Quota> {
971        let burst = NonZeroU32::new(quota.limit)?;
972        match quota.interval {
973            BinanceRateLimitInterval::Second => Quota::per_second(burst),
974            BinanceRateLimitInterval::Minute => Some(Quota::per_minute(burst)),
975            BinanceRateLimitInterval::Day => {
976                Quota::with_period(std::time::Duration::from_secs(SECONDS_IN_DAY))
977                    .map(|q| q.allow_burst(burst))
978            }
979            BinanceRateLimitInterval::Unknown => None,
980        }
981    }
982
983    /// Tests connectivity to the API.
984    ///
985    /// # Errors
986    ///
987    /// Returns an error if the request fails or SBE decoding fails.
988    pub async fn ping(&self) -> BinanceSpotHttpResult<()> {
989        let bytes = self.get("ping", None::<&()>).await?;
990        parse::decode_ping(&bytes)?;
991        Ok(())
992    }
993
994    /// Returns the server time in **microseconds** since epoch.
995    ///
996    /// Note: SBE provides microsecond precision vs JSON's milliseconds.
997    ///
998    /// # Errors
999    ///
1000    /// Returns an error if the request fails or SBE decoding fails.
1001    pub async fn server_time(&self) -> BinanceSpotHttpResult<i64> {
1002        if self.json_responses {
1003            #[derive(Deserialize)]
1004            #[serde(rename_all = "camelCase")]
1005            struct ServerTimeJson {
1006                server_time: i64,
1007            }
1008
1009            let bytes = self.get_json("time", None::<&()>).await?;
1010            let response: ServerTimeJson = serde_json::from_slice(&bytes)
1011                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1012            return millis_to_micros(response.server_time);
1013        }
1014
1015        let bytes = self.get("time", None::<&()>).await?;
1016        let timestamp = parse::decode_server_time(&bytes)?;
1017        Ok(timestamp)
1018    }
1019
1020    /// Returns exchange information including trading symbols.
1021    ///
1022    /// # Errors
1023    ///
1024    /// Returns an error if the request fails or SBE decoding fails.
1025    pub async fn exchange_info(
1026        &self,
1027    ) -> BinanceSpotHttpResult<super::models::BinanceExchangeInfoSbe> {
1028        let bytes = self.get("exchangeInfo", None::<&()>).await?;
1029        let info = parse::decode_exchange_info(&bytes)?;
1030        Ok(info)
1031    }
1032
1033    /// Returns JSON exchange information for endpoints that do not support SBE.
1034    ///
1035    /// # Errors
1036    ///
1037    /// Returns an error if the request or JSON decode fails.
1038    pub async fn exchange_info_json(&self) -> BinanceSpotHttpResult<BinanceExchangeInfoJson> {
1039        let bytes = self.get_json("exchangeInfo", None::<&()>).await?;
1040        serde_json::from_slice(&bytes).map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))
1041    }
1042
1043    /// Returns order book depth for a symbol.
1044    ///
1045    /// # Errors
1046    ///
1047    /// Returns an error if the request fails or SBE decoding fails.
1048    pub async fn depth(&self, params: &DepthParams) -> BinanceSpotHttpResult<BinanceDepth> {
1049        self.depth_with_admission(params, None).await
1050    }
1051
1052    pub(crate) async fn depth_paced(
1053        &self,
1054        params: &DepthParams,
1055        permit: SnapshotPermit,
1056    ) -> BinanceSpotHttpResult<BinanceDepth> {
1057        self.depth_with_admission(params, Some(&SnapshotAdmission::new(permit)))
1058            .await
1059    }
1060
1061    async fn depth_with_admission(
1062        &self,
1063        params: &DepthParams,
1064        snapshot: Option<&SnapshotAdmission>,
1065    ) -> BinanceSpotHttpResult<BinanceDepth> {
1066        let headers = self
1067            .json_responses
1068            .then(|| HashMap::from([("Accept".to_string(), "application/json".to_string())]));
1069        let bytes = self
1070            .request_with_extra_headers(
1071                Method::GET,
1072                "depth",
1073                Some(params),
1074                false,
1075                false,
1076                headers,
1077                snapshot,
1078            )
1079            .await?;
1080
1081        if self.json_responses {
1082            let response: SpotDepthJson = serde_json::from_slice(&bytes)
1083                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1084            spot_depth_from_json(response)
1085        } else {
1086            Ok(parse::decode_depth(&bytes)?)
1087        }
1088    }
1089
1090    /// Returns recent trades for a symbol.
1091    ///
1092    /// # Errors
1093    ///
1094    /// Returns an error if the request fails or SBE decoding fails.
1095    pub async fn trades(
1096        &self,
1097        symbol: &str,
1098        limit: Option<u32>,
1099    ) -> BinanceSpotHttpResult<BinanceTrades> {
1100        let params = TradesParams {
1101            symbol: symbol.to_string(),
1102            limit,
1103        };
1104
1105        if self.json_responses {
1106            let bytes = self.get_json("trades", Some(&params)).await?;
1107            let response: Vec<SpotTradeJson> = serde_json::from_slice(&bytes)
1108                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1109            spot_trades_from_json(response)
1110        } else {
1111            let bytes = self.get("trades", Some(&params)).await?;
1112            Ok(parse::decode_trades(&bytes)?)
1113        }
1114    }
1115
1116    /// Returns aggregate trades for a symbol.
1117    ///
1118    /// # Errors
1119    ///
1120    /// Returns an error if the bounds are invalid or the request cannot be decoded.
1121    pub async fn agg_trades(
1122        &self,
1123        params: &AggTradesParams,
1124    ) -> BinanceSpotHttpResult<BinanceAggTrades> {
1125        if params.limit.is_some_and(|limit| limit > 1000) {
1126            return Err(BinanceSpotHttpError::ValidationError(
1127                "aggregate trade limit must not exceed 1000".to_string(),
1128            ));
1129        }
1130
1131        if matches!((params.start_time, params.end_time), (Some(start), Some(end)) if start > end) {
1132            return Err(BinanceSpotHttpError::ValidationError(
1133                "aggregate trade startTime must not exceed endTime".to_string(),
1134            ));
1135        }
1136
1137        if self.json_responses {
1138            let bytes = self.get_json("aggTrades", Some(params)).await?;
1139            let response: Vec<SpotAggTradeJson> = serde_json::from_slice(&bytes)
1140                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1141            spot_agg_trades_from_json(response)
1142        } else {
1143            let bytes = self.get("aggTrades", Some(params)).await?;
1144            Ok(parse::decode_agg_trades(&bytes)?)
1145        }
1146    }
1147
1148    /// Returns kline (candlestick) data for a symbol.
1149    ///
1150    /// # Errors
1151    ///
1152    /// Returns an error if the request fails or SBE decoding fails.
1153    pub async fn klines(
1154        &self,
1155        symbol: &str,
1156        interval: &str,
1157        start_time: Option<i64>,
1158        end_time: Option<i64>,
1159        limit: Option<u32>,
1160    ) -> BinanceSpotHttpResult<BinanceKlines> {
1161        let params = KlinesParams {
1162            symbol: symbol.to_string(),
1163            interval: interval.to_string(),
1164            start_time,
1165            end_time,
1166            time_zone: None,
1167            limit,
1168        };
1169
1170        if self.json_responses {
1171            let bytes = self.get_json("klines", Some(&params)).await?;
1172            let response: Vec<SpotKlineJson> = serde_json::from_slice(&bytes)
1173                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1174            spot_klines_from_json(response)
1175        } else {
1176            let bytes = self.get("klines", Some(&params)).await?;
1177            Ok(parse::decode_klines(&bytes)?)
1178        }
1179    }
1180
1181    /// Performs a public GET request that returns JSON.
1182    async fn get_json<P>(&self, path: &str, params: Option<&P>) -> BinanceSpotHttpResult<Vec<u8>>
1183    where
1184        P: Serialize + ?Sized,
1185    {
1186        self.request_with_extra_headers(
1187            Method::GET,
1188            path,
1189            params,
1190            false,
1191            false,
1192            Some(HashMap::from([(
1193                "Accept".to_string(),
1194                "application/json".to_string(),
1195            )])),
1196            None,
1197        )
1198        .await
1199    }
1200
1201    /// Returns 24-hour ticker price change statistics.
1202    ///
1203    /// If `symbol` is None, returns statistics for all symbols.
1204    ///
1205    /// # Errors
1206    ///
1207    /// Returns an error if the request fails.
1208    pub async fn ticker_24hr(
1209        &self,
1210        symbol: Option<&str>,
1211    ) -> BinanceSpotHttpResult<Vec<Ticker24hr>> {
1212        let params = symbol.map(TickerParams::for_symbol);
1213        let bytes = self.get_json("ticker/24hr", params.as_ref()).await?;
1214
1215        // Single symbol returns object, multiple returns array
1216        if symbol.is_some() {
1217            let ticker: Ticker24hr = serde_json::from_slice(&bytes)
1218                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1219            Ok(vec![ticker])
1220        } else {
1221            let tickers: Vec<Ticker24hr> = serde_json::from_slice(&bytes)
1222                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1223            Ok(tickers)
1224        }
1225    }
1226
1227    /// Returns latest price for a symbol or all symbols.
1228    ///
1229    /// If `symbol` is None, returns prices for all symbols.
1230    ///
1231    /// # Errors
1232    ///
1233    /// Returns an error if the request fails.
1234    pub async fn ticker_price(
1235        &self,
1236        symbol: Option<&str>,
1237    ) -> BinanceSpotHttpResult<Vec<TickerPrice>> {
1238        let params = symbol.map(TickerParams::for_symbol);
1239        let bytes = self.get_json("ticker/price", params.as_ref()).await?;
1240
1241        // Single symbol returns object, multiple returns array
1242        if symbol.is_some() {
1243            let ticker: TickerPrice = serde_json::from_slice(&bytes)
1244                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1245            Ok(vec![ticker])
1246        } else {
1247            let tickers: Vec<TickerPrice> = serde_json::from_slice(&bytes)
1248                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1249            Ok(tickers)
1250        }
1251    }
1252
1253    /// Returns best bid/ask price for a symbol or all symbols.
1254    ///
1255    /// If `symbol` is None, returns book ticker for all symbols.
1256    ///
1257    /// # Errors
1258    ///
1259    /// Returns an error if the request fails.
1260    pub async fn ticker_book(
1261        &self,
1262        symbol: Option<&str>,
1263    ) -> BinanceSpotHttpResult<Vec<BookTicker>> {
1264        let params = symbol.map(TickerParams::for_symbol);
1265        let bytes = self.get_json("ticker/bookTicker", params.as_ref()).await?;
1266
1267        // Single symbol returns object, multiple returns array
1268        if symbol.is_some() {
1269            let ticker: BookTicker = serde_json::from_slice(&bytes)
1270                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1271            Ok(vec![ticker])
1272        } else {
1273            let tickers: Vec<BookTicker> = serde_json::from_slice(&bytes)
1274                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1275            Ok(tickers)
1276        }
1277    }
1278
1279    /// Returns current average price for a symbol.
1280    ///
1281    /// # Errors
1282    ///
1283    /// Returns an error if the request fails.
1284    pub async fn avg_price(&self, symbol: &str) -> BinanceSpotHttpResult<AvgPrice> {
1285        let params = AvgPriceParams::new(symbol);
1286        let bytes = self.get_json("avgPrice", Some(&params)).await?;
1287
1288        let avg_price: AvgPrice = serde_json::from_slice(&bytes)
1289            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1290        Ok(avg_price)
1291    }
1292
1293    /// Returns trading fee rates for symbols.
1294    ///
1295    /// If `symbol` is None, returns fee rates for all symbols.
1296    /// Uses SAPI endpoint (requires authentication).
1297    ///
1298    /// # Errors
1299    ///
1300    /// Returns an error if credentials are missing or the request fails.
1301    pub async fn get_trade_fee(
1302        &self,
1303        symbol: Option<&str>,
1304    ) -> BinanceSpotHttpResult<Vec<TradeFee>> {
1305        let params = symbol.map(TradeFeeParams::for_symbol);
1306        let bytes = self
1307            .get_signed_sapi("asset/tradeFee", params.as_ref())
1308            .await?;
1309
1310        let fees: Vec<TradeFee> = serde_json::from_slice(&bytes)
1311            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1312        Ok(fees)
1313    }
1314
1315    /// Performs a signed GET request to SAPI endpoints (returns JSON).
1316    async fn get_signed_sapi<P>(
1317        &self,
1318        path: &str,
1319        params: Option<&P>,
1320    ) -> BinanceSpotHttpResult<Vec<u8>>
1321    where
1322        P: Serialize + ?Sized,
1323    {
1324        let path = format!("{SAPI_PATH}/{}", path.trim_start_matches('/'));
1325        self.request(Method::GET, &path, params, true, false).await
1326    }
1327
1328    /// Percent-encodes a string for use in URL query parameters.
1329    fn percent_encode(input: &str) -> String {
1330        let mut result = String::with_capacity(input.len() * 3);
1331        for byte in input.bytes() {
1332            match byte {
1333                // Unreserved characters (RFC 3986)
1334                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
1335                    result.push(byte as char);
1336                }
1337                _ => {
1338                    result.push('%');
1339                    result.push_str(&format!("{byte:02X}"));
1340                }
1341            }
1342        }
1343        result
1344    }
1345
1346    /// Submits multiple orders in a single request (up to 5 orders).
1347    ///
1348    /// Each order in the batch is processed independently. The response contains
1349    /// the result for each order, which can be either a success or an error.
1350    ///
1351    /// # Errors
1352    ///
1353    /// Returns an error if credentials are missing, the request fails, or JSON parsing fails.
1354    /// Individual order failures are returned in the response array as `BatchOrderResult::Error`.
1355    pub async fn batch_submit_orders(
1356        &self,
1357        orders: &[BatchOrderItem],
1358    ) -> BinanceSpotHttpResult<Vec<BatchOrderResult>> {
1359        if orders.is_empty() {
1360            return Ok(Vec::new());
1361        }
1362
1363        if orders.len() > 5 {
1364            return Err(BinanceSpotHttpError::ValidationError(
1365                "Batch order limit is 5 orders maximum".to_string(),
1366            ));
1367        }
1368
1369        let batch_json = serde_json::to_string(orders)
1370            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?;
1371
1372        let bytes = self
1373            .batch_request(Method::POST, "batchOrders", &batch_json)
1374            .await?;
1375
1376        let results: Vec<BatchOrderResult> = serde_json::from_slice(&bytes)
1377            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1378
1379        Ok(results)
1380    }
1381
1382    /// Cancels multiple orders in a single request (up to 5 orders).
1383    ///
1384    /// Each cancel in the batch is processed independently. The response contains
1385    /// the result for each cancel, which can be either a success or an error.
1386    ///
1387    /// # Errors
1388    ///
1389    /// Returns an error if credentials are missing, the request fails, or JSON parsing fails.
1390    /// Individual cancel failures are returned in the response array as `BatchCancelResult::Error`.
1391    pub async fn batch_cancel_orders(
1392        &self,
1393        cancels: &[BatchCancelItem],
1394    ) -> BinanceSpotHttpResult<Vec<BatchCancelResult>> {
1395        if cancels.is_empty() {
1396            return Ok(Vec::new());
1397        }
1398
1399        if cancels.len() > 5 {
1400            return Err(BinanceSpotHttpError::ValidationError(
1401                "Batch cancel limit is 5 orders maximum".to_string(),
1402            ));
1403        }
1404
1405        let batch_json = serde_json::to_string(cancels)
1406            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?;
1407
1408        let bytes = self
1409            .batch_request(Method::DELETE, "batchOrders", &batch_json)
1410            .await?;
1411
1412        let results: Vec<BatchCancelResult> = serde_json::from_slice(&bytes)
1413            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1414
1415        Ok(results)
1416    }
1417
1418    /// Performs a signed batch request with the batchOrders parameter.
1419    async fn batch_request(
1420        &self,
1421        method: Method,
1422        path: &str,
1423        batch_json: &str,
1424    ) -> BinanceSpotHttpResult<Vec<u8>> {
1425        let cred = self
1426            .credential
1427            .as_ref()
1428            .ok_or(BinanceSpotHttpError::MissingCredentials)?;
1429
1430        let encoded_batch = Self::percent_encode(batch_json);
1431        let use_order_quota = method == Method::POST;
1432        let keys = self.rate_limit_keys(&method, path, "", use_order_quota);
1433        self.backoff
1434            .admit(&self.client, keys, use_order_quota, false)
1435            .await
1436            .map_err(|()| BinanceSpotHttpError::RateLimitBlocked)?;
1437
1438        let timestamp = Timestamp::now().as_millisecond();
1439        let mut query = format!("batchOrders={encoded_batch}&timestamp={timestamp}");
1440
1441        if let Some(recv_window) = self.recv_window {
1442            query.push_str(&format!("&recvWindow={recv_window}"));
1443        }
1444
1445        let signature = Self::percent_encode(&cred.sign(&query));
1446        query.push_str(&format!("&signature={signature}"));
1447
1448        let url = self.build_url(path, &query);
1449
1450        let mut headers = HashMap::new();
1451        headers.insert(
1452            BINANCE_API_KEY_HEADER.to_string(),
1453            cred.api_key().to_string(),
1454        );
1455
1456        let response = self
1457            .client
1458            .request(
1459                method,
1460                url,
1461                None::<&HashMap<String, Vec<String>>>,
1462                Some(headers),
1463                None,
1464                None,
1465                None,
1466            )
1467            .await?;
1468
1469        if !response.status.is_success() {
1470            return self.parse_error_response(&response);
1471        }
1472
1473        Ok(response.body.to_vec())
1474    }
1475
1476    /// Returns account information including balances.
1477    ///
1478    /// # Errors
1479    ///
1480    /// Returns an error if the request fails or SBE decoding fails.
1481    pub async fn account(
1482        &self,
1483        params: &AccountInfoParams,
1484    ) -> BinanceSpotHttpResult<BinanceAccountInfo> {
1485        if self.json_responses {
1486            let bytes = self.get_signed_json("account", Some(params)).await?;
1487            let response: SpotAccountJson = serde_json::from_slice(&bytes)
1488                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1489            spot_account_from_json(response)
1490        } else {
1491            let bytes = self.get_signed("account", Some(params)).await?;
1492            Ok(parse::decode_account(&bytes)?)
1493        }
1494    }
1495
1496    /// Returns account-specific commission rates for one symbol.
1497    ///
1498    /// # Errors
1499    ///
1500    /// Returns an error if credentials are missing, the request fails, or JSON is malformed.
1501    pub async fn account_commission(
1502        &self,
1503        symbol: &str,
1504    ) -> BinanceSpotHttpResult<BinanceAccountCommission> {
1505        let params = AccountCommissionParams::new(symbol);
1506        let bytes = self
1507            .get_signed_json("account/commission", Some(&params))
1508            .await?;
1509        serde_json::from_slice(&bytes).map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))
1510    }
1511
1512    /// Returns the minimal JSON account commission view used by Binance US.
1513    ///
1514    /// # Errors
1515    ///
1516    /// Returns an error if credentials are missing, the request fails, or JSON is malformed.
1517    pub async fn account_rates_json(&self) -> BinanceSpotHttpResult<BinanceAccountRatesJson> {
1518        let params = AccountInfoParams::default();
1519        let bytes = self.get_signed_json("account", Some(&params)).await?;
1520        serde_json::from_slice(&bytes).map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))
1521    }
1522
1523    /// Returns account trade history for a symbol.
1524    ///
1525    /// # Errors
1526    ///
1527    /// Returns an error if the request fails or SBE decoding fails.
1528    pub async fn account_trades(
1529        &self,
1530        symbol: &str,
1531        order_id: Option<i64>,
1532        start_time: Option<i64>,
1533        end_time: Option<i64>,
1534        limit: Option<u32>,
1535    ) -> BinanceSpotHttpResult<Vec<BinanceAccountTrade>> {
1536        self.account_trades_with_cursor(symbol, order_id, start_time, end_time, None, limit)
1537            .await
1538    }
1539
1540    async fn account_trades_with_cursor(
1541        &self,
1542        symbol: &str,
1543        order_id: Option<i64>,
1544        start_time: Option<i64>,
1545        end_time: Option<i64>,
1546        from_id: Option<i64>,
1547        limit: Option<u32>,
1548    ) -> BinanceSpotHttpResult<Vec<BinanceAccountTrade>> {
1549        let params = AccountTradesParams {
1550            symbol: symbol.to_string(),
1551            order_id,
1552            start_time,
1553            end_time,
1554            from_id,
1555            limit,
1556        };
1557
1558        if self.json_responses {
1559            let bytes = self.get_signed_json("myTrades", Some(&params)).await?;
1560            let response: Vec<SpotAccountTradeJson> = serde_json::from_slice(&bytes)
1561                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1562            response
1563                .into_iter()
1564                .map(spot_account_trade_from_json)
1565                .collect()
1566        } else {
1567            let bytes = self.get_signed("myTrades", Some(&params)).await?;
1568            Ok(parse::decode_account_trades(&bytes)?)
1569        }
1570    }
1571
1572    /// Queries an order's status.
1573    ///
1574    /// Either `order_id` or `client_order_id` must be provided.
1575    ///
1576    /// # Errors
1577    ///
1578    /// Returns an error if the request fails or SBE decoding fails.
1579    pub async fn query_order(
1580        &self,
1581        symbol: &str,
1582        order_id: Option<i64>,
1583        client_order_id: Option<&str>,
1584    ) -> BinanceSpotHttpResult<BinanceOrderResponse> {
1585        let Some(legacy) = client_order_id
1586            .and_then(|id| legacy_client_order_id(id, BINANCE_NAUTILUS_SPOT_BROKER_ID))
1587        else {
1588            return self
1589                .query_order_exact(symbol, order_id, client_order_id)
1590                .await;
1591        };
1592
1593        if order_id.is_some() {
1594            return self.query_order_exact(symbol, order_id, None).await;
1595        }
1596
1597        let current = self.query_order_exact(symbol, None, client_order_id).await;
1598        if let Err(e) = &current
1599            && !matches!(
1600                e,
1601                BinanceSpotHttpError::BinanceError {
1602                    code: BINANCE_NO_SUCH_ORDER_CODE,
1603                    ..
1604                }
1605            )
1606        {
1607            return current;
1608        }
1609
1610        let historical = self.query_order_exact(symbol, None, Some(&legacy)).await;
1611        match (current, historical) {
1612            (Ok(current), Ok(historical)) if current.order_id != historical.order_id => {
1613                Err(BinanceSpotHttpError::ValidationError(
1614                    "Ambiguous historical client order ID".to_string(),
1615                ))
1616            }
1617            (Ok(current), Ok(_)) => Ok(current),
1618            (
1619                Ok(current),
1620                Err(BinanceSpotHttpError::BinanceError {
1621                    code: BINANCE_NO_SUCH_ORDER_CODE,
1622                    ..
1623                }),
1624            ) => Ok(current),
1625            (Err(_), Ok(historical)) => Ok(historical),
1626            (_, Err(e)) => Err(e),
1627        }
1628    }
1629
1630    async fn query_order_exact(
1631        &self,
1632        symbol: &str,
1633        order_id: Option<i64>,
1634        client_order_id: Option<&str>,
1635    ) -> BinanceSpotHttpResult<BinanceOrderResponse> {
1636        let params = QueryOrderParams {
1637            symbol: symbol.to_string(),
1638            order_id,
1639            orig_client_order_id: client_order_id.map(|s| s.to_string()),
1640        };
1641
1642        if self.json_responses {
1643            let bytes = self.get_signed_json("order", Some(&params)).await?;
1644            let response: SpotOrderJson = serde_json::from_slice(&bytes)
1645                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1646            spot_order_from_json(response)
1647        } else {
1648            let bytes = self.get_signed("order", Some(&params)).await?;
1649            Ok(parse::decode_order(&bytes)?)
1650        }
1651    }
1652
1653    /// Returns all open orders for a symbol or all symbols.
1654    ///
1655    /// # Errors
1656    ///
1657    /// Returns an error if the request fails or SBE decoding fails.
1658    pub async fn open_orders(
1659        &self,
1660        symbol: Option<&str>,
1661    ) -> BinanceSpotHttpResult<Vec<BinanceOrderResponse>> {
1662        let params = OpenOrdersParams {
1663            symbol: symbol.map(|s| s.to_string()),
1664        };
1665
1666        if self.json_responses {
1667            let bytes = self.get_signed_json("openOrders", Some(&params)).await?;
1668            let response: Vec<SpotOrderJson> = serde_json::from_slice(&bytes)
1669                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1670            response.into_iter().map(spot_order_from_json).collect()
1671        } else {
1672            let bytes = self.get_signed("openOrders", Some(&params)).await?;
1673            Ok(parse::decode_orders(&bytes)?)
1674        }
1675    }
1676
1677    /// Returns all orders (including closed) for a symbol.
1678    ///
1679    /// # Errors
1680    ///
1681    /// Returns an error if the request fails or SBE decoding fails.
1682    pub async fn all_orders(
1683        &self,
1684        symbol: &str,
1685        start_time: Option<i64>,
1686        end_time: Option<i64>,
1687        limit: Option<u32>,
1688    ) -> BinanceSpotHttpResult<Vec<BinanceOrderResponse>> {
1689        self.all_orders_with_cursor(symbol, None, start_time, end_time, limit)
1690            .await
1691    }
1692
1693    async fn all_orders_with_cursor(
1694        &self,
1695        symbol: &str,
1696        order_id: Option<i64>,
1697        start_time: Option<i64>,
1698        end_time: Option<i64>,
1699        limit: Option<u32>,
1700    ) -> BinanceSpotHttpResult<Vec<BinanceOrderResponse>> {
1701        let params = AllOrdersParams {
1702            symbol: symbol.to_string(),
1703            order_id,
1704            start_time,
1705            end_time,
1706            limit,
1707        };
1708
1709        if self.json_responses {
1710            let bytes = self.get_signed_json("allOrders", Some(&params)).await?;
1711            let response: Vec<SpotOrderJson> = serde_json::from_slice(&bytes)
1712                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1713            response.into_iter().map(spot_order_from_json).collect()
1714        } else {
1715            let bytes = self.get_signed("allOrders", Some(&params)).await?;
1716            Ok(parse::decode_orders(&bytes)?)
1717        }
1718    }
1719
1720    /// Performs a signed POST request for order operations.
1721    async fn post_order<P>(&self, path: &str, params: Option<&P>) -> BinanceSpotHttpResult<Vec<u8>>
1722    where
1723        P: Serialize + ?Sized,
1724    {
1725        if self.json_responses {
1726            self.post_signed_json(path, params).await
1727        } else {
1728            self.post_signed(path, params).await
1729        }
1730    }
1731
1732    /// Performs a signed DELETE request for cancel operations.
1733    async fn delete_order<P>(
1734        &self,
1735        path: &str,
1736        params: Option<&P>,
1737    ) -> BinanceSpotHttpResult<Vec<u8>>
1738    where
1739        P: Serialize + ?Sized,
1740    {
1741        if self.json_responses {
1742            self.delete_signed_json(path, params).await
1743        } else {
1744            self.delete_signed(path, params).await
1745        }
1746    }
1747
1748    /// Creates a new order.
1749    ///
1750    /// # Errors
1751    ///
1752    /// Returns an error if the request fails or SBE decoding fails.
1753    #[expect(clippy::too_many_arguments)]
1754    pub async fn new_order(
1755        &self,
1756        symbol: &str,
1757        side: BinanceSide,
1758        order_type: BinanceSpotOrderType,
1759        time_in_force: Option<BinanceTimeInForce>,
1760        quantity: Option<&str>,
1761        price: Option<&str>,
1762        client_order_id: Option<&str>,
1763        stop_price: Option<&str>,
1764    ) -> BinanceSpotHttpResult<BinanceNewOrderResponse> {
1765        let params = NewOrderParams {
1766            symbol: symbol.to_string(),
1767            side,
1768            order_type,
1769            time_in_force,
1770            quantity: quantity.map(|s| s.to_string()),
1771            quote_order_qty: None,
1772            price: price.map(|s| s.to_string()),
1773            new_client_order_id: client_order_id.map(|s| s.to_string()),
1774            stop_price: stop_price.map(|s| s.to_string()),
1775            trailing_delta: None,
1776            iceberg_qty: None,
1777            new_order_resp_type: Some(BinanceOrderResponseType::Full),
1778            self_trade_prevention_mode: None,
1779            strategy_id: None,
1780            strategy_type: None,
1781        };
1782        let bytes = self.post_order("order", Some(&params)).await?;
1783        self.decode_new_order_response(&bytes)
1784    }
1785
1786    /// Creates a new order with full parameter support.
1787    ///
1788    /// Extends [`new_order`](Self::new_order) with `quote_order_qty` (for market
1789    /// orders denominated in quote currency) and `iceberg_qty` (display
1790    /// quantity for iceberg orders).
1791    ///
1792    /// # Errors
1793    ///
1794    /// Returns an error if the request fails or SBE decoding fails.
1795    #[expect(clippy::too_many_arguments)]
1796    pub async fn new_order_full(
1797        &self,
1798        symbol: &str,
1799        side: BinanceSide,
1800        order_type: BinanceSpotOrderType,
1801        time_in_force: Option<BinanceTimeInForce>,
1802        quantity: Option<&str>,
1803        quote_order_qty: Option<&str>,
1804        price: Option<&str>,
1805        client_order_id: Option<&str>,
1806        stop_price: Option<&str>,
1807        iceberg_qty: Option<&str>,
1808    ) -> BinanceSpotHttpResult<BinanceNewOrderResponse> {
1809        let params = NewOrderParams {
1810            symbol: symbol.to_string(),
1811            side,
1812            order_type,
1813            time_in_force,
1814            quantity: quantity.map(|s| s.to_string()),
1815            quote_order_qty: quote_order_qty.map(|s| s.to_string()),
1816            price: price.map(|s| s.to_string()),
1817            new_client_order_id: client_order_id.map(|s| s.to_string()),
1818            stop_price: stop_price.map(|s| s.to_string()),
1819            trailing_delta: None,
1820            iceberg_qty: iceberg_qty.map(|s| s.to_string()),
1821            new_order_resp_type: Some(BinanceOrderResponseType::Full),
1822            self_trade_prevention_mode: None,
1823            strategy_id: None,
1824            strategy_type: None,
1825        };
1826        let bytes = self.post_order("order", Some(&params)).await?;
1827        self.decode_new_order_response(&bytes)
1828    }
1829
1830    /// Creates a new OCO order list.
1831    ///
1832    /// # Errors
1833    ///
1834    /// Returns an error if the request fails or JSON decoding fails.
1835    pub async fn new_oco_order_list(
1836        &self,
1837        params: &NewOcoOrderListParams,
1838    ) -> BinanceSpotHttpResult<NewOcoOrderListResponse> {
1839        let bytes = self.post_signed_json("orderList/oco", Some(params)).await?;
1840        serde_json::from_slice(&bytes).map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))
1841    }
1842
1843    /// Cancels an existing order and places a new order atomically.
1844    ///
1845    /// # Errors
1846    ///
1847    /// Returns an error if the request fails or SBE decoding fails.
1848    #[expect(clippy::too_many_arguments)]
1849    pub async fn cancel_replace_order(
1850        &self,
1851        symbol: &str,
1852        side: BinanceSide,
1853        order_type: BinanceSpotOrderType,
1854        time_in_force: Option<BinanceTimeInForce>,
1855        quantity: Option<&str>,
1856        price: Option<&str>,
1857        cancel_order_id: Option<i64>,
1858        cancel_client_order_id: Option<&str>,
1859        cancel_new_client_order_id: Option<&str>,
1860        new_client_order_id: Option<&str>,
1861    ) -> BinanceSpotHttpResult<BinanceNewOrderResponse> {
1862        let mut params = CancelReplaceOrderParams {
1863            symbol: symbol.to_string(),
1864            side,
1865            order_type,
1866            cancel_replace_mode: BinanceCancelReplaceMode::StopOnFailure,
1867            time_in_force,
1868            quantity: quantity.map(|s| s.to_string()),
1869            quote_order_qty: None,
1870            price: price.map(|s| s.to_string()),
1871            cancel_order_id,
1872            cancel_orig_client_order_id: cancel_client_order_id.map(|s| s.to_string()),
1873            cancel_new_client_order_id: cancel_new_client_order_id.map(|s| s.to_string()),
1874            new_client_order_id: new_client_order_id.map(|s| s.to_string()),
1875            stop_price: None,
1876            trailing_delta: None,
1877            iceberg_qty: None,
1878            new_order_resp_type: Some(BinanceOrderResponseType::Full),
1879            self_trade_prevention_mode: None,
1880        };
1881
1882        self.resolve_cancel_replace(&mut params).await?;
1883        let bytes = self
1884            .post_order("order/cancelReplace", Some(&params))
1885            .await?;
1886
1887        if self.json_responses {
1888            let response: SpotCancelReplaceJson = serde_json::from_slice(&bytes)
1889                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
1890            spot_new_order_from_json(response.new_order_response)
1891        } else {
1892            Ok(parse::decode_cancel_replace(&bytes)?)
1893        }
1894    }
1895
1896    pub(crate) async fn resolve_cancel_replace(
1897        &self,
1898        params: &mut CancelReplaceOrderParams,
1899    ) -> BinanceSpotHttpResult<()> {
1900        let replacement = params
1901            .new_client_order_id
1902            .as_deref()
1903            .and_then(|id| legacy_client_order_id(id, BINANCE_NAUTILUS_SPOT_BROKER_ID));
1904        let historical = params
1905            .cancel_orig_client_order_id
1906            .as_deref()
1907            .and_then(|id| legacy_client_order_id(id, BINANCE_NAUTILUS_SPOT_BROKER_ID));
1908
1909        if replacement.is_none() && historical.is_none() {
1910            return Ok(());
1911        }
1912
1913        let order = self
1914            .for_command(true)
1915            .query_order(
1916                &params.symbol,
1917                params.cancel_order_id,
1918                params.cancel_orig_client_order_id.as_deref(),
1919            )
1920            .await
1921            .map_err(|e| {
1922                BinanceSpotHttpError::ValidationError(format!(
1923                    "Cancel-replace identity lookup failed before submission: {e}"
1924                ))
1925            })?;
1926
1927        params.cancel_order_id = Some(order.order_id);
1928        params.cancel_orig_client_order_id = None;
1929
1930        if let Some(replacement) = replacement {
1931            let original =
1932                decode_client_order_id(&order.client_order_id, BINANCE_NAUTILUS_SPOT_BROKER_ID)
1933                    .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?;
1934
1935            if original.as_str() == replacement {
1936                // Changing the wire ID would make later lookups ambiguous
1937                params.new_client_order_id = Some(order.client_order_id);
1938            }
1939        }
1940
1941        Ok(())
1942    }
1943
1944    /// Cancels an existing order.
1945    ///
1946    /// Either `order_id` or `client_order_id` must be provided.
1947    ///
1948    /// # Errors
1949    ///
1950    /// Returns an error if the request fails or SBE decoding fails.
1951    pub async fn cancel_order(
1952        &self,
1953        symbol: &str,
1954        order_id: Option<i64>,
1955        client_order_id: Option<&str>,
1956    ) -> BinanceSpotHttpResult<BinanceCancelOrderResponse> {
1957        let mut params = match (order_id, client_order_id) {
1958            (Some(id), _) => CancelOrderParams::by_order_id(symbol, id),
1959            (None, Some(id)) => CancelOrderParams::by_client_order_id(symbol, id.to_string()),
1960            (None, None) => {
1961                return Err(BinanceSpotHttpError::ValidationError(
1962                    "Either order_id or client_order_id must be provided".to_string(),
1963                ));
1964            }
1965        };
1966
1967        self.resolve_cancel_order(&mut params).await?;
1968        let bytes = self.delete_order("order", Some(&params)).await?;
1969        self.decode_cancel_order_response(&bytes)
1970    }
1971
1972    pub(crate) async fn resolve_cancel_order(
1973        &self,
1974        params: &mut CancelOrderParams,
1975    ) -> BinanceSpotHttpResult<()> {
1976        let Some(id) = params
1977            .orig_client_order_id
1978            .as_deref()
1979            .filter(|id| legacy_client_order_id(id, BINANCE_NAUTILUS_SPOT_BROKER_ID).is_some())
1980        else {
1981            return Ok(());
1982        };
1983
1984        if params.order_id.is_none() {
1985            params.order_id = Some(
1986                self.for_command(false)
1987                    .query_order(&params.symbol, None, Some(id))
1988                    .await
1989                    .map_err(|e| {
1990                        BinanceSpotHttpError::ValidationError(format!(
1991                            "Cancel identity lookup failed before submission: {e}"
1992                        ))
1993                    })?
1994                    .order_id,
1995            );
1996        }
1997
1998        params.orig_client_order_id = None;
1999        Ok(())
2000    }
2001
2002    fn for_command(&self, use_order_quota: bool) -> Self {
2003        Self {
2004            command_order_quota: Some(use_order_quota),
2005            ..self.clone()
2006        }
2007    }
2008
2009    /// Cancels all open orders for a symbol.
2010    ///
2011    /// Returns one response per ordinary order and order-list child.
2012    ///
2013    /// # Errors
2014    ///
2015    /// Returns an error if the request fails or SBE decoding fails.
2016    pub async fn cancel_open_orders(
2017        &self,
2018        symbol: &str,
2019    ) -> BinanceSpotHttpResult<Vec<BinanceCancelOrderResponse>> {
2020        Ok(self
2021            .cancel_open_order_responses(symbol)
2022            .await?
2023            .into_iter()
2024            .flat_map(|response| match response {
2025                BinanceCancelOpenOrdersResponse::Order(response) => vec![response],
2026                BinanceCancelOpenOrdersResponse::OrderList(response) => response.order_reports,
2027            })
2028            .collect())
2029    }
2030
2031    /// Cancels all open orders for a symbol and preserves order-list responses.
2032    ///
2033    /// # Errors
2034    ///
2035    /// Returns an error if the request fails or SBE decoding fails.
2036    pub async fn cancel_open_order_responses(
2037        &self,
2038        symbol: &str,
2039    ) -> BinanceSpotHttpResult<Vec<BinanceCancelOpenOrdersResponse>> {
2040        let params = CancelOpenOrdersParams::new(symbol.to_string());
2041        let bytes = self.delete_order("openOrders", Some(&params)).await?;
2042        if self.json_responses {
2043            spot_cancel_open_orders_from_json(&bytes)
2044        } else {
2045            Ok(parse::decode_cancel_open_orders(&bytes)?)
2046        }
2047    }
2048
2049    fn decode_new_order_response(
2050        &self,
2051        bytes: &[u8],
2052    ) -> BinanceSpotHttpResult<BinanceNewOrderResponse> {
2053        if self.json_responses {
2054            let response: SpotOrderJson = serde_json::from_slice(bytes)
2055                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
2056            spot_new_order_from_json(response)
2057        } else {
2058            Ok(parse::decode_new_order_full(bytes)?)
2059        }
2060    }
2061
2062    fn decode_cancel_order_response(
2063        &self,
2064        bytes: &[u8],
2065    ) -> BinanceSpotHttpResult<BinanceCancelOrderResponse> {
2066        if self.json_responses {
2067            let response: SpotOrderJson = serde_json::from_slice(bytes)
2068                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
2069            spot_cancel_order_from_json(response)
2070        } else {
2071            Ok(parse::decode_cancel_order(bytes)?)
2072        }
2073    }
2074
2075    /// Performs an API-key authenticated request (no signature) that returns JSON.
2076    async fn request_with_api_key<P>(
2077        &self,
2078        method: Method,
2079        path: &str,
2080        params: Option<&P>,
2081    ) -> BinanceSpotHttpResult<Vec<u8>>
2082    where
2083        P: Serialize + ?Sized,
2084    {
2085        let cred = self
2086            .credential
2087            .as_ref()
2088            .ok_or(BinanceSpotHttpError::MissingCredentials)?;
2089
2090        let keys = vec![Ustr::from(BINANCE_GLOBAL_RATE_KEY)];
2091        self.backoff
2092            .admit(
2093                &self.client,
2094                keys,
2095                false,
2096                method == Method::GET && self.command_order_quota.is_none(),
2097            )
2098            .await
2099            .map_err(|()| BinanceSpotHttpError::RateLimitBlocked)?;
2100
2101        let query = params
2102            .map(serde_urlencoded::to_string)
2103            .transpose()
2104            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?
2105            .unwrap_or_default();
2106
2107        let url = self.build_url(path, &query);
2108
2109        let mut headers = HashMap::new();
2110        headers.insert(
2111            BINANCE_API_KEY_HEADER.to_string(),
2112            cred.api_key().to_string(),
2113        );
2114
2115        let response = self
2116            .client
2117            .request(
2118                method,
2119                url,
2120                None::<&HashMap<String, Vec<String>>>,
2121                Some(headers),
2122                None,
2123                None,
2124                None,
2125            )
2126            .await?;
2127
2128        if !response.status.is_success() {
2129            return self.parse_error_response(&response);
2130        }
2131
2132        Ok(response.body.to_vec())
2133    }
2134
2135    /// Creates a new listen key for the user data stream.
2136    ///
2137    /// Listen keys are valid for 60 minutes. Use `extend_listen_key` to keep
2138    /// the stream alive.
2139    ///
2140    /// # Errors
2141    ///
2142    /// Returns an error if credentials are missing or the request fails.
2143    pub async fn create_listen_key(&self) -> BinanceSpotHttpResult<ListenKeyResponse> {
2144        let bytes = self
2145            .request_with_api_key(Method::POST, "userDataStream", None::<&()>)
2146            .await?;
2147
2148        let response: ListenKeyResponse = serde_json::from_slice(&bytes)
2149            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
2150
2151        Ok(response)
2152    }
2153
2154    /// Extends the validity of a listen key by 60 minutes.
2155    ///
2156    /// Should be called periodically to keep the user data stream alive.
2157    ///
2158    /// # Errors
2159    ///
2160    /// Returns an error if credentials are missing or the request fails.
2161    pub async fn extend_listen_key(&self, listen_key: &str) -> BinanceSpotHttpResult<()> {
2162        let params = ListenKeyParams::new(listen_key);
2163        self.request_with_api_key(Method::PUT, "userDataStream", Some(&params))
2164            .await?;
2165        Ok(())
2166    }
2167
2168    /// Closes a listen key, terminating the user data stream.
2169    ///
2170    /// # Errors
2171    ///
2172    /// Returns an error if credentials are missing or the request fails.
2173    pub async fn close_listen_key(&self, listen_key: &str) -> BinanceSpotHttpResult<()> {
2174        let params = ListenKeyParams::new(listen_key);
2175        self.request_with_api_key(Method::DELETE, "userDataStream", Some(&params))
2176            .await?;
2177        Ok(())
2178    }
2179}
2180
2181fn spot_depth_from_json(response: SpotDepthJson) -> BinanceSpotHttpResult<BinanceDepth> {
2182    let price_scale = decimal_common_scale(
2183        response
2184            .bids
2185            .iter()
2186            .chain(&response.asks)
2187            .map(|level| level[0].as_str()),
2188    )?;
2189    let qty_scale = decimal_common_scale(
2190        response
2191            .bids
2192            .iter()
2193            .chain(&response.asks)
2194            .map(|level| level[1].as_str()),
2195    )?;
2196    let parse_levels = |levels: Vec<[String; 2]>| {
2197        levels
2198            .into_iter()
2199            .map(|level| {
2200                Ok(BinancePriceLevel {
2201                    price_mantissa: decimal_mantissa(&level[0], price_scale)?,
2202                    qty_mantissa: decimal_mantissa(&level[1], qty_scale)?,
2203                })
2204            })
2205            .collect::<BinanceSpotHttpResult<Vec<_>>>()
2206    };
2207
2208    Ok(BinanceDepth {
2209        last_update_id: response.last_update_id,
2210        price_exponent: decimal_exponent(price_scale)?,
2211        qty_exponent: decimal_exponent(qty_scale)?,
2212        bids: parse_levels(response.bids)?,
2213        asks: parse_levels(response.asks)?,
2214    })
2215}
2216
2217fn spot_trades_from_json(response: Vec<SpotTradeJson>) -> BinanceSpotHttpResult<BinanceTrades> {
2218    let price_scale = decimal_common_scale(
2219        response
2220            .iter()
2221            .flat_map(|trade| [trade.price.as_str(), trade.quote_qty.as_str()]),
2222    )?;
2223    let qty_scale = decimal_common_scale(response.iter().map(|trade| trade.qty.as_str()))?;
2224    let trades = response
2225        .into_iter()
2226        .map(|trade| {
2227            Ok(BinanceTrade {
2228                id: trade.id,
2229                price_mantissa: decimal_mantissa(&trade.price, price_scale)?,
2230                qty_mantissa: decimal_mantissa(&trade.qty, qty_scale)?,
2231                quote_qty_mantissa: decimal_mantissa(&trade.quote_qty, price_scale)?,
2232                time: millis_to_micros(trade.time)?,
2233                is_buyer_maker: trade.is_buyer_maker,
2234                is_best_match: trade.is_best_match,
2235            })
2236        })
2237        .collect::<BinanceSpotHttpResult<Vec<_>>>()?;
2238
2239    Ok(BinanceTrades {
2240        price_exponent: decimal_exponent(price_scale)?,
2241        qty_exponent: decimal_exponent(qty_scale)?,
2242        trades,
2243    })
2244}
2245
2246fn spot_agg_trades_from_json(
2247    response: Vec<SpotAggTradeJson>,
2248) -> BinanceSpotHttpResult<BinanceAggTrades> {
2249    let price_scale = decimal_common_scale(response.iter().map(|trade| trade.price.as_str()))?;
2250    let qty_scale = decimal_common_scale(response.iter().map(|trade| trade.qty.as_str()))?;
2251    let trades = response
2252        .into_iter()
2253        .map(|trade| {
2254            Ok(BinanceAggTrade {
2255                id: trade.id,
2256                price_mantissa: decimal_mantissa(&trade.price, price_scale)?,
2257                qty_mantissa: decimal_mantissa(&trade.qty, qty_scale)?,
2258                first_trade_id: trade.first_trade_id,
2259                last_trade_id: trade.last_trade_id,
2260                time: millis_to_micros(trade.time)?,
2261                is_buyer_maker: trade.is_buyer_maker,
2262                is_best_match: trade.is_best_match,
2263            })
2264        })
2265        .collect::<BinanceSpotHttpResult<Vec<_>>>()?;
2266
2267    Ok(BinanceAggTrades {
2268        price_exponent: decimal_exponent(price_scale)?,
2269        qty_exponent: decimal_exponent(qty_scale)?,
2270        trades,
2271    })
2272}
2273
2274fn spot_klines_from_json(response: Vec<SpotKlineJson>) -> BinanceSpotHttpResult<BinanceKlines> {
2275    let price_scale = decimal_common_scale(response.iter().flat_map(|kline| {
2276        [
2277            kline.1.as_str(),
2278            kline.2.as_str(),
2279            kline.3.as_str(),
2280            kline.4.as_str(),
2281            kline.7.as_str(),
2282            kline.10.as_str(),
2283        ]
2284    }))?;
2285    let qty_scale = decimal_common_scale(
2286        response
2287            .iter()
2288            .flat_map(|kline| [kline.5.as_str(), kline.9.as_str()]),
2289    )?;
2290    let klines = response
2291        .into_iter()
2292        .map(|kline| {
2293            let volume = decimal_i128_bytes(&kline.5, qty_scale)?;
2294            let quote_volume = decimal_i128_bytes(&kline.7, price_scale)?;
2295            let taker_buy_base_volume = decimal_i128_bytes(&kline.9, qty_scale)?;
2296            let taker_buy_quote_volume = decimal_i128_bytes(&kline.10, price_scale)?;
2297            Ok(BinanceKline {
2298                open_time: millis_to_micros(kline.0)?,
2299                open_price: decimal_mantissa(&kline.1, price_scale)?,
2300                high_price: decimal_mantissa(&kline.2, price_scale)?,
2301                low_price: decimal_mantissa(&kline.3, price_scale)?,
2302                close_price: decimal_mantissa(&kline.4, price_scale)?,
2303                volume,
2304                close_time: millis_to_micros(kline.6)?,
2305                quote_volume,
2306                num_trades: kline.8,
2307                taker_buy_base_volume,
2308                taker_buy_quote_volume,
2309            })
2310        })
2311        .collect::<BinanceSpotHttpResult<Vec<_>>>()?;
2312
2313    Ok(BinanceKlines {
2314        price_exponent: decimal_exponent(price_scale)?,
2315        qty_exponent: decimal_exponent(qty_scale)?,
2316        klines,
2317    })
2318}
2319
2320fn decimal_i128_bytes(value: &str, scale: u32) -> BinanceSpotHttpResult<[u8; 16]> {
2321    let mut decimal = Decimal::from_str_exact(value)
2322        .map_err(|e| BinanceSpotHttpError::ResponseParseError(e.to_string()))?;
2323    decimal.rescale(scale);
2324    Ok(decimal.mantissa().to_le_bytes())
2325}
2326
2327fn spot_account_from_json(response: SpotAccountJson) -> BinanceSpotHttpResult<BinanceAccountInfo> {
2328    let commission_rates = response.commission_rates.map_or_else(
2329        || {
2330            [
2331                Decimal::new(response.maker_commission, 4).to_string(),
2332                Decimal::new(response.taker_commission, 4).to_string(),
2333                Decimal::new(response.buyer_commission, 4).to_string(),
2334                Decimal::new(response.seller_commission, 4).to_string(),
2335            ]
2336        },
2337        |rates| [rates.maker, rates.taker, rates.buyer, rates.seller],
2338    );
2339    let commission_scale = decimal_common_scale(commission_rates.iter().map(String::as_str))?;
2340    let balances = response
2341        .balances
2342        .into_iter()
2343        .map(|balance| {
2344            let scale = decimal_common_scale([balance.free.as_str(), balance.locked.as_str()])?;
2345            Ok(BinanceBalance {
2346                asset: balance.asset,
2347                free_mantissa: decimal_mantissa(&balance.free, scale)?,
2348                locked_mantissa: decimal_mantissa(&balance.locked, scale)?,
2349                exponent: decimal_exponent(scale)?,
2350            })
2351        })
2352        .collect::<BinanceSpotHttpResult<Vec<_>>>()?;
2353
2354    Ok(BinanceAccountInfo {
2355        commission_exponent: decimal_exponent(commission_scale)?,
2356        maker_commission_mantissa: decimal_mantissa(&commission_rates[0], commission_scale)?,
2357        taker_commission_mantissa: decimal_mantissa(&commission_rates[1], commission_scale)?,
2358        buyer_commission_mantissa: decimal_mantissa(&commission_rates[2], commission_scale)?,
2359        seller_commission_mantissa: decimal_mantissa(&commission_rates[3], commission_scale)?,
2360        can_trade: response.can_trade,
2361        can_withdraw: response.can_withdraw,
2362        can_deposit: response.can_deposit,
2363        require_self_trade_prevention: response.require_self_trade_prevention,
2364        prevent_sor: response.prevent_sor,
2365        update_time: millis_to_micros(response.update_time)?,
2366        account_type: response.account_type,
2367        balances,
2368    })
2369}
2370
2371fn spot_new_order_from_json(
2372    response: SpotOrderJson,
2373) -> BinanceSpotHttpResult<BinanceNewOrderResponse> {
2374    let (price_scale, qty_scale) = spot_order_scales(&response)?;
2375    let fills = response
2376        .fills
2377        .iter()
2378        .map(|fill| {
2379            let commission_scale = decimal_common_scale([fill.commission.as_str()])?;
2380            Ok(BinanceOrderFill {
2381                price_mantissa: decimal_mantissa(&fill.price, price_scale)?,
2382                qty_mantissa: decimal_mantissa(&fill.qty, qty_scale)?,
2383                commission_mantissa: decimal_mantissa(&fill.commission, commission_scale)?,
2384                commission_exponent: decimal_exponent(commission_scale)?,
2385                commission_asset: fill.commission_asset.clone(),
2386                trade_id: fill.trade_id,
2387            })
2388        })
2389        .collect::<BinanceSpotHttpResult<Vec<_>>>()?;
2390
2391    Ok(BinanceNewOrderResponse {
2392        price_exponent: decimal_exponent(price_scale)?,
2393        qty_exponent: decimal_exponent(qty_scale)?,
2394        order_id: response.order_id,
2395        order_list_id: valid_order_list_id(response.order_list_id),
2396        transact_time: millis_to_micros(response.transact_time)?,
2397        price_mantissa: decimal_mantissa(&response.price, price_scale)?,
2398        orig_qty_mantissa: decimal_mantissa(&response.orig_qty, qty_scale)?,
2399        executed_qty_mantissa: decimal_mantissa(&response.executed_qty, qty_scale)?,
2400        cummulative_quote_qty_mantissa: decimal_mantissa(
2401            &response.cummulative_quote_qty,
2402            price_scale + qty_scale,
2403        )?,
2404        status: spot_sbe_order_status(response.status),
2405        time_in_force: spot_sbe_time_in_force(response.time_in_force),
2406        order_type: spot_sbe_order_type(response.order_type),
2407        side: spot_sbe_order_side(response.side),
2408        stop_price_mantissa: decimal_optional_mantissa(&response.stop_price, price_scale)?,
2409        working_time: response.working_time.map(millis_to_micros).transpose()?,
2410        self_trade_prevention_mode: spot_sbe_stp(response.self_trade_prevention_mode),
2411        client_order_id: response.client_order_id,
2412        symbol: response.symbol,
2413        fills,
2414        expiry_reason: None,
2415    })
2416}
2417
2418fn spot_cancel_order_from_json(
2419    response: SpotOrderJson,
2420) -> BinanceSpotHttpResult<BinanceCancelOrderResponse> {
2421    let (price_scale, qty_scale) = spot_order_scales(&response)?;
2422    Ok(BinanceCancelOrderResponse {
2423        price_exponent: decimal_exponent(price_scale)?,
2424        qty_exponent: decimal_exponent(qty_scale)?,
2425        order_id: response.order_id,
2426        order_list_id: valid_order_list_id(response.order_list_id),
2427        transact_time: millis_to_micros(response.transact_time)?,
2428        price_mantissa: decimal_mantissa(&response.price, price_scale)?,
2429        orig_qty_mantissa: decimal_mantissa(&response.orig_qty, qty_scale)?,
2430        executed_qty_mantissa: decimal_mantissa(&response.executed_qty, qty_scale)?,
2431        cummulative_quote_qty_mantissa: decimal_mantissa(
2432            &response.cummulative_quote_qty,
2433            price_scale + qty_scale,
2434        )?,
2435        status: spot_sbe_order_status(response.status),
2436        time_in_force: spot_sbe_time_in_force(response.time_in_force),
2437        order_type: spot_sbe_order_type(response.order_type),
2438        side: spot_sbe_order_side(response.side),
2439        self_trade_prevention_mode: spot_sbe_stp(response.self_trade_prevention_mode),
2440        client_order_id: response.client_order_id,
2441        orig_client_order_id: response.orig_client_order_id,
2442        symbol: response.symbol,
2443    })
2444}
2445
2446fn spot_cancel_open_orders_from_json(
2447    bytes: &[u8],
2448) -> BinanceSpotHttpResult<Vec<BinanceCancelOpenOrdersResponse>> {
2449    let responses: Vec<Value> = serde_json::from_slice(bytes)
2450        .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
2451
2452    responses
2453        .into_iter()
2454        .map(|response| {
2455            let is_order_list =
2456                response.get("orders").is_some() || response.get("orderReports").is_some();
2457            if is_order_list {
2458                let response: SpotCancelOrderListJson = serde_json::from_value(response)
2459                    .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
2460                spot_cancel_order_list_from_json(response)
2461                    .map(BinanceCancelOpenOrdersResponse::OrderList)
2462            } else {
2463                let response: SpotOrderJson = serde_json::from_value(response)
2464                    .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
2465                spot_cancel_order_from_json(response).map(BinanceCancelOpenOrdersResponse::Order)
2466            }
2467        })
2468        .collect()
2469}
2470
2471fn spot_cancel_order_list_from_json(
2472    response: SpotCancelOrderListJson,
2473) -> BinanceSpotHttpResult<BinanceCancelOrderListResponse> {
2474    let contingency_type = match response.contingency_type.as_str() {
2475        "OCO" => SbeContingencyType::Oco,
2476        "OTO" => SbeContingencyType::Oto,
2477        _ => {
2478            return Err(BinanceSpotHttpError::ResponseParseError(format!(
2479                "unknown order-list contingency type: {}",
2480                response.contingency_type
2481            )));
2482        }
2483    };
2484    let list_status_type = match response.list_status_type.as_str() {
2485        "RESPONSE" => SbeListStatusType::Response,
2486        "EXEC_STARTED" => SbeListStatusType::ExecStarted,
2487        "ALL_DONE" => SbeListStatusType::AllDone,
2488        "UPDATED" => SbeListStatusType::Updated,
2489        _ => {
2490            return Err(BinanceSpotHttpError::ResponseParseError(format!(
2491                "unknown order-list status type: {}",
2492                response.list_status_type
2493            )));
2494        }
2495    };
2496    let list_order_status = match response.list_order_status.as_str() {
2497        "CANCELING" => SbeListOrderStatus::Canceling,
2498        "EXECUTING" => SbeListOrderStatus::Executing,
2499        "ALL_DONE" => SbeListOrderStatus::AllDone,
2500        "REJECT" => SbeListOrderStatus::Reject,
2501        _ => {
2502            return Err(BinanceSpotHttpError::ResponseParseError(format!(
2503                "unknown aggregate order-list status: {}",
2504                response.list_order_status
2505            )));
2506        }
2507    };
2508    let order_reports = response
2509        .order_reports
2510        .into_iter()
2511        .map(spot_cancel_order_from_json)
2512        .collect::<BinanceSpotHttpResult<Vec<_>>>()?;
2513
2514    Ok(BinanceCancelOrderListResponse {
2515        order_list_id: response.order_list_id,
2516        contingency_type,
2517        list_status_type,
2518        list_order_status,
2519        transaction_time: millis_to_micros(response.transaction_time)?,
2520        list_client_order_id: response.list_client_order_id,
2521        symbol: response.symbol,
2522        orders: response
2523            .orders
2524            .into_iter()
2525            .map(|order| super::models::BinanceCancelOrderListOrder {
2526                symbol: order.symbol,
2527                order_id: order.order_id,
2528                client_order_id: order.client_order_id,
2529            })
2530            .collect(),
2531        order_reports,
2532    })
2533}
2534
2535fn spot_order_from_json(response: SpotOrderJson) -> BinanceSpotHttpResult<BinanceOrderResponse> {
2536    let (price_scale, qty_scale) = spot_order_scales(&response)?;
2537    Ok(BinanceOrderResponse {
2538        price_exponent: decimal_exponent(price_scale)?,
2539        qty_exponent: decimal_exponent(qty_scale)?,
2540        order_id: response.order_id,
2541        order_list_id: valid_order_list_id(response.order_list_id),
2542        price_mantissa: decimal_mantissa(&response.price, price_scale)?,
2543        orig_qty_mantissa: decimal_mantissa(&response.orig_qty, qty_scale)?,
2544        executed_qty_mantissa: decimal_mantissa(&response.executed_qty, qty_scale)?,
2545        cummulative_quote_qty_mantissa: decimal_mantissa(
2546            &response.cummulative_quote_qty,
2547            price_scale + qty_scale,
2548        )?,
2549        status: spot_sbe_order_status(response.status),
2550        time_in_force: spot_sbe_time_in_force(response.time_in_force),
2551        order_type: spot_sbe_order_type(response.order_type),
2552        side: spot_sbe_order_side(response.side),
2553        stop_price_mantissa: decimal_optional_mantissa(&response.stop_price, price_scale)?,
2554        iceberg_qty_mantissa: decimal_optional_mantissa(&response.iceberg_qty, qty_scale)?,
2555        time: millis_to_micros(response.time)?,
2556        update_time: millis_to_micros(response.update_time)?,
2557        is_working: response.is_working,
2558        working_time: response.working_time.map(millis_to_micros).transpose()?,
2559        orig_quote_order_qty_mantissa: decimal_mantissa(
2560            &response.orig_quote_order_qty,
2561            price_scale + qty_scale,
2562        )?,
2563        self_trade_prevention_mode: spot_sbe_stp(response.self_trade_prevention_mode),
2564        client_order_id: response.client_order_id,
2565        symbol: response.symbol,
2566        expiry_reason: None,
2567    })
2568}
2569
2570fn spot_account_trade_from_json(
2571    response: SpotAccountTradeJson,
2572) -> BinanceSpotHttpResult<BinanceAccountTrade> {
2573    let price_scale = decimal_common_scale([response.price.as_str()])?;
2574    let qty_scale = decimal_common_scale([response.qty.as_str()])?;
2575    let commission_scale = decimal_common_scale([response.commission.as_str()])?;
2576    Ok(BinanceAccountTrade {
2577        price_exponent: decimal_exponent(price_scale)?,
2578        qty_exponent: decimal_exponent(qty_scale)?,
2579        commission_exponent: decimal_exponent(commission_scale)?,
2580        id: response.id,
2581        order_id: response.order_id,
2582        order_list_id: valid_order_list_id(response.order_list_id),
2583        price_mantissa: decimal_mantissa(&response.price, price_scale)?,
2584        qty_mantissa: decimal_mantissa(&response.qty, qty_scale)?,
2585        quote_qty_mantissa: decimal_mantissa(&response.quote_qty, price_scale + qty_scale)?,
2586        commission_mantissa: decimal_mantissa(&response.commission, commission_scale)?,
2587        time: millis_to_micros(response.time)?,
2588        is_buyer: response.is_buyer,
2589        is_maker: response.is_maker,
2590        is_best_match: response.is_best_match,
2591        symbol: response.symbol,
2592        commission_asset: response.commission_asset,
2593    })
2594}
2595
2596fn spot_order_scales(response: &SpotOrderJson) -> BinanceSpotHttpResult<(u32, u32)> {
2597    let price_scale = decimal_common_scale(
2598        [response.price.as_str(), response.stop_price.as_str()]
2599            .into_iter()
2600            .chain(response.fills.iter().map(|fill| fill.price.as_str())),
2601    )?;
2602    let qty_scale = decimal_common_scale(
2603        [
2604            response.orig_qty.as_str(),
2605            response.executed_qty.as_str(),
2606            response.iceberg_qty.as_str(),
2607        ]
2608        .into_iter()
2609        .chain(response.fills.iter().map(|fill| fill.qty.as_str())),
2610    )?;
2611    Ok((price_scale, qty_scale))
2612}
2613
2614fn decimal_common_scale<'a>(
2615    values: impl IntoIterator<Item = &'a str>,
2616) -> BinanceSpotHttpResult<u32> {
2617    values
2618        .into_iter()
2619        .filter(|value| !value.is_empty())
2620        .try_fold(0, |scale, value| {
2621            let decimal = Decimal::from_str_exact(value)
2622                .map_err(|e| BinanceSpotHttpError::ResponseParseError(e.to_string()))?;
2623            Ok(scale.max(decimal.scale()))
2624        })
2625}
2626
2627fn decimal_mantissa(value: &str, scale: u32) -> BinanceSpotHttpResult<i64> {
2628    if value.is_empty() {
2629        return Ok(0);
2630    }
2631    let mut decimal = Decimal::from_str_exact(value)
2632        .map_err(|e| BinanceSpotHttpError::ResponseParseError(e.to_string()))?;
2633    decimal.rescale(scale);
2634    i64::try_from(decimal.mantissa()).map_err(|_| {
2635        BinanceSpotHttpError::ResponseParseError(format!(
2636            "decimal mantissa is outside i64 range: {value}"
2637        ))
2638    })
2639}
2640
2641fn decimal_optional_mantissa(value: &str, scale: u32) -> BinanceSpotHttpResult<Option<i64>> {
2642    let mantissa = decimal_mantissa(value, scale)?;
2643    Ok((mantissa != 0).then_some(mantissa))
2644}
2645
2646fn decimal_exponent(scale: u32) -> BinanceSpotHttpResult<i8> {
2647    i8::try_from(scale)
2648        .map(|scale| -scale)
2649        .map_err(|_| BinanceSpotHttpError::ResponseParseError("decimal scale exceeds i8".into()))
2650}
2651
2652fn millis_to_micros(timestamp: i64) -> BinanceSpotHttpResult<i64> {
2653    timestamp.checked_mul(1_000).ok_or_else(|| {
2654        BinanceSpotHttpError::ResponseParseError(format!(
2655            "timestamp overflows microseconds: {timestamp}"
2656        ))
2657    })
2658}
2659
2660fn valid_order_list_id(order_list_id: Option<i64>) -> Option<i64> {
2661    order_list_id.filter(|value| *value >= 0)
2662}
2663
2664const fn spot_sbe_order_status(status: BinanceOrderStatus) -> SbeOrderStatus {
2665    match status {
2666        BinanceOrderStatus::New => SbeOrderStatus::New,
2667        BinanceOrderStatus::PendingNew => SbeOrderStatus::PendingNew,
2668        BinanceOrderStatus::PartiallyFilled => SbeOrderStatus::PartiallyFilled,
2669        BinanceOrderStatus::Filled => SbeOrderStatus::Filled,
2670        BinanceOrderStatus::Canceled => SbeOrderStatus::Canceled,
2671        BinanceOrderStatus::PendingCancel => SbeOrderStatus::PendingCancel,
2672        BinanceOrderStatus::Rejected => SbeOrderStatus::Rejected,
2673        BinanceOrderStatus::Expired => SbeOrderStatus::Expired,
2674        BinanceOrderStatus::ExpiredInMatch => SbeOrderStatus::ExpiredInMatch,
2675        BinanceOrderStatus::NewInsurance
2676        | BinanceOrderStatus::NewAdl
2677        | BinanceOrderStatus::Unknown => SbeOrderStatus::Unknown,
2678    }
2679}
2680
2681const fn spot_sbe_time_in_force(time_in_force: BinanceTimeInForce) -> SbeTimeInForce {
2682    match time_in_force {
2683        BinanceTimeInForce::Gtc => SbeTimeInForce::Gtc,
2684        BinanceTimeInForce::Ioc => SbeTimeInForce::Ioc,
2685        BinanceTimeInForce::Fok => SbeTimeInForce::Fok,
2686        BinanceTimeInForce::GteGtc
2687        | BinanceTimeInForce::Gtx
2688        | BinanceTimeInForce::Gtd
2689        | BinanceTimeInForce::Rpi
2690        | BinanceTimeInForce::Unknown => SbeTimeInForce::NonRepresentable,
2691    }
2692}
2693
2694const fn spot_sbe_order_type(order_type: BinanceSpotOrderType) -> SbeOrderType {
2695    match order_type {
2696        BinanceSpotOrderType::Market => SbeOrderType::Market,
2697        BinanceSpotOrderType::Limit => SbeOrderType::Limit,
2698        BinanceSpotOrderType::StopLoss => SbeOrderType::StopLoss,
2699        BinanceSpotOrderType::StopLossLimit => SbeOrderType::StopLossLimit,
2700        BinanceSpotOrderType::TakeProfit => SbeOrderType::TakeProfit,
2701        BinanceSpotOrderType::TakeProfitLimit => SbeOrderType::TakeProfitLimit,
2702        BinanceSpotOrderType::LimitMaker => SbeOrderType::LimitMaker,
2703        BinanceSpotOrderType::Unknown => SbeOrderType::NonRepresentable,
2704    }
2705}
2706
2707const fn spot_sbe_order_side(side: BinanceSide) -> SbeOrderSide {
2708    match side {
2709        BinanceSide::Buy => SbeOrderSide::Buy,
2710        BinanceSide::Sell => SbeOrderSide::Sell,
2711    }
2712}
2713
2714fn spot_sbe_stp(mode: Option<BinanceSelfTradePreventionMode>) -> SbeSelfTradePreventionMode {
2715    match mode.unwrap_or(BinanceSelfTradePreventionMode::None) {
2716        BinanceSelfTradePreventionMode::None => SbeSelfTradePreventionMode::None,
2717        BinanceSelfTradePreventionMode::ExpireMaker => SbeSelfTradePreventionMode::ExpireMaker,
2718        BinanceSelfTradePreventionMode::ExpireTaker => SbeSelfTradePreventionMode::ExpireTaker,
2719        BinanceSelfTradePreventionMode::ExpireBoth => SbeSelfTradePreventionMode::ExpireBoth,
2720        BinanceSelfTradePreventionMode::Decrement => SbeSelfTradePreventionMode::Decrement,
2721        BinanceSelfTradePreventionMode::Transfer => SbeSelfTradePreventionMode::Transfer,
2722        BinanceSelfTradePreventionMode::Unknown => SbeSelfTradePreventionMode::NonRepresentable,
2723    }
2724}
2725
2726/// High-level HTTP client for Binance Spot API.
2727///
2728/// Wraps [`BinanceRawSpotHttpClient`] and provides domain-level methods:
2729/// - Simple types (ping, server_time): Pass through from raw client.
2730/// - Complex types (instruments, orders): Transform to Nautilus domain types.
2731pub struct BinanceSpotHttpClient {
2732    inner: Arc<BinanceRawSpotHttpClient>,
2733    clock: &'static AtomicTime,
2734    instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
2735}
2736
2737impl Clone for BinanceSpotHttpClient {
2738    fn clone(&self) -> Self {
2739        Self {
2740            inner: self.inner.clone(),
2741            clock: self.clock,
2742            instruments_cache: self.instruments_cache.clone(),
2743        }
2744    }
2745}
2746
2747impl Debug for BinanceSpotHttpClient {
2748    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2749        f.debug_struct(stringify!(BinanceSpotHttpClient))
2750            .field("inner", &self.inner)
2751            .field("instruments_cached", &self.instruments_cache.len())
2752            .finish()
2753    }
2754}
2755
2756impl BinanceSpotHttpClient {
2757    /// Creates a new Binance Spot HTTP client.
2758    ///
2759    /// # Errors
2760    ///
2761    /// Returns an error if the underlying HTTP client cannot be created.
2762    #[expect(clippy::too_many_arguments)]
2763    pub fn new(
2764        environment: BinanceEnvironment,
2765        clock: &'static AtomicTime,
2766        api_key: Option<String>,
2767        api_secret: Option<String>,
2768        base_url_override: Option<String>,
2769        recv_window: Option<u64>,
2770        timeout_secs: Option<u64>,
2771        proxy_url: Option<String>,
2772    ) -> BinanceSpotHttpResult<Self> {
2773        Self::new_with_json_responses(
2774            environment,
2775            clock,
2776            api_key,
2777            api_secret,
2778            base_url_override,
2779            recv_window,
2780            timeout_secs,
2781            proxy_url,
2782            false,
2783        )
2784    }
2785
2786    pub(crate) fn with_retry_config(mut self, config: RetryConfig) -> Self {
2787        Arc::make_mut(&mut self.inner).retry_manager = Arc::new(RetryManager::new(config));
2788        self
2789    }
2790
2791    /// Creates a Spot client for an endpoint that returns JSON REST payloads.
2792    ///
2793    /// # Errors
2794    ///
2795    /// Returns an error if the underlying HTTP client cannot be created.
2796    #[expect(clippy::too_many_arguments)]
2797    pub fn new_with_json_responses(
2798        environment: BinanceEnvironment,
2799        clock: &'static AtomicTime,
2800        api_key: Option<String>,
2801        api_secret: Option<String>,
2802        base_url_override: Option<String>,
2803        recv_window: Option<u64>,
2804        timeout_secs: Option<u64>,
2805        proxy_url: Option<String>,
2806        json_responses: bool,
2807    ) -> BinanceSpotHttpResult<Self> {
2808        let inner = BinanceRawSpotHttpClient::new_with_json_responses(
2809            environment,
2810            api_key,
2811            api_secret,
2812            base_url_override,
2813            recv_window,
2814            timeout_secs,
2815            proxy_url,
2816            json_responses,
2817        )?;
2818
2819        Ok(Self {
2820            inner: Arc::new(inner),
2821            clock,
2822            instruments_cache: Arc::new(AtomicMap::new()),
2823        })
2824    }
2825
2826    /// Returns a reference to the inner raw client.
2827    #[must_use]
2828    pub fn inner(&self) -> &BinanceRawSpotHttpClient {
2829        &self.inner
2830    }
2831
2832    /// Returns whether signed requests can be made.
2833    #[must_use]
2834    pub fn has_credentials(&self) -> bool {
2835        self.inner.has_credentials()
2836    }
2837
2838    /// Returns the SBE schema ID.
2839    #[must_use]
2840    pub const fn schema_id() -> u16 {
2841        SBE_SCHEMA_ID
2842    }
2843
2844    /// Returns the SBE schema version.
2845    #[must_use]
2846    pub const fn schema_version() -> u16 {
2847        SBE_SCHEMA_VERSION
2848    }
2849
2850    /// Generates a timestamp for initialization.
2851    fn generate_ts_init(&self) -> UnixNanos {
2852        self.clock.get_time_ns()
2853    }
2854
2855    fn command_validation_error(message: impl Into<String>) -> anyhow::Error {
2856        anyhow::anyhow!(BinanceSpotHttpError::ValidationError(message.into()))
2857    }
2858
2859    fn response_parse_error(message: impl Into<String>) -> anyhow::Error {
2860        anyhow::anyhow!(BinanceSpotHttpError::ResponseParseError(message.into()))
2861    }
2862
2863    /// Retrieves an instrument from the cache.
2864    fn instrument_from_cache(&self, symbol: Ustr) -> anyhow::Result<InstrumentAny> {
2865        self.instruments_cache
2866            .get_cloned(&symbol)
2867            .ok_or_else(|| anyhow::anyhow!("Instrument {symbol} not in cache"))
2868    }
2869
2870    /// Caches multiple instruments.
2871    pub fn cache_instruments(&self, instruments: Vec<InstrumentAny>) {
2872        self.instruments_cache.rcu(move |cache| {
2873            for instrument in &instruments {
2874                cache.insert(instrument.raw_symbol().inner(), instrument.clone());
2875            }
2876        });
2877    }
2878
2879    /// Replaces the complete instrument cache.
2880    pub fn replace_instruments(&self, instruments: &[InstrumentAny]) {
2881        let cache = instruments
2882            .iter()
2883            .map(|instrument| (instrument.raw_symbol().inner(), instrument.clone()))
2884            .collect();
2885        self.instruments_cache.store(cache);
2886    }
2887
2888    /// Caches a single instrument.
2889    pub fn cache_instrument(&self, instrument: InstrumentAny) {
2890        self.instruments_cache
2891            .insert(instrument.raw_symbol().inner(), instrument);
2892    }
2893
2894    /// Gets an instrument from the cache by symbol.
2895    #[must_use]
2896    pub fn get_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
2897        self.instruments_cache.get_cloned(symbol)
2898    }
2899
2900    pub(crate) fn instrument_ids_reconciliation(&self) -> Vec<InstrumentId> {
2901        self.instruments_cache
2902            .load()
2903            .values()
2904            .map(|instrument| instrument.id())
2905            .collect()
2906    }
2907
2908    /// Tests connectivity to the API.
2909    ///
2910    /// # Errors
2911    ///
2912    /// Returns an error if the request fails or SBE decoding fails.
2913    pub async fn ping(&self) -> BinanceSpotHttpResult<()> {
2914        self.inner.ping().await
2915    }
2916
2917    /// Returns the server time in **microseconds** since epoch.
2918    ///
2919    /// Note: SBE provides microsecond precision vs JSON's milliseconds.
2920    ///
2921    /// # Errors
2922    ///
2923    /// Returns an error if the request fails or SBE decoding fails.
2924    pub async fn server_time(&self) -> BinanceSpotHttpResult<i64> {
2925        self.inner.server_time().await
2926    }
2927
2928    /// Returns exchange information including trading symbols.
2929    ///
2930    /// # Errors
2931    ///
2932    /// Returns an error if the request fails or SBE decoding fails.
2933    pub async fn exchange_info(
2934        &self,
2935    ) -> BinanceSpotHttpResult<super::models::BinanceExchangeInfoSbe> {
2936        self.inner.exchange_info().await
2937    }
2938
2939    /// Returns a fresh status snapshot for Global or US Spot symbols.
2940    ///
2941    /// # Errors
2942    ///
2943    /// Returns an error if exchange info cannot be requested or decoded.
2944    pub async fn request_symbol_statuses(
2945        &self,
2946        us: bool,
2947    ) -> BinanceSpotHttpResult<AHashMap<InstrumentId, MarketStatusAction>> {
2948        let mut statuses = AHashMap::new();
2949
2950        if us {
2951            let info = self.inner.exchange_info_json().await?;
2952            for symbol in info.symbols {
2953                let instrument_id =
2954                    InstrumentId::new(Symbol::from(symbol.symbol.as_str()), *BINANCE_VENUE);
2955                statuses.insert(instrument_id, spot_json_market_status(&symbol.status));
2956            }
2957        } else {
2958            let info = self.exchange_info().await?;
2959            for symbol in info.symbols {
2960                let instrument_id =
2961                    InstrumentId::new(Symbol::from(symbol.symbol.as_str()), *BINANCE_VENUE);
2962                statuses.insert(
2963                    instrument_id,
2964                    MarketStatusAction::from(SymbolStatus::from(symbol.status)),
2965                );
2966            }
2967        }
2968        Ok(statuses)
2969    }
2970
2971    /// Requests Nautilus instruments for all trading symbols.
2972    ///
2973    /// Fetches exchange info via SBE and parses each symbol into a CurrencyPair.
2974    /// Non-trading symbols are skipped with a debug log.
2975    ///
2976    /// # Errors
2977    ///
2978    /// Returns an error if the request fails or SBE decoding fails.
2979    pub async fn request_instruments(&self) -> BinanceSpotHttpResult<Vec<InstrumentAny>> {
2980        self.request_instruments_with_config(&BinanceInstrumentProviderConfig::default(), false)
2981            .await
2982    }
2983
2984    /// Requests configured Nautilus instruments.
2985    ///
2986    /// Non-trading symbols are skipped with a debug log unless explicitly
2987    /// selected via `load_ids` or the `symbols` filter.
2988    ///
2989    /// # Errors
2990    ///
2991    /// Returns an error if configuration, exchange info, or required parsing fails.
2992    pub async fn request_instruments_with_config(
2993        &self,
2994        config: &BinanceInstrumentProviderConfig,
2995        us: bool,
2996    ) -> BinanceSpotHttpResult<Vec<InstrumentAny>> {
2997        let selector = BinanceInstrumentSelector::new(config, BinanceProductType::Spot)
2998            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?;
2999        let ts_init = self.generate_ts_init();
3000
3001        let mut instruments = if us {
3002            if config.query_commission_rates {
3003                if config.log_warnings {
3004                    log::warn!("query_commission_rates does not copy commission onto instruments");
3005                } else {
3006                    log::debug!("query_commission_rates does not copy commission onto instruments");
3007                }
3008            }
3009            let info = self.inner.exchange_info_json().await?;
3010            let mut instruments = Vec::with_capacity(info.symbols.len());
3011            for symbol in &info.symbols {
3012                let instrument_id =
3013                    InstrumentId::new(Symbol::from(symbol.symbol.as_str()), *BINANCE_VENUE);
3014
3015                if !selector.includes(
3016                    instrument_id,
3017                    &symbol.symbol,
3018                    &symbol.base_asset,
3019                    &symbol.quote_asset,
3020                    None,
3021                ) {
3022                    continue;
3023                }
3024
3025                match parse_spot_instrument_json_with_fees(symbol, ts_init, ts_init) {
3026                    Ok(instrument) => instruments.push(instrument),
3027                    Err(e) => log_instrument_parse_error(
3028                        config,
3029                        &selector,
3030                        instrument_id,
3031                        &symbol.symbol,
3032                        &e,
3033                    ),
3034                }
3035            }
3036            instruments
3037        } else {
3038            let info = self.exchange_info().await?;
3039            let mut instruments = Vec::with_capacity(info.symbols.len());
3040            for symbol in &info.symbols {
3041                let instrument_id =
3042                    InstrumentId::new(Symbol::from(symbol.symbol.as_str()), *BINANCE_VENUE);
3043
3044                if !selector.includes(
3045                    instrument_id,
3046                    &symbol.symbol,
3047                    &symbol.base_asset,
3048                    &symbol.quote_asset,
3049                    None,
3050                ) {
3051                    continue;
3052                }
3053
3054                match parse_spot_instrument_sbe_with_fees(symbol, ts_init, ts_init) {
3055                    Ok(instrument) => instruments.push(instrument),
3056                    Err(e) => log_instrument_parse_error(
3057                        config,
3058                        &selector,
3059                        instrument_id,
3060                        &symbol.symbol,
3061                        &e,
3062                    ),
3063                }
3064            }
3065            instruments
3066        };
3067
3068        instruments.shrink_to_fit();
3069        self.replace_instruments(&instruments);
3070
3071        log::debug!("Loaded spot instruments: count={}", instruments.len());
3072        Ok(instruments)
3073    }
3074
3075    /// Requests recent trades for an instrument.
3076    ///
3077    /// # Errors
3078    ///
3079    /// Returns an error if the request fails, the instrument is not cached,
3080    /// or trade parsing fails.
3081    pub async fn request_trades(
3082        &self,
3083        instrument_id: InstrumentId,
3084        limit: Option<u32>,
3085    ) -> anyhow::Result<Vec<TradeTick>> {
3086        let symbol = instrument_id.symbol.inner();
3087        let instrument = self.instrument_from_cache_by_id(instrument_id)?;
3088        let ts_init = self.generate_ts_init();
3089
3090        let trades = self
3091            .inner
3092            .trades(symbol.as_str(), limit)
3093            .await
3094            .map_err(|e| anyhow::anyhow!(e))?;
3095
3096        parse_spot_trades_sbe(&trades, &instrument, ts_init)
3097    }
3098
3099    /// Requests bounded aggregate trades for an instrument.
3100    ///
3101    /// # Errors
3102    ///
3103    /// Returns an error if the request fails, the instrument is not cached, or parsing fails.
3104    pub async fn request_agg_trades(
3105        &self,
3106        instrument_id: InstrumentId,
3107        start: Option<Timestamp>,
3108        end: Option<Timestamp>,
3109        limit: Option<u32>,
3110    ) -> anyhow::Result<Vec<TradeTick>> {
3111        let symbol = instrument_id.symbol.inner();
3112        let instrument = self.instrument_from_cache_by_id(instrument_id)?;
3113        let params = AggTradesParams {
3114            symbol: symbol.to_string(),
3115            from_id: None,
3116            start_time: start.map(|dt| dt.as_millisecond()),
3117            end_time: end.map(|dt| dt.as_millisecond()),
3118            limit,
3119        };
3120        let response = self.inner.agg_trades(&params).await?;
3121        let trades = BinanceTrades {
3122            price_exponent: response.price_exponent,
3123            qty_exponent: response.qty_exponent,
3124            trades: response
3125                .trades
3126                .into_iter()
3127                .map(|trade| super::models::BinanceTrade {
3128                    id: trade.id,
3129                    price_mantissa: trade.price_mantissa,
3130                    qty_mantissa: trade.qty_mantissa,
3131                    quote_qty_mantissa: 0,
3132                    time: trade.time,
3133                    is_buyer_maker: trade.is_buyer_maker,
3134                    is_best_match: trade.is_best_match,
3135                })
3136                .collect(),
3137        };
3138
3139        let mut parsed = parse_spot_trades_sbe(&trades, &instrument, UnixNanos::default())?;
3140        for trade in &mut parsed {
3141            trade.ts_init = trade.ts_event;
3142        }
3143        Ok(parsed)
3144    }
3145
3146    /// Requests bar (kline/candlestick) data.
3147    ///
3148    /// # Errors
3149    ///
3150    /// Returns an error if the bar type is not supported, instrument is not cached,
3151    /// or the request fails.
3152    pub async fn request_binance_bars(
3153        &self,
3154        bar_type: BarType,
3155        start: Option<Timestamp>,
3156        end: Option<Timestamp>,
3157        limit: Option<u32>,
3158    ) -> anyhow::Result<Vec<crate::common::bar::BinanceBar>> {
3159        anyhow::ensure!(
3160            bar_type.aggregation_source() == AggregationSource::External,
3161            "Only EXTERNAL aggregation is supported"
3162        );
3163
3164        let spec = bar_type.spec();
3165        let step = spec.step.get();
3166        let interval = match spec.aggregation {
3167            BarAggregation::Second if step == 1 => "1s".to_string(),
3168            BarAggregation::Second => {
3169                anyhow::bail!("Binance Spot supports only the 1s kline interval")
3170            }
3171            BarAggregation::Minute => format!("{step}m"),
3172            BarAggregation::Hour => format!("{step}h"),
3173            BarAggregation::Day => format!("{step}d"),
3174            BarAggregation::Week => format!("{step}w"),
3175            BarAggregation::Month => format!("{step}M"),
3176            a => anyhow::bail!("Binance does not support {a:?} aggregation"),
3177        };
3178
3179        let instrument_id = bar_type.instrument_id();
3180        let symbol = instrument_id.symbol;
3181        let instrument = self.instrument_from_cache_by_id(instrument_id)?;
3182        let klines = self
3183            .inner
3184            .klines(
3185                symbol.as_str(),
3186                &interval,
3187                start.map(|dt| dt.as_millisecond()),
3188                end.map(|dt| dt.as_millisecond()),
3189                limit,
3190            )
3191            .await
3192            .map_err(|e| anyhow::anyhow!(e))?;
3193
3194        let mut bars =
3195            parse_klines_to_binance_bars(&klines, bar_type, &instrument, UnixNanos::default())?;
3196        let now = self.clock.get_time_ns();
3197        bars.retain(|bar| bar.ts_event < now);
3198        for bar in &mut bars {
3199            bar.ts_init = bar.ts_event;
3200        }
3201        Ok(bars)
3202    }
3203
3204    /// Requests core bars for an instrument.
3205    ///
3206    /// # Errors
3207    ///
3208    /// Returns an error if the bar type is unsupported or the request fails.
3209    pub async fn request_bars(
3210        &self,
3211        bar_type: BarType,
3212        start: Option<Timestamp>,
3213        end: Option<Timestamp>,
3214        limit: Option<u32>,
3215    ) -> anyhow::Result<Vec<Bar>> {
3216        Ok(self
3217            .request_binance_bars(bar_type, start, end, limit)
3218            .await?
3219            .into_iter()
3220            .map(|bar| bar.bar())
3221            .collect())
3222    }
3223
3224    /// Requests an explicit L2 order-book snapshot.
3225    ///
3226    /// # Errors
3227    ///
3228    /// Returns an error if the depth is invalid, the instrument is missing, the request fails, or a
3229    /// level is invalid.
3230    pub async fn request_book_snapshot(
3231        &self,
3232        instrument_id: InstrumentId,
3233        depth: Option<u32>,
3234    ) -> anyhow::Result<OrderBook> {
3235        self.request_book_snapshot_with_permit(instrument_id, depth, None)
3236            .await
3237    }
3238
3239    pub(crate) async fn request_book_snapshot_with_permit(
3240        &self,
3241        instrument_id: InstrumentId,
3242        depth: Option<u32>,
3243        permit: Option<SnapshotPermit>,
3244    ) -> anyhow::Result<OrderBook> {
3245        if depth.is_some_and(|value| value == 0 || value > 5000) {
3246            anyhow::bail!("Binance Spot order-book depth must be between 1 and 5000");
3247        }
3248        let instrument = self.instrument_from_cache_by_id(instrument_id)?;
3249        let params = DepthParams {
3250            symbol: instrument_id.symbol.to_string(),
3251            limit: depth,
3252        };
3253
3254        let snapshot = match permit {
3255            Some(permit) => self.inner.depth_paced(&params, permit).await?,
3256            None => self.inner.depth(&params).await?,
3257        };
3258
3259        let ts_event = self.generate_ts_init();
3260        Self::parse_book_snapshot_response(instrument_id, &instrument, &snapshot, ts_event)
3261    }
3262
3263    fn parse_book_snapshot_response(
3264        instrument_id: InstrumentId,
3265        instrument: &InstrumentAny,
3266        snapshot: &BinanceDepth,
3267        ts_event: UnixNanos,
3268    ) -> anyhow::Result<OrderBook> {
3269        let sequence = u64::try_from(snapshot.last_update_id)
3270            .map_err(|_| anyhow::anyhow!("invalid negative order-book update ID"))?;
3271        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
3272        let mut add_level = |level: &super::models::BinancePriceLevel,
3273                             side: OrderSide,
3274                             order_id: usize,
3275                             name: &str|
3276         -> anyhow::Result<()> {
3277            let price = Price::from_mantissa_exponent_checked(
3278                level.price_mantissa,
3279                snapshot.price_exponent,
3280                instrument.price_precision(),
3281            )
3282            .map_err(|e| anyhow::anyhow!("invalid {name} price: {e}"))?;
3283            anyhow::ensure!(price.is_positive(), "invalid non-positive {name} price");
3284            let qty_mantissa = u64::try_from(level.qty_mantissa)
3285                .map_err(|_| anyhow::anyhow!("invalid negative {name} quantity"))?;
3286            let quantity = Quantity::from_mantissa_exponent_checked(
3287                qty_mantissa,
3288                snapshot.qty_exponent,
3289                instrument.size_precision(),
3290            )
3291            .map_err(|e| anyhow::anyhow!("invalid {name} quantity: {e}"))?;
3292            anyhow::ensure!(
3293                quantity.is_positive(),
3294                "invalid non-positive {name} quantity"
3295            );
3296            let order = BookOrder::new(
3297                side,
3298                price,
3299                quantity,
3300                u64::try_from(order_id)
3301                    .map_err(|_| anyhow::anyhow!("order-book level index overflow"))?,
3302            );
3303            book.add(order, 0, sequence, ts_event);
3304            Ok(())
3305        };
3306
3307        for (index, level) in snapshot.bids.iter().enumerate() {
3308            add_level(level, OrderSide::Buy, index, "bid")?;
3309        }
3310        let bid_count = snapshot.bids.len();
3311        for (index, level) in snapshot.asks.iter().enumerate() {
3312            let order_id = bid_count
3313                .checked_add(index)
3314                .ok_or_else(|| anyhow::anyhow!("order-book level index overflow"))?;
3315            add_level(level, OrderSide::Sell, order_id, "ask")?;
3316        }
3317        Ok(book)
3318    }
3319
3320    fn instrument_from_cache_by_id(
3321        &self,
3322        instrument_id: InstrumentId,
3323    ) -> anyhow::Result<InstrumentAny> {
3324        self.instruments_cache
3325            .get_cloned(&instrument_id.symbol.inner())
3326            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id).into())
3327    }
3328
3329    /// Requests the account state with Nautilus types.
3330    ///
3331    /// # Errors
3332    ///
3333    /// Returns an error if the request fails, SBE decoding fails, or a balance cannot be converted
3334    /// to a decimal or money amount.
3335    pub async fn request_account_state(
3336        &self,
3337        account_id: AccountId,
3338    ) -> anyhow::Result<AccountState> {
3339        let ts_init = self.clock.get_time_ns();
3340        let params = AccountInfoParams::default();
3341        let account_info = self.inner.account(&params).await?;
3342        account_info.to_account_state(account_id, ts_init)
3343    }
3344
3345    /// Requests the status of a specific order.
3346    ///
3347    /// Either `venue_order_id` or `client_order_id` must be provided.
3348    ///
3349    /// # Errors
3350    ///
3351    /// Returns an error if neither identifier is provided, the request fails for any
3352    /// reason other than a missing order, instrument is not cached, or parsing fails.
3353    pub async fn request_order_status_report(
3354        &self,
3355        account_id: AccountId,
3356        instrument_id: InstrumentId,
3357        venue_order_id: Option<VenueOrderId>,
3358        client_order_id: Option<ClientOrderId>,
3359    ) -> anyhow::Result<Option<OrderStatusReport>> {
3360        anyhow::ensure!(
3361            venue_order_id.is_some() || client_order_id.is_some(),
3362            "Either venue_order_id or client_order_id must be provided"
3363        );
3364
3365        let symbol = instrument_id.symbol.inner();
3366        let instrument = self.instrument_from_cache(symbol)?;
3367        let ts_init = self.generate_ts_init();
3368
3369        let order_id = venue_order_id
3370            .map(|id| id.inner().parse::<i64>())
3371            .transpose()
3372            .map_err(|_| anyhow::anyhow!("Invalid venue order ID"))?;
3373
3374        let client_id_str =
3375            client_order_id.map(|id| encode_broker_id(&id, BINANCE_NAUTILUS_SPOT_BROKER_ID));
3376
3377        let order = match self
3378            .inner
3379            .query_order(symbol.as_str(), order_id, client_id_str.as_deref())
3380            .await
3381        {
3382            Ok(order) => order,
3383            Err(e) if Self::is_no_such_order_error(&e) => {
3384                log::debug!("Binance Spot order not found: instrument_id={instrument_id}");
3385                return Ok(None);
3386            }
3387            Err(e) => anyhow::bail!(e),
3388        };
3389
3390        parse_order_status_report_sbe(
3391            &order,
3392            account_id,
3393            &instrument,
3394            BINANCE_NAUTILUS_SPOT_BROKER_ID,
3395            ts_init,
3396        )
3397        .map(Some)
3398    }
3399
3400    const fn is_no_such_order_error(error: &BinanceSpotHttpError) -> bool {
3401        matches!(
3402            error,
3403            BinanceSpotHttpError::BinanceError { code, .. } if *code == BINANCE_NO_SUCH_ORDER_CODE
3404        )
3405    }
3406
3407    /// Requests order status reports.
3408    ///
3409    /// When `open_only` is true, returns only open orders (instrument_id optional).
3410    /// When `open_only` is false, returns order history (instrument_id required).
3411    ///
3412    /// # Errors
3413    ///
3414    /// Returns an error if the request fails, any order's instrument is not cached,
3415    /// or parsing fails.
3416    pub async fn request_order_status_reports(
3417        &self,
3418        account_id: AccountId,
3419        instrument_id: Option<InstrumentId>,
3420        start: Option<Timestamp>,
3421        end: Option<Timestamp>,
3422        open_only: bool,
3423        limit: Option<u32>,
3424    ) -> anyhow::Result<Vec<OrderStatusReport>> {
3425        self.request_order_status_reports_scoped(
3426            account_id,
3427            instrument_id,
3428            start,
3429            end,
3430            open_only,
3431            limit,
3432            None,
3433        )
3434        .await
3435    }
3436
3437    #[expect(clippy::too_many_arguments)]
3438    pub(crate) async fn request_order_status_reports_scoped(
3439        &self,
3440        account_id: AccountId,
3441        instrument_id: Option<InstrumentId>,
3442        start: Option<Timestamp>,
3443        end: Option<Timestamp>,
3444        open_only: bool,
3445        limit: Option<u32>,
3446        provider: Option<&BinanceInstrumentProviderConfig>,
3447    ) -> anyhow::Result<Vec<OrderStatusReport>> {
3448        if instrument_id.is_some_and(|id| provider.is_some_and(|provider| provider.excludes(id))) {
3449            log::debug!("Dropping out-of-scope Binance Spot order request for {instrument_id:?}");
3450            return Ok(Vec::new());
3451        }
3452        let ts_init = self.generate_ts_init();
3453        let symbol = instrument_id.map(|id| id.symbol.to_string());
3454
3455        let orders = if open_only {
3456            self.inner
3457                .open_orders(symbol.as_deref())
3458                .await
3459                .map_err(|e| anyhow::anyhow!(e))?
3460        } else {
3461            let symbol = symbol
3462                .ok_or_else(|| anyhow::anyhow!("instrument_id is required when open_only=false"))?;
3463            self.inner
3464                .all_orders(
3465                    &symbol,
3466                    start.map(|dt| dt.as_millisecond()),
3467                    end.map(|dt| dt.as_millisecond()),
3468                    limit,
3469                )
3470                .await
3471                .map_err(|e| anyhow::anyhow!(e))?
3472        };
3473
3474        orders
3475            .iter()
3476            .filter(|order| {
3477                let id = format_instrument_id(&Ustr::from(&order.symbol), BinanceProductType::Spot);
3478                if provider.is_some_and(|provider| provider.excludes(id)) {
3479                    log::debug!("Dropping out-of-scope Binance Spot order for {id}");
3480                    false
3481                } else {
3482                    true
3483                }
3484            })
3485            .map(|order| {
3486                let symbol = Ustr::from(&order.symbol);
3487                let instrument = self.instrument_from_cache(symbol)?;
3488                parse_order_status_report_sbe(
3489                    order,
3490                    account_id,
3491                    &instrument,
3492                    BINANCE_NAUTILUS_SPOT_BROKER_ID,
3493                    ts_init,
3494                )
3495            })
3496            .collect()
3497    }
3498
3499    pub(crate) async fn request_order_history(
3500        &self,
3501        account_id: AccountId,
3502        instrument_id: InstrumentId,
3503        start: Option<UnixNanos>,
3504        end: UnixNanos,
3505    ) -> anyhow::Result<Vec<OrderStatusReport>> {
3506        const PAGE_LIMIT: u32 = 1_000;
3507        const MAX_INTERVAL_MS: i64 = SECONDS_IN_DAY as i64 * 1_000;
3508
3509        let instrument = self.instrument_from_cache(instrument_id.symbol.inner())?;
3510        let end_ms = end.as_i64() / NANOSECONDS_IN_MILLISECOND as i64;
3511        let mut window_start = start.map(|time| time.as_i64() / NANOSECONDS_IN_MILLISECOND as i64);
3512        let mut reports = IndexMap::new();
3513
3514        loop {
3515            let window_end = window_start.map_or(end_ms, |start_ms| {
3516                start_ms.saturating_add(MAX_INTERVAL_MS - 1).min(end_ms)
3517            });
3518
3519            let mut order_id = window_start.is_none().then_some(0);
3520            let window_end_micros = window_end
3521                .saturating_add(1)
3522                .saturating_mul((NANOSECONDS_IN_MILLISECOND / NANOSECONDS_IN_MICROSECOND) as i64)
3523                .saturating_sub(1);
3524
3525            loop {
3526                let orders = self
3527                    .inner
3528                    .all_orders_with_cursor(
3529                        instrument_id.symbol.as_str(),
3530                        order_id,
3531                        window_start.filter(|_| order_id.is_none()),
3532                        order_id.is_none().then_some(window_end),
3533                        Some(PAGE_LIMIT),
3534                    )
3535                    .await?;
3536                let page_len = orders.len();
3537
3538                let Some(last_id) = orders.iter().map(|order| order.order_id).max() else {
3539                    break;
3540                };
3541
3542                let past_end = orders.iter().any(|order| order.time > window_end_micros);
3543                for order in orders
3544                    .into_iter()
3545                    .filter(|order| order.time <= window_end_micros)
3546                {
3547                    let Entry::Vacant(entry) = reports.entry(order.order_id) else {
3548                        continue;
3549                    };
3550
3551                    let report = parse_order_status_report_sbe(
3552                        &order,
3553                        account_id,
3554                        &instrument,
3555                        BINANCE_NAUTILUS_SPOT_BROKER_ID,
3556                        end,
3557                    )?;
3558                    entry.insert(report);
3559                }
3560
3561                if page_len < PAGE_LIMIT as usize || past_end {
3562                    break;
3563                }
3564
3565                let next_id = last_id
3566                    .checked_add(1)
3567                    .context("Binance Spot order ID overflow during pagination")?;
3568                anyhow::ensure!(
3569                    next_id > order_id.unwrap_or_default(),
3570                    "Binance Spot order history pagination made no progress"
3571                );
3572                order_id = Some(next_id);
3573            }
3574
3575            if window_start.is_none() || window_end >= end_ms {
3576                break;
3577            }
3578
3579            window_start = Some(window_end + 1);
3580        }
3581
3582        Ok(reports.into_values().collect())
3583    }
3584
3585    /// Requests fill reports (trade history) for an instrument.
3586    ///
3587    /// # Errors
3588    ///
3589    /// Returns an error if the request fails, any trade's instrument is not cached,
3590    /// or parsing fails.
3591    pub async fn request_fill_reports(
3592        &self,
3593        account_id: AccountId,
3594        instrument_id: InstrumentId,
3595        venue_order_id: Option<VenueOrderId>,
3596        start: Option<Timestamp>,
3597        end: Option<Timestamp>,
3598        limit: Option<u32>,
3599    ) -> anyhow::Result<Vec<FillReport>> {
3600        self.request_fill_reports_with_cursor(
3601            account_id,
3602            instrument_id,
3603            venue_order_id,
3604            start,
3605            end,
3606            None,
3607            limit,
3608        )
3609        .await
3610    }
3611
3612    #[expect(clippy::too_many_arguments)]
3613    pub(crate) async fn request_fill_reports_with_cursor(
3614        &self,
3615        account_id: AccountId,
3616        instrument_id: InstrumentId,
3617        venue_order_id: Option<VenueOrderId>,
3618        start: Option<Timestamp>,
3619        end: Option<Timestamp>,
3620        from_id: Option<i64>,
3621        limit: Option<u32>,
3622    ) -> anyhow::Result<Vec<FillReport>> {
3623        let ts_init = self.generate_ts_init();
3624        let symbol = instrument_id.symbol.inner();
3625
3626        let order_id = venue_order_id
3627            .map(|id| id.inner().parse::<i64>())
3628            .transpose()
3629            .map_err(|_| anyhow::anyhow!("Invalid venue order ID"))?;
3630
3631        let trades = self
3632            .inner
3633            .account_trades_with_cursor(
3634                symbol.as_str(),
3635                order_id,
3636                start.map(|dt| dt.as_millisecond()),
3637                end.map(|dt| dt.as_millisecond()),
3638                from_id,
3639                limit,
3640            )
3641            .await
3642            .map_err(|e| anyhow::anyhow!(e))?;
3643
3644        trades
3645            .iter()
3646            .map(|trade| {
3647                let symbol = Ustr::from(&trade.symbol);
3648                let instrument = self.instrument_from_cache(symbol)?;
3649                let commission_currency = get_currency(&trade.commission_asset);
3650                parse_fill_report_sbe(trade, account_id, &instrument, commission_currency, ts_init)
3651            })
3652            .collect()
3653    }
3654
3655    /// Submits a new order to the venue.
3656    ///
3657    /// Converts Nautilus domain types to Binance-specific parameters
3658    /// and returns an `OrderStatusReport`.
3659    ///
3660    /// # Errors
3661    ///
3662    /// Returns an error if:
3663    /// - The instrument is not cached.
3664    /// - The order type or time-in-force is unsupported.
3665    /// - Stop orders are submitted without a trigger price.
3666    /// - The request fails or SBE decoding fails.
3667    #[expect(clippy::too_many_arguments)]
3668    pub async fn submit_order(
3669        &self,
3670        account_id: AccountId,
3671        instrument_id: InstrumentId,
3672        client_order_id: ClientOrderId,
3673        order_side: OrderSide,
3674        order_type: OrderType,
3675        quantity: Quantity,
3676        time_in_force: TimeInForce,
3677        price: Option<Price>,
3678        trigger_price: Option<Price>,
3679        post_only: bool,
3680        quote_quantity: bool,
3681        display_qty: Option<Quantity>,
3682        use_gtd: bool,
3683    ) -> anyhow::Result<OrderStatusReport> {
3684        let symbol = instrument_id.symbol.inner();
3685        let instrument = self
3686            .instrument_from_cache(symbol)
3687            .map_err(|e| Self::command_validation_error(e.to_string()))?;
3688        let ts_init = self.generate_ts_init();
3689
3690        let binance_side = BinanceSide::try_from(order_side)
3691            .map_err(|e| Self::command_validation_error(e.to_string()))?;
3692        let binance_order_type = order_type_to_binance_spot(order_type, post_only)
3693            .map_err(|e| Self::command_validation_error(e.to_string()))?;
3694
3695        // Validate trigger price for conditional orders
3696        let requires_trigger = matches!(
3697            order_type,
3698            OrderType::StopMarket
3699                | OrderType::StopLimit
3700                | OrderType::MarketIfTouched
3701                | OrderType::LimitIfTouched
3702        );
3703
3704        if requires_trigger && trigger_price.is_none() {
3705            return Err(Self::command_validation_error(
3706                "Conditional orders require a trigger price",
3707            ));
3708        }
3709
3710        // Validate price for order types that require it
3711        let requires_price = matches!(
3712            binance_order_type,
3713            BinanceSpotOrderType::Limit
3714                | BinanceSpotOrderType::StopLossLimit
3715                | BinanceSpotOrderType::TakeProfitLimit
3716                | BinanceSpotOrderType::LimitMaker
3717        );
3718
3719        if requires_price && price.is_none() {
3720            return Err(Self::command_validation_error(format!(
3721                "{binance_order_type:?} orders require a price"
3722            )));
3723        }
3724
3725        // Only send TIF for order types that support it
3726        let supports_tif = matches!(
3727            binance_order_type,
3728            BinanceSpotOrderType::Limit
3729                | BinanceSpotOrderType::StopLossLimit
3730                | BinanceSpotOrderType::TakeProfitLimit
3731        );
3732        let binance_tif = if supports_tif {
3733            Some(
3734                time_in_force_to_binance_spot(time_in_force, use_gtd)
3735                    .map_err(|e| Self::command_validation_error(e.to_string()))?,
3736            )
3737        } else {
3738            None
3739        };
3740
3741        let qty_str = quantity.to_string();
3742        let price_str = price.map(|p| p.to_string());
3743        let stop_price_str = trigger_price.map(|p| p.to_string());
3744        let iceberg_qty_str = display_qty.map(|q| q.to_string());
3745        let client_id_str = encode_broker_id(&client_order_id, BINANCE_NAUTILUS_SPOT_BROKER_ID);
3746
3747        if quote_quantity && binance_order_type != BinanceSpotOrderType::Market {
3748            return Err(Self::command_validation_error(
3749                "quoteOrderQty is only supported for MARKET orders",
3750            ));
3751        }
3752
3753        let (base_qty, quote_qty) = if quote_quantity {
3754            (None, Some(qty_str.as_str()))
3755        } else {
3756            (Some(qty_str.as_str()), None)
3757        };
3758
3759        let response = self
3760            .inner
3761            .new_order_full(
3762                symbol.as_str(),
3763                binance_side,
3764                binance_order_type,
3765                binance_tif,
3766                base_qty,
3767                quote_qty,
3768                price_str.as_deref(),
3769                Some(&client_id_str),
3770                stop_price_str.as_deref(),
3771                iceberg_qty_str.as_deref(),
3772            )
3773            .await?;
3774
3775        parse_new_order_response_sbe(
3776            &response,
3777            account_id,
3778            &instrument,
3779            BINANCE_NAUTILUS_SPOT_BROKER_ID,
3780            ts_init,
3781        )
3782        .map_err(|e| Self::response_parse_error(e.to_string()))
3783    }
3784
3785    /// Submits multiple orders in a single batch request.
3786    ///
3787    /// Binance limits batch submit to 5 orders maximum.
3788    ///
3789    /// # Errors
3790    ///
3791    /// Returns an error if the request fails or JSON parsing fails.
3792    pub async fn submit_order_list(
3793        &self,
3794        orders: &[BatchOrderItem],
3795    ) -> BinanceSpotHttpResult<Vec<BatchOrderResult>> {
3796        self.inner.batch_submit_orders(orders).await
3797    }
3798
3799    /// Submits a Spot OCO order list.
3800    ///
3801    /// # Errors
3802    ///
3803    /// Returns an error if the request fails or JSON parsing fails.
3804    pub async fn submit_oco_order_list(
3805        &self,
3806        params: &NewOcoOrderListParams,
3807    ) -> BinanceSpotHttpResult<NewOcoOrderListResponse> {
3808        self.inner.new_oco_order_list(params).await
3809    }
3810
3811    /// Modifies an existing order (cancel and replace atomically).
3812    ///
3813    /// # Errors
3814    ///
3815    /// Returns an error if:
3816    /// - The instrument is not cached.
3817    /// - The order type or time-in-force is unsupported.
3818    /// - The request fails or SBE decoding fails.
3819    #[expect(clippy::too_many_arguments)]
3820    pub async fn modify_order(
3821        &self,
3822        account_id: AccountId,
3823        instrument_id: InstrumentId,
3824        venue_order_id: VenueOrderId,
3825        client_order_id: ClientOrderId,
3826        order_side: OrderSide,
3827        order_type: OrderType,
3828        quantity: Quantity,
3829        time_in_force: TimeInForce,
3830        price: Option<Price>,
3831        use_gtd: bool,
3832        cancel_new_client_order_id: &str,
3833    ) -> anyhow::Result<OrderStatusReport> {
3834        let symbol = instrument_id.symbol.inner();
3835        let instrument = self
3836            .instrument_from_cache(symbol)
3837            .map_err(|e| Self::command_validation_error(e.to_string()))?;
3838        let ts_init = self.generate_ts_init();
3839
3840        let binance_side = BinanceSide::try_from(order_side)
3841            .map_err(|e| Self::command_validation_error(e.to_string()))?;
3842        let binance_order_type = order_type_to_binance_spot(order_type, false)
3843            .map_err(|e| Self::command_validation_error(e.to_string()))?;
3844        let binance_tif = time_in_force_to_binance_spot(time_in_force, use_gtd)
3845            .map_err(|e| Self::command_validation_error(e.to_string()))?;
3846
3847        let cancel_order_id: i64 = venue_order_id.inner().parse().map_err(|_| {
3848            Self::command_validation_error(format!("Invalid venue order ID: {venue_order_id}"))
3849        })?;
3850
3851        let qty_str = quantity.to_string();
3852        let price_str = price.map(|p| p.to_string());
3853        let client_id_str = encode_broker_id(&client_order_id, BINANCE_NAUTILUS_SPOT_BROKER_ID);
3854
3855        let response = self
3856            .inner
3857            .cancel_replace_order(
3858                symbol.as_str(),
3859                binance_side,
3860                binance_order_type,
3861                Some(binance_tif),
3862                Some(&qty_str),
3863                price_str.as_deref(),
3864                Some(cancel_order_id),
3865                None,
3866                Some(cancel_new_client_order_id),
3867                Some(&client_id_str),
3868            )
3869            .await
3870            .map_err(|e| anyhow::anyhow!(e))?;
3871
3872        parse_new_order_response_sbe(
3873            &response,
3874            account_id,
3875            &instrument,
3876            BINANCE_NAUTILUS_SPOT_BROKER_ID,
3877            ts_init,
3878        )
3879        .map_err(|e| Self::response_parse_error(e.to_string()))
3880    }
3881
3882    /// Cancels an existing order on the venue.
3883    ///
3884    /// Either `venue_order_id` or `client_order_id` must be provided.
3885    ///
3886    /// # Errors
3887    ///
3888    /// Returns an error if the request fails or SBE decoding fails.
3889    pub async fn cancel_order(
3890        &self,
3891        instrument_id: InstrumentId,
3892        venue_order_id: Option<VenueOrderId>,
3893        client_order_id: Option<ClientOrderId>,
3894    ) -> anyhow::Result<VenueOrderId> {
3895        let symbol = instrument_id.symbol.inner();
3896
3897        let order_id = match venue_order_id {
3898            Some(venue_order_id) => match venue_order_id.inner().parse::<i64>() {
3899                Ok(order_id) => Some(order_id),
3900                Err(e) if client_order_id.is_some() => {
3901                    log::warn!(
3902                        "Unable to parse venue_order_id {venue_order_id} for cancel, canceling by client_order_id: {e}"
3903                    );
3904                    None
3905                }
3906                Err(e) => {
3907                    return Err(Self::command_validation_error(format!(
3908                        "Invalid venue order ID: {e}"
3909                    )));
3910                }
3911            },
3912            None => None,
3913        };
3914
3915        let client_id_str =
3916            client_order_id.map(|id| encode_broker_id(&id, BINANCE_NAUTILUS_SPOT_BROKER_ID));
3917
3918        let response = self
3919            .inner
3920            .cancel_order(symbol.as_str(), order_id, client_id_str.as_deref())
3921            .await
3922            .map_err(|e| anyhow::anyhow!(e))?;
3923
3924        Ok(VenueOrderId::new(response.order_id.to_string()))
3925    }
3926
3927    /// Cancels multiple orders in a single batch request.
3928    ///
3929    /// Binance limits batch cancel to 5 orders maximum.
3930    ///
3931    /// # Errors
3932    ///
3933    /// Returns an error if the request fails or JSON parsing fails.
3934    pub async fn batch_cancel_orders(
3935        &self,
3936        cancels: &[BatchCancelItem],
3937    ) -> BinanceSpotHttpResult<Vec<BatchCancelResult>> {
3938        self.inner.batch_cancel_orders(cancels).await
3939    }
3940
3941    /// Cancels all open orders for a symbol.
3942    ///
3943    /// Returns the venue order IDs of all canceled orders.
3944    ///
3945    /// # Errors
3946    ///
3947    /// Returns an error if the request fails or SBE decoding fails.
3948    pub async fn cancel_all_orders(
3949        &self,
3950        instrument_id: InstrumentId,
3951    ) -> anyhow::Result<Vec<(VenueOrderId, ClientOrderId)>> {
3952        let responses = self.cancel_all_order_responses(instrument_id).await?;
3953
3954        responses
3955            .into_iter()
3956            .flat_map(|response| match response {
3957                BinanceCancelOpenOrdersResponse::Order(response) => vec![response],
3958                BinanceCancelOpenOrdersResponse::OrderList(response) => response.order_reports,
3959            })
3960            .map(|response| {
3961                Ok((
3962                    VenueOrderId::new(response.order_id.to_string()),
3963                    decode_client_order_id(
3964                        &response.orig_client_order_id,
3965                        BINANCE_NAUTILUS_SPOT_BROKER_ID,
3966                    )?,
3967                ))
3968            })
3969            .collect()
3970    }
3971
3972    /// Cancels all open orders and preserves the venue response shape.
3973    ///
3974    /// # Errors
3975    ///
3976    /// Returns an error if the request or response decoding fails.
3977    pub(crate) async fn cancel_all_order_responses(
3978        &self,
3979        instrument_id: InstrumentId,
3980    ) -> anyhow::Result<Vec<BinanceCancelOpenOrdersResponse>> {
3981        let symbol = instrument_id.symbol.inner();
3982
3983        let responses = self
3984            .inner
3985            .cancel_open_order_responses(symbol.as_str())
3986            .await
3987            .map_err(|e| anyhow::anyhow!(e))?;
3988
3989        Ok(responses)
3990    }
3991}
3992
3993fn spot_json_market_status(status: &str) -> MarketStatusAction {
3994    match status {
3995        "TRADING" => MarketStatusAction::Trading,
3996        "BREAK" => MarketStatusAction::Pause,
3997        _ => MarketStatusAction::NotAvailableForTrading,
3998    }
3999}
4000
4001fn log_instrument_parse_error(
4002    config: &BinanceInstrumentProviderConfig,
4003    selector: &BinanceInstrumentSelector,
4004    instrument_id: InstrumentId,
4005    symbol: &str,
4006    error: &anyhow::Error,
4007) {
4008    let explicit = selector.is_explicit(instrument_id, symbol);
4009    if should_warn_on_instrument_parse_error(config.log_warnings, explicit, error) {
4010        log::warn!("Skipping Binance Spot instrument {symbol}: {error}");
4011    } else {
4012        log::debug!("Skipping Binance Spot instrument {symbol}: {error}");
4013    }
4014}
4015
4016#[cfg(test)]
4017mod tests {
4018    use std::{
4019        sync::atomic::{AtomicUsize, Ordering},
4020        time::Duration,
4021    };
4022
4023    use axum::{
4024        Router,
4025        http::{Method, StatusCode},
4026        response::IntoResponse,
4027        routing::any,
4028    };
4029    use nautilus_model::instruments::stubs::currency_pair_btcusdt;
4030    use nautilus_network::ratelimiter::{RateLimiter, clock::MonotonicClock};
4031    use nautilus_testkit::http::assert_http_redirect_rejected;
4032    use parking_lot::Mutex;
4033    use rstest::rstest;
4034
4035    use super::*;
4036    use crate::spot::http::models::BinancePriceLevel;
4037
4038    #[tokio::test]
4039    async fn test_weighted_concurrent_clients_share_atomic_quota() {
4040        let requests = Arc::new(AtomicUsize::new(0));
4041        let captured = requests.clone();
4042        let response = include_str!("../../../test_data/spot/http_json/server_time_response.json");
4043
4044        let app = Router::new().fallback(any(move || {
4045            let captured = captured.clone();
4046            async move {
4047                captured.fetch_add(1, Ordering::Relaxed);
4048                response
4049            }
4050        }));
4051
4052        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4053        let url = format!("http://{}", listener.local_addr().unwrap());
4054
4055        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4056        let quota = Quota::with_period(Duration::from_secs(3600))
4057            .unwrap()
4058            .allow_burst(NonZeroU32::new(30).unwrap());
4059
4060        let limiter = Arc::new(RateLimiter::new_with_quota(
4061            None,
4062            vec![(Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota)],
4063        ));
4064        let mut client = BinanceRawSpotHttpClient::new(
4065            BinanceEnvironment::Live,
4066            Some("key".into()),
4067            Some("secret".into()),
4068            Some(url.clone()),
4069            None,
4070            None,
4071            None,
4072        )
4073        .unwrap()
4074        .for_command(false);
4075        client.client = HttpClient::builder()
4076            .rate_limiters(vec![limiter.clone()])
4077            .build()
4078            .unwrap();
4079        let other = client.clone();
4080
4081        let (first, second) = tokio::join!(
4082            async { client.get("exchangeInfo", None::<&()>).await },
4083            async { other.get("exchangeInfo", None::<&()>).await }
4084        );
4085        let successes = usize::from(first.is_ok()) + usize::from(second.is_ok());
4086        let blocked = usize::from(matches!(first, Err(BinanceSpotHttpError::RateLimitBlocked)))
4087            + usize::from(matches!(
4088                second,
4089                Err(BinanceSpotHttpError::RateLimitBlocked)
4090            ));
4091        let mut remaining = 0;
4092        while limiter
4093            .check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY))
4094            .is_ok()
4095        {
4096            remaining += 1;
4097        }
4098
4099        server.abort();
4100
4101        assert_eq!(successes, 1);
4102        assert_eq!(blocked, 1);
4103        assert_eq!(remaining, 10);
4104        assert_eq!(requests.load(Ordering::Relaxed), 1);
4105    }
4106
4107    #[tokio::test]
4108    async fn test_weighted_history_pages_consume_each_page() {
4109        let cursors = Arc::new(Mutex::new(Vec::new()));
4110        let captured = cursors.clone();
4111        let response = include_str!("../../../test_data/spot/http_json/server_time_response.json");
4112
4113        let app = Router::new().fallback(any(move |uri: axum::http::Uri| {
4114            let captured = captured.clone();
4115            async move {
4116                let query: AHashMap<String, String> =
4117                    serde_urlencoded::from_str(uri.query().unwrap()).unwrap();
4118                captured.lock().push(query["fromId"].clone());
4119                response
4120            }
4121        }));
4122
4123        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4124        let url = format!("http://{}", listener.local_addr().unwrap());
4125
4126        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4127        let quota = Quota::with_period(Duration::from_secs(3600))
4128            .unwrap()
4129            .allow_burst(NonZeroU32::new(40).unwrap());
4130
4131        let limiter = Arc::new(RateLimiter::new_with_quota(
4132            None,
4133            vec![(Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota)],
4134        ));
4135        let mut client = BinanceRawSpotHttpClient::new(
4136            BinanceEnvironment::Live,
4137            Some("key".into()),
4138            Some("secret".into()),
4139            Some(url.clone()),
4140            None,
4141            None,
4142            None,
4143        )
4144        .unwrap()
4145        .for_command(false);
4146        client.client = HttpClient::builder()
4147            .rate_limiters(vec![limiter.clone()])
4148            .build()
4149            .unwrap();
4150        let mut responses = Vec::new();
4151
4152        for from_id in [1, 101] {
4153            let params = [
4154                ("symbol", "BTCUSDT".to_string()),
4155                ("fromId", from_id.to_string()),
4156            ];
4157            responses.push(
4158                client
4159                    .get_signed_json("myTrades", Some(&params))
4160                    .await
4161                    .unwrap(),
4162            );
4163        }
4164
4165        let exhausted = limiter
4166            .check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY))
4167            .is_err();
4168        server.abort();
4169
4170        assert_eq!(responses, vec![response.as_bytes().to_vec(); 2]);
4171        assert_eq!(*cursors.lock(), ["1", "101"]);
4172        assert!(exhausted);
4173    }
4174
4175    #[rstest]
4176    #[case("time", 1)]
4177    #[case("exchangeInfo", 20)]
4178    #[tokio::test]
4179    async fn test_weighted_request_consumes_endpoint_cost(#[case] path: &str, #[case] weight: u32) {
4180        let requests = Arc::new(AtomicUsize::new(0));
4181        let captured = requests.clone();
4182        let response = include_str!("../../../test_data/spot/http_json/server_time_response.json");
4183
4184        let app = Router::new().fallback(any(move || {
4185            let captured = captured.clone();
4186            async move {
4187                captured.fetch_add(1, Ordering::Relaxed);
4188                response
4189            }
4190        }));
4191
4192        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4193        let url = format!("http://{}", listener.local_addr().unwrap());
4194
4195        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4196        let quota = Quota::with_period(Duration::from_secs(3600))
4197            .unwrap()
4198            .allow_burst(NonZeroU32::new(weight).unwrap());
4199
4200        let limiter = Arc::new(RateLimiter::<Ustr, MonotonicClock>::new_with_quota(
4201            None,
4202            vec![(Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota)],
4203        ));
4204        let mut client = BinanceRawSpotHttpClient::new(
4205            BinanceEnvironment::Live,
4206            None,
4207            None,
4208            Some(url),
4209            None,
4210            None,
4211            None,
4212        )
4213        .unwrap()
4214        .for_command(false);
4215        client.client = HttpClient::builder()
4216            .rate_limiters(vec![limiter.clone()])
4217            .build()
4218            .unwrap();
4219
4220        let first = client.get(path, None::<&()>).await;
4221        let blocked = client.get("time", None::<&()>).await;
4222        let exhausted = limiter
4223            .check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY))
4224            .is_err();
4225        server.abort();
4226
4227        assert_eq!(first.unwrap(), response.as_bytes());
4228        assert!(matches!(
4229            blocked,
4230            Err(BinanceSpotHttpError::RateLimitBlocked)
4231        ));
4232        assert!(exhausted);
4233        assert_eq!(requests.load(Ordering::Relaxed), 1);
4234    }
4235
4236    #[tokio::test]
4237    async fn test_weighted_read_retry_consumes_each_attempt() {
4238        let requests = Arc::new(AtomicUsize::new(0));
4239        let captured = requests.clone();
4240        let response = include_str!("../../../test_data/spot/http_json/server_time_response.json");
4241
4242        let app = Router::new().fallback(any(move || {
4243            let captured = captured.clone();
4244            async move {
4245                if captured.fetch_add(1, Ordering::Relaxed) == 0 {
4246                    (StatusCode::SERVICE_UNAVAILABLE, "retry").into_response()
4247                } else {
4248                    (StatusCode::OK, response).into_response()
4249                }
4250            }
4251        }));
4252
4253        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4254        let url = format!("http://{}", listener.local_addr().unwrap());
4255
4256        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4257        let quota = Quota::with_period(Duration::from_secs(3600))
4258            .unwrap()
4259            .allow_burst(NonZeroU32::new(40).unwrap());
4260
4261        let limiter = Arc::new(RateLimiter::<Ustr, MonotonicClock>::new_with_quota(
4262            None,
4263            vec![(Ustr::from(BINANCE_GLOBAL_RATE_KEY), quota)],
4264        ));
4265        let mut client = BinanceRawSpotHttpClient::new(
4266            BinanceEnvironment::Live,
4267            None,
4268            None,
4269            Some(url),
4270            None,
4271            None,
4272            None,
4273        )
4274        .unwrap();
4275        client.client = HttpClient::builder()
4276            .rate_limiters(vec![limiter.clone()])
4277            .build()
4278            .unwrap();
4279
4280        client.retry_manager = Arc::new(RetryManager::new(RetryConfig {
4281            max_retries: 1,
4282            initial_delay_ms: 1,
4283            max_delay_ms: 1,
4284            jitter_ms: 0,
4285            ..crate::common::http::retry_config()
4286        }));
4287
4288        let path = "exchangeInfo";
4289        let result = client.get(path, None::<&()>).await;
4290        let exhausted = limiter
4291            .check_key(&Ustr::from(BINANCE_GLOBAL_RATE_KEY))
4292            .is_err();
4293        server.abort();
4294
4295        assert_eq!(result.unwrap(), response.as_bytes());
4296        assert_eq!(requests.load(Ordering::Relaxed), 2);
4297        assert!(exhausted);
4298    }
4299
4300    #[rstest]
4301    #[tokio::test]
4302    async fn test_cancel_bypasses_exhausted_order_bucket() {
4303        let requests = Arc::new(Mutex::new(Vec::new()));
4304        let captured = requests.clone();
4305        let app = Router::new().fallback(any(move |method: Method| {
4306            let captured = captured.clone();
4307            async move {
4308                captured.lock().push(method.clone());
4309
4310                let body = if method == Method::DELETE {
4311                    include_str!("../../../test_data/spot/http_json/cancel_order_response.json")
4312                        .to_string()
4313                } else {
4314                    "{}".into()
4315                };
4316
4317                (StatusCode::OK, body).into_response()
4318            }
4319        }));
4320
4321        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4322        let url = format!("http://{}", listener.local_addr().unwrap());
4323
4324        let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4325        let mut client = BinanceRawSpotHttpClient::new_with_json_responses(
4326            BinanceEnvironment::Live,
4327            Some("key".into()),
4328            Some("secret".into()),
4329            Some(url),
4330            None,
4331            None,
4332            None,
4333            true,
4334        )
4335        .unwrap();
4336        client.client = HttpClient::builder()
4337            .keyed_quotas(
4338                client
4339                    .order_rate_keys
4340                    .iter()
4341                    .map(|key| {
4342                        (
4343                            key.clone(),
4344                            Quota::per_minute(std::num::NonZeroU32::MIN)
4345                                .allow_burst(std::num::NonZeroU32::MIN),
4346                        )
4347                    })
4348                    .collect(),
4349            )
4350            .build()
4351            .unwrap();
4352
4353        let first = client.post_signed("order", None::<&()>).await;
4354        let blocked = client.post_signed("order", None::<&()>).await;
4355        let cancel = tokio::time::timeout(Duration::from_millis(250), async {
4356            client.cancel_order("LTCBTC", Some(4), None).await
4357        })
4358        .await
4359        .unwrap();
4360
4361        server.abort();
4362
4363        assert!(first.is_ok());
4364        assert!(matches!(
4365            blocked,
4366            Err(BinanceSpotHttpError::RateLimitBlocked)
4367        ));
4368        assert_eq!(cancel.unwrap().order_id, 4);
4369        assert_eq!(*requests.lock(), [Method::POST, Method::DELETE]);
4370    }
4371
4372    #[tokio::test]
4373    async fn test_authenticated_client_rejects_redirects() {
4374        let client = BinanceRawSpotHttpClient::new(
4375            BinanceEnvironment::Testnet,
4376            Some("key".into()),
4377            Some("secret".into()),
4378            None,
4379            None,
4380            Some(3),
4381            None,
4382        )
4383        .unwrap()
4384        .client;
4385        assert_http_redirect_rejected(|url| async move {
4386            client
4387                .get(url, None, None, Some(3), None)
4388                .await
4389                .unwrap()
4390                .status
4391                .as_u16()
4392        })
4393        .await;
4394    }
4395
4396    #[rstest]
4397    fn test_schema_constants() {
4398        assert_eq!(BinanceRawSpotHttpClient::schema_id(), 3);
4399        assert_eq!(BinanceRawSpotHttpClient::schema_version(), 5);
4400        assert_eq!(BinanceSpotHttpClient::schema_id(), 3);
4401        assert_eq!(BinanceSpotHttpClient::schema_version(), 5);
4402    }
4403
4404    #[rstest]
4405    fn test_sbe_schema_header() {
4406        assert_eq!(SBE_SCHEMA_HEADER, "3:5");
4407    }
4408
4409    #[rstest]
4410    fn test_parse_book_snapshot_response_rejects_negative_update_id() {
4411        let instrument = InstrumentAny::CurrencyPair(currency_pair_btcusdt());
4412        let snapshot = BinanceDepth {
4413            last_update_id: -1,
4414            price_exponent: -2,
4415            qty_exponent: -5,
4416            bids: vec![],
4417            asks: vec![],
4418        };
4419
4420        let error = BinanceSpotHttpClient::parse_book_snapshot_response(
4421            InstrumentId::from("BTCUSDT.BINANCE"),
4422            &instrument,
4423            &snapshot,
4424            UnixNanos::from(1_700_000_000_000_000_001u64),
4425        )
4426        .unwrap_err();
4427
4428        assert_eq!(error.to_string(), "invalid negative order-book update ID");
4429    }
4430
4431    #[rstest]
4432    fn test_parse_book_snapshot_response_rejects_negative_quantity() {
4433        let instrument = InstrumentAny::CurrencyPair(currency_pair_btcusdt());
4434        let snapshot = BinanceDepth {
4435            last_update_id: 12345,
4436            price_exponent: -2,
4437            qty_exponent: -5,
4438            bids: vec![BinancePriceLevel {
4439                price_mantissa: 4_200_001,
4440                qty_mantissa: -1,
4441            }],
4442            asks: vec![],
4443        };
4444
4445        let error = BinanceSpotHttpClient::parse_book_snapshot_response(
4446            InstrumentId::from("BTCUSDT.BINANCE"),
4447            &instrument,
4448            &snapshot,
4449            UnixNanos::from(1_700_000_000_000_000_001u64),
4450        )
4451        .unwrap_err();
4452
4453        assert_eq!(error.to_string(), "invalid negative bid quantity");
4454    }
4455
4456    #[rstest]
4457    fn test_default_headers_include_sbe() {
4458        let headers = BinanceRawSpotHttpClient::default_headers(&None, false);
4459
4460        assert_eq!(headers.get("Accept"), Some(&"application/sbe".to_string()));
4461        assert_eq!(headers.get("X-MBX-SBE"), Some(&"3:5".to_string()));
4462    }
4463
4464    #[rstest]
4465    fn test_json_headers_exclude_sbe() {
4466        let headers = BinanceRawSpotHttpClient::default_headers(&None, true);
4467
4468        assert_eq!(headers.get("Accept"), Some(&"application/json".to_string()));
4469        assert_eq!(headers.get("X-MBX-SBE"), None);
4470    }
4471
4472    #[rstest]
4473    fn test_spot_cancel_open_orders_from_json_decodes_mixed_results() {
4474        let bytes = serde_json::to_vec(&serde_json::json!([
4475            {
4476                "symbol": "BTCUSDT",
4477                "orderId": 11,
4478                "orderListId": -1,
4479                "clientOrderId": "cancel-11",
4480                "origClientOrderId": "orig-11",
4481                "transactTime": 1_734_300_000_000_i64,
4482                "price": "100.00",
4483                "origQty": "1.000",
4484                "executedQty": "0.000",
4485                "cummulativeQuoteQty": "0.00",
4486                "status": "CANCELED",
4487                "timeInForce": "GTC",
4488                "type": "LIMIT",
4489                "side": "SELL"
4490            },
4491            {
4492                "orderListId": 44,
4493                "contingencyType": "OCO",
4494                "listStatusType": "ALL_DONE",
4495                "listOrderStatus": "ALL_DONE",
4496                "listClientOrderId": "list-44",
4497                "transactionTime": 1_734_300_000_000_i64,
4498                "symbol": "BTCUSDT",
4499                "orders": [
4500                    {"symbol": "BTCUSDT", "orderId": 21, "clientOrderId": "orig-21"},
4501                    {"symbol": "BTCUSDT", "orderId": 22, "clientOrderId": "orig-22"}
4502                ],
4503                "orderReports": [
4504                    {
4505                        "symbol": "BTCUSDT",
4506                        "orderId": 21,
4507                        "orderListId": 44,
4508                        "clientOrderId": "cancel-list",
4509                        "origClientOrderId": "orig-21",
4510                        "transactTime": 1_734_300_000_000_i64,
4511                        "price": "101.00",
4512                        "origQty": "1.000",
4513                        "executedQty": "0.000",
4514                        "cummulativeQuoteQty": "0.00",
4515                        "status": "CANCELED",
4516                        "timeInForce": "GTC",
4517                        "type": "LIMIT_MAKER",
4518                        "side": "SELL"
4519                    },
4520                    {
4521                        "symbol": "BTCUSDT",
4522                        "orderId": 22,
4523                        "orderListId": 44,
4524                        "clientOrderId": "cancel-list",
4525                        "origClientOrderId": "orig-22",
4526                        "transactTime": 1_734_300_000_000_i64,
4527                        "price": "99.00",
4528                        "origQty": "1.000",
4529                        "executedQty": "0.000",
4530                        "cummulativeQuoteQty": "0.00",
4531                        "status": "CANCELED",
4532                        "timeInForce": "GTC",
4533                        "type": "STOP_LOSS_LIMIT",
4534                        "side": "SELL"
4535                    }
4536                ]
4537            }
4538        ]))
4539        .unwrap();
4540
4541        let responses = spot_cancel_open_orders_from_json(&bytes).unwrap();
4542
4543        assert_eq!(responses.len(), 2);
4544        assert!(matches!(
4545            &responses[0],
4546            BinanceCancelOpenOrdersResponse::Order(order) if order.order_id == 11
4547        ));
4548        let BinanceCancelOpenOrdersResponse::OrderList(order_list) = &responses[1] else {
4549            panic!("Expected JSON order-list result");
4550        };
4551        assert_eq!(order_list.order_list_id, 44);
4552        assert_eq!(order_list.transaction_time, 1_734_300_000_000_000);
4553        assert_eq!(order_list.orders.len(), 2);
4554        assert_eq!(order_list.order_reports.len(), 2);
4555        assert_eq!(order_list.order_reports[0].orig_client_order_id, "orig-21");
4556        assert_eq!(order_list.order_reports[1].orig_client_order_id, "orig-22");
4557    }
4558
4559    #[rstest]
4560    fn test_spot_cancel_open_orders_from_json_rejects_partial_order_list_shape() {
4561        let bytes = br#"[{"orders": []}]"#;
4562
4563        let error = spot_cancel_open_orders_from_json(bytes).unwrap_err();
4564
4565        assert!(matches!(error, BinanceSpotHttpError::JsonError(_)));
4566    }
4567
4568    #[rstest]
4569    fn test_spot_trades_from_json_preserves_all_fields() {
4570        let response: Vec<SpotTradeJson> = serde_json::from_value(serde_json::json!([{
4571            "id": 17,
4572            "price": "123.45",
4573            "qty": "0.06789",
4574            "quoteQty": "8.3810205",
4575            "time": 1_700_000_000_123_i64,
4576            "isBuyerMaker": true,
4577            "isBestMatch": false
4578        }]))
4579        .unwrap();
4580
4581        let parsed = spot_trades_from_json(response).unwrap();
4582
4583        assert_eq!(parsed.price_exponent, -7);
4584        assert_eq!(parsed.qty_exponent, -5);
4585        assert_eq!(parsed.trades.len(), 1);
4586        assert_eq!(parsed.trades[0].id, 17);
4587        assert_eq!(parsed.trades[0].price_mantissa, 1_234_500_000);
4588        assert_eq!(parsed.trades[0].qty_mantissa, 6_789);
4589        assert_eq!(parsed.trades[0].quote_qty_mantissa, 83_810_205);
4590        assert_eq!(parsed.trades[0].time, 1_700_000_000_123_000);
4591        assert!(parsed.trades[0].is_buyer_maker);
4592        assert!(!parsed.trades[0].is_best_match);
4593    }
4594
4595    #[rstest]
4596    fn test_spot_agg_trades_from_json_preserves_all_fields() {
4597        let response: Vec<SpotAggTradeJson> = serde_json::from_value(serde_json::json!([{
4598            "a": 21,
4599            "p": "432.10",
4600            "q": "1.234",
4601            "f": 31,
4602            "l": 32,
4603            "T": 1_700_000_000_456_i64,
4604            "m": false,
4605            "M": true
4606        }]))
4607        .unwrap();
4608
4609        let parsed = spot_agg_trades_from_json(response).unwrap();
4610
4611        assert_eq!(parsed.price_exponent, -2);
4612        assert_eq!(parsed.qty_exponent, -3);
4613        assert_eq!(parsed.trades.len(), 1);
4614        assert_eq!(parsed.trades[0].id, 21);
4615        assert_eq!(parsed.trades[0].price_mantissa, 43_210);
4616        assert_eq!(parsed.trades[0].qty_mantissa, 1_234);
4617        assert_eq!(parsed.trades[0].first_trade_id, 31);
4618        assert_eq!(parsed.trades[0].last_trade_id, 32);
4619        assert_eq!(parsed.trades[0].time, 1_700_000_000_456_000);
4620        assert!(!parsed.trades[0].is_buyer_maker);
4621        assert!(parsed.trades[0].is_best_match);
4622    }
4623
4624    #[rstest]
4625    fn test_spot_klines_from_json_preserves_all_fields() {
4626        let response: Vec<SpotKlineJson> = serde_json::from_value(serde_json::json!([[
4627            1_700_000_000_000_i64,
4628            "10.10",
4629            "11.20",
4630            "9.30",
4631            "10.40",
4632            "12.345",
4633            1_700_000_059_999_i64,
4634            "128.765",
4635            37,
4636            "5.432",
4637            "56.789",
4638            "0"
4639        ]]))
4640        .unwrap();
4641
4642        let parsed = spot_klines_from_json(response).unwrap();
4643        let kline = &parsed.klines[0];
4644
4645        assert_eq!(parsed.price_exponent, -3);
4646        assert_eq!(parsed.qty_exponent, -3);
4647        assert_eq!(parsed.klines.len(), 1);
4648        assert_eq!(kline.open_time, 1_700_000_000_000_000);
4649        assert_eq!(kline.open_price, 10_100);
4650        assert_eq!(kline.high_price, 11_200);
4651        assert_eq!(kline.low_price, 9_300);
4652        assert_eq!(kline.close_price, 10_400);
4653        assert_eq!(i128::from_le_bytes(kline.volume), 12_345);
4654        assert_eq!(kline.close_time, 1_700_000_059_999_000);
4655        assert_eq!(i128::from_le_bytes(kline.quote_volume), 128_765);
4656        assert_eq!(kline.num_trades, 37);
4657        assert_eq!(i128::from_le_bytes(kline.taker_buy_base_volume), 5_432);
4658        assert_eq!(i128::from_le_bytes(kline.taker_buy_quote_volume), 56_789);
4659    }
4660
4661    #[rstest]
4662    fn test_spot_account_from_json_preserves_all_fields() {
4663        let response: SpotAccountJson = serde_json::from_value(serde_json::json!({
4664            "commissionRates": {
4665                "maker": "0.0008",
4666                "taker": "0.0011",
4667                "buyer": "0.0002",
4668                "seller": "0.0003"
4669            },
4670            "canTrade": true,
4671            "canWithdraw": false,
4672            "canDeposit": true,
4673            "requireSelfTradePrevention": true,
4674            "preventSor": false,
4675            "updateTime": 1_700_000_000_789_i64,
4676            "accountType": "SPOT",
4677            "balances": [{"asset": "USD", "free": "123.45", "locked": "6.789"}]
4678        }))
4679        .unwrap();
4680
4681        let account = spot_account_from_json(response).unwrap();
4682
4683        assert_eq!(account.commission_exponent, -4);
4684        assert_eq!(account.maker_commission_mantissa, 8);
4685        assert_eq!(account.taker_commission_mantissa, 11);
4686        assert_eq!(account.buyer_commission_mantissa, 2);
4687        assert_eq!(account.seller_commission_mantissa, 3);
4688        assert!(account.can_trade);
4689        assert!(!account.can_withdraw);
4690        assert!(account.can_deposit);
4691        assert!(account.require_self_trade_prevention);
4692        assert!(!account.prevent_sor);
4693        assert_eq!(account.update_time, 1_700_000_000_789_000);
4694        assert_eq!(account.account_type, "SPOT");
4695        assert_eq!(account.balances.len(), 1);
4696        assert_eq!(account.balances[0].asset, "USD");
4697        assert_eq!(account.balances[0].free_mantissa, 123_450);
4698        assert_eq!(account.balances[0].locked_mantissa, 6_789);
4699        assert_eq!(account.balances[0].exponent, -3);
4700    }
4701
4702    #[rstest]
4703    fn test_spot_cancel_replace_json_uses_nested_new_order_response() {
4704        let response: SpotCancelReplaceJson = serde_json::from_value(serde_json::json!({
4705            "cancelResult": "SUCCESS",
4706            "newOrderResult": "SUCCESS",
4707            "cancelResponse": {},
4708            "newOrderResponse": {
4709                "symbol": "ETHUSD",
4710                "orderId": 101,
4711                "orderListId": -1,
4712                "clientOrderId": "new-order",
4713                "transactTime": 1_700_000_000_123_i64,
4714                "price": "12.34",
4715                "origQty": "5.678",
4716                "executedQty": "1.234",
4717                "cummulativeQuoteQty": "15.22756",
4718                "status": "PARTIALLY_FILLED",
4719                "timeInForce": "GTC",
4720                "type": "LIMIT",
4721                "side": "BUY",
4722                "stopPrice": "11.11",
4723                "workingTime": 1_700_000_000_124_i64,
4724                "selfTradePreventionMode": "EXPIRE_MAKER",
4725                "fills": [{
4726                    "price": "12.34",
4727                    "qty": "1.234",
4728                    "commission": "0.001234",
4729                    "commissionAsset": "USD",
4730                    "tradeId": 44
4731                }]
4732            }
4733        }))
4734        .unwrap();
4735
4736        let order = spot_new_order_from_json(response.new_order_response).unwrap();
4737
4738        assert_eq!(order.price_exponent, -2);
4739        assert_eq!(order.qty_exponent, -3);
4740        assert_eq!(order.order_id, 101);
4741        assert_eq!(order.order_list_id, None);
4742        assert_eq!(order.transact_time, 1_700_000_000_123_000);
4743        assert_eq!(order.price_mantissa, 1_234);
4744        assert_eq!(order.orig_qty_mantissa, 5_678);
4745        assert_eq!(order.executed_qty_mantissa, 1_234);
4746        assert_eq!(order.cummulative_quote_qty_mantissa, 1_522_756);
4747        assert_eq!(order.status, SbeOrderStatus::PartiallyFilled);
4748        assert_eq!(order.time_in_force, SbeTimeInForce::Gtc);
4749        assert_eq!(order.order_type, SbeOrderType::Limit);
4750        assert_eq!(order.side, SbeOrderSide::Buy);
4751        assert_eq!(order.stop_price_mantissa, Some(1_111));
4752        assert_eq!(order.working_time, Some(1_700_000_000_124_000));
4753        assert_eq!(
4754            order.self_trade_prevention_mode,
4755            SbeSelfTradePreventionMode::ExpireMaker
4756        );
4757        assert_eq!(order.client_order_id, "new-order");
4758        assert_eq!(order.symbol, "ETHUSD");
4759        assert_eq!(order.fills.len(), 1);
4760        assert_eq!(order.fills[0].price_mantissa, 1_234);
4761        assert_eq!(order.fills[0].qty_mantissa, 1_234);
4762        assert_eq!(order.fills[0].commission_mantissa, 1_234);
4763        assert_eq!(order.fills[0].commission_exponent, -6);
4764        assert_eq!(order.fills[0].commission_asset, "USD");
4765        assert_eq!(order.fills[0].trade_id, Some(44));
4766        assert_eq!(order.expiry_reason, None);
4767    }
4768
4769    #[rstest]
4770    fn test_rate_limit_config() {
4771        let config = BinanceRawSpotHttpClient::rate_limit_config();
4772
4773        assert!(config.default_quota.is_some());
4774        // Spot has 2 ORDERS quotas (SECOND and DAY)
4775        assert_eq!(config.order_keys.len(), 2);
4776    }
4777
4778    #[rstest]
4779    fn test_quota_from_unknown_interval_returns_none() {
4780        let quota = BinanceRateLimitQuota {
4781            rate_limit_type: BinanceRateLimitType::Orders,
4782            interval: BinanceRateLimitInterval::Unknown,
4783            interval_num: 1,
4784            limit: 10,
4785        };
4786
4787        assert!(BinanceRawSpotHttpClient::quota_from(&quota).is_none());
4788    }
4789
4790    fn create_test_raw_client() -> BinanceRawSpotHttpClient {
4791        BinanceRawSpotHttpClient::new(
4792            BinanceEnvironment::Live,
4793            None,
4794            None,
4795            Some("http://127.0.0.1:1".to_string()),
4796            None,
4797            Some(1),
4798            None,
4799        )
4800        .unwrap()
4801    }
4802
4803    #[rstest]
4804    #[case::limit(
4805        AggTradesParams {
4806            symbol: "BTCUSDT".to_string(),
4807            from_id: None,
4808            start_time: None,
4809            end_time: None,
4810            limit: Some(1001),
4811        },
4812        "Validation error: aggregate trade limit must not exceed 1000"
4813    )]
4814    #[case::bounds(
4815        AggTradesParams {
4816            symbol: "BTCUSDT".to_string(),
4817            from_id: None,
4818            start_time: Some(2000),
4819            end_time: Some(1000),
4820            limit: Some(1000),
4821        },
4822        "Validation error: aggregate trade startTime must not exceed endTime"
4823    )]
4824    #[tokio::test]
4825    async fn test_agg_trades_rejects_invalid_bounds(
4826        #[case] params: AggTradesParams,
4827        #[case] expected: &str,
4828    ) {
4829        let error = create_test_raw_client()
4830            .agg_trades(&params)
4831            .await
4832            .unwrap_err();
4833
4834        assert_eq!(error.to_string(), expected);
4835    }
4836}