Skip to main content

nautilus_binance/common/
parse.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//! Parsing utilities for Binance API responses.
17//!
18//! Provides conversion functions to transform raw Binance exchange data
19//! into Nautilus domain objects such as instruments and market data.
20
21use std::str::FromStr;
22
23use anyhow::Context;
24use nautilus_core::nanos::UnixNanos;
25use nautilus_model::{
26    data::{
27        Bar, BarSpecification, BarType, BookOrder, OrderBookDelta, OrderBookDeltas, QuoteTick,
28        TradeTick,
29    },
30    enums::{
31        AggressorSide, AssetClass, BarAggregation, BookAction, LiquiditySide, OrderSide,
32        OrderStatus, OrderType, RecordFlag, TimeInForce, TriggerType,
33    },
34    identifiers::{AccountId, InstrumentId, OrderListId, Symbol, TradeId, Venue, VenueOrderId},
35    instruments::{
36        Instrument, any::InstrumentAny, crypto_future::CryptoFuture,
37        crypto_perpetual::CryptoPerpetual, currency_pair::CurrencyPair,
38        perpetual_contract::PerpetualContract,
39    },
40    reports::{FillReport, OrderStatusReport},
41    types::{AccountBalance, Currency, Money, Price, Quantity},
42};
43use rust_decimal::Decimal;
44use serde_json::Value;
45
46use crate::{
47    common::{
48        consts::BINANCE,
49        encoder::decode_client_order_id,
50        enums::{
51            BinanceContractStatus, BinanceKlineInterval, BinanceProductType, BinanceTradingStatus,
52        },
53        symbol::format_instrument_id,
54    },
55    futures::http::models::{BinanceFuturesCoinSymbol, BinanceFuturesUsdSymbol},
56    spot::{
57        http::models::{
58            BinanceAccountTrade, BinanceKlines, BinanceLotSizeFilterSbe, BinanceNewOrderResponse,
59            BinanceNotionalFilter, BinanceOrderResponse, BinancePriceFilterSbe, BinanceSymbolJson,
60            BinanceSymbolSbe, BinanceTrades,
61        },
62        sbe::spot::{
63            order_side::OrderSide as SbeOrderSide, order_status::OrderStatus as SbeOrderStatus,
64            order_type::OrderType as SbeOrderType, time_in_force::TimeInForce as SbeTimeInForce,
65        },
66    },
67};
68const CONTRACT_TYPE_PERPETUAL: &str = "PERPETUAL";
69const CONTRACT_TYPE_TRADIFI_PERPETUAL: &str = "TRADIFI_PERPETUAL";
70const CONTRACT_TYPE_CURRENT_WEEK: &str = "CURRENT_WEEK";
71const CONTRACT_TYPE_NEXT_WEEK: &str = "NEXT_WEEK";
72const CONTRACT_TYPE_CURRENT_MONTH: &str = "CURRENT_MONTH";
73const CONTRACT_TYPE_NEXT_MONTH: &str = "NEXT_MONTH";
74const CONTRACT_TYPE_CURRENT_QUARTER: &str = "CURRENT_QUARTER";
75const CONTRACT_TYPE_NEXT_QUARTER: &str = "NEXT_QUARTER";
76
77pub(crate) fn parse_millis(value: i64, field: &str) -> anyhow::Result<UnixNanos> {
78    parse_timestamp(value, UnixNanos::from_millis_checked(value), field)
79}
80
81pub(crate) fn parse_micros(value: i64, field: &str) -> anyhow::Result<UnixNanos> {
82    parse_timestamp(value, UnixNanos::from_micros_checked(value), field)
83}
84
85fn parse_timestamp(
86    value: i64,
87    timestamp: Option<UnixNanos>,
88    field: &str,
89) -> anyhow::Result<UnixNanos> {
90    timestamp.ok_or_else(|| {
91        if value < 0 {
92            anyhow::anyhow!("invalid negative Binance {field} timestamp: {value}")
93        } else {
94            anyhow::anyhow!("Binance {field} timestamp is outside the UnixNanos range: {value}")
95        }
96    })
97}
98
99pub(crate) fn parse_millis_or_init(value: i64, field: &str, ts_init: UnixNanos) -> UnixNanos {
100    timestamp_or_init(parse_millis(value, field), ts_init)
101}
102
103pub(crate) fn parse_micros_or_init(value: i64, field: &str, ts_init: UnixNanos) -> UnixNanos {
104    timestamp_or_init(parse_micros(value, field), ts_init)
105}
106
107fn timestamp_or_init(timestamp: anyhow::Result<UnixNanos>, ts_init: UnixNanos) -> UnixNanos {
108    match timestamp {
109        Ok(timestamp) => timestamp,
110        Err(e) => {
111            log::warn!("{e}; using initialization timestamp");
112            ts_init
113        }
114    }
115}
116
117fn parse_tradifi_asset_class(symbol: &BinanceFuturesUsdSymbol) -> anyhow::Result<AssetClass> {
118    let underlying_type = symbol.underlying_type.as_deref().with_context(|| {
119        format!(
120            "Missing underlying type for TRADIFI_PERPETUAL symbol '{}'",
121            symbol.symbol
122        )
123    })?;
124
125    // Binance uses CN_EQUITY for some China-listed TradFi perpetuals,
126    // including UNITREEUSDT. It has the same instrument semantics as the
127    // other equity underlying types supported here.
128    match underlying_type {
129        "EQUITY" | "CN_EQUITY" | "KR_EQUITY" | "HK_EQUITY" | "PREMARKET" => Ok(AssetClass::Equity),
130        "COMMODITY" => Ok(AssetClass::Commodity),
131        _ => anyhow::bail!(
132            "Unsupported underlying type '{underlying_type}' for TRADIFI_PERPETUAL symbol '{}'",
133            symbol.symbol
134        ),
135    }
136}
137
138/// Returns a currency from the internal map or creates a new crypto currency.
139pub fn get_currency(code: &str) -> Currency {
140    Currency::get_or_create_crypto(code)
141}
142
143/// Extracts filter values from Binance symbol filters array.
144fn get_filter<'a>(filters: &'a [Value], filter_type: &str) -> Option<&'a Value> {
145    filters.iter().find(|f| {
146        f.get("filterType")
147            .and_then(|v| v.as_str())
148            .is_some_and(|t| t == filter_type)
149    })
150}
151
152/// Parses a string field from a JSON value.
153fn parse_filter_string(filter: &Value, field: &str) -> anyhow::Result<String> {
154    filter
155        .get(field)
156        .and_then(|v| v.as_str())
157        .map(String::from)
158        .ok_or_else(|| anyhow::anyhow!("Missing field '{field}' in filter"))
159}
160
161/// Parses a Price from a filter field.
162fn parse_filter_price(filter: &Value, field: &str) -> anyhow::Result<Price> {
163    let value = parse_filter_string(filter, field)?;
164    Price::from_str(&value).map_err(|e| anyhow::anyhow!("Failed to parse {field}='{value}': {e}"))
165}
166
167/// Parses a Quantity from a filter field.
168fn parse_filter_quantity(filter: &Value, field: &str) -> anyhow::Result<Quantity> {
169    let value = parse_filter_string(filter, field)?;
170    Quantity::from_str(&value)
171        .map_err(|e| anyhow::anyhow!("Failed to parse {field}='{value}': {e}"))
172}
173
174/// Parses the futures `MIN_NOTIONAL` filter into a `Money` value in `currency`.
175///
176/// Returns `None` when the filter is absent, the `notional` field cannot be
177/// parsed, or the value is non-positive.
178fn parse_futures_min_notional(filters: &[Value], currency: Currency) -> Option<Money> {
179    let filter = get_filter(filters, "MIN_NOTIONAL")?;
180    let raw = filter.get("notional").and_then(|v| v.as_str())?;
181    let amount = f64::from_str(raw).ok()?;
182    if amount <= 0.0 {
183        return None;
184    }
185    Some(Money::new(amount, currency))
186}
187
188/// Parses a venue quantity string into a `Quantity` at the given precision.
189///
190/// Returns `None` for unparsable, zero, or negative values. Goes through
191/// `Decimal` so equality comparisons against domain quantities are exact and
192/// independent of `f64` rounding.
193#[must_use]
194pub(crate) fn parse_quantity_at_precision(raw: &str, precision: u8) -> Option<Quantity> {
195    let decimal = Decimal::from_str(raw).ok()?;
196    if !decimal.is_sign_positive() || decimal.is_zero() {
197        return None;
198    }
199
200    Quantity::from_decimal_dp(decimal, precision).ok()
201}
202
203/// Parses a venue price string into a `Price` at the given precision.
204///
205/// Returns `None` for unparsable, zero, or negative values. Goes through
206/// `Decimal` for exact comparison semantics.
207#[must_use]
208pub(crate) fn parse_price_at_precision(raw: &str, precision: u8) -> Option<Price> {
209    let decimal = Decimal::from_str(raw).ok()?;
210    if !decimal.is_sign_positive() || decimal.is_zero() {
211        return None;
212    }
213
214    Price::from_decimal_dp(decimal, precision).ok()
215}
216
217/// Parses a required venue decimal string.
218pub(crate) fn parse_required_decimal(raw: &str, field: &str) -> anyhow::Result<Decimal> {
219    Decimal::from_str(raw).map_err(|e| anyhow::anyhow!("invalid {field}='{raw}': {e}"))
220}
221
222/// Parses a required venue quantity string into a `Quantity` at the given precision.
223pub(crate) fn parse_required_quantity_at_precision(
224    raw: &str,
225    precision: u8,
226    field: &str,
227) -> anyhow::Result<Quantity> {
228    let decimal = parse_required_decimal(raw, field)?;
229    Quantity::from_decimal_dp(decimal, precision)
230        .map_err(|e| anyhow::anyhow!("invalid {field}='{raw}' at precision {precision}: {e}"))
231}
232
233/// Parses a required venue price string into a `Price` at the given precision.
234pub(crate) fn parse_required_price_at_precision(
235    raw: &str,
236    precision: u8,
237    field: &str,
238) -> anyhow::Result<Price> {
239    let decimal = parse_required_decimal(raw, field)?;
240    Price::from_decimal_dp(decimal, precision)
241        .map_err(|e| anyhow::anyhow!("invalid {field}='{raw}' at precision {precision}: {e}"))
242}
243
244/// Re-precisions an existing `Quantity` to the given precision via `Decimal`.
245#[must_use]
246pub(crate) fn quantity_at_precision(quantity: Quantity, precision: u8) -> Option<Quantity> {
247    Quantity::from_decimal_dp(quantity.as_decimal(), precision).ok()
248}
249
250/// Re-precisions an existing `Price` to the given precision via `Decimal`.
251#[must_use]
252pub(crate) fn price_at_precision(price: Price, precision: u8) -> Option<Price> {
253    Price::from_decimal_dp(price.as_decimal(), precision).ok()
254}
255
256/// Returns whether an instrument parse error reports a non-trading venue status.
257///
258/// Non-trading symbols are routine in full-catalog loads, so callers demote
259/// these skips to debug unless the symbol was explicitly selected.
260#[must_use]
261pub(crate) fn is_not_trading_error(error: &anyhow::Error) -> bool {
262    error
263        .chain()
264        .any(|cause| cause.to_string().contains("is not trading"))
265}
266
267/// Returns whether an instrument parse failure should be logged as a warning.
268///
269/// Non-trading skips stay at debug during bulk loads; explicitly selected
270/// symbols and unexpected parse failures honor `log_warnings`.
271#[must_use]
272pub(crate) fn should_warn_on_instrument_parse_error(
273    log_warnings: bool,
274    explicit: bool,
275    error: &anyhow::Error,
276) -> bool {
277    if !explicit && is_not_trading_error(error) {
278        return false;
279    }
280    log_warnings
281}
282
283/// Parses a USD-M Futures symbol definition into a Nautilus futures instrument.
284///
285/// # Errors
286///
287/// Returns an error if:
288/// - Required filter values are missing (PRICE_FILTER, LOT_SIZE).
289/// - Price or quantity values cannot be parsed.
290/// - The contract type is not a supported perpetual or delivery contract.
291/// - A TRADIFI_PERPETUAL underlying type is missing or unsupported.
292pub fn parse_usdm_instrument(
293    symbol: &BinanceFuturesUsdSymbol,
294    ts_event: UnixNanos,
295    ts_init: UnixNanos,
296) -> anyhow::Result<InstrumentAny> {
297    parse_usdm_instrument_with_fees(symbol, ts_event, ts_init)
298}
299
300pub(crate) fn parse_usdm_instrument_with_fees(
301    symbol: &BinanceFuturesUsdSymbol,
302    ts_event: UnixNanos,
303    ts_init: UnixNanos,
304) -> anyhow::Result<InstrumentAny> {
305    enum ContractKind {
306        CryptoPerpetual,
307        TradFi(AssetClass),
308        Delivery,
309    }
310
311    let contract_kind = match symbol.contract_type.as_str() {
312        CONTRACT_TYPE_PERPETUAL => ContractKind::CryptoPerpetual,
313        CONTRACT_TYPE_TRADIFI_PERPETUAL => ContractKind::TradFi(parse_tradifi_asset_class(symbol)?),
314        CONTRACT_TYPE_CURRENT_WEEK
315        | CONTRACT_TYPE_NEXT_WEEK
316        | CONTRACT_TYPE_CURRENT_MONTH
317        | CONTRACT_TYPE_NEXT_MONTH
318        | CONTRACT_TYPE_CURRENT_QUARTER
319        | CONTRACT_TYPE_NEXT_QUARTER => ContractKind::Delivery,
320        _ => anyhow::bail!(
321            "Unsupported USD-M contract type '{}' for symbol '{}'",
322            symbol.contract_type,
323            symbol.symbol,
324        ),
325    };
326
327    if symbol.status != BinanceTradingStatus::Trading {
328        anyhow::bail!(
329            "Symbol '{}' is not trading (status: {:?})",
330            symbol.symbol,
331            symbol.status
332        );
333    }
334
335    let quote_currency = get_currency(symbol.quote_asset.as_str());
336    let settlement_currency = get_currency(symbol.margin_asset.as_str());
337
338    let instrument_id = format_instrument_id(&symbol.symbol, BinanceProductType::UsdM);
339    let raw_symbol = Symbol::new(symbol.symbol.as_str());
340
341    let price_filter = get_filter(&symbol.filters, "PRICE_FILTER")
342        .context("Missing PRICE_FILTER in symbol filters")?;
343
344    let tick_size = parse_filter_price(price_filter, "tickSize")?;
345    if tick_size.is_zero() {
346        anyhow::bail!(
347            "Invalid tickSize of 0 for symbol '{}', cannot create instrument",
348            symbol.symbol,
349        );
350    }
351    let max_price = parse_filter_price(price_filter, "maxPrice").ok();
352    let min_price = parse_filter_price(price_filter, "minPrice").ok();
353
354    let lot_filter =
355        get_filter(&symbol.filters, "LOT_SIZE").context("Missing LOT_SIZE in symbol filters")?;
356
357    let step_size = parse_filter_quantity(lot_filter, "stepSize")?;
358    let max_quantity = parse_filter_quantity(lot_filter, "maxQty").ok();
359    let min_quantity = parse_filter_quantity(lot_filter, "minQty").ok();
360
361    let min_notional = parse_futures_min_notional(&symbol.filters, quote_currency);
362
363    let margin_maint = Decimal::new(1, 1);
364
365    match contract_kind {
366        ContractKind::TradFi(asset_class) => {
367            let instrument = PerpetualContract::builder()
368                .instrument_id(instrument_id)
369                .raw_symbol(raw_symbol)
370                .underlying(symbol.base_asset)
371                .asset_class(asset_class)
372                .quote_currency(quote_currency)
373                .settlement_currency(settlement_currency)
374                .is_inverse(false)
375                .price_precision(tick_size.precision)
376                .size_precision(step_size.precision)
377                .price_increment(tick_size)
378                .size_increment(step_size)
379                .lot_size(step_size)
380                .maybe_max_quantity(max_quantity)
381                .maybe_min_quantity(min_quantity)
382                .maybe_min_notional(min_notional)
383                .maybe_max_price(max_price)
384                .maybe_min_price(min_price)
385                .margin_init(Decimal::ONE)
386                .margin_maint(margin_maint)
387                .ts_event(ts_event)
388                .ts_init(ts_init)
389                .build()?;
390            Ok(InstrumentAny::PerpetualContract(instrument))
391        }
392        ContractKind::CryptoPerpetual => {
393            let instrument = CryptoPerpetual::builder()
394                .instrument_id(instrument_id)
395                .raw_symbol(raw_symbol)
396                .base_currency(get_currency(symbol.base_asset.as_str()))
397                .quote_currency(quote_currency)
398                .settlement_currency(settlement_currency)
399                .is_inverse(false)
400                .price_precision(tick_size.precision)
401                .size_precision(step_size.precision)
402                .price_increment(tick_size)
403                .size_increment(step_size)
404                .lot_size(step_size)
405                .maybe_max_quantity(max_quantity)
406                .maybe_min_quantity(min_quantity)
407                .maybe_min_notional(min_notional)
408                .maybe_max_price(max_price)
409                .maybe_min_price(min_price)
410                .margin_init(Decimal::ONE)
411                .margin_maint(margin_maint)
412                .ts_event(ts_event)
413                .ts_init(ts_init)
414                .build()
415                .unwrap();
416            Ok(InstrumentAny::CryptoPerpetual(instrument))
417        }
418        ContractKind::Delivery => {
419            let activation_ns = parse_millis(symbol.onboard_date, "Futures onboardDate")?;
420            let expiration_ns = parse_millis(symbol.delivery_date, "Futures deliveryDate")?;
421            let instrument = CryptoFuture::builder()
422                .instrument_id(instrument_id)
423                .raw_symbol(raw_symbol)
424                .underlying(get_currency(symbol.base_asset.as_str()))
425                .quote_currency(quote_currency)
426                .settlement_currency(settlement_currency)
427                .is_inverse(false)
428                .activation_ns(activation_ns)
429                .expiration_ns(expiration_ns)
430                .price_precision(tick_size.precision)
431                .size_precision(step_size.precision)
432                .price_increment(tick_size)
433                .size_increment(step_size)
434                .lot_size(step_size)
435                .maybe_max_quantity(max_quantity)
436                .maybe_min_quantity(min_quantity)
437                .maybe_min_notional(min_notional)
438                .maybe_max_price(max_price)
439                .maybe_min_price(min_price)
440                .margin_init(Decimal::ONE)
441                .margin_maint(margin_maint)
442                .ts_event(ts_event)
443                .ts_init(ts_init)
444                .build()
445                .unwrap();
446            Ok(InstrumentAny::CryptoFuture(instrument))
447        }
448    }
449}
450
451/// Parses a COIN-M Futures symbol definition into a Nautilus crypto futures instrument.
452///
453/// COIN-M perpetuals are inverse contracts settled in base currency (e.g., BTC).
454///
455/// # Errors
456///
457/// Returns an error if:
458/// - Required filter values are missing (PRICE_FILTER, LOT_SIZE).
459/// - Price or quantity values cannot be parsed.
460/// - The contract type is not a supported perpetual or quarterly delivery contract.
461/// - The contract is not in TRADING status.
462pub fn parse_coinm_instrument(
463    symbol: &BinanceFuturesCoinSymbol,
464    ts_event: UnixNanos,
465    ts_init: UnixNanos,
466) -> anyhow::Result<InstrumentAny> {
467    parse_coinm_instrument_with_fees(symbol, ts_event, ts_init)
468}
469
470pub(crate) fn parse_coinm_instrument_with_fees(
471    symbol: &BinanceFuturesCoinSymbol,
472    ts_event: UnixNanos,
473    ts_init: UnixNanos,
474) -> anyhow::Result<InstrumentAny> {
475    let is_perpetual = symbol.contract_type == CONTRACT_TYPE_PERPETUAL;
476    let is_delivery = matches!(
477        symbol.contract_type.as_str(),
478        CONTRACT_TYPE_CURRENT_QUARTER | CONTRACT_TYPE_NEXT_QUARTER
479    );
480
481    if !is_perpetual && !is_delivery {
482        anyhow::bail!(
483            "Unsupported COIN-M contract type '{}' for symbol '{}'",
484            symbol.contract_type,
485            symbol.symbol,
486        );
487    }
488
489    if symbol.contract_status != Some(BinanceContractStatus::Trading) {
490        anyhow::bail!(
491            "Symbol '{}' is not trading (status: {:?})",
492            symbol.symbol,
493            symbol.contract_status
494        );
495    }
496
497    let base_currency = get_currency(symbol.base_asset.as_str());
498    let quote_currency = get_currency(symbol.quote_asset.as_str());
499
500    // COIN-M contracts are settled in the base currency (inverse)
501    let settlement_currency = get_currency(symbol.margin_asset.as_str());
502
503    let instrument_id = format_instrument_id(&symbol.symbol, BinanceProductType::CoinM);
504    let raw_symbol = Symbol::new(symbol.symbol.as_str());
505
506    let price_filter = get_filter(&symbol.filters, "PRICE_FILTER")
507        .context("Missing PRICE_FILTER in symbol filters")?;
508
509    let tick_size = parse_filter_price(price_filter, "tickSize")?;
510    if tick_size.is_zero() {
511        anyhow::bail!(
512            "Invalid tickSize of 0 for symbol '{}', cannot create instrument",
513            symbol.symbol,
514        );
515    }
516    let max_price = parse_filter_price(price_filter, "maxPrice").ok();
517    let min_price = parse_filter_price(price_filter, "minPrice").ok();
518
519    let lot_filter =
520        get_filter(&symbol.filters, "LOT_SIZE").context("Missing LOT_SIZE in symbol filters")?;
521
522    let step_size = parse_filter_quantity(lot_filter, "stepSize")?;
523    let max_quantity = parse_filter_quantity(lot_filter, "maxQty").ok();
524    let min_quantity = parse_filter_quantity(lot_filter, "minQty").ok();
525
526    // COIN-M has contract_size as the multiplier
527    let multiplier = Quantity::from(symbol.contract_size);
528
529    let min_notional = parse_futures_min_notional(&symbol.filters, quote_currency);
530
531    let margin_maint = Decimal::new(1, 1);
532
533    if is_perpetual {
534        let instrument = CryptoPerpetual::builder()
535            .instrument_id(instrument_id)
536            .raw_symbol(raw_symbol)
537            .base_currency(base_currency)
538            .quote_currency(quote_currency)
539            .settlement_currency(settlement_currency)
540            .is_inverse(true)
541            .price_precision(tick_size.precision)
542            .size_precision(step_size.precision)
543            .price_increment(tick_size)
544            .size_increment(step_size)
545            .multiplier(multiplier)
546            .lot_size(step_size)
547            .maybe_max_quantity(max_quantity)
548            .maybe_min_quantity(min_quantity)
549            .maybe_min_notional(min_notional)
550            .maybe_max_price(max_price)
551            .maybe_min_price(min_price)
552            .margin_init(Decimal::ONE)
553            .margin_maint(margin_maint)
554            .ts_event(ts_event)
555            .ts_init(ts_init)
556            .build()
557            .unwrap();
558        Ok(InstrumentAny::CryptoPerpetual(instrument))
559    } else {
560        let activation_ns = parse_millis(symbol.onboard_date, "Futures onboardDate")?;
561        let expiration_ns = parse_millis(symbol.delivery_date, "Futures deliveryDate")?;
562        let instrument = CryptoFuture::builder()
563            .instrument_id(instrument_id)
564            .raw_symbol(raw_symbol)
565            .underlying(base_currency)
566            .quote_currency(quote_currency)
567            .settlement_currency(settlement_currency)
568            .is_inverse(true)
569            .activation_ns(activation_ns)
570            .expiration_ns(expiration_ns)
571            .price_precision(tick_size.precision)
572            .size_precision(step_size.precision)
573            .price_increment(tick_size)
574            .size_increment(step_size)
575            .multiplier(multiplier)
576            .lot_size(step_size)
577            .maybe_max_quantity(max_quantity)
578            .maybe_min_quantity(min_quantity)
579            .maybe_min_notional(min_notional)
580            .maybe_max_price(max_price)
581            .maybe_min_price(min_price)
582            .margin_init(Decimal::ONE)
583            .margin_maint(margin_maint)
584            .ts_event(ts_event)
585            .ts_init(ts_init)
586            .build()
587            .unwrap();
588        Ok(InstrumentAny::CryptoFuture(instrument))
589    }
590}
591
592/// SBE status value for Trading.
593const SBE_STATUS_TRADING: u8 = 0;
594
595/// Converts an SBE `mantissa * 10^exponent` pair to a [`Decimal`] with exact integer scaling.
596///
597/// # Errors
598///
599/// Returns an error if the magnitude of a negative `exponent` exceeds [`Decimal`]'s maximum scale of 28, or if
600/// scaling by a positive exponent overflows. The conversion does not wrap and does not replace a
601/// nonzero mantissa with zero.
602pub(crate) fn sbe_mantissa_to_decimal(mantissa: i64, exponent: i8) -> anyhow::Result<Decimal> {
603    if exponent >= 0 {
604        let mut value = Decimal::from(mantissa);
605        for _ in 0..exponent {
606            value = value.checked_mul(Decimal::TEN).ok_or_else(|| {
607                anyhow::anyhow!("decimal overflow for mantissa {mantissa}, exponent {exponent}")
608            })?;
609        }
610
611        Ok(value)
612    } else {
613        let scale = u32::from(exponent.unsigned_abs());
614        Decimal::try_new(mantissa, scale).map_err(|e| {
615            anyhow::anyhow!("invalid decimal for mantissa {mantissa}, exponent {exponent}: {e}")
616        })
617    }
618}
619
620/// Builds an account balance from free and locked decimals.
621///
622/// # Errors
623///
624/// Returns an error if `free + locked` overflows, or if the total, locked, or derived free amount
625/// cannot be represented as [`Money`] for `currency`.
626pub(crate) fn account_balance_from_free_locked(
627    asset: &str,
628    free: Decimal,
629    locked: Decimal,
630    currency: Currency,
631) -> anyhow::Result<AccountBalance> {
632    let total = free
633        .checked_add(locked)
634        .ok_or_else(|| anyhow::anyhow!("decimal overflow adding free and locked for {asset}"))?;
635    AccountBalance::from_total_and_locked(total, locked, currency)
636        .with_context(|| format!("failed to build account balance for {asset}"))
637}
638
639/// Derives the number of significant decimal places from an SBE mantissa/exponent pair.
640///
641/// Binance SBE encodes values as `mantissa * 10^exponent` where `exponent` is a global
642/// fixed-point encoding parameter (typically -8), not the instrument's trading precision.
643/// The actual precision is determined by how many trailing zeros the mantissa carries.
644///
645/// # Examples
646///
647/// - ETHUSDC tick_size: mantissa=1_000_000, exp=-8 → 0.01 → precision=2
648/// - DOGEUSDT tick_size: mantissa=1_000, exp=-8 → 0.00001 → precision=5
649/// - SHIBUSDT tick_size: mantissa=1, exp=-8 → 0.00000001 → precision=8
650/// - BTCTRY tick_size: mantissa=100_000_000, exp=-8 → 1.0 → precision=0
651fn sbe_mantissa_precision(mantissa: i64, exponent: i8) -> u8 {
652    if mantissa == 0 {
653        return 0;
654    }
655    let mut m = mantissa.abs();
656    let mut trailing_zeros: i8 = 0;
657
658    while m > 0 && m % 10 == 0 {
659        m /= 10;
660        trailing_zeros += 1;
661    }
662    (-exponent - trailing_zeros).max(0) as u8
663}
664
665/// Parses an SBE price filter into tick_size, max_price, min_price.
666fn parse_sbe_price_filter(
667    filter: &BinancePriceFilterSbe,
668) -> anyhow::Result<(Price, Option<Price>, Option<Price>)> {
669    let precision = sbe_mantissa_precision(filter.tick_size, filter.price_exponent);
670
671    let tick_size =
672        Price::from_mantissa_exponent_checked(filter.tick_size, filter.price_exponent, precision)?;
673
674    let max_price = if filter.max_price != 0 {
675        Some(Price::from_mantissa_exponent_checked(
676            filter.max_price,
677            filter.price_exponent,
678            precision,
679        )?)
680    } else {
681        None
682    };
683
684    let min_price = if filter.min_price != 0 {
685        Some(Price::from_mantissa_exponent_checked(
686            filter.min_price,
687            filter.price_exponent,
688            precision,
689        )?)
690    } else {
691        None
692    };
693
694    Ok((tick_size, max_price, min_price))
695}
696
697/// Parses an SBE lot size filter into step_size, max_qty, min_qty.
698fn parse_sbe_lot_size_filter(
699    filter: &BinanceLotSizeFilterSbe,
700) -> anyhow::Result<(Quantity, Option<Quantity>, Option<Quantity>)> {
701    let precision = sbe_mantissa_precision(filter.step_size, filter.qty_exponent);
702
703    let step_size = Quantity::from_mantissa_exponent_checked(
704        filter.step_size as u64,
705        filter.qty_exponent,
706        precision,
707    )?;
708
709    let max_qty = if filter.max_qty != 0 {
710        Some(Quantity::from_mantissa_exponent_checked(
711            filter.max_qty as u64,
712            filter.qty_exponent,
713            precision,
714        )?)
715    } else {
716        None
717    };
718
719    let min_qty = if filter.min_qty != 0 {
720        Some(Quantity::from_mantissa_exponent_checked(
721            filter.min_qty as u64,
722            filter.qty_exponent,
723            precision,
724        )?)
725    } else {
726        None
727    };
728
729    Ok((step_size, max_qty, min_qty))
730}
731
732/// Parses a Binance Spot SBE symbol into a Nautilus CurrencyPair instrument.
733///
734/// # Errors
735///
736/// Returns an error if:
737/// - Required filter values are missing (PRICE_FILTER, LOT_SIZE).
738/// - Price or quantity values cannot be parsed.
739/// - The symbol is not actively trading.
740pub fn parse_spot_instrument_sbe(
741    symbol: &BinanceSymbolSbe,
742    ts_event: UnixNanos,
743    ts_init: UnixNanos,
744) -> anyhow::Result<InstrumentAny> {
745    parse_spot_instrument_sbe_with_fees(symbol, ts_event, ts_init)
746}
747
748pub(crate) fn parse_spot_instrument_sbe_with_fees(
749    symbol: &BinanceSymbolSbe,
750    ts_event: UnixNanos,
751    ts_init: UnixNanos,
752) -> anyhow::Result<InstrumentAny> {
753    if symbol.status != SBE_STATUS_TRADING {
754        anyhow::bail!(
755            "Symbol '{}' is not trading (status: {})",
756            symbol.symbol,
757            symbol.status
758        );
759    }
760
761    let base_currency = get_currency(&symbol.base_asset);
762    let quote_currency = get_currency(&symbol.quote_asset);
763
764    let instrument_id = InstrumentId::new(
765        Symbol::from_str_unchecked(&symbol.symbol),
766        Venue::new(BINANCE),
767    );
768    let raw_symbol = Symbol::new(&symbol.symbol);
769
770    let price_filter = symbol
771        .filters
772        .price_filter
773        .as_ref()
774        .context("Missing PRICE_FILTER in symbol filters")?;
775
776    let (tick_size, max_price, min_price) = parse_sbe_price_filter(price_filter)?;
777
778    let lot_filter = symbol
779        .filters
780        .lot_size_filter
781        .as_ref()
782        .context("Missing LOT_SIZE in symbol filters")?;
783
784    let (step_size, max_quantity, min_quantity) = parse_sbe_lot_size_filter(lot_filter)?;
785
786    let (min_notional, max_notional) =
787        parse_spot_notional_rules(&symbol.filters.notional_filters, quote_currency)?;
788
789    // Spot has no leverage, use 1.0 margin
790    let default_margin = Decimal::new(1, 0);
791
792    let instrument = CurrencyPair::builder()
793        .instrument_id(instrument_id)
794        .raw_symbol(raw_symbol)
795        .base_currency(base_currency)
796        .quote_currency(quote_currency)
797        .price_precision(tick_size.precision)
798        .size_precision(step_size.precision)
799        .price_increment(tick_size)
800        .size_increment(step_size)
801        .lot_size(step_size)
802        .maybe_max_quantity(max_quantity)
803        .maybe_min_quantity(min_quantity)
804        .maybe_min_notional(min_notional)
805        .maybe_max_notional(max_notional)
806        .maybe_max_price(max_price)
807        .maybe_min_price(min_price)
808        .margin_init(default_margin)
809        .margin_maint(default_margin)
810        .ts_event(ts_event)
811        .ts_init(ts_init)
812        .build()
813        .unwrap();
814
815    Ok(InstrumentAny::CurrencyPair(instrument))
816}
817
818pub(crate) fn parse_spot_instrument_json_with_fees(
819    symbol: &BinanceSymbolJson,
820    ts_event: UnixNanos,
821    ts_init: UnixNanos,
822) -> anyhow::Result<InstrumentAny> {
823    anyhow::ensure!(
824        symbol.status == "TRADING",
825        "Symbol '{}' is not trading (status: {})",
826        symbol.symbol,
827        symbol.status,
828    );
829
830    let price_filter = symbol
831        .filters
832        .iter()
833        .find(|filter| filter.filter_type == "PRICE_FILTER")
834        .context("Missing PRICE_FILTER in symbol filters")?;
835    let lot_filter = symbol
836        .filters
837        .iter()
838        .find(|filter| filter.filter_type == "LOT_SIZE")
839        .context("Missing LOT_SIZE in symbol filters")?;
840
841    let tick_size = decimal_price(
842        price_filter
843            .tick_size
844            .as_deref()
845            .context("Missing PRICE_FILTER tickSize")?,
846    )?;
847    anyhow::ensure!(!tick_size.is_zero(), "Invalid tickSize of 0");
848    let step_size = decimal_quantity(
849        lot_filter
850            .step_size
851            .as_deref()
852            .context("Missing LOT_SIZE stepSize")?,
853    )?;
854    anyhow::ensure!(!step_size.is_zero(), "Invalid stepSize of 0");
855
856    let quote_currency = get_currency(&symbol.quote_asset);
857    let mut rules = Vec::new();
858
859    for filter in &symbol.filters {
860        if !matches!(filter.filter_type.as_str(), "MIN_NOTIONAL" | "NOTIONAL") {
861            continue;
862        }
863
864        let range = filter.filter_type == "NOTIONAL";
865
866        rules.push(BinanceNotionalFilter {
867            min: Decimal::from_str_exact(
868                filter
869                    .min_notional
870                    .as_deref()
871                    .context("missing minNotional")?,
872            )?,
873
874            max: if range {
875                Some(Decimal::from_str_exact(
876                    filter
877                        .max_notional
878                        .as_deref()
879                        .context("missing maxNotional")?,
880                )?)
881            } else {
882                None
883            },
884
885            apply_min_to_market: if range {
886                filter.apply_min_to_market
887            } else {
888                filter.apply_to_market
889            }
890            .context("missing minimum notional market flag")?,
891
892            apply_max_to_market: if range {
893                filter
894                    .apply_max_to_market
895                    .context("missing applyMaxToMarket")?
896            } else {
897                false
898            },
899
900            avg_price_mins: filter.avg_price_mins.context("missing avgPriceMins")?,
901        });
902    }
903
904    let (min_notional, max_notional) = parse_spot_notional_rules(&rules, quote_currency)?;
905
906    let instrument = CurrencyPair::builder()
907        .instrument_id(InstrumentId::new(
908            Symbol::from_str_unchecked(&symbol.symbol),
909            Venue::new(BINANCE),
910        ))
911        .raw_symbol(Symbol::new(&symbol.symbol))
912        .base_currency(get_currency(&symbol.base_asset))
913        .quote_currency(quote_currency)
914        .maybe_min_notional(min_notional)
915        .maybe_max_notional(max_notional)
916        .price_precision(tick_size.precision)
917        .size_precision(step_size.precision)
918        .price_increment(tick_size)
919        .size_increment(step_size)
920        .lot_size(step_size)
921        .maybe_max_quantity(optional_decimal_quantity(
922            lot_filter.max_qty.as_deref(),
923            step_size.precision,
924        )?)
925        .maybe_min_quantity(optional_decimal_quantity(
926            lot_filter.min_qty.as_deref(),
927            step_size.precision,
928        )?)
929        .maybe_max_price(optional_decimal_price(
930            price_filter.max_price.as_deref(),
931            tick_size.precision,
932        )?)
933        .maybe_min_price(optional_decimal_price(
934            price_filter.min_price.as_deref(),
935            tick_size.precision,
936        )?)
937        .margin_init(Decimal::ONE)
938        .margin_maint(Decimal::ONE)
939        .ts_event(ts_event)
940        .ts_init(ts_init)
941        .build()
942        .unwrap();
943
944    Ok(InstrumentAny::CurrencyPair(instrument))
945}
946
947fn parse_spot_notional_rules(
948    rules: &[BinanceNotionalFilter],
949    currency: Currency,
950) -> anyhow::Result<(Option<Money>, Option<Money>)> {
951    let mut minimum: Option<Decimal> = None;
952    let mut maximum: Option<Decimal> = None;
953    for rule in rules {
954        anyhow::ensure!(rule.min >= Decimal::ZERO, "negative minimum notional");
955        minimum = Some(minimum.map_or(rule.min, |min| min.max(rule.min)));
956
957        if let Some(max) = rule.max {
958            anyhow::ensure!(max >= rule.min, "maximum notional is below minimum");
959            maximum = Some(maximum.map_or(max, |current| current.min(max)));
960        }
961    }
962
963    if let (Some(min), Some(max)) = (minimum, maximum) {
964        anyhow::ensure!(min <= max, "conflicting notional bounds");
965    }
966    Ok((
967        minimum
968            .map(|value| Money::from_decimal(value, currency))
969            .transpose()?,
970        maximum
971            .map(|value| Money::from_decimal(value, currency))
972            .transpose()?,
973    ))
974}
975
976fn decimal_price(value: &str) -> anyhow::Result<Price> {
977    let decimal = Decimal::from_str_exact(value)?.normalize();
978    let precision = u8::try_from(decimal.scale()).context("price precision exceeds u8")?;
979    Ok(Price::from_decimal_dp(decimal, precision)?)
980}
981
982fn decimal_quantity(value: &str) -> anyhow::Result<Quantity> {
983    let decimal = Decimal::from_str_exact(value)?.normalize();
984    let precision = u8::try_from(decimal.scale()).context("quantity precision exceeds u8")?;
985    Ok(Quantity::from_decimal_dp(decimal, precision)?)
986}
987
988fn optional_decimal_price(value: Option<&str>, precision: u8) -> anyhow::Result<Option<Price>> {
989    let Some(value) = value else {
990        return Ok(None);
991    };
992    let decimal = Decimal::from_str_exact(value)?;
993    if decimal.is_zero() {
994        return Ok(None);
995    }
996    Ok(Some(Price::from_decimal_dp(decimal, precision)?))
997}
998
999fn optional_decimal_quantity(
1000    value: Option<&str>,
1001    precision: u8,
1002) -> anyhow::Result<Option<Quantity>> {
1003    let Some(value) = value else {
1004        return Ok(None);
1005    };
1006    let decimal = Decimal::from_str_exact(value)?;
1007    if decimal.is_zero() {
1008        return Ok(None);
1009    }
1010    Ok(Some(Quantity::from_decimal_dp(decimal, precision)?))
1011}
1012
1013/// Parses Binance SBE trades into Nautilus TradeTick objects.
1014///
1015/// Uses mantissa/exponent encoding from SBE to construct proper Price and Quantity.
1016///
1017/// # Errors
1018///
1019/// Returns an error if any trade cannot be parsed.
1020pub fn parse_spot_trades_sbe(
1021    trades: &BinanceTrades,
1022    instrument: &InstrumentAny,
1023    ts_init: UnixNanos,
1024) -> anyhow::Result<Vec<TradeTick>> {
1025    let instrument_id = instrument.id();
1026    let price_precision = instrument.price_precision();
1027    let size_precision = instrument.size_precision();
1028
1029    let mut result = Vec::with_capacity(trades.trades.len());
1030
1031    for trade in &trades.trades {
1032        let price = Price::from_mantissa_exponent(
1033            trade.price_mantissa,
1034            trades.price_exponent,
1035            price_precision,
1036        );
1037        let size = Quantity::from_mantissa_exponent(
1038            trade.qty_mantissa as u64,
1039            trades.qty_exponent,
1040            size_precision,
1041        );
1042
1043        // is_buyer_maker means the buyer was the maker, so the aggressor was selling
1044        let aggressor_side = if trade.is_buyer_maker {
1045            AggressorSide::Sell
1046        } else {
1047            AggressorSide::Buy
1048        };
1049
1050        // SBE trade timestamps are in microseconds
1051        let ts_event = parse_micros(trade.time, "Spot SBE trade time")?;
1052
1053        let tick = TradeTick::new(
1054            instrument_id,
1055            price,
1056            size,
1057            aggressor_side,
1058            TradeId::new(trade.id.to_string()),
1059            ts_event,
1060            ts_init,
1061        );
1062
1063        result.push(tick);
1064    }
1065
1066    Ok(result)
1067}
1068
1069/// Maps Binance SBE order status to Nautilus order status.
1070///
1071/// # Errors
1072///
1073/// Returns an error if the venue value is unknown or absent.
1074pub fn map_order_status_sbe(status: SbeOrderStatus) -> anyhow::Result<OrderStatus> {
1075    Ok(match status {
1076        SbeOrderStatus::New => OrderStatus::Accepted,
1077        SbeOrderStatus::PendingNew => OrderStatus::Submitted,
1078        SbeOrderStatus::PartiallyFilled => OrderStatus::PartiallyFilled,
1079        SbeOrderStatus::Filled => OrderStatus::Filled,
1080        SbeOrderStatus::Canceled => OrderStatus::Canceled,
1081        SbeOrderStatus::PendingCancel => OrderStatus::PendingCancel,
1082        SbeOrderStatus::Rejected => OrderStatus::Rejected,
1083        SbeOrderStatus::Expired | SbeOrderStatus::ExpiredInMatch => OrderStatus::Expired,
1084        SbeOrderStatus::Unknown | SbeOrderStatus::NonRepresentable | SbeOrderStatus::NullVal => {
1085            anyhow::bail!("unknown Binance SBE order status")
1086        }
1087    })
1088}
1089
1090/// Maps Binance SBE order type to Nautilus order type.
1091///
1092/// # Errors
1093///
1094/// Returns an error if the venue value is unknown or absent.
1095pub fn map_order_type_sbe(order_type: SbeOrderType) -> anyhow::Result<OrderType> {
1096    Ok(match order_type {
1097        SbeOrderType::Market => OrderType::Market,
1098        SbeOrderType::Limit | SbeOrderType::LimitMaker => OrderType::Limit,
1099        SbeOrderType::StopLoss => OrderType::StopMarket,
1100        SbeOrderType::StopLossLimit => OrderType::StopLimit,
1101        SbeOrderType::TakeProfit => OrderType::MarketIfTouched,
1102        SbeOrderType::TakeProfitLimit => OrderType::LimitIfTouched,
1103        SbeOrderType::NonRepresentable | SbeOrderType::NullVal => {
1104            anyhow::bail!("unknown Binance SBE order type")
1105        }
1106    })
1107}
1108
1109/// Maps Binance SBE order side to Nautilus order side.
1110#[must_use]
1111pub const fn map_order_side_sbe(side: SbeOrderSide) -> Option<OrderSide> {
1112    match side {
1113        SbeOrderSide::Buy => Some(OrderSide::Buy),
1114        SbeOrderSide::Sell => Some(OrderSide::Sell),
1115        SbeOrderSide::NonRepresentable | SbeOrderSide::NullVal => None,
1116    }
1117}
1118
1119/// Maps Binance SBE time in force to Nautilus time in force.
1120///
1121/// # Errors
1122///
1123/// Returns an error if the venue value is unknown or absent.
1124pub fn map_time_in_force_sbe(tif: SbeTimeInForce) -> anyhow::Result<TimeInForce> {
1125    Ok(match tif {
1126        SbeTimeInForce::Gtc => TimeInForce::Gtc,
1127        SbeTimeInForce::Ioc => TimeInForce::Ioc,
1128        SbeTimeInForce::Fok => TimeInForce::Fok,
1129        SbeTimeInForce::NonRepresentable | SbeTimeInForce::NullVal => {
1130            anyhow::bail!("unknown Binance SBE time in force")
1131        }
1132    })
1133}
1134
1135/// Parses a Binance SBE order response into a Nautilus `OrderStatusReport`.
1136///
1137/// # Errors
1138///
1139/// Returns an error if any field cannot be parsed.
1140pub fn parse_order_status_report_sbe(
1141    order: &BinanceOrderResponse,
1142    account_id: AccountId,
1143    instrument: &InstrumentAny,
1144    broker_id: &str,
1145    ts_init: UnixNanos,
1146) -> anyhow::Result<OrderStatusReport> {
1147    let instrument_id = instrument.id();
1148    let price_precision = instrument.price_precision();
1149    let size_precision = instrument.size_precision();
1150
1151    let price = if order.price_mantissa != 0 {
1152        Some(Price::from_mantissa_exponent(
1153            order.price_mantissa,
1154            order.price_exponent,
1155            price_precision,
1156        ))
1157    } else {
1158        None
1159    };
1160
1161    let quantity = Quantity::from_mantissa_exponent(
1162        order.orig_qty_mantissa as u64,
1163        order.qty_exponent,
1164        size_precision,
1165    );
1166    let filled_qty = Quantity::from_mantissa_exponent(
1167        order.executed_qty_mantissa as u64,
1168        order.qty_exponent,
1169        size_precision,
1170    );
1171
1172    // Calculate average price from cumulative quote qty / executed qty
1173    // This requires decimal arithmetic since we're dividing two mantissas
1174    let avg_px = if order.executed_qty_mantissa > 0 {
1175        let quote_exp = (order.price_exponent as i32) + (order.qty_exponent as i32);
1176        let cum_quote_dec = Decimal::new(order.cummulative_quote_qty_mantissa, (-quote_exp) as u32);
1177        let filled_dec = Decimal::new(
1178            order.executed_qty_mantissa,
1179            (-order.qty_exponent as i32) as u32,
1180        );
1181        let avg_dec = cum_quote_dec / filled_dec;
1182        Some(
1183            Price::from_decimal_dp(avg_dec, price_precision)
1184                .unwrap_or(Price::zero(price_precision)),
1185        )
1186    } else {
1187        None
1188    };
1189
1190    // Parse trigger price for stop orders
1191    let trigger_price = order.stop_price_mantissa.and_then(|mantissa| {
1192        if mantissa != 0 {
1193            Some(Price::from_mantissa_exponent(
1194                mantissa,
1195                order.price_exponent,
1196                price_precision,
1197            ))
1198        } else {
1199            None
1200        }
1201    });
1202
1203    // Map enums
1204    let order_status = map_order_status_sbe(order.status)?;
1205    let order_type = map_order_type_sbe(order.order_type)?;
1206    let order_side = map_order_side_sbe(order.side);
1207    let time_in_force = map_time_in_force_sbe(order.time_in_force)?;
1208
1209    // Determine trigger type for stop orders
1210    let trigger_type = if trigger_price.is_some() {
1211        Some(TriggerType::LastPrice)
1212    } else {
1213        None
1214    };
1215
1216    // Parse timestamps (SBE uses microseconds)
1217    let ts_event = parse_micros(order.update_time, "Spot SBE order update time")?;
1218
1219    // Build order list ID if present
1220    let order_list_id = order.order_list_id.and_then(|id| {
1221        if id > 0 {
1222            Some(OrderListId::new(id.to_string()))
1223        } else {
1224            None
1225        }
1226    });
1227
1228    // Determine post-only (limit maker orders are post-only)
1229    let post_only = order.order_type == SbeOrderType::LimitMaker;
1230
1231    // Parse order creation time (SBE uses microseconds)
1232    let ts_accepted = parse_micros(order.time, "Spot SBE order time")?;
1233
1234    let mut report = OrderStatusReport::new(
1235        account_id,
1236        instrument_id,
1237        Some(decode_client_order_id(&order.client_order_id, broker_id)?),
1238        VenueOrderId::new(order.order_id.to_string()),
1239        order_side,
1240        order_type,
1241        time_in_force,
1242        order_status,
1243        quantity,
1244        filled_qty,
1245        ts_accepted,
1246        ts_event,
1247        ts_init,
1248        None, // report_id (auto-generated)
1249    );
1250
1251    // Apply optional fields using builder methods
1252    if let Some(p) = price {
1253        report = report.with_price(p);
1254    }
1255
1256    if let Some(ap) = avg_px {
1257        report = report.with_avg_px(ap.as_decimal());
1258    }
1259
1260    if let Some(tp) = trigger_price {
1261        report = report.with_trigger_price(tp);
1262    }
1263
1264    if let Some(tt) = trigger_type {
1265        report = report.with_trigger_type(tt);
1266    }
1267
1268    if let Some(oli) = order_list_id {
1269        report = report.with_order_list_id(oli);
1270    }
1271
1272    if post_only {
1273        report = report.with_post_only(true);
1274    }
1275
1276    Ok(report)
1277}
1278
1279/// Parses a Binance new order response (SBE) into a Nautilus `OrderStatusReport`.
1280///
1281/// # Errors
1282///
1283/// Returns an error if any field cannot be parsed.
1284pub fn parse_new_order_response_sbe(
1285    response: &BinanceNewOrderResponse,
1286    account_id: AccountId,
1287    instrument: &InstrumentAny,
1288    broker_id: &str,
1289    ts_init: UnixNanos,
1290) -> anyhow::Result<OrderStatusReport> {
1291    let instrument_id = instrument.id();
1292    let price_precision = instrument.price_precision();
1293    let size_precision = instrument.size_precision();
1294
1295    let price = if response.price_mantissa != 0 {
1296        Some(Price::from_mantissa_exponent(
1297            response.price_mantissa,
1298            response.price_exponent,
1299            price_precision,
1300        ))
1301    } else {
1302        None
1303    };
1304
1305    let quantity = Quantity::from_mantissa_exponent(
1306        response.orig_qty_mantissa as u64,
1307        response.qty_exponent,
1308        size_precision,
1309    );
1310    let filled_qty = Quantity::from_mantissa_exponent(
1311        response.executed_qty_mantissa as u64,
1312        response.qty_exponent,
1313        size_precision,
1314    );
1315
1316    // Calculate average price from cumulative quote qty / executed qty
1317    // This requires decimal arithmetic since we're dividing two mantissas
1318    let avg_px = if response.executed_qty_mantissa > 0 {
1319        let quote_exp = (response.price_exponent as i32) + (response.qty_exponent as i32);
1320        let cum_quote_dec =
1321            Decimal::new(response.cummulative_quote_qty_mantissa, (-quote_exp) as u32);
1322        let filled_dec = Decimal::new(
1323            response.executed_qty_mantissa,
1324            (-response.qty_exponent as i32) as u32,
1325        );
1326        let avg_dec = cum_quote_dec / filled_dec;
1327        Some(
1328            Price::from_decimal_dp(avg_dec, price_precision)
1329                .unwrap_or(Price::zero(price_precision)),
1330        )
1331    } else {
1332        None
1333    };
1334
1335    let trigger_price = response.stop_price_mantissa.and_then(|mantissa| {
1336        if mantissa != 0 {
1337            Some(Price::from_mantissa_exponent(
1338                mantissa,
1339                response.price_exponent,
1340                price_precision,
1341            ))
1342        } else {
1343            None
1344        }
1345    });
1346
1347    let order_status = map_order_status_sbe(response.status)?;
1348    let order_type = map_order_type_sbe(response.order_type)?;
1349    let order_side = map_order_side_sbe(response.side);
1350    let time_in_force = map_time_in_force_sbe(response.time_in_force)?;
1351
1352    let trigger_type = if trigger_price.is_some() {
1353        Some(TriggerType::LastPrice)
1354    } else {
1355        None
1356    };
1357
1358    // SBE uses microseconds; for new orders transact_time is both creation and event time
1359    let ts_event = parse_micros(response.transact_time, "Spot SBE transaction time")?;
1360    let ts_accepted = ts_event;
1361
1362    let order_list_id = response.order_list_id.and_then(|id| {
1363        if id > 0 {
1364            Some(OrderListId::new(id.to_string()))
1365        } else {
1366            None
1367        }
1368    });
1369
1370    // Limit maker orders are post-only
1371    let post_only = response.order_type == SbeOrderType::LimitMaker;
1372
1373    let mut report = OrderStatusReport::new(
1374        account_id,
1375        instrument_id,
1376        Some(decode_client_order_id(
1377            &response.client_order_id,
1378            broker_id,
1379        )?),
1380        VenueOrderId::new(response.order_id.to_string()),
1381        order_side,
1382        order_type,
1383        time_in_force,
1384        order_status,
1385        quantity,
1386        filled_qty,
1387        ts_accepted,
1388        ts_event,
1389        ts_init,
1390        None,
1391    );
1392
1393    if let Some(p) = price {
1394        report = report.with_price(p);
1395    }
1396
1397    if let Some(ap) = avg_px {
1398        report = report.with_avg_px(ap.as_decimal());
1399    }
1400
1401    if let Some(tp) = trigger_price {
1402        report = report.with_trigger_price(tp);
1403    }
1404
1405    if let Some(tt) = trigger_type {
1406        report = report.with_trigger_type(tt);
1407    }
1408
1409    if let Some(oli) = order_list_id {
1410        report = report.with_order_list_id(oli);
1411    }
1412
1413    if post_only {
1414        report = report.with_post_only(true);
1415    }
1416
1417    Ok(report)
1418}
1419
1420/// Parses a Binance SBE account trade into a Nautilus `FillReport`.
1421///
1422/// # Errors
1423///
1424/// Returns an error if any field cannot be parsed.
1425pub fn parse_fill_report_sbe(
1426    trade: &BinanceAccountTrade,
1427    account_id: AccountId,
1428    instrument: &InstrumentAny,
1429    commission_currency: Currency,
1430    ts_init: UnixNanos,
1431) -> anyhow::Result<FillReport> {
1432    let instrument_id = instrument.id();
1433    let price_precision = instrument.price_precision();
1434    let size_precision = instrument.size_precision();
1435
1436    let last_px =
1437        Price::from_mantissa_exponent(trade.price_mantissa, trade.price_exponent, price_precision);
1438    let last_qty = Quantity::from_mantissa_exponent(
1439        trade.qty_mantissa as u64,
1440        trade.qty_exponent,
1441        size_precision,
1442    );
1443
1444    let comm_exp = trade.commission_exponent as i32;
1445    let comm_dec = Decimal::new(trade.commission_mantissa, (-comm_exp) as u32);
1446    let commission = Money::from_decimal(comm_dec, commission_currency)?;
1447
1448    // Determine order side from is_buyer
1449    let order_side = if trade.is_buyer {
1450        OrderSide::Buy
1451    } else {
1452        OrderSide::Sell
1453    };
1454
1455    // Determine liquidity side from is_maker
1456    let liquidity_side = if trade.is_maker {
1457        LiquiditySide::Maker
1458    } else {
1459        LiquiditySide::Taker
1460    };
1461
1462    // Parse timestamp (SBE uses microseconds)
1463    let ts_event = parse_micros(trade.time, "Spot SBE account trade time")?;
1464
1465    Ok(FillReport::new(
1466        account_id,
1467        instrument_id,
1468        VenueOrderId::new(trade.order_id.to_string()),
1469        TradeId::new(trade.id.to_string()),
1470        order_side,
1471        last_qty,
1472        last_px,
1473        commission,
1474        liquidity_side,
1475        None, // client_order_id (not in account trades response)
1476        None, // venue_position_id
1477        ts_event,
1478        ts_init,
1479        None, // report_id
1480    ))
1481}
1482
1483/// Parses Binance klines (candlesticks) into Nautilus Bar objects.
1484///
1485/// # Errors
1486///
1487/// Returns an error if any kline cannot be parsed.
1488pub fn parse_klines_to_binance_bars(
1489    klines: &BinanceKlines,
1490    bar_type: BarType,
1491    instrument: &InstrumentAny,
1492    ts_init: UnixNanos,
1493) -> anyhow::Result<Vec<crate::common::bar::BinanceBar>> {
1494    let price_precision = instrument.price_precision();
1495    let size_precision = instrument.size_precision();
1496
1497    let mut bars = Vec::with_capacity(klines.klines.len());
1498
1499    for kline in &klines.klines {
1500        let open =
1501            Price::from_mantissa_exponent(kline.open_price, klines.price_exponent, price_precision);
1502        let high =
1503            Price::from_mantissa_exponent(kline.high_price, klines.price_exponent, price_precision);
1504        let low =
1505            Price::from_mantissa_exponent(kline.low_price, klines.price_exponent, price_precision);
1506        let close = Price::from_mantissa_exponent(
1507            kline.close_price,
1508            klines.price_exponent,
1509            price_precision,
1510        );
1511
1512        let volume_mantissa = i128::from_le_bytes(kline.volume);
1513        let volume_dec =
1514            Decimal::from_i128_with_scale(volume_mantissa, (-klines.qty_exponent as i32) as u32);
1515        let volume = Quantity::from_decimal_dp(volume_dec, size_precision)?;
1516
1517        let quote_volume = Decimal::from_i128_with_scale(
1518            i128::from_le_bytes(kline.quote_volume),
1519            (-klines.price_exponent as i32) as u32,
1520        );
1521        let taker_buy_base_volume = Decimal::from_i128_with_scale(
1522            i128::from_le_bytes(kline.taker_buy_base_volume),
1523            (-klines.qty_exponent as i32) as u32,
1524        );
1525        let taker_buy_quote_volume = Decimal::from_i128_with_scale(
1526            i128::from_le_bytes(kline.taker_buy_quote_volume),
1527            (-klines.price_exponent as i32) as u32,
1528        );
1529        let count = u64::try_from(kline.num_trades).map_err(|_| {
1530            anyhow::anyhow!("invalid negative kline trade count {}", kline.num_trades)
1531        })?;
1532        let ts_event = parse_micros(kline.close_time, "Spot SBE kline close time")?;
1533
1534        let bar = crate::common::bar::BinanceBar::new(
1535            bar_type,
1536            open,
1537            high,
1538            low,
1539            close,
1540            volume,
1541            quote_volume,
1542            count,
1543            taker_buy_base_volume,
1544            taker_buy_quote_volume,
1545            ts_event,
1546            ts_init,
1547        );
1548        bars.push(bar);
1549    }
1550
1551    Ok(bars)
1552}
1553
1554/// Parses Binance SBE klines into core bars.
1555///
1556/// # Errors
1557///
1558/// Returns an error if any kline cannot be parsed.
1559pub fn parse_klines_to_bars(
1560    klines: &BinanceKlines,
1561    bar_type: BarType,
1562    instrument: &InstrumentAny,
1563    ts_init: UnixNanos,
1564) -> anyhow::Result<Vec<Bar>> {
1565    Ok(
1566        parse_klines_to_binance_bars(klines, bar_type, instrument, ts_init)?
1567            .into_iter()
1568            .map(|bar| bar.bar())
1569            .collect(),
1570    )
1571}
1572
1573/// Converts a Nautilus bar specification to a Binance kline interval.
1574///
1575/// # Errors
1576///
1577/// Returns an error if the bar specification does not map to a supported
1578/// Binance kline interval.
1579pub fn bar_spec_to_binance_interval(
1580    bar_spec: BarSpecification,
1581) -> anyhow::Result<BinanceKlineInterval> {
1582    let step = bar_spec.step.get();
1583    let interval = match bar_spec.aggregation {
1584        BarAggregation::Second => match step {
1585            1 => BinanceKlineInterval::Second1,
1586            _ => anyhow::bail!("Unsupported second interval: {step}s"),
1587        },
1588        BarAggregation::Minute => match step {
1589            1 => BinanceKlineInterval::Minute1,
1590            3 => BinanceKlineInterval::Minute3,
1591            5 => BinanceKlineInterval::Minute5,
1592            15 => BinanceKlineInterval::Minute15,
1593            30 => BinanceKlineInterval::Minute30,
1594            _ => anyhow::bail!("Unsupported minute interval: {step}m"),
1595        },
1596        BarAggregation::Hour => match step {
1597            1 => BinanceKlineInterval::Hour1,
1598            2 => BinanceKlineInterval::Hour2,
1599            4 => BinanceKlineInterval::Hour4,
1600            6 => BinanceKlineInterval::Hour6,
1601            8 => BinanceKlineInterval::Hour8,
1602            12 => BinanceKlineInterval::Hour12,
1603            _ => anyhow::bail!("Unsupported hour interval: {step}h"),
1604        },
1605        BarAggregation::Day => match step {
1606            1 => BinanceKlineInterval::Day1,
1607            3 => BinanceKlineInterval::Day3,
1608            _ => anyhow::bail!("Unsupported day interval: {step}d"),
1609        },
1610        BarAggregation::Week => match step {
1611            1 => BinanceKlineInterval::Week1,
1612            _ => anyhow::bail!("Unsupported week interval: {step}w"),
1613        },
1614        BarAggregation::Month => match step {
1615            1 => BinanceKlineInterval::Month1,
1616            _ => anyhow::bail!("Unsupported month interval: {step}M"),
1617        },
1618        agg => anyhow::bail!("Unsupported bar aggregation for Binance: {agg:?}"),
1619    };
1620
1621    Ok(interval)
1622}
1623
1624pub(crate) fn quote_to_l1_deltas(quote: QuoteTick, sequence: u64) -> OrderBookDeltas {
1625    let bid_action = if quote.bid_size.is_zero() {
1626        BookAction::Delete
1627    } else {
1628        BookAction::Update
1629    };
1630    let ask_action = if quote.ask_size.is_zero() {
1631        BookAction::Delete
1632    } else {
1633        BookAction::Update
1634    };
1635    let bid = OrderBookDelta::new(
1636        quote.instrument_id,
1637        bid_action,
1638        BookOrder::new(OrderSide::Buy, quote.bid_price, quote.bid_size, 0),
1639        RecordFlag::F_MBP as u8,
1640        sequence,
1641        quote.ts_event,
1642        quote.ts_init,
1643    );
1644    let ask = OrderBookDelta::new(
1645        quote.instrument_id,
1646        ask_action,
1647        BookOrder::new(OrderSide::Sell, quote.ask_price, quote.ask_size, 0),
1648        RecordFlag::F_MBP as u8 | RecordFlag::F_LAST as u8,
1649        sequence,
1650        quote.ts_event,
1651        quote.ts_init,
1652    );
1653
1654    OrderBookDeltas::new(quote.instrument_id, vec![bid, ask])
1655}
1656
1657#[cfg(test)]
1658mod tests {
1659    use nautilus_model::identifiers::ClientOrderId;
1660    use rstest::rstest;
1661    use rust_decimal_macros::dec;
1662    use serde_json::json;
1663    use ustr::Ustr;
1664
1665    use super::*;
1666    use crate::{
1667        common::{
1668            consts::BINANCE_NAUTILUS_SPOT_BROKER_ID,
1669            enums::{BinanceContractStatus, BinanceTradingStatus},
1670            testing::load_fixture_string,
1671        },
1672        spot::websocket::trading::{
1673            parse::parse_spot_exec_report_to_order_status, user_data::BinanceSpotExecutionReport,
1674        },
1675    };
1676
1677    #[rstest]
1678    #[case(SbeOrderType::TakeProfit, "TAKE_PROFIT", OrderType::MarketIfTouched)]
1679    #[case(
1680        SbeOrderType::TakeProfitLimit,
1681        "TAKE_PROFIT_LIMIT",
1682        OrderType::LimitIfTouched
1683    )]
1684    #[case(SbeOrderType::StopLoss, "STOP_LOSS", OrderType::StopMarket)]
1685    #[case(SbeOrderType::StopLossLimit, "STOP_LOSS_LIMIT", OrderType::StopLimit)]
1686    fn test_sbe_order_type_matches_json_report(
1687        #[case] sbe_order_type: SbeOrderType,
1688        #[case] json_order_type: &str,
1689        #[case] expected: OrderType,
1690    ) {
1691        let json = load_fixture_string("spot/user_data_json/execution_report_new.json");
1692        let mut msg: BinanceSpotExecutionReport = serde_json::from_str(&json).unwrap();
1693        msg.order_type = json_order_type.to_string();
1694        let report = parse_spot_exec_report_to_order_status(
1695            &msg,
1696            InstrumentId::from("ETHUSDT.BINANCE"),
1697            2,
1698            5,
1699            sample_account_id(),
1700            false,
1701            UnixNanos::default(),
1702        )
1703        .unwrap();
1704
1705        assert_eq!(report.order_type, expected);
1706        assert_eq!(
1707            map_order_type_sbe(sbe_order_type).unwrap(),
1708            report.order_type
1709        );
1710    }
1711
1712    #[rstest]
1713    fn test_sbe_order_mappings_reject_unknown_values() {
1714        for status in [
1715            SbeOrderStatus::Unknown,
1716            SbeOrderStatus::NonRepresentable,
1717            SbeOrderStatus::NullVal,
1718        ] {
1719            assert_eq!(
1720                map_order_status_sbe(status).unwrap_err().to_string(),
1721                "unknown Binance SBE order status"
1722            );
1723        }
1724
1725        for order_type in [SbeOrderType::NonRepresentable, SbeOrderType::NullVal] {
1726            assert_eq!(
1727                map_order_type_sbe(order_type).unwrap_err().to_string(),
1728                "unknown Binance SBE order type"
1729            );
1730        }
1731
1732        for tif in [SbeTimeInForce::NonRepresentable, SbeTimeInForce::NullVal] {
1733            assert_eq!(
1734                map_time_in_force_sbe(tif).unwrap_err().to_string(),
1735                "unknown Binance SBE time in force"
1736            );
1737        }
1738    }
1739
1740    #[rstest]
1741    fn test_quote_to_l1_deltas_maps_all_fields() {
1742        let instrument_id = InstrumentId::from("BTCUSDT.BINANCE");
1743        let ts_event = UnixNanos::from(1_700_000_000_000_000_001u64);
1744        let ts_init = UnixNanos::from(1_700_000_000_000_000_002u64);
1745        let quote = QuoteTick::new(
1746            instrument_id,
1747            Price::from("42000.01"),
1748            Price::from("42000.02"),
1749            Quantity::from("1.23456"),
1750            Quantity::from("2.34567"),
1751            ts_event,
1752            ts_init,
1753        );
1754        let expected = OrderBookDeltas::new(
1755            instrument_id,
1756            vec![
1757                OrderBookDelta::new(
1758                    instrument_id,
1759                    BookAction::Update,
1760                    BookOrder::new(
1761                        OrderSide::Buy,
1762                        Price::from("42000.01"),
1763                        Quantity::from("1.23456"),
1764                        0,
1765                    ),
1766                    RecordFlag::F_MBP as u8,
1767                    12345,
1768                    ts_event,
1769                    ts_init,
1770                ),
1771                OrderBookDelta::new(
1772                    instrument_id,
1773                    BookAction::Update,
1774                    BookOrder::new(
1775                        OrderSide::Sell,
1776                        Price::from("42000.02"),
1777                        Quantity::from("2.34567"),
1778                        0,
1779                    ),
1780                    RecordFlag::F_MBP as u8 | RecordFlag::F_LAST as u8,
1781                    12345,
1782                    ts_event,
1783                    ts_init,
1784                ),
1785            ],
1786        );
1787
1788        let actual = quote_to_l1_deltas(quote, 12345);
1789
1790        assert_eq!(actual, expected);
1791    }
1792
1793    #[rstest]
1794    fn test_quote_to_l1_deltas_deletes_empty_sides() {
1795        let instrument_id = InstrumentId::from("BTCUSDT.BINANCE");
1796        let quote = QuoteTick::new(
1797            instrument_id,
1798            Price::from("42000.01"),
1799            Price::from("42000.02"),
1800            Quantity::from("0.00000"),
1801            Quantity::from("0.00000"),
1802            UnixNanos::from(1_700_000_000_000_000_001u64),
1803            UnixNanos::from(1_700_000_000_000_000_002u64),
1804        );
1805
1806        let actual = quote_to_l1_deltas(quote, 12345);
1807
1808        assert_eq!(actual.deltas[0].action, BookAction::Delete);
1809        assert_eq!(actual.deltas[1].action, BookAction::Delete);
1810    }
1811
1812    #[rstest]
1813    #[case::positive("0.001", 8, Some(Quantity::from_decimal_dp(Decimal::from_str("0.001").unwrap(), 8).unwrap()))]
1814    #[case::trailing_zero("0.00100000", 8, Some(Quantity::from_decimal_dp(Decimal::from_str("0.001").unwrap(), 8).unwrap()))]
1815    #[case::zero("0", 8, None)]
1816    #[case::negative("-1", 8, None)]
1817    #[case::empty("", 8, None)]
1818    #[case::garbage("abc", 8, None)]
1819    fn test_parse_quantity_at_precision(
1820        #[case] raw: &str,
1821        #[case] precision: u8,
1822        #[case] expected: Option<Quantity>,
1823    ) {
1824        assert_eq!(parse_quantity_at_precision(raw, precision), expected);
1825    }
1826
1827    #[rstest]
1828    #[case::positive("7100.50", 2, Some(Price::from_decimal_dp(Decimal::from_str("7100.50").unwrap(), 2).unwrap()))]
1829    #[case::high_precision("0.000000001", 9, Some(Price::from_decimal_dp(Decimal::from_str("0.000000001").unwrap(), 9).unwrap()))]
1830    #[case::zero("0", 2, None)]
1831    #[case::negative("-100", 2, None)]
1832    #[case::empty("", 2, None)]
1833    fn test_parse_price_at_precision(
1834        #[case] raw: &str,
1835        #[case] precision: u8,
1836        #[case] expected: Option<Price>,
1837    ) {
1838        assert_eq!(parse_price_at_precision(raw, precision), expected);
1839    }
1840
1841    #[rstest]
1842    fn test_quantity_at_precision_re_precisions_via_decimal() {
1843        let original = Quantity::from_decimal_dp(Decimal::from_str("0.001").unwrap(), 3).unwrap();
1844        let widened = quantity_at_precision(original, 8).unwrap();
1845        let expected = Quantity::from_decimal_dp(Decimal::from_str("0.001").unwrap(), 8).unwrap();
1846        assert_eq!(widened, expected);
1847    }
1848
1849    #[rstest]
1850    fn test_price_at_precision_re_precisions_via_decimal() {
1851        let original = Price::from_decimal_dp(Decimal::from_str("7100.5").unwrap(), 1).unwrap();
1852        let widened = price_at_precision(original, 8).unwrap();
1853        let expected = Price::from_decimal_dp(Decimal::from_str("7100.5").unwrap(), 8).unwrap();
1854        assert_eq!(widened, expected);
1855    }
1856
1857    fn sample_usdm_symbol() -> BinanceFuturesUsdSymbol {
1858        BinanceFuturesUsdSymbol {
1859            symbol: Ustr::from("BTCUSDT"),
1860            pair: Ustr::from("BTCUSDT"),
1861            contract_type: "PERPETUAL".to_string(),
1862            delivery_date: 4133404800000,
1863            onboard_date: 1569398400000,
1864            status: BinanceTradingStatus::Trading,
1865            maint_margin_percent: "2.5000".to_string(),
1866            required_margin_percent: "5.0000".to_string(),
1867            base_asset: Ustr::from("BTC"),
1868            quote_asset: Ustr::from("USDT"),
1869            margin_asset: Ustr::from("USDT"),
1870            price_precision: 2,
1871            quantity_precision: 3,
1872            base_asset_precision: 8,
1873            quote_precision: 8,
1874            underlying_type: Some("COIN".to_string()),
1875            underlying_sub_type: vec!["PoW".to_string()],
1876            settle_plan: None,
1877            trigger_protect: Some("0.0500".to_string()),
1878            liquidation_fee: Some("0.012500".to_string()),
1879            market_take_bound: Some("0.05".to_string()),
1880            order_types: vec!["LIMIT".to_string(), "MARKET".to_string()],
1881            time_in_force: vec!["GTC".to_string(), "IOC".to_string()],
1882            filters: vec![
1883                json!({
1884                    "filterType": "PRICE_FILTER",
1885                    "tickSize": "0.10",
1886                    "maxPrice": "4529764",
1887                    "minPrice": "556.80"
1888                }),
1889                json!({
1890                    "filterType": "LOT_SIZE",
1891                    "stepSize": "0.001",
1892                    "maxQty": "1000",
1893                    "minQty": "0.001"
1894                }),
1895                json!({
1896                    "filterType": "MIN_NOTIONAL",
1897                    "notional": "5"
1898                }),
1899            ],
1900        }
1901    }
1902
1903    fn sample_tradifi_usdm_symbol(
1904        symbol: &str,
1905        underlying: &str,
1906        underlying_type: Option<&str>,
1907    ) -> BinanceFuturesUsdSymbol {
1908        let mut definition = sample_usdm_symbol();
1909        definition.symbol = Ustr::from(symbol);
1910        definition.pair = Ustr::from(symbol);
1911        definition.contract_type = CONTRACT_TYPE_TRADIFI_PERPETUAL.to_string();
1912        definition.base_asset = Ustr::from(underlying);
1913        definition.underlying_type = underlying_type.map(str::to_string);
1914        definition
1915    }
1916
1917    fn sample_coinm_symbol() -> BinanceFuturesCoinSymbol {
1918        BinanceFuturesCoinSymbol {
1919            symbol: Ustr::from("BTCUSD_PERP"),
1920            pair: Ustr::from("BTCUSD"),
1921            contract_type: "PERPETUAL".to_string(),
1922            delivery_date: 4_133_404_800_000,
1923            onboard_date: 1_569_398_400_000,
1924            contract_status: Some(BinanceContractStatus::Trading),
1925            contract_size: 100,
1926            maint_margin_percent: "2.5000".to_string(),
1927            required_margin_percent: "5.0000".to_string(),
1928            base_asset: Ustr::from("BTC"),
1929            quote_asset: Ustr::from("USD"),
1930            margin_asset: Ustr::from("BTC"),
1931            price_precision: 1,
1932            quantity_precision: 0,
1933            base_asset_precision: 8,
1934            quote_precision: 8,
1935            equal_qty_precision: None,
1936            trigger_protect: Some("0.0500".to_string()),
1937            liquidation_fee: Some("0.012500".to_string()),
1938            market_take_bound: Some("0.05".to_string()),
1939            order_types: vec!["LIMIT".to_string(), "MARKET".to_string()],
1940            time_in_force: vec!["GTC".to_string(), "IOC".to_string()],
1941            filters: vec![
1942                json!({
1943                    "filterType": "PRICE_FILTER",
1944                    "tickSize": "0.10",
1945                    "maxPrice": "1000000",
1946                    "minPrice": "0.10"
1947                }),
1948                json!({
1949                    "filterType": "LOT_SIZE",
1950                    "stepSize": "1",
1951                    "maxQty": "1000",
1952                    "minQty": "1"
1953                }),
1954                json!({
1955                    "filterType": "MIN_NOTIONAL",
1956                    "notional": "1"
1957                }),
1958            ],
1959        }
1960    }
1961
1962    fn sample_spot_symbol_sbe() -> BinanceSymbolSbe {
1963        BinanceSymbolSbe {
1964            symbol: "ETHUSDT".to_string(),
1965            base_asset: "ETH".to_string(),
1966            quote_asset: "USDT".to_string(),
1967            base_asset_precision: 8,
1968            quote_asset_precision: 8,
1969            status: SBE_STATUS_TRADING,
1970            order_types: 0,
1971            iceberg_allowed: true,
1972            oco_allowed: true,
1973            oto_allowed: false,
1974            quote_order_qty_market_allowed: true,
1975            allow_trailing_stop: true,
1976            cancel_replace_allowed: true,
1977            amend_allowed: true,
1978            is_spot_trading_allowed: true,
1979            is_margin_trading_allowed: false,
1980            filters: crate::spot::http::models::BinanceSymbolFiltersSbe {
1981                notional_filters: Vec::new(),
1982                price_filter: Some(BinancePriceFilterSbe {
1983                    price_exponent: -8,
1984                    min_price: 1_000_000,
1985                    max_price: 100_000_000_000_000,
1986                    tick_size: 1_000_000,
1987                }),
1988                lot_size_filter: Some(BinanceLotSizeFilterSbe {
1989                    qty_exponent: -8,
1990                    min_qty: 10_000,
1991                    max_qty: 900_000_000_000,
1992                    step_size: 10_000,
1993                }),
1994            },
1995            permissions: vec![vec!["SPOT".to_string()]],
1996        }
1997    }
1998
1999    #[rstest]
2000    #[case::min(
2001        include_bytes!("../../test_data/spot/http_sbe/notional_min.sbe").as_slice(),
2002        include_str!("../../test_data/spot/http_json/notional_min.json"),
2003        dec!(12.34567891), None,
2004    )]
2005    #[case::range(
2006        include_bytes!("../../test_data/spot/http_sbe/notional_range.sbe").as_slice(),
2007        include_str!("../../test_data/spot/http_json/notional_range.json"),
2008        dec!(23.45678912), Some(dec!(98.76543219)),
2009    )]
2010    #[case::both(
2011        include_bytes!("../../test_data/spot/http_sbe/notional_both.sbe").as_slice(),
2012        include_str!("../../test_data/spot/http_json/notional_both.json"),
2013        dec!(23.45678912), Some(dec!(98.76543219)),
2014    )]
2015    fn test_spot_notional_fixtures(
2016        #[case] wire: &[u8],
2017        #[case] json: &str,
2018        #[case] minimum: Decimal,
2019        #[case] maximum: Option<Decimal>,
2020    ) {
2021        let decoded = crate::spot::http::parse::decode_exchange_info(wire).unwrap();
2022        let symbol: BinanceSymbolJson = serde_json::from_str(json).unwrap();
2023        let ts_event = UnixNanos::from(123u64);
2024        let ts_init = UnixNanos::from(456u64);
2025        let sbe =
2026            parse_spot_instrument_sbe_with_fees(&decoded.symbols[0], ts_event, ts_init).unwrap();
2027        let json = parse_spot_instrument_json_with_fees(&symbol, ts_event, ts_init).unwrap();
2028        let InstrumentAny::CurrencyPair(mut expected) =
2029            parse_spot_instrument_sbe_with_fees(&sample_spot_symbol_sbe(), ts_event, ts_init)
2030                .unwrap()
2031        else {
2032            panic!("Expected CurrencyPair")
2033        };
2034        let rules = decoded.symbols[0].filters.notional_filters.clone();
2035        expected.min_notional =
2036            Some(Money::from_decimal(minimum, expected.quote_currency).unwrap());
2037        expected.max_notional =
2038            maximum.map(|value| Money::from_decimal(value, expected.quote_currency).unwrap());
2039        let expected = serde_json::to_value(InstrumentAny::CurrencyPair(expected)).unwrap();
2040
2041        assert_eq!(serde_json::to_value(sbe).unwrap(), expected);
2042        assert_eq!(serde_json::to_value(json).unwrap(), expected);
2043        assert_eq!(
2044            rules[0].min,
2045            if rules.len() == 2 || maximum.is_none() {
2046                dec!(12.34567891)
2047            } else {
2048                minimum
2049            }
2050        );
2051
2052        for rule in &rules {
2053            if rule.max.is_none() {
2054                assert_eq!(
2055                    rule,
2056                    &BinanceNotionalFilter {
2057                        min: dec!(12.34567891),
2058                        max: None,
2059                        apply_min_to_market: true,
2060                        apply_max_to_market: false,
2061                        avg_price_mins: 7
2062                    }
2063                );
2064            } else {
2065                assert_eq!(
2066                    rule,
2067                    &BinanceNotionalFilter {
2068                        min: dec!(23.45678912),
2069                        max: Some(dec!(98.76543219)),
2070                        apply_min_to_market: false,
2071                        apply_max_to_market: true,
2072                        avg_price_mins: 3
2073                    }
2074                );
2075            }
2076        }
2077    }
2078
2079    #[rstest]
2080    #[case("minNotional", "missing minNotional")]
2081    #[case("maxNotional", "missing maxNotional")]
2082    #[case("applyMinToMarket", "missing minimum notional market flag")]
2083    #[case("applyMaxToMarket", "missing applyMaxToMarket")]
2084    #[case("avgPriceMins", "missing avgPriceMins")]
2085    fn test_spot_notional_json_missing_fields(#[case] field: &str, #[case] error: &str) {
2086        let mut value: Value = serde_json::from_str(include_str!(
2087            "../../test_data/spot/http_json/notional_range.json"
2088        ))
2089        .unwrap();
2090        value["filters"][2].as_object_mut().unwrap().remove(field);
2091        let symbol = serde_json::from_value(value).unwrap();
2092        let result = parse_spot_instrument_json_with_fees(
2093            &symbol,
2094            UnixNanos::default(),
2095            UnixNanos::default(),
2096        );
2097        assert_eq!(result.unwrap_err().to_string(), error);
2098    }
2099
2100    #[rstest]
2101    #[case(vec![(dec!(-1), None)], "negative minimum notional")]
2102    #[case(vec![(dec!(2), Some(dec!(1)))], "maximum notional is below minimum")]
2103    #[case(vec![(dec!(2), None), (dec!(0), Some(dec!(1)))], "conflicting notional bounds")]
2104    fn test_spot_notional_invalid_bounds(
2105        #[case] bounds: Vec<(Decimal, Option<Decimal>)>,
2106        #[case] error: &str,
2107    ) {
2108        let rules = bounds
2109            .into_iter()
2110            .map(|(min, max)| BinanceNotionalFilter {
2111                min,
2112                max,
2113                apply_min_to_market: false,
2114                apply_max_to_market: true,
2115                avg_price_mins: 7,
2116            })
2117            .collect::<Vec<_>>();
2118
2119        let result = parse_spot_notional_rules(&rules, Currency::USD());
2120
2121        assert_eq!(result.unwrap_err().to_string(), error);
2122    }
2123
2124    fn sample_spot_instrument() -> InstrumentAny {
2125        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2126        parse_spot_instrument_sbe(&sample_spot_symbol_sbe(), ts, ts).unwrap()
2127    }
2128
2129    fn sample_account_id() -> AccountId {
2130        AccountId::from("BINANCE-SPOT-001")
2131    }
2132
2133    #[rstest]
2134    #[case::usdm_perpetual(BinanceProductType::UsdM, CONTRACT_TYPE_PERPETUAL)]
2135    #[case::usdm_delivery(BinanceProductType::UsdM, CONTRACT_TYPE_CURRENT_QUARTER)]
2136    #[case::usdm_tradfi(BinanceProductType::UsdM, CONTRACT_TYPE_TRADIFI_PERPETUAL)]
2137    #[case::coinm_perpetual(BinanceProductType::CoinM, CONTRACT_TYPE_PERPETUAL)]
2138    #[case::coinm_delivery(BinanceProductType::CoinM, CONTRACT_TYPE_CURRENT_QUARTER)]
2139    fn test_futures_initial_margin_factor(
2140        #[case] product: BinanceProductType,
2141        #[case] contract_type: &str,
2142    ) {
2143        let ts = UnixNanos::default();
2144
2145        let instrument = if product == BinanceProductType::UsdM {
2146            let mut symbol = if contract_type == CONTRACT_TYPE_TRADIFI_PERPETUAL {
2147                sample_tradifi_usdm_symbol("XAUUSDT", "XAU", Some("COMMODITY"))
2148            } else {
2149                sample_usdm_symbol()
2150            };
2151
2152            symbol.contract_type = contract_type.to_string();
2153            parse_usdm_instrument(&symbol, ts, ts).unwrap()
2154        } else {
2155            let mut symbol = sample_coinm_symbol();
2156            symbol.contract_type = contract_type.to_string();
2157            parse_coinm_instrument(&symbol, ts, ts).unwrap()
2158        };
2159
2160        assert_eq!(instrument.margin_init(), Decimal::ONE);
2161        assert_eq!(instrument.margin_maint(), dec!(0.1));
2162    }
2163
2164    #[rstest]
2165    fn test_parse_usdm_perpetual() {
2166        let symbol = sample_usdm_symbol();
2167        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2168
2169        let result = parse_usdm_instrument(&symbol, ts, ts);
2170        assert!(result.is_ok(), "Failed: {:?}", result.err());
2171
2172        let instrument = result.unwrap();
2173        match instrument {
2174            InstrumentAny::CryptoPerpetual(perp) => {
2175                assert_eq!(perp.id.to_string(), "BTCUSDT-PERP.BINANCE");
2176                assert_eq!(perp.raw_symbol.to_string(), "BTCUSDT");
2177                assert_eq!(perp.base_currency.code, "BTC");
2178                assert_eq!(perp.quote_currency.code, "USDT");
2179                assert_eq!(perp.settlement_currency.code, "USDT");
2180                assert!(!perp.is_inverse);
2181                assert_eq!(perp.price_increment, Price::from_str("0.10").unwrap());
2182                assert_eq!(perp.size_increment, Quantity::from_str("0.001").unwrap());
2183                assert_eq!(
2184                    perp.min_notional,
2185                    Some(Money::new(5.0, perp.quote_currency)),
2186                );
2187            }
2188            other => panic!("Expected CryptoPerpetual, was {other:?}"),
2189        }
2190    }
2191
2192    #[rstest]
2193    #[case::equity("SNDKUSDT", "SNDK", "EQUITY", AssetClass::Equity)]
2194    #[case::chinese_equity("UNITREEUSDT", "UNITREE", "CN_EQUITY", AssetClass::Equity)]
2195    #[case::korean_equity("005930USDT", "005930", "KR_EQUITY", AssetClass::Equity)]
2196    #[case::hong_kong_equity("0700USDT", "0700", "HK_EQUITY", AssetClass::Equity)]
2197    #[case::premarket("SPCXUSDT", "SPCX", "PREMARKET", AssetClass::Equity)]
2198    #[case::commodity("XAUUSDT", "XAU", "COMMODITY", AssetClass::Commodity)]
2199    fn test_parse_usdm_tradifi_perpetual(
2200        #[case] raw_symbol: &str,
2201        #[case] underlying: &str,
2202        #[case] underlying_type: &str,
2203        #[case] expected_asset_class: AssetClass,
2204    ) {
2205        let symbol = sample_tradifi_usdm_symbol(raw_symbol, underlying, Some(underlying_type));
2206        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2207
2208        let instrument = parse_usdm_instrument(&symbol, ts, ts).unwrap();
2209        match instrument {
2210            InstrumentAny::PerpetualContract(perp) => {
2211                assert_eq!(perp.id.to_string(), format!("{raw_symbol}-PERP.BINANCE"));
2212                assert_eq!(perp.raw_symbol.to_string(), raw_symbol);
2213                assert_eq!(perp.underlying, Ustr::from(underlying));
2214                assert_eq!(perp.asset_class, expected_asset_class);
2215                assert_eq!(perp.base_currency, None);
2216                assert_eq!(perp.quote_currency.code, "USDT");
2217                assert_eq!(perp.settlement_currency.code, "USDT");
2218                assert!(!perp.is_inverse);
2219                assert_eq!(perp.price_increment, Price::from_str("0.10").unwrap());
2220                assert_eq!(perp.size_increment, Quantity::from_str("0.001").unwrap());
2221                assert_eq!(
2222                    perp.min_notional,
2223                    Some(Money::new(5.0, perp.quote_currency)),
2224                );
2225            }
2226            other => panic!("Expected PerpetualContract, was {other:?}"),
2227        }
2228    }
2229
2230    #[rstest]
2231    #[case::missing(
2232        None,
2233        "Missing underlying type for TRADIFI_PERPETUAL symbol 'SNDKUSDT'"
2234    )]
2235    #[case::unknown(
2236        Some("INDEX"),
2237        "Unsupported underlying type 'INDEX' for TRADIFI_PERPETUAL symbol 'SNDKUSDT'"
2238    )]
2239    fn test_parse_usdm_tradifi_perpetual_rejects_invalid_underlying_type(
2240        #[case] underlying_type: Option<&str>,
2241        #[case] expected_error: &str,
2242    ) {
2243        let symbol = sample_tradifi_usdm_symbol("SNDKUSDT", "SNDK", underlying_type);
2244        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2245
2246        let error = parse_usdm_instrument(&symbol, ts, ts).unwrap_err();
2247        assert_eq!(error.to_string(), expected_error);
2248    }
2249
2250    #[rstest]
2251    #[case::current_week(CONTRACT_TYPE_CURRENT_WEEK)]
2252    #[case::next_week(CONTRACT_TYPE_NEXT_WEEK)]
2253    #[case::current_month(CONTRACT_TYPE_CURRENT_MONTH)]
2254    #[case::next_month(CONTRACT_TYPE_NEXT_MONTH)]
2255    #[case::current_quarter(CONTRACT_TYPE_CURRENT_QUARTER)]
2256    #[case::next_quarter(CONTRACT_TYPE_NEXT_QUARTER)]
2257    fn test_parse_usdm_delivery(#[case] contract_type: &str) {
2258        let mut symbol = sample_usdm_symbol();
2259        symbol.symbol = Ustr::from("BTCUSDT_260925");
2260        symbol.contract_type = contract_type.to_string();
2261        symbol.onboard_date = 1_774_598_400_000;
2262        symbol.delivery_date = 1_790_323_200_000;
2263        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2264
2265        let result = parse_usdm_instrument(&symbol, ts, ts).unwrap();
2266        let InstrumentAny::CryptoFuture(future) = result else {
2267            panic!("Expected CryptoFuture, was {result:?}");
2268        };
2269
2270        assert_eq!(future.id.to_string(), "BTCUSDT_260925.BINANCE");
2271        assert_eq!(future.raw_symbol.to_string(), "BTCUSDT_260925");
2272        assert_eq!(future.underlying.code, "BTC");
2273        assert_eq!(future.quote_currency.code, "USDT");
2274        assert_eq!(future.settlement_currency.code, "USDT");
2275        assert!(!future.is_inverse);
2276        assert_eq!(
2277            future.activation_ns,
2278            UnixNanos::from_millis(1_774_598_400_000)
2279        );
2280        assert_eq!(
2281            future.expiration_ns,
2282            UnixNanos::from_millis(1_790_323_200_000)
2283        );
2284        assert_eq!(future.price_increment, Price::from_str("0.10").unwrap());
2285        assert_eq!(future.size_increment, Quantity::from_str("0.001").unwrap());
2286        assert_eq!(future.multiplier, Quantity::from(1));
2287        assert_eq!(
2288            future.max_quantity,
2289            Some(Quantity::from_str("1000").unwrap())
2290        );
2291        assert_eq!(
2292            future.min_quantity,
2293            Some(Quantity::from_str("0.001").unwrap())
2294        );
2295        assert_eq!(
2296            future.min_notional,
2297            Some(Money::new(5.0, future.quote_currency)),
2298        );
2299        assert_eq!(future.max_price, Some(Price::from_str("4529764").unwrap()));
2300        assert_eq!(future.min_price, Some(Price::from_str("556.80").unwrap()));
2301    }
2302
2303    #[rstest]
2304    fn test_parse_usdm_unsupported_contract_type_fails() {
2305        let mut symbol = sample_usdm_symbol();
2306        symbol.contract_type = "UNKNOWN".to_string();
2307        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2308
2309        let error = parse_usdm_instrument(&symbol, ts, ts).unwrap_err();
2310
2311        assert!(
2312            error
2313                .to_string()
2314                .contains("Unsupported USD-M contract type")
2315        );
2316    }
2317
2318    #[rstest]
2319    fn test_parse_missing_price_filter_fails() {
2320        let mut symbol = sample_usdm_symbol();
2321        symbol.filters = vec![json!({
2322            "filterType": "LOT_SIZE",
2323            "stepSize": "0.001",
2324            "maxQty": "1000",
2325            "minQty": "0.001"
2326        })];
2327        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2328
2329        let result = parse_usdm_instrument(&symbol, ts, ts);
2330        assert!(result.is_err());
2331        assert!(
2332            result
2333                .unwrap_err()
2334                .to_string()
2335                .contains("Missing PRICE_FILTER")
2336        );
2337    }
2338
2339    #[rstest]
2340    fn test_parse_coinm_perpetual() {
2341        let symbol = sample_coinm_symbol();
2342        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2343
2344        let result = parse_coinm_instrument(&symbol, ts, ts).unwrap();
2345
2346        match result {
2347            InstrumentAny::CryptoPerpetual(perp) => {
2348                assert_eq!(perp.id.to_string(), "BTCUSD_PERP.BINANCE");
2349                assert_eq!(perp.raw_symbol.to_string(), "BTCUSD_PERP");
2350                assert_eq!(perp.base_currency.code, "BTC");
2351                assert_eq!(perp.quote_currency.code, "USD");
2352                assert_eq!(perp.settlement_currency.code, "BTC");
2353                assert!(perp.is_inverse);
2354                assert_eq!(perp.price_increment, Price::from_str("0.10").unwrap());
2355                assert_eq!(perp.size_increment, Quantity::from_str("1").unwrap());
2356                assert_eq!(
2357                    perp.min_notional,
2358                    Some(Money::new(1.0, perp.quote_currency)),
2359                );
2360            }
2361            other => panic!("Expected CryptoPerpetual, was {other:?}"),
2362        }
2363    }
2364
2365    #[rstest]
2366    #[case::current_quarter(CONTRACT_TYPE_CURRENT_QUARTER)]
2367    #[case::next_quarter(CONTRACT_TYPE_NEXT_QUARTER)]
2368    fn test_parse_coinm_delivery(#[case] contract_type: &str) {
2369        let mut symbol = sample_coinm_symbol();
2370        symbol.symbol = Ustr::from("BTCUSD_260925");
2371        symbol.contract_type = contract_type.to_string();
2372        symbol.onboard_date = 1_774_598_400_000;
2373        symbol.delivery_date = 1_790_323_200_000;
2374        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2375
2376        let result = parse_coinm_instrument(&symbol, ts, ts).unwrap();
2377        let InstrumentAny::CryptoFuture(future) = result else {
2378            panic!("Expected CryptoFuture, was {result:?}");
2379        };
2380
2381        assert_eq!(future.id.to_string(), "BTCUSD_260925.BINANCE");
2382        assert_eq!(future.raw_symbol.to_string(), "BTCUSD_260925");
2383        assert_eq!(future.underlying.code, "BTC");
2384        assert_eq!(future.quote_currency.code, "USD");
2385        assert_eq!(future.settlement_currency.code, "BTC");
2386        assert!(future.is_inverse);
2387        assert_eq!(
2388            future.activation_ns,
2389            UnixNanos::from_millis(1_774_598_400_000)
2390        );
2391        assert_eq!(
2392            future.expiration_ns,
2393            UnixNanos::from_millis(1_790_323_200_000)
2394        );
2395        assert_eq!(future.price_increment, Price::from_str("0.10").unwrap());
2396        assert_eq!(future.size_increment, Quantity::from_str("1").unwrap());
2397        assert_eq!(future.multiplier, Quantity::from(100));
2398        assert_eq!(
2399            future.max_quantity,
2400            Some(Quantity::from_str("1000").unwrap())
2401        );
2402        assert_eq!(future.min_quantity, Some(Quantity::from_str("1").unwrap()));
2403        assert_eq!(future.max_price, Some(Price::from_str("1000000").unwrap()));
2404        assert_eq!(future.min_price, Some(Price::from_str("0.10").unwrap()));
2405    }
2406
2407    #[rstest]
2408    fn test_parse_coinm_month_contract_fails() {
2409        let mut symbol = sample_coinm_symbol();
2410        symbol.contract_type = CONTRACT_TYPE_CURRENT_MONTH.to_string();
2411        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2412
2413        let error = parse_coinm_instrument(&symbol, ts, ts).unwrap_err();
2414
2415        assert!(
2416            error
2417                .to_string()
2418                .contains("Unsupported COIN-M contract type")
2419        );
2420    }
2421
2422    #[rstest]
2423    fn test_parse_spot_instrument_sbe() {
2424        let symbol = sample_spot_symbol_sbe();
2425        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2426
2427        let result = parse_spot_instrument_sbe(&symbol, ts, ts).unwrap();
2428
2429        match result {
2430            InstrumentAny::CurrencyPair(pair) => {
2431                assert_eq!(pair.id.to_string(), "ETHUSDT.BINANCE");
2432                assert_eq!(pair.raw_symbol.to_string(), "ETHUSDT");
2433                assert_eq!(pair.base_currency.code, "ETH");
2434                assert_eq!(pair.quote_currency.code, "USDT");
2435                assert_eq!(pair.price_increment, Price::from_str("0.01").unwrap());
2436                assert_eq!(pair.size_increment, Quantity::from_str("0.0001").unwrap());
2437            }
2438            other => panic!("Expected CurrencyPair, was {other:?}"),
2439        }
2440    }
2441
2442    #[rstest]
2443    fn test_not_trading_parse_errors_stay_debug_for_bulk_loads() {
2444        let mut symbol = sample_spot_symbol_sbe();
2445        symbol.status = 3;
2446        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2447        let error = parse_spot_instrument_sbe(&symbol, ts, ts).unwrap_err();
2448
2449        assert!(is_not_trading_error(&error));
2450        assert!(!should_warn_on_instrument_parse_error(true, false, &error));
2451        assert!(should_warn_on_instrument_parse_error(true, true, &error));
2452    }
2453
2454    #[rstest]
2455    fn test_all_producers_emit_detectable_not_trading_errors() {
2456        let ts = UnixNanos::from(1_700_000_000_000_000_000u64);
2457
2458        let mut sbe = sample_spot_symbol_sbe();
2459        sbe.status = 3;
2460        let sbe_err = parse_spot_instrument_sbe(&sbe, ts, ts).unwrap_err();
2461
2462        let json = BinanceSymbolJson {
2463            symbol: "ETHUSDT".to_string(),
2464            status: "BREAK".to_string(),
2465            base_asset: "ETH".to_string(),
2466            quote_asset: "USDT".to_string(),
2467            base_asset_precision: 8,
2468            quote_asset_precision: 8,
2469            filters: Vec::new(),
2470        };
2471        let json_err = parse_spot_instrument_json_with_fees(&json, ts, ts).unwrap_err();
2472
2473        let mut usdm = sample_usdm_symbol();
2474        usdm.status = BinanceTradingStatus::Halt;
2475        let usdm_err = parse_usdm_instrument(&usdm, ts, ts).unwrap_err();
2476
2477        let mut coinm = sample_coinm_symbol();
2478        coinm.contract_status = Some(BinanceContractStatus::TradingHalt);
2479        let coinm_err = parse_coinm_instrument(&coinm, ts, ts).unwrap_err();
2480
2481        for error in [&sbe_err, &json_err, &usdm_err, &coinm_err] {
2482            assert!(is_not_trading_error(error), "undetected: {error}");
2483        }
2484    }
2485
2486    #[rstest]
2487    fn test_unexpected_parse_errors_honor_log_warnings() {
2488        let error = anyhow::anyhow!("Missing PRICE_FILTER in symbol filters");
2489
2490        assert!(!is_not_trading_error(&error));
2491        assert!(should_warn_on_instrument_parse_error(true, false, &error));
2492        assert!(!should_warn_on_instrument_parse_error(false, true, &error));
2493    }
2494
2495    #[rstest]
2496    fn test_parse_spot_trades_sbe() {
2497        let instrument = sample_spot_instrument();
2498        let trades = BinanceTrades {
2499            price_exponent: -2,
2500            qty_exponent: -4,
2501            trades: vec![
2502                crate::spot::http::models::BinanceTrade {
2503                    id: 1,
2504                    price_mantissa: 12_345,
2505                    qty_mantissa: 25_000,
2506                    quote_qty_mantissa: 0,
2507                    time: 1_700_000_000_000_000,
2508                    is_buyer_maker: false,
2509                    is_best_match: true,
2510                },
2511                crate::spot::http::models::BinanceTrade {
2512                    id: 2,
2513                    price_mantissa: 12_340,
2514                    qty_mantissa: 10_000,
2515                    quote_qty_mantissa: 0,
2516                    time: 1_700_000_000_500_000,
2517                    is_buyer_maker: true,
2518                    is_best_match: true,
2519                },
2520            ],
2521        };
2522        let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
2523
2524        let result = parse_spot_trades_sbe(&trades, &instrument, ts_init).unwrap();
2525
2526        assert_eq!(result.len(), 2);
2527        assert_eq!(result[0].instrument_id, instrument.id());
2528        assert_eq!(result[0].price.as_f64(), 123.45);
2529        assert_eq!(result[0].size.as_f64(), 2.5);
2530        assert_eq!(result[0].aggressor_side, AggressorSide::Buy);
2531        assert_eq!(result[0].trade_id, TradeId::new("1"));
2532        assert_eq!(
2533            result[0].ts_event,
2534            UnixNanos::from(1_700_000_000_000_000_000u64)
2535        );
2536        assert_eq!(result[0].ts_init, ts_init);
2537        assert_eq!(result[1].aggressor_side, AggressorSide::Sell);
2538    }
2539
2540    #[rstest]
2541    #[case(SbeOrderType::LimitMaker, OrderType::Limit, None)]
2542    #[case(SbeOrderType::TakeProfit, OrderType::MarketIfTouched, Some(12_000))]
2543    #[case(SbeOrderType::TakeProfitLimit, OrderType::LimitIfTouched, Some(12_000))]
2544    #[case(SbeOrderType::StopLoss, OrderType::StopMarket, Some(12_000))]
2545    #[case(SbeOrderType::StopLossLimit, OrderType::StopLimit, Some(12_000))]
2546    fn test_parse_order_status_report_sbe(
2547        #[case] order_type: SbeOrderType,
2548        #[case] expected: OrderType,
2549        #[case] stop_price_mantissa: Option<i64>,
2550    ) {
2551        let instrument = sample_spot_instrument();
2552        let order = BinanceOrderResponse {
2553            price_exponent: -2,
2554            qty_exponent: -4,
2555            order_id: 42,
2556            order_list_id: Some(77),
2557            price_mantissa: 12_345,
2558            orig_qty_mantissa: 25_000,
2559            executed_qty_mantissa: 10_000,
2560            cummulative_quote_qty_mantissa: 123_450_000,
2561            status: SbeOrderStatus::PartiallyFilled,
2562            time_in_force: SbeTimeInForce::Gtc,
2563            order_type,
2564            side: SbeOrderSide::Buy,
2565            stop_price_mantissa,
2566            iceberg_qty_mantissa: None,
2567            time: 1_700_000_000_000_000,
2568            update_time: 1_700_000_000_100_000,
2569            is_working: true,
2570            working_time: Some(1_700_000_000_050_000),
2571            orig_quote_order_qty_mantissa: 0,
2572            self_trade_prevention_mode:
2573                crate::spot::sbe::spot::self_trade_prevention_mode::SelfTradePreventionMode::None,
2574            client_order_id: "client-123".to_string(),
2575            symbol: "ETHUSDT".to_string(),
2576            expiry_reason: None,
2577        };
2578        let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
2579
2580        let report = parse_order_status_report_sbe(
2581            &order,
2582            sample_account_id(),
2583            &instrument,
2584            BINANCE_NAUTILUS_SPOT_BROKER_ID,
2585            ts_init,
2586        )
2587        .unwrap();
2588
2589        assert_eq!(report.account_id, sample_account_id());
2590        assert_eq!(report.instrument_id, instrument.id());
2591        assert_eq!(
2592            report.client_order_id,
2593            Some(ClientOrderId::new("client-123"))
2594        );
2595        assert_eq!(report.venue_order_id, VenueOrderId::new("42"));
2596        assert_eq!(report.order_side, OrderSide::Buy.into());
2597        assert_eq!(report.order_type, expected);
2598        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
2599        assert_eq!(report.quantity.as_f64(), 2.5);
2600        assert_eq!(report.filled_qty.as_f64(), 1.0);
2601        assert_eq!(report.order_list_id, Some(OrderListId::new("77")));
2602        assert_eq!(report.price, Some(Price::new(123.45, 2)));
2603        assert_eq!(report.avg_px.unwrap().to_string(), "123.45");
2604        assert_eq!(report.post_only, order_type == SbeOrderType::LimitMaker);
2605        assert_eq!(
2606            report.trigger_price,
2607            stop_price_mantissa.map(|_| Price::from("120.00"))
2608        );
2609        assert_eq!(
2610            report.trigger_type,
2611            stop_price_mantissa.map(|_| TriggerType::LastPrice)
2612        );
2613        assert_eq!(
2614            report.ts_accepted,
2615            UnixNanos::from(1_700_000_000_000_000_000u64)
2616        );
2617        assert_eq!(
2618            report.ts_last,
2619            UnixNanos::from(1_700_000_000_100_000_000u64)
2620        );
2621        assert_eq!(report.ts_init, ts_init);
2622    }
2623
2624    #[rstest]
2625    #[case(SbeOrderType::TakeProfit, OrderType::MarketIfTouched)]
2626    #[case(SbeOrderType::TakeProfitLimit, OrderType::LimitIfTouched)]
2627    #[case(SbeOrderType::StopLoss, OrderType::StopMarket)]
2628    #[case(SbeOrderType::StopLossLimit, OrderType::StopLimit)]
2629    fn test_parse_new_order_response_sbe(
2630        #[case] order_type: SbeOrderType,
2631        #[case] expected: OrderType,
2632    ) {
2633        let instrument = sample_spot_instrument();
2634        let response = BinanceNewOrderResponse {
2635            price_exponent: -2,
2636            qty_exponent: -4,
2637            order_id: 99,
2638            order_list_id: Some(7),
2639            transact_time: 1_700_000_000_000_000,
2640            price_mantissa: 12_100,
2641            orig_qty_mantissa: 20_000,
2642            executed_qty_mantissa: 5_000,
2643            cummulative_quote_qty_mantissa: 60_500_000,
2644            status: SbeOrderStatus::New,
2645            time_in_force: SbeTimeInForce::Gtc,
2646            order_type,
2647            side: SbeOrderSide::Sell,
2648            stop_price_mantissa: Some(12_000),
2649            working_time: Some(1_700_000_000_000_000),
2650            self_trade_prevention_mode:
2651                crate::spot::sbe::spot::self_trade_prevention_mode::SelfTradePreventionMode::None,
2652            client_order_id: "client-456".to_string(),
2653            symbol: "ETHUSDT".to_string(),
2654            fills: vec![],
2655            expiry_reason: None,
2656        };
2657        let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
2658
2659        let report = parse_new_order_response_sbe(
2660            &response,
2661            sample_account_id(),
2662            &instrument,
2663            BINANCE_NAUTILUS_SPOT_BROKER_ID,
2664            ts_init,
2665        )
2666        .unwrap();
2667
2668        assert_eq!(report.account_id, sample_account_id());
2669        assert_eq!(report.instrument_id, instrument.id());
2670        assert_eq!(
2671            report.client_order_id,
2672            Some(ClientOrderId::new("client-456"))
2673        );
2674        assert_eq!(report.venue_order_id, VenueOrderId::new("99"));
2675        assert_eq!(report.order_side, OrderSide::Sell.into());
2676        assert_eq!(report.order_type, expected);
2677        assert_eq!(report.order_status, OrderStatus::Accepted);
2678        assert_eq!(report.quantity.as_f64(), 2.0);
2679        assert_eq!(report.filled_qty.as_f64(), 0.5);
2680        assert_eq!(report.order_list_id, Some(OrderListId::new("7")));
2681        assert_eq!(report.price, Some(Price::new(121.0, 2)));
2682        assert_eq!(report.trigger_price, Some(Price::new(120.0, 2)));
2683        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2684        // `as_decimal()` carries the price precision, where the old `as_f64()` hop dropped it
2685        assert_eq!(report.avg_px, Some(dec!(121.00)));
2686        assert_eq!(report.avg_px.unwrap().to_string(), "121.00");
2687        assert!(!report.post_only);
2688        assert_eq!(
2689            report.ts_accepted,
2690            UnixNanos::from(1_700_000_000_000_000_000u64)
2691        );
2692        assert_eq!(
2693            report.ts_last,
2694            UnixNanos::from(1_700_000_000_000_000_000u64)
2695        );
2696    }
2697
2698    #[rstest]
2699    fn test_parse_fill_report_sbe() {
2700        let instrument = sample_spot_instrument();
2701        let trade = BinanceAccountTrade {
2702            price_exponent: -2,
2703            qty_exponent: -4,
2704            commission_exponent: -8,
2705            id: 123,
2706            order_id: 456,
2707            order_list_id: None,
2708            price_mantissa: 12_345,
2709            qty_mantissa: 25_000,
2710            quote_qty_mantissa: 0,
2711            commission_mantissa: 10_000,
2712            time: 1_700_000_000_000_000,
2713            is_buyer: false,
2714            is_maker: true,
2715            is_best_match: true,
2716            symbol: "ETHUSDT".to_string(),
2717            commission_asset: "USDT".to_string(),
2718        };
2719        let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
2720
2721        let report = parse_fill_report_sbe(
2722            &trade,
2723            sample_account_id(),
2724            &instrument,
2725            Currency::from("USDT"),
2726            ts_init,
2727        )
2728        .unwrap();
2729
2730        assert_eq!(report.account_id, sample_account_id());
2731        assert_eq!(report.instrument_id, instrument.id());
2732        assert_eq!(report.venue_order_id, VenueOrderId::new("456"));
2733        assert_eq!(report.trade_id, TradeId::new("123"));
2734        assert_eq!(report.order_side, OrderSide::Sell);
2735        assert_eq!(report.last_qty.as_f64(), 2.5);
2736        assert_eq!(report.last_px.as_f64(), 123.45);
2737        assert_eq!(report.liquidity_side, LiquiditySide::Maker);
2738        assert_eq!(report.commission.as_f64(), 0.0001);
2739        assert_eq!(
2740            report.ts_event,
2741            UnixNanos::from(1_700_000_000_000_000_000u64)
2742        );
2743        assert_eq!(report.ts_init, ts_init);
2744        assert!(report.client_order_id.is_none());
2745    }
2746
2747    #[rstest]
2748    fn test_parse_klines_to_bars() {
2749        use nautilus_model::enums::{AggregationSource, PriceType};
2750
2751        let instrument = sample_spot_instrument();
2752        let bar_type = BarType::new(
2753            instrument.id(),
2754            BarSpecification::new(1, BarAggregation::Minute, PriceType::Last),
2755            AggregationSource::External,
2756        );
2757        let klines = BinanceKlines {
2758            price_exponent: -2,
2759            qty_exponent: -4,
2760            klines: vec![crate::spot::http::models::BinanceKline {
2761                open_time: 1_700_000_000_000_000,
2762                open_price: 12_000,
2763                high_price: 12_500,
2764                low_price: 11_900,
2765                close_price: 12_345,
2766                volume: 1_234_500_i128.to_le_bytes(),
2767                close_time: 1_700_000_059_999_000,
2768                quote_volume: 777_788_i128.to_le_bytes(),
2769                num_trades: 100,
2770                taker_buy_base_volume: 56_789_i128.to_le_bytes(),
2771                taker_buy_quote_volume: 9_901_i128.to_le_bytes(),
2772            }],
2773        };
2774        let ts_init = UnixNanos::from(1_700_000_001_000_000_000u64);
2775
2776        let bars = parse_klines_to_binance_bars(&klines, bar_type, &instrument, ts_init).unwrap();
2777
2778        assert_eq!(bars.len(), 1);
2779        assert_eq!(bars[0].bar_type, bar_type);
2780        assert_eq!(bars[0].open, Price::new(120.0, 2));
2781        assert_eq!(bars[0].high, Price::new(125.0, 2));
2782        assert_eq!(bars[0].low, Price::new(119.0, 2));
2783        assert_eq!(bars[0].close, Price::new(123.45, 2));
2784        assert_eq!(bars[0].volume, Quantity::new(123.45, 4));
2785        assert_eq!(bars[0].quote_volume, dec!(7777.88));
2786        assert_eq!(bars[0].count, 100);
2787        assert_eq!(bars[0].taker_buy_base_volume, dec!(5.6789));
2788        assert_eq!(bars[0].taker_buy_quote_volume, dec!(99.01));
2789        assert_eq!(
2790            bars[0].ts_event,
2791            UnixNanos::from(1_700_000_059_999_000_000u64)
2792        );
2793        assert_eq!(bars[0].ts_init, ts_init);
2794    }
2795
2796    mod bar_spec_tests {
2797        use std::num::NonZeroUsize;
2798
2799        use nautilus_model::{
2800            data::BarSpecification,
2801            enums::{BarAggregation, PriceType},
2802        };
2803
2804        use super::*;
2805        use crate::common::enums::BinanceKlineInterval;
2806
2807        fn make_bar_spec(step: usize, aggregation: BarAggregation) -> BarSpecification {
2808            BarSpecification {
2809                step: NonZeroUsize::new(step).unwrap(),
2810                aggregation,
2811                price_type: PriceType::Last,
2812            }
2813        }
2814
2815        #[rstest]
2816        #[case(1, BarAggregation::Second, BinanceKlineInterval::Second1)]
2817        #[case(1, BarAggregation::Minute, BinanceKlineInterval::Minute1)]
2818        #[case(3, BarAggregation::Minute, BinanceKlineInterval::Minute3)]
2819        #[case(5, BarAggregation::Minute, BinanceKlineInterval::Minute5)]
2820        #[case(15, BarAggregation::Minute, BinanceKlineInterval::Minute15)]
2821        #[case(30, BarAggregation::Minute, BinanceKlineInterval::Minute30)]
2822        #[case(1, BarAggregation::Hour, BinanceKlineInterval::Hour1)]
2823        #[case(2, BarAggregation::Hour, BinanceKlineInterval::Hour2)]
2824        #[case(4, BarAggregation::Hour, BinanceKlineInterval::Hour4)]
2825        #[case(6, BarAggregation::Hour, BinanceKlineInterval::Hour6)]
2826        #[case(8, BarAggregation::Hour, BinanceKlineInterval::Hour8)]
2827        #[case(12, BarAggregation::Hour, BinanceKlineInterval::Hour12)]
2828        #[case(1, BarAggregation::Day, BinanceKlineInterval::Day1)]
2829        #[case(3, BarAggregation::Day, BinanceKlineInterval::Day3)]
2830        #[case(1, BarAggregation::Week, BinanceKlineInterval::Week1)]
2831        #[case(1, BarAggregation::Month, BinanceKlineInterval::Month1)]
2832        fn test_bar_spec_to_binance_interval(
2833            #[case] step: usize,
2834            #[case] aggregation: BarAggregation,
2835            #[case] expected: BinanceKlineInterval,
2836        ) {
2837            let bar_spec = make_bar_spec(step, aggregation);
2838            let result = bar_spec_to_binance_interval(bar_spec).unwrap();
2839            assert_eq!(result, expected);
2840        }
2841
2842        #[rstest]
2843        fn test_unsupported_second_interval() {
2844            let bar_spec = make_bar_spec(2, BarAggregation::Second);
2845            let result = bar_spec_to_binance_interval(bar_spec);
2846            assert!(result.is_err());
2847            assert!(
2848                result
2849                    .unwrap_err()
2850                    .to_string()
2851                    .contains("Unsupported second interval")
2852            );
2853        }
2854
2855        #[rstest]
2856        fn test_unsupported_minute_interval() {
2857            let bar_spec = make_bar_spec(7, BarAggregation::Minute);
2858            let result = bar_spec_to_binance_interval(bar_spec);
2859            assert!(result.is_err());
2860            assert!(
2861                result
2862                    .unwrap_err()
2863                    .to_string()
2864                    .contains("Unsupported minute interval")
2865            );
2866        }
2867
2868        #[rstest]
2869        fn test_unsupported_aggregation() {
2870            let bar_spec = make_bar_spec(100, BarAggregation::Tick);
2871            let result = bar_spec_to_binance_interval(bar_spec);
2872            assert!(result.is_err());
2873            assert!(
2874                result
2875                    .unwrap_err()
2876                    .to_string()
2877                    .contains("Unsupported bar aggregation")
2878            );
2879        }
2880    }
2881
2882    mod sbe_precision_tests {
2883        use super::*;
2884        use crate::spot::http::models::{BinanceLotSizeFilterSbe, BinancePriceFilterSbe};
2885
2886        #[rstest]
2887        #[case::precision_0(100_000_000, -8, 0)]
2888        #[case::precision_1(10_000_000, -8, 1)]
2889        #[case::precision_2(1_000_000, -8, 2)]
2890        #[case::precision_3(100_000, -8, 3)]
2891        #[case::precision_4(10_000, -8, 4)]
2892        #[case::precision_5(1_000, -8, 5)]
2893        #[case::precision_6(100, -8, 6)]
2894        #[case::precision_7(10, -8, 7)]
2895        #[case::precision_8(1, -8, 8)]
2896        fn test_sbe_mantissa_precision(
2897            #[case] mantissa: i64,
2898            #[case] exponent: i8,
2899            #[case] expected: u8,
2900        ) {
2901            let result = sbe_mantissa_precision(mantissa, exponent);
2902            assert_eq!(
2903                result, expected,
2904                "mantissa={mantissa}, exponent={exponent}: expected {expected}, was {result}"
2905            );
2906        }
2907
2908        #[rstest]
2909        fn test_sbe_mantissa_precision_zero_mantissa() {
2910            assert_eq!(sbe_mantissa_precision(0, -8), 0);
2911        }
2912
2913        #[rstest]
2914        fn test_sbe_mantissa_precision_positive_exponent() {
2915            assert_eq!(sbe_mantissa_precision(1, 0), 0);
2916            assert_eq!(sbe_mantissa_precision(5, 2), 0);
2917        }
2918
2919        #[rstest]
2920        fn test_parse_sbe_price_filter_ethusdc() {
2921            let filter = BinancePriceFilterSbe {
2922                price_exponent: -8,
2923                min_price: 1_000_000,
2924                max_price: 100_000_000_000_000,
2925                tick_size: 1_000_000,
2926            };
2927
2928            let (tick_size, max_price, min_price) = parse_sbe_price_filter(&filter).unwrap();
2929            let max_price = max_price.unwrap();
2930            let min_price = min_price.unwrap();
2931
2932            assert_eq!(tick_size.precision, 2, "tick_size precision");
2933            assert_eq!(tick_size.as_decimal(), dec!(0.01));
2934            assert_eq!(max_price.precision, 2);
2935            assert_eq!(max_price.as_decimal(), dec!(1000000.00));
2936            assert_eq!(min_price.precision, 2);
2937            assert_eq!(min_price.as_decimal(), dec!(0.01));
2938        }
2939
2940        #[rstest]
2941        fn test_parse_sbe_price_filter_shibusdt() {
2942            let filter = BinancePriceFilterSbe {
2943                price_exponent: -8,
2944                min_price: 1,
2945                max_price: 100_000_000,
2946                tick_size: 1,
2947            };
2948
2949            let (tick_size, _, _) = parse_sbe_price_filter(&filter).unwrap();
2950
2951            assert_eq!(tick_size.precision, 8);
2952            assert_eq!(tick_size.as_decimal(), dec!(0.00000001));
2953        }
2954
2955        #[rstest]
2956        fn test_parse_sbe_lot_size_filter_ethusdc() {
2957            let filter = BinanceLotSizeFilterSbe {
2958                qty_exponent: -8,
2959                min_qty: 10_000,
2960                max_qty: 900_000_000_000,
2961                step_size: 10_000,
2962            };
2963
2964            let (step_size, max_qty, min_qty) = parse_sbe_lot_size_filter(&filter).unwrap();
2965            let max_qty = max_qty.unwrap();
2966            let min_qty = min_qty.unwrap();
2967
2968            assert_eq!(step_size.precision, 4, "step_size precision");
2969            assert_eq!(step_size.as_decimal(), dec!(0.0001));
2970            assert_eq!(min_qty.precision, 4);
2971            assert_eq!(min_qty.as_decimal(), dec!(0.0001));
2972            assert_eq!(max_qty.precision, 4);
2973            assert_eq!(max_qty.as_decimal(), dec!(9000.0000));
2974        }
2975    }
2976}