Skip to main content

nautilus_binance/futures/http/
models.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Binance Futures HTTP response models.
17
18use std::fmt::Debug;
19
20use anyhow::Context;
21use nautilus_core::{
22    UUID4, UnixNanos,
23    serialization::{
24        deserialize_decimal_or_zero, deserialize_optional_decimal_from_str,
25        serialize_decimal_as_str, serialize_optional_decimal_as_str,
26    },
27    string::secret::SecretString,
28};
29use nautilus_model::{
30    enums::{
31        AccountType, LiquiditySide, OrderSide, OrderStatus, OrderType, TimeInForce,
32        TrailingOffsetType, TriggerType,
33    },
34    events::AccountState,
35    identifiers::{AccountId, InstrumentId, TradeId, VenueOrderId},
36    reports::{FillReport, OrderStatusReport},
37    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
38};
39use rust_decimal::Decimal;
40use serde::{Deserialize, Serialize};
41use serde_json::Value;
42use ustr::Ustr;
43use zeroize::{Zeroize, ZeroizeOnDrop};
44
45use crate::{
46    common::{
47        consts::BINANCE_NAUTILUS_FUTURES_BROKER_ID,
48        encoder::decode_client_order_id,
49        enums::{
50            BinanceAlgoStatus, BinanceAlgoType, BinanceContractStatus, BinanceFuturesOrderType,
51            BinanceIncomeType, BinanceMarginType, BinanceOrderStatus, BinancePositionSide,
52            BinancePriceMatch, BinanceSelfTradePreventionMode, BinanceSide, BinanceTimeInForce,
53            BinanceTradingStatus, BinanceWorkingType,
54        },
55        models::BinanceRateLimit,
56        parse::{parse_millis, parse_required_decimal},
57    },
58    futures::conversions::{normalize_futures_asset, parse_good_till_date},
59};
60
61/// Server time response from `GET /fapi/v1/time`.
62#[derive(Clone, Debug, Serialize, Deserialize)]
63#[serde(rename_all = "camelCase")]
64pub struct BinanceServerTime {
65    /// Server timestamp in milliseconds.
66    pub server_time: i64,
67}
68
69/// Public trade from `GET /fapi/v1/trades`.
70#[derive(Clone, Debug, Serialize, Deserialize)]
71#[serde(rename_all = "camelCase")]
72pub struct BinanceFuturesTrade {
73    /// Trade ID.
74    pub id: i64,
75    /// Trade price.
76    pub price: String,
77    /// Trade quantity.
78    pub qty: String,
79    /// Quote asset quantity.
80    pub quote_qty: String,
81    /// Trade timestamp in milliseconds.
82    pub time: i64,
83    /// Whether the buyer is the maker.
84    pub is_buyer_maker: bool,
85}
86
87/// Aggregate public trade from `GET /fapi/v1/aggTrades` or `GET /dapi/v1/aggTrades`.
88#[derive(Clone, Debug, Serialize, Deserialize)]
89pub struct BinanceFuturesAggTrade {
90    /// Aggregate trade ID.
91    #[serde(rename = "a")]
92    pub id: i64,
93    /// Trade price.
94    #[serde(rename = "p")]
95    pub price: String,
96    /// Trade quantity.
97    #[serde(rename = "q")]
98    pub qty: String,
99    /// First raw trade ID represented by this aggregate.
100    #[serde(rename = "f")]
101    pub first_trade_id: i64,
102    /// Last raw trade ID represented by this aggregate.
103    #[serde(rename = "l")]
104    pub last_trade_id: i64,
105    /// Trade timestamp in milliseconds.
106    #[serde(rename = "T")]
107    pub time: i64,
108    /// Whether the buyer is the maker.
109    #[serde(rename = "m")]
110    pub is_buyer_maker: bool,
111}
112
113/// Kline/candlestick data from `GET /fapi/v1/klines`.
114#[derive(Clone, Debug)]
115pub struct BinanceFuturesKline {
116    /// Open time in milliseconds.
117    pub open_time: i64,
118    /// Open price.
119    pub open: String,
120    /// High price.
121    pub high: String,
122    /// Low price.
123    pub low: String,
124    /// Close price.
125    pub close: String,
126    /// Volume.
127    pub volume: String,
128    /// Close time in milliseconds.
129    pub close_time: i64,
130    /// Quote asset volume.
131    pub quote_volume: String,
132    /// Number of trades.
133    pub num_trades: i64,
134    /// Taker buy base volume.
135    pub taker_buy_base_volume: String,
136    /// Taker buy quote volume.
137    pub taker_buy_quote_volume: String,
138}
139
140impl<'de> Deserialize<'de> for BinanceFuturesKline {
141    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
142    where
143        D: serde::Deserializer<'de>,
144    {
145        let arr: Vec<Value> = Vec::deserialize(deserializer)?;
146        if arr.len() < 11 {
147            return Err(serde::de::Error::custom("Invalid kline array length"));
148        }
149
150        Ok(Self {
151            open_time: required_kline_i64::<D::Error>(&arr, 0, "open_time")?,
152            open: required_kline_string::<D::Error>(&arr, 1, "open")?,
153            high: required_kline_string::<D::Error>(&arr, 2, "high")?,
154            low: required_kline_string::<D::Error>(&arr, 3, "low")?,
155            close: required_kline_string::<D::Error>(&arr, 4, "close")?,
156            volume: required_kline_string::<D::Error>(&arr, 5, "volume")?,
157            close_time: required_kline_i64::<D::Error>(&arr, 6, "close_time")?,
158            quote_volume: required_kline_string::<D::Error>(&arr, 7, "quote_volume")?,
159            num_trades: required_kline_i64::<D::Error>(&arr, 8, "num_trades")?,
160            taker_buy_base_volume: required_kline_string::<D::Error>(
161                &arr,
162                9,
163                "taker_buy_base_volume",
164            )?,
165            taker_buy_quote_volume: required_kline_string::<D::Error>(
166                &arr,
167                10,
168                "taker_buy_quote_volume",
169            )?,
170        })
171    }
172}
173
174fn required_kline_i64<E>(arr: &[Value], index: usize, field: &str) -> Result<i64, E>
175where
176    E: serde::de::Error,
177{
178    arr[index]
179        .as_i64()
180        .ok_or_else(|| E::custom(format!("invalid kline {field}")))
181}
182
183fn required_kline_string<E>(arr: &[Value], index: usize, field: &str) -> Result<String, E>
184where
185    E: serde::de::Error,
186{
187    arr[index]
188        .as_str()
189        .map(ToString::to_string)
190        .ok_or_else(|| E::custom(format!("invalid kline {field}")))
191}
192
193/// USD-M Futures exchange information response from `GET /fapi/v1/exchangeInfo`.
194#[derive(Clone, Debug, Serialize, Deserialize)]
195#[serde(rename_all = "camelCase")]
196pub struct BinanceFuturesUsdExchangeInfo {
197    /// Server timezone.
198    pub timezone: String,
199    /// Server timestamp in milliseconds.
200    pub server_time: i64,
201    /// Rate limit definitions.
202    pub rate_limits: Vec<BinanceRateLimit>,
203    /// Exchange-level filters.
204    #[serde(default)]
205    pub exchange_filters: Vec<Value>,
206    /// Asset definitions.
207    #[serde(default)]
208    pub assets: Vec<BinanceFuturesAsset>,
209    /// Trading symbols.
210    pub symbols: Vec<BinanceFuturesUsdSymbol>,
211}
212
213/// Futures asset definition.
214#[derive(Clone, Debug, Serialize, Deserialize)]
215#[serde(rename_all = "camelCase")]
216pub struct BinanceFuturesAsset {
217    /// Asset name.
218    pub asset: Ustr,
219    /// Whether margin is available.
220    pub margin_available: bool,
221    /// Auto asset exchange threshold.
222    #[serde(default)]
223    pub auto_asset_exchange: Option<String>,
224}
225
226/// USD-M Futures symbol definition.
227#[derive(Clone, Debug, Serialize, Deserialize)]
228#[serde(rename_all = "camelCase")]
229pub struct BinanceFuturesUsdSymbol {
230    /// Symbol name (e.g., "BTCUSDT").
231    pub symbol: Ustr,
232    /// Trading pair (e.g., "BTCUSDT").
233    pub pair: Ustr,
234    /// Contract type (PERPETUAL, TRADIFI_PERPETUAL, CURRENT_MONTH, NEXT_MONTH,
235    /// CURRENT_QUARTER, NEXT_QUARTER).
236    pub contract_type: String,
237    /// Delivery date timestamp.
238    pub delivery_date: i64,
239    /// Onboard date timestamp.
240    pub onboard_date: i64,
241    /// Trading status.
242    pub status: BinanceTradingStatus,
243    /// Maintenance margin percent.
244    pub maint_margin_percent: String,
245    /// Required margin percent.
246    pub required_margin_percent: String,
247    /// Base asset.
248    pub base_asset: Ustr,
249    /// Quote asset.
250    pub quote_asset: Ustr,
251    /// Margin asset.
252    pub margin_asset: Ustr,
253    /// Price precision.
254    pub price_precision: i32,
255    /// Quantity precision.
256    pub quantity_precision: i32,
257    /// Base asset precision.
258    pub base_asset_precision: i32,
259    /// Quote precision.
260    pub quote_precision: i32,
261    /// Underlying type.
262    #[serde(default)]
263    pub underlying_type: Option<String>,
264    /// Underlying sub type.
265    #[serde(default)]
266    pub underlying_sub_type: Vec<String>,
267    /// Settle plan.
268    #[serde(default)]
269    pub settle_plan: Option<i64>,
270    /// Trigger protect threshold.
271    #[serde(default)]
272    pub trigger_protect: Option<String>,
273    /// Liquidation fee.
274    #[serde(default)]
275    pub liquidation_fee: Option<String>,
276    /// Market take bound.
277    #[serde(default)]
278    pub market_take_bound: Option<String>,
279    /// Allowed order types.
280    pub order_types: Vec<String>,
281    /// Time in force options.
282    pub time_in_force: Vec<String>,
283    /// Symbol filters.
284    pub filters: Vec<Value>,
285}
286
287/// COIN-M Futures exchange information response from `GET /dapi/v1/exchangeInfo`.
288#[derive(Clone, Debug, Serialize, Deserialize)]
289#[serde(rename_all = "camelCase")]
290pub struct BinanceFuturesCoinExchangeInfo {
291    /// Server timezone.
292    pub timezone: String,
293    /// Server timestamp in milliseconds.
294    pub server_time: i64,
295    /// Rate limit definitions.
296    pub rate_limits: Vec<BinanceRateLimit>,
297    /// Exchange-level filters.
298    #[serde(default)]
299    pub exchange_filters: Vec<Value>,
300    /// Trading symbols.
301    pub symbols: Vec<BinanceFuturesCoinSymbol>,
302}
303
304/// COIN-M Futures symbol definition.
305#[derive(Clone, Debug, Serialize, Deserialize)]
306#[serde(rename_all = "camelCase")]
307pub struct BinanceFuturesCoinSymbol {
308    /// Symbol name (e.g., "BTCUSD_PERP").
309    pub symbol: Ustr,
310    /// Trading pair (e.g., "BTCUSD").
311    pub pair: Ustr,
312    /// Contract type (PERPETUAL, CURRENT_QUARTER, NEXT_QUARTER).
313    pub contract_type: String,
314    /// Delivery date timestamp.
315    pub delivery_date: i64,
316    /// Onboard date timestamp.
317    pub onboard_date: i64,
318    /// Trading status.
319    #[serde(default)]
320    pub contract_status: Option<BinanceContractStatus>,
321    /// Contract size.
322    pub contract_size: i64,
323    /// Maintenance margin percent.
324    pub maint_margin_percent: String,
325    /// Required margin percent.
326    pub required_margin_percent: String,
327    /// Base asset.
328    pub base_asset: Ustr,
329    /// Quote asset.
330    pub quote_asset: Ustr,
331    /// Margin asset.
332    pub margin_asset: Ustr,
333    /// Price precision.
334    pub price_precision: i32,
335    /// Quantity precision.
336    pub quantity_precision: i32,
337    /// Base asset precision.
338    pub base_asset_precision: i32,
339    /// Quote precision.
340    pub quote_precision: i32,
341    /// Equal quantity precision.
342    #[serde(default, rename = "equalQtyPrecision")]
343    pub equal_qty_precision: Option<i32>,
344    /// Trigger protect threshold.
345    #[serde(default)]
346    pub trigger_protect: Option<String>,
347    /// Liquidation fee.
348    #[serde(default)]
349    pub liquidation_fee: Option<String>,
350    /// Market take bound.
351    #[serde(default)]
352    pub market_take_bound: Option<String>,
353    /// Allowed order types.
354    pub order_types: Vec<String>,
355    /// Time in force options.
356    pub time_in_force: Vec<String>,
357    /// Symbol filters.
358    pub filters: Vec<Value>,
359}
360
361/// 24hr ticker price change statistics for futures.
362#[derive(Clone, Debug, Serialize, Deserialize)]
363#[serde(rename_all = "camelCase")]
364pub struct BinanceFuturesTicker24hr {
365    /// Symbol name.
366    pub symbol: Ustr,
367    /// Price change in quote asset.
368    pub price_change: String,
369    /// Price change percentage.
370    pub price_change_percent: String,
371    /// Weighted average price.
372    pub weighted_avg_price: String,
373    /// Last traded price.
374    pub last_price: String,
375    /// Last traded quantity.
376    #[serde(default)]
377    pub last_qty: Option<String>,
378    /// Opening price.
379    pub open_price: String,
380    /// Highest price.
381    pub high_price: String,
382    /// Lowest price.
383    pub low_price: String,
384    /// Total traded base asset volume.
385    pub volume: String,
386    /// Total traded quote asset volume.
387    pub quote_volume: String,
388    /// Statistics open time.
389    pub open_time: i64,
390    /// Statistics close time.
391    pub close_time: i64,
392    /// First trade ID.
393    #[serde(default)]
394    pub first_id: Option<i64>,
395    /// Last trade ID.
396    #[serde(default)]
397    pub last_id: Option<i64>,
398    /// Total number of trades.
399    #[serde(default)]
400    pub count: Option<i64>,
401}
402
403/// Mark price and funding rate for futures.
404#[derive(Clone, Debug, Serialize, Deserialize)]
405#[serde(rename_all = "camelCase")]
406pub struct BinanceFuturesMarkPrice {
407    /// Symbol name.
408    pub symbol: Ustr,
409    /// Mark price.
410    pub mark_price: String,
411    /// Index price.
412    #[serde(default)]
413    pub index_price: Option<String>,
414    /// Estimated settle price (only for delivery contracts).
415    #[serde(default)]
416    pub estimated_settle_price: Option<String>,
417    /// Last funding rate.
418    #[serde(default)]
419    pub last_funding_rate: Option<String>,
420    /// Next funding time.
421    #[serde(default)]
422    pub next_funding_time: Option<i64>,
423    /// Interest rate.
424    #[serde(default)]
425    pub interest_rate: Option<String>,
426    /// Timestamp.
427    pub time: i64,
428}
429
430/// Order book depth snapshot.
431#[derive(Clone, Debug, Serialize, Deserialize)]
432#[serde(rename_all = "camelCase")]
433pub struct BinanceOrderBook {
434    /// Last update ID.
435    pub last_update_id: i64,
436    /// Bid levels as `[price, quantity]` arrays.
437    pub bids: Vec<(String, String)>,
438    /// Ask levels as `[price, quantity]` arrays.
439    pub asks: Vec<(String, String)>,
440    /// Message output time.
441    #[serde(default, rename = "E")]
442    pub event_time: Option<i64>,
443    /// Transaction time.
444    #[serde(default, rename = "T")]
445    pub transaction_time: Option<i64>,
446}
447
448/// Best bid/ask from book ticker endpoint.
449#[derive(Clone, Debug, Serialize, Deserialize)]
450#[serde(rename_all = "camelCase")]
451pub struct BinanceBookTicker {
452    /// Symbol name.
453    pub symbol: Ustr,
454    /// Best bid price.
455    pub bid_price: String,
456    /// Best bid quantity.
457    pub bid_qty: String,
458    /// Best ask price.
459    pub ask_price: String,
460    /// Best ask quantity.
461    pub ask_qty: String,
462    /// Event time.
463    #[serde(default)]
464    pub time: Option<i64>,
465}
466
467/// Price ticker.
468#[derive(Clone, Debug, Serialize, Deserialize)]
469#[serde(rename_all = "camelCase")]
470pub struct BinancePriceTicker {
471    /// Symbol name.
472    pub symbol: Ustr,
473    /// Current price.
474    pub price: String,
475    /// Event time.
476    #[serde(default)]
477    pub time: Option<i64>,
478}
479
480/// Funding rate history record.
481#[derive(Clone, Debug, Serialize, Deserialize)]
482#[serde(rename_all = "camelCase")]
483pub struct BinanceFundingRate {
484    /// Symbol name.
485    pub symbol: Ustr,
486    /// Funding rate value.
487    pub funding_rate: String,
488    /// Funding time in milliseconds.
489    pub funding_time: i64,
490    /// Mark price at the funding time.
491    #[serde(default)]
492    pub mark_price: Option<String>,
493    /// Index price at the funding time.
494    #[serde(default)]
495    pub index_price: Option<String>,
496}
497
498/// Open interest record.
499#[derive(Clone, Debug, Serialize, Deserialize)]
500#[serde(rename_all = "camelCase")]
501pub struct BinanceOpenInterest {
502    /// Symbol name.
503    pub symbol: Ustr,
504    /// Total open interest.
505    pub open_interest: String,
506    /// Timestamp in milliseconds.
507    pub time: i64,
508}
509
510/// Historical open interest record from `GET /futures/data/openInterestHist`.
511#[derive(Clone, Debug, Serialize, Deserialize)]
512#[serde(rename_all = "camelCase")]
513pub struct BinanceOpenInterestHistRecord {
514    /// Symbol name for USD-M responses.
515    #[serde(default)]
516    pub symbol: Option<Ustr>,
517    /// Trading pair for COIN-M responses.
518    #[serde(default)]
519    pub pair: Option<Ustr>,
520    /// Contract type for COIN-M responses.
521    #[serde(default)]
522    pub contract_type: Option<String>,
523    /// Total open interest for the bucket.
524    pub sum_open_interest: String,
525    /// Total open interest notional value for the bucket.
526    pub sum_open_interest_value: String,
527    /// Bucket timestamp in milliseconds.
528    pub timestamp: i64,
529    /// USD-M-specific optional circulating supply field.
530    #[serde(default, rename = "CMCCirculatingSupply")]
531    pub cmc_circulating_supply: Option<String>,
532}
533
534/// Futures account balance entry.
535#[derive(Clone, Debug, Serialize, Deserialize)]
536#[serde(rename_all = "camelCase")]
537pub struct BinanceFuturesBalance {
538    /// Account alias (only USD-M).
539    #[serde(default)]
540    pub account_alias: Option<String>,
541    /// Asset code (e.g., "USDT").
542    pub asset: Ustr,
543    /// Wallet balance (v2 uses walletBalance, v1 uses balance).
544    #[serde(
545        alias = "balance",
546        deserialize_with = "deserialize_decimal_or_zero",
547        serialize_with = "serialize_decimal_as_str"
548    )]
549    pub wallet_balance: Decimal,
550    /// Unrealized profit.
551    #[serde(
552        default,
553        deserialize_with = "deserialize_optional_decimal_from_str",
554        serialize_with = "serialize_optional_decimal_as_str"
555    )]
556    pub unrealized_profit: Option<Decimal>,
557    /// Margin balance.
558    #[serde(
559        default,
560        deserialize_with = "deserialize_optional_decimal_from_str",
561        serialize_with = "serialize_optional_decimal_as_str"
562    )]
563    pub margin_balance: Option<Decimal>,
564    /// Maintenance margin required.
565    #[serde(
566        default,
567        deserialize_with = "deserialize_optional_decimal_from_str",
568        serialize_with = "serialize_optional_decimal_as_str"
569    )]
570    pub maint_margin: Option<Decimal>,
571    /// Initial margin required.
572    #[serde(
573        default,
574        deserialize_with = "deserialize_optional_decimal_from_str",
575        serialize_with = "serialize_optional_decimal_as_str"
576    )]
577    pub initial_margin: Option<Decimal>,
578    /// Position initial margin.
579    #[serde(
580        default,
581        deserialize_with = "deserialize_optional_decimal_from_str",
582        serialize_with = "serialize_optional_decimal_as_str"
583    )]
584    pub position_initial_margin: Option<Decimal>,
585    /// Open order initial margin.
586    #[serde(
587        default,
588        deserialize_with = "deserialize_optional_decimal_from_str",
589        serialize_with = "serialize_optional_decimal_as_str"
590    )]
591    pub open_order_initial_margin: Option<Decimal>,
592    /// Cross wallet balance.
593    #[serde(
594        default,
595        deserialize_with = "deserialize_optional_decimal_from_str",
596        serialize_with = "serialize_optional_decimal_as_str"
597    )]
598    pub cross_wallet_balance: Option<Decimal>,
599    /// Unrealized PnL for cross positions.
600    #[serde(
601        default,
602        deserialize_with = "deserialize_optional_decimal_from_str",
603        serialize_with = "serialize_optional_decimal_as_str"
604    )]
605    pub cross_un_pnl: Option<Decimal>,
606    /// Available balance.
607    #[serde(
608        deserialize_with = "deserialize_decimal_or_zero",
609        serialize_with = "serialize_decimal_as_str"
610    )]
611    pub available_balance: Decimal,
612    /// Maximum withdrawable amount.
613    #[serde(
614        default,
615        deserialize_with = "deserialize_optional_decimal_from_str",
616        serialize_with = "serialize_optional_decimal_as_str"
617    )]
618    pub max_withdraw_amount: Option<Decimal>,
619    /// Whether margin trading is available.
620    #[serde(default)]
621    pub margin_available: Option<bool>,
622    /// Timestamp of last update in milliseconds.
623    pub update_time: i64,
624    /// Withdrawable amount (COIN-M specific).
625    #[serde(
626        default,
627        deserialize_with = "deserialize_optional_decimal_from_str",
628        serialize_with = "serialize_optional_decimal_as_str"
629    )]
630    pub withdraw_available: Option<Decimal>,
631}
632
633/// Account position from `GET /fapi/v2/account` positions array.
634#[derive(Clone, Debug, Serialize, Deserialize)]
635#[serde(rename_all = "camelCase")]
636pub struct BinanceAccountPosition {
637    /// Symbol name.
638    pub symbol: Ustr,
639    /// Initial margin.
640    #[serde(default)]
641    pub initial_margin: Option<String>,
642    /// Maintenance margin.
643    #[serde(default)]
644    pub maint_margin: Option<String>,
645    /// Unrealized profit.
646    #[serde(default)]
647    pub unrealized_profit: Option<String>,
648    /// Position initial margin.
649    #[serde(default)]
650    pub position_initial_margin: Option<String>,
651    /// Open order initial margin.
652    #[serde(default)]
653    pub open_order_initial_margin: Option<String>,
654    /// Leverage.
655    #[serde(default)]
656    pub leverage: Option<String>,
657    /// Isolated margin mode.
658    #[serde(default)]
659    pub isolated: Option<bool>,
660    /// Entry price.
661    #[serde(default)]
662    pub entry_price: Option<String>,
663    /// Max notional value.
664    #[serde(default)]
665    pub max_notional: Option<String>,
666    /// Bid notional.
667    #[serde(default)]
668    pub bid_notional: Option<String>,
669    /// Ask notional.
670    #[serde(default)]
671    pub ask_notional: Option<String>,
672    /// Position side (BOTH, LONG, SHORT).
673    #[serde(default)]
674    pub position_side: Option<BinancePositionSide>,
675    /// Position amount.
676    #[serde(default)]
677    pub position_amt: Option<String>,
678    /// Update time.
679    #[serde(default)]
680    pub update_time: Option<i64>,
681}
682
683/// Position risk from `GET /fapi/v2/positionRisk`.
684#[derive(Clone, Debug, Serialize, Deserialize)]
685#[serde(rename_all = "camelCase")]
686pub struct BinancePositionRisk {
687    /// Symbol name.
688    pub symbol: Ustr,
689    /// Position quantity.
690    pub position_amt: String,
691    /// Entry price.
692    pub entry_price: String,
693    /// Mark price.
694    pub mark_price: String,
695    /// Unrealized profit and loss.
696    #[serde(default)]
697    pub un_realized_profit: Option<String>,
698    /// Liquidation price.
699    #[serde(default)]
700    pub liquidation_price: Option<String>,
701    /// Applied leverage.
702    pub leverage: String,
703    /// Max notional value.
704    #[serde(default)]
705    pub max_notional_value: Option<String>,
706    /// Margin type (CROSSED or ISOLATED).
707    #[serde(default)]
708    pub margin_type: Option<BinanceMarginType>,
709    /// Isolated margin amount.
710    #[serde(default)]
711    pub isolated_margin: Option<String>,
712    /// Auto add margin flag (as string from API).
713    #[serde(default)]
714    pub is_auto_add_margin: Option<String>,
715    /// Position side (BOTH, LONG, SHORT).
716    #[serde(default)]
717    pub position_side: Option<BinancePositionSide>,
718    /// Notional position value.
719    #[serde(default)]
720    pub notional: Option<String>,
721    /// Isolated wallet balance.
722    #[serde(default)]
723    pub isolated_wallet: Option<String>,
724    /// ADL quantile indicator.
725    #[serde(default)]
726    pub adl_quantile: Option<u8>,
727    /// Last update time.
728    #[serde(default)]
729    pub update_time: Option<i64>,
730    /// Break-even price.
731    #[serde(default)]
732    pub break_even_price: Option<String>,
733    /// Bankruptcy price.
734    #[serde(default)]
735    pub bust_price: Option<String>,
736}
737
738/// Income history record.
739#[derive(Clone, Debug, Serialize, Deserialize)]
740#[serde(rename_all = "camelCase")]
741pub struct BinanceIncomeRecord {
742    /// Symbol name (may be empty for transfers).
743    #[serde(default)]
744    pub symbol: Option<Ustr>,
745    /// Income type (e.g., FUNDING_FEE, COMMISSION).
746    pub income_type: BinanceIncomeType,
747    /// Income amount.
748    pub income: String,
749    /// Asset code.
750    pub asset: Ustr,
751    /// Event time in milliseconds.
752    pub time: i64,
753    /// Additional info field.
754    #[serde(default)]
755    pub info: Option<String>,
756    /// Transaction ID.
757    #[serde(default)]
758    pub tran_id: Option<i64>,
759    /// Related trade ID.
760    #[serde(default)]
761    pub trade_id: Option<i64>,
762}
763
764/// User trade record.
765#[derive(Clone, Debug, Serialize, Deserialize)]
766#[serde(rename_all = "camelCase")]
767pub struct BinanceUserTrade {
768    /// Symbol name.
769    pub symbol: Ustr,
770    /// Trade ID.
771    pub id: i64,
772    /// Order ID.
773    pub order_id: i64,
774    /// Trade price.
775    pub price: String,
776    /// Executed quantity.
777    pub qty: String,
778    /// Quote quantity.
779    #[serde(default)]
780    pub quote_qty: Option<String>,
781    /// Realized PnL for the trade.
782    pub realized_pnl: String,
783    /// Buy/sell side.
784    pub side: BinanceSide,
785    /// Position side (BOTH, LONG, SHORT).
786    #[serde(default)]
787    pub position_side: Option<BinancePositionSide>,
788    /// Trade time in milliseconds.
789    pub time: i64,
790    /// Was the buyer the maker?
791    pub buyer: bool,
792    /// Was the trade maker liquidity?
793    pub maker: bool,
794    /// Commission paid.
795    #[serde(default)]
796    pub commission: Option<String>,
797    /// Commission asset.
798    #[serde(default)]
799    pub commission_asset: Option<Ustr>,
800    /// Margin asset (if provided).
801    #[serde(default)]
802    pub margin_asset: Option<Ustr>,
803}
804
805/// Futures account information from `GET /fapi/v2/account` or `GET /dapi/v1/account`.
806#[derive(Clone, Debug, Serialize, Deserialize)]
807#[serde(rename_all = "camelCase")]
808pub struct BinanceFuturesAccountInfo {
809    /// Futures VIP fee tier.
810    #[serde(default)]
811    pub fee_tier: u8,
812    /// Total initial margin required.
813    #[serde(
814        default,
815        deserialize_with = "deserialize_optional_decimal_from_str",
816        serialize_with = "serialize_optional_decimal_as_str"
817    )]
818    pub total_initial_margin: Option<Decimal>,
819    /// Total maintenance margin required.
820    #[serde(
821        default,
822        deserialize_with = "deserialize_optional_decimal_from_str",
823        serialize_with = "serialize_optional_decimal_as_str"
824    )]
825    pub total_maint_margin: Option<Decimal>,
826    /// Total wallet balance.
827    #[serde(
828        default,
829        deserialize_with = "deserialize_optional_decimal_from_str",
830        serialize_with = "serialize_optional_decimal_as_str"
831    )]
832    pub total_wallet_balance: Option<Decimal>,
833    /// Total unrealized profit.
834    #[serde(
835        default,
836        deserialize_with = "deserialize_optional_decimal_from_str",
837        serialize_with = "serialize_optional_decimal_as_str"
838    )]
839    pub total_unrealized_profit: Option<Decimal>,
840    /// Total margin balance.
841    #[serde(
842        default,
843        deserialize_with = "deserialize_optional_decimal_from_str",
844        serialize_with = "serialize_optional_decimal_as_str"
845    )]
846    pub total_margin_balance: Option<Decimal>,
847    /// Total position initial margin.
848    #[serde(
849        default,
850        deserialize_with = "deserialize_optional_decimal_from_str",
851        serialize_with = "serialize_optional_decimal_as_str"
852    )]
853    pub total_position_initial_margin: Option<Decimal>,
854    /// Total open order initial margin.
855    #[serde(
856        default,
857        deserialize_with = "deserialize_optional_decimal_from_str",
858        serialize_with = "serialize_optional_decimal_as_str"
859    )]
860    pub total_open_order_initial_margin: Option<Decimal>,
861    /// Total cross wallet balance.
862    #[serde(
863        default,
864        deserialize_with = "deserialize_optional_decimal_from_str",
865        serialize_with = "serialize_optional_decimal_as_str"
866    )]
867    pub total_cross_wallet_balance: Option<Decimal>,
868    /// Total cross unrealized PnL.
869    #[serde(
870        default,
871        deserialize_with = "deserialize_optional_decimal_from_str",
872        serialize_with = "serialize_optional_decimal_as_str"
873    )]
874    pub total_cross_un_pnl: Option<Decimal>,
875    /// Available balance.
876    #[serde(
877        default,
878        deserialize_with = "deserialize_optional_decimal_from_str",
879        serialize_with = "serialize_optional_decimal_as_str"
880    )]
881    pub available_balance: Option<Decimal>,
882    /// Max withdraw amount.
883    #[serde(
884        default,
885        deserialize_with = "deserialize_optional_decimal_from_str",
886        serialize_with = "serialize_optional_decimal_as_str"
887    )]
888    pub max_withdraw_amount: Option<Decimal>,
889    /// Can deposit.
890    #[serde(default)]
891    pub can_deposit: Option<bool>,
892    /// Can trade.
893    #[serde(default)]
894    pub can_trade: Option<bool>,
895    /// Can withdraw.
896    #[serde(default)]
897    pub can_withdraw: Option<bool>,
898    /// Multi-assets margin mode.
899    #[serde(default)]
900    pub multi_assets_margin: Option<bool>,
901    /// Update time.
902    #[serde(default)]
903    pub update_time: Option<i64>,
904    /// Account balances.
905    #[serde(default)]
906    pub assets: Vec<BinanceFuturesBalance>,
907    /// Account positions.
908    #[serde(default)]
909    pub positions: Vec<BinanceAccountPosition>,
910}
911
912/// Account-specific Futures commission rates for one symbol.
913#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
914#[serde(rename_all = "camelCase")]
915pub struct BinanceFuturesCommissionRate {
916    /// Venue symbol.
917    pub symbol: Ustr,
918    /// Maker commission rate.
919    pub maker_commission_rate: String,
920    /// Taker commission rate.
921    pub taker_commission_rate: String,
922}
923
924impl BinanceFuturesAccountInfo {
925    /// Converts this Binance account info to a Nautilus [`AccountState`].
926    ///
927    /// # Errors
928    ///
929    /// Returns an error if balance parsing fails.
930    pub fn to_account_state(
931        &self,
932        account_id: AccountId,
933        ts_init: UnixNanos,
934    ) -> anyhow::Result<AccountState> {
935        let mut balances = Vec::with_capacity(self.assets.len());
936
937        for asset in &self.assets {
938            let currency = Currency::get_or_create_crypto_with_context(
939                asset.asset.as_str(),
940                Some("futures balance"),
941            );
942
943            let balance = AccountBalance::from_total_and_free(
944                asset.wallet_balance,
945                asset.available_balance,
946                currency,
947            )
948            .context("failed to build account balance")?;
949            balances.push(balance);
950        }
951
952        // Ensure at least one balance exists
953        if balances.is_empty() {
954            let zero_currency = Currency::USDT();
955            let zero_money = Money::zero(zero_currency);
956            let zero_balance = AccountBalance::new(zero_money, zero_money, zero_money);
957            balances.push(zero_balance);
958        }
959
960        // Emit account-wide (cross-margin) margin balances per collateral asset.
961        // Binance reports per-asset `initialMargin` / `maintMargin` which covers both
962        // USDT-M (single collateral, typically USDT or BNB under multi-assets mode) and
963        // COIN-M (one entry per base coin, e.g. BTC / ETH).
964        let mut margins = Vec::new();
965
966        for asset in &self.assets {
967            let initial_dec = asset.initial_margin.unwrap_or_default();
968            let maint_dec = asset.maint_margin.unwrap_or_default();
969
970            if initial_dec.is_zero() && maint_dec.is_zero() {
971                continue;
972            }
973
974            let currency = Currency::get_or_create_crypto_with_context(
975                asset.asset.as_str(),
976                Some("futures margin"),
977            );
978            let initial = Money::from_decimal(initial_dec, currency)
979                .unwrap_or_else(|_| Money::zero(currency));
980            let maintenance =
981                Money::from_decimal(maint_dec, currency).unwrap_or_else(|_| Money::zero(currency));
982            margins.push(MarginBalance::new(initial, maintenance, None));
983        }
984
985        let ts_event = self
986            .update_time
987            .map(|value| parse_millis(value, "Futures account update time"))
988            .transpose()?
989            .unwrap_or(ts_init);
990
991        Ok(AccountState::new(
992            account_id,
993            AccountType::Margin,
994            balances,
995            margins,
996            true, // is_reported
997            UUID4::new(),
998            ts_event,
999            ts_init,
1000            None,
1001        ))
1002    }
1003}
1004
1005/// Hedge mode (dual side position) response.
1006#[derive(Clone, Debug, Serialize, Deserialize)]
1007#[serde(rename_all = "camelCase")]
1008pub struct BinanceHedgeModeResponse {
1009    /// Whether dual side position mode is enabled.
1010    pub dual_side_position: bool,
1011}
1012
1013/// Leverage change response.
1014#[derive(Clone, Debug, Serialize, Deserialize)]
1015#[serde(rename_all = "camelCase")]
1016pub struct BinanceLeverageResponse {
1017    /// Symbol.
1018    pub symbol: Ustr,
1019    /// New leverage value.
1020    pub leverage: u32,
1021    /// Max notional value at this leverage.
1022    #[serde(default)]
1023    pub max_notional_value: Option<String>,
1024}
1025
1026/// Cancel all orders response.
1027#[derive(Clone, Debug, Serialize, Deserialize)]
1028#[serde(rename_all = "camelCase")]
1029pub struct BinanceCancelAllOrdersResponse {
1030    /// Response code (200 = success).
1031    pub code: i32,
1032    /// Response message.
1033    pub msg: String,
1034}
1035
1036/// Futures order information.
1037#[derive(Clone, Debug, Serialize, Deserialize)]
1038#[serde(rename_all = "camelCase")]
1039pub struct BinanceFuturesOrder {
1040    /// Symbol name.
1041    pub symbol: Ustr,
1042    /// Order ID.
1043    pub order_id: i64,
1044    /// Client order ID.
1045    pub client_order_id: String,
1046    /// Original order quantity.
1047    pub orig_qty: String,
1048    /// Executed quantity.
1049    pub executed_qty: String,
1050    /// Cumulative quote asset transacted.
1051    #[serde(default = "zero_decimal_string")]
1052    pub cum_quote: String,
1053    /// Original limit price.
1054    pub price: String,
1055    /// Average execution price.
1056    #[serde(default)]
1057    pub avg_price: Option<String>,
1058    /// Stop price.
1059    #[serde(default)]
1060    pub stop_price: Option<String>,
1061    /// Order status.
1062    pub status: BinanceOrderStatus,
1063    /// Time in force.
1064    pub time_in_force: BinanceTimeInForce,
1065    /// Order type.
1066    #[serde(rename = "type")]
1067    pub order_type: BinanceFuturesOrderType,
1068    /// Original order type.
1069    #[serde(default)]
1070    pub orig_type: Option<BinanceFuturesOrderType>,
1071    /// Order side (BUY/SELL).
1072    pub side: BinanceSide,
1073    /// Position side (BOTH/LONG/SHORT).
1074    #[serde(default)]
1075    pub position_side: Option<BinancePositionSide>,
1076    /// Reduce-only flag.
1077    #[serde(default)]
1078    pub reduce_only: Option<bool>,
1079    /// Close position flag (for stop orders).
1080    #[serde(default)]
1081    pub close_position: Option<bool>,
1082    /// Trailing delta activation price.
1083    #[serde(default)]
1084    pub activate_price: Option<String>,
1085    /// Trailing callback rate.
1086    #[serde(default)]
1087    pub price_rate: Option<String>,
1088    /// Working type (CONTRACT_PRICE or MARK_PRICE).
1089    #[serde(default)]
1090    pub working_type: Option<BinanceWorkingType>,
1091    /// Whether price protection is enabled.
1092    #[serde(default)]
1093    pub price_protect: Option<bool>,
1094    /// Whether order uses isolated margin.
1095    #[serde(default)]
1096    pub is_isolated: Option<bool>,
1097    /// Good till date (for GTD orders).
1098    #[serde(default)]
1099    pub good_till_date: Option<i64>,
1100    /// Price match mode.
1101    #[serde(default)]
1102    pub price_match: Option<BinancePriceMatch>,
1103    /// Self-trade prevention mode.
1104    #[serde(default)]
1105    pub self_trade_prevention_mode: Option<BinanceSelfTradePreventionMode>,
1106    /// Order creation time in milliseconds.
1107    #[serde(default)]
1108    pub time: Option<i64>,
1109    /// Last update time.
1110    #[serde(default)]
1111    pub update_time: Option<i64>,
1112    /// Working order ID for tracking.
1113    #[serde(default)]
1114    pub working_type_id: Option<i64>,
1115}
1116
1117fn zero_decimal_string() -> String {
1118    "0".to_string()
1119}
1120
1121impl BinanceFuturesOrder {
1122    /// Converts this Binance order to a Nautilus [`OrderStatusReport`].
1123    ///
1124    /// # Errors
1125    ///
1126    /// Returns an error if client order ID, quantity, or price parsing fails.
1127    pub fn to_order_status_report(
1128        &self,
1129        account_id: AccountId,
1130        instrument_id: InstrumentId,
1131        price_precision: u8,
1132        size_precision: u8,
1133        treat_expired_as_canceled: bool,
1134        ts_init: UnixNanos,
1135    ) -> anyhow::Result<OrderStatusReport> {
1136        let ts_event = self
1137            .update_time
1138            .map(|value| parse_millis(value, "Futures order update time"))
1139            .transpose()?
1140            .unwrap_or(ts_init);
1141        let ts_accepted = self
1142            .time
1143            .map(|value| parse_millis(value, "Futures order creation time"))
1144            .transpose()?
1145            .unwrap_or(ts_event);
1146
1147        let client_order_id =
1148            decode_client_order_id(&self.client_order_id, BINANCE_NAUTILUS_FUTURES_BROKER_ID)?;
1149        let venue_order_id = VenueOrderId::new(self.order_id.to_string());
1150
1151        let order_side = match self.side {
1152            BinanceSide::Buy => OrderSide::Buy,
1153            BinanceSide::Sell => OrderSide::Sell,
1154        };
1155
1156        let order_type = self.order_type.to_nautilus_order_type()?;
1157        let time_in_force = self.time_in_force.to_nautilus_time_in_force()?;
1158        let order_status = self
1159            .status
1160            .to_nautilus_order_status(treat_expired_as_canceled)?;
1161
1162        let quantity: Decimal = self.orig_qty.parse().context("invalid orig_qty")?;
1163        let filled_qty: Decimal = self.executed_qty.parse().context("invalid executed_qty")?;
1164        let price = if self.price.is_empty() {
1165            None
1166        } else {
1167            let price: Decimal = self.price.parse().context("invalid price")?;
1168            if price == Decimal::ZERO {
1169                None
1170            } else {
1171                Some(
1172                    Price::from_decimal_dp(price, price_precision)
1173                        .context("invalid price precision")?,
1174                )
1175            }
1176        };
1177        let avg_px = parse_avg_px(self.avg_price.as_deref(), filled_qty, price_precision)?;
1178
1179        let mut report = OrderStatusReport::new(
1180            account_id,
1181            instrument_id,
1182            Some(client_order_id),
1183            venue_order_id,
1184            order_side.into(),
1185            order_type,
1186            time_in_force,
1187            order_status,
1188            Quantity::from_decimal_dp(quantity, size_precision)
1189                .context("invalid orig_qty precision")?,
1190            Quantity::from_decimal_dp(filled_qty, size_precision)
1191                .context("invalid executed_qty precision")?,
1192            ts_accepted,
1193            ts_event,
1194            ts_init,
1195            Some(UUID4::new()),
1196        );
1197
1198        report.post_only = self.order_type == BinanceFuturesOrderType::Limit
1199            && matches!(
1200                self.time_in_force,
1201                BinanceTimeInForce::Gtx | BinanceTimeInForce::Rpi
1202            );
1203
1204        if let Some(price) = price {
1205            report = report.with_price(price);
1206        }
1207
1208        if let Some(expire_time) = parse_good_till_date(self.good_till_date)? {
1209            report = report.with_expire_time(expire_time);
1210        }
1211
1212        report.avg_px = avg_px;
1213
1214        Ok(report)
1215    }
1216}
1217
1218impl BinanceFuturesOrderType {
1219    /// Returns whether this order type is post-only.
1220    #[must_use]
1221    pub fn is_post_only(&self) -> bool {
1222        false // Binance Futures doesn't have a dedicated post-only type
1223    }
1224
1225    /// Converts to Nautilus order type.
1226    ///
1227    /// # Errors
1228    ///
1229    /// Returns an error if the order type is unknown.
1230    pub fn to_nautilus_order_type(&self) -> anyhow::Result<OrderType> {
1231        (*self).try_into()
1232    }
1233}
1234
1235impl BinanceTimeInForce {
1236    /// Converts to Nautilus time in force.
1237    ///
1238    /// # Errors
1239    ///
1240    /// Returns an error if the time in force is unknown.
1241    pub fn to_nautilus_time_in_force(&self) -> anyhow::Result<TimeInForce> {
1242        Ok(match self {
1243            Self::Gtc | Self::GteGtc => TimeInForce::Gtc,
1244            Self::Ioc => TimeInForce::Ioc,
1245            Self::Fok => TimeInForce::Fok,
1246            Self::Gtx => TimeInForce::Gtc, // GTX is GTC with post-only
1247            Self::Gtd => TimeInForce::Gtd,
1248            Self::Rpi => TimeInForce::Gtc,
1249            Self::Unknown => anyhow::bail!("unknown Binance time in force"),
1250        })
1251    }
1252}
1253
1254impl BinanceOrderStatus {
1255    /// Converts to Nautilus order status.
1256    ///
1257    /// # Errors
1258    ///
1259    /// Returns an error if the order status is unknown.
1260    pub fn to_nautilus_order_status(
1261        &self,
1262        treat_expired_as_canceled: bool,
1263    ) -> anyhow::Result<OrderStatus> {
1264        Ok(match self {
1265            Self::New | Self::PendingNew => OrderStatus::Accepted,
1266            Self::PartiallyFilled => OrderStatus::PartiallyFilled,
1267            Self::Filled | Self::NewAdl | Self::NewInsurance => OrderStatus::Filled,
1268            Self::Canceled => OrderStatus::Canceled,
1269            Self::PendingCancel => OrderStatus::PendingCancel,
1270            Self::Rejected => OrderStatus::Rejected,
1271            Self::Expired | Self::ExpiredInMatch => {
1272                if treat_expired_as_canceled {
1273                    OrderStatus::Canceled
1274                } else {
1275                    OrderStatus::Expired
1276                }
1277            }
1278            Self::Unknown => anyhow::bail!("unknown Binance order status"),
1279        })
1280    }
1281}
1282
1283impl BinanceUserTrade {
1284    /// Converts this Binance trade to a Nautilus [`FillReport`].
1285    ///
1286    /// # Errors
1287    ///
1288    /// Returns an error if quantity or price parsing fails.
1289    pub fn to_fill_report(
1290        &self,
1291        account_id: AccountId,
1292        instrument_id: InstrumentId,
1293        price_precision: u8,
1294        size_precision: u8,
1295        bnfcr_currency: Currency,
1296        ts_init: UnixNanos,
1297    ) -> anyhow::Result<FillReport> {
1298        let ts_event = parse_millis(self.time, "Futures user trade time")?;
1299
1300        let venue_order_id = VenueOrderId::new(self.order_id.to_string());
1301        let trade_id = TradeId::new(self.id.to_string());
1302
1303        let order_side = match self.side {
1304            BinanceSide::Buy => OrderSide::Buy,
1305            BinanceSide::Sell => OrderSide::Sell,
1306        };
1307
1308        let liquidity_side = if self.maker {
1309            LiquiditySide::Maker
1310        } else {
1311            LiquiditySide::Taker
1312        };
1313
1314        let last_qty: Decimal = self.qty.parse().context("invalid qty")?;
1315        let last_px: Decimal = self.price.parse().context("invalid price")?;
1316
1317        let commission_currency = self
1318            .commission_asset
1319            .as_ref()
1320            .map_or(bnfcr_currency, |asset| {
1321                normalize_futures_asset(asset, bnfcr_currency)
1322            });
1323        let commission = match self.commission.as_ref() {
1324            Some(raw) => {
1325                let decimal = parse_required_decimal(raw, "commission")?;
1326                Money::from_decimal(decimal, commission_currency)?
1327            }
1328            None => Money::zero(commission_currency),
1329        };
1330
1331        Ok(FillReport::new(
1332            account_id,
1333            instrument_id,
1334            venue_order_id,
1335            trade_id,
1336            order_side,
1337            Quantity::from_decimal_dp(last_qty, size_precision).context("invalid qty precision")?,
1338            Price::from_decimal_dp(last_px, price_precision).context("invalid price precision")?,
1339            commission,
1340            liquidity_side,
1341            None, // client_order_id
1342            None, // venue_position_id
1343            ts_event,
1344            ts_init,
1345            Some(UUID4::new()),
1346        ))
1347    }
1348}
1349
1350/// Result of a single order in a batch operation.
1351///
1352/// Each item in a batch response can be either a success or an error.
1353#[derive(Clone, Debug, Deserialize)]
1354#[serde(untagged)]
1355pub enum BatchOrderResult {
1356    /// Successful order operation.
1357    Success(Box<BinanceFuturesOrder>),
1358    /// Failed order operation.
1359    Error(BatchOrderError),
1360}
1361
1362/// Error for an individual batch operation.
1363#[derive(Clone, Debug, Deserialize)]
1364pub struct BatchOrderError {
1365    /// Error code from Binance.
1366    pub code: i64,
1367    /// Error message.
1368    pub msg: String,
1369    /// Whether a local identity lookup prevented submitting this item.
1370    #[serde(skip)]
1371    pub not_sent: bool,
1372}
1373
1374/// Listen key response from user data stream endpoints.
1375#[derive(Debug, Clone, Deserialize, Zeroize, ZeroizeOnDrop)]
1376#[serde(rename_all = "camelCase")]
1377pub struct ListenKeyResponse {
1378    /// The listen key for WebSocket user data stream.
1379    pub listen_key: SecretString,
1380}
1381
1382impl ListenKeyResponse {
1383    /// Consumes the response and returns the listen key.
1384    #[must_use]
1385    pub fn into_listen_key(mut self) -> SecretString {
1386        std::mem::take(&mut self.listen_key)
1387    }
1388}
1389
1390/// Algo order response from Binance Futures Algo Service API.
1391///
1392/// Algo orders are conditional orders (STOP_MARKET, STOP_LIMIT, TAKE_PROFIT,
1393/// TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET) that are managed by Binance's
1394/// Algo Service rather than the traditional order matching engine.
1395///
1396/// # References
1397///
1398/// - <https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Algo-Order>
1399#[derive(Clone, Debug, Serialize, Deserialize)]
1400#[serde(rename_all = "camelCase")]
1401pub struct BinanceFuturesAlgoOrder {
1402    /// Unique algo order ID assigned by Binance.
1403    pub algo_id: i64,
1404    /// Client-specified algo order ID for idempotency.
1405    pub client_algo_id: String,
1406    /// Algo type (currently only `Conditional` is supported).
1407    pub algo_type: BinanceAlgoType,
1408    /// Order type (STOP_MARKET, STOP, TAKE_PROFIT, TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET).
1409    #[serde(rename = "orderType", alias = "type")]
1410    pub order_type: BinanceFuturesOrderType,
1411    /// Trading symbol.
1412    pub symbol: Ustr,
1413    /// Order side (BUY/SELL).
1414    pub side: BinanceSide,
1415    /// Position side (BOTH, LONG, SHORT).
1416    #[serde(default)]
1417    pub position_side: Option<BinancePositionSide>,
1418    /// Time in force.
1419    #[serde(default)]
1420    pub time_in_force: Option<BinanceTimeInForce>,
1421    /// Order quantity.
1422    #[serde(default)]
1423    pub quantity: Option<String>,
1424    /// Algo order status.
1425    #[serde(default)]
1426    pub algo_status: Option<BinanceAlgoStatus>,
1427    /// Trigger price for the conditional order.
1428    #[serde(default)]
1429    pub trigger_price: Option<String>,
1430    /// Limit price (for STOP/TAKE_PROFIT limit orders).
1431    #[serde(default)]
1432    pub price: Option<String>,
1433    /// Working type for trigger price calculation (CONTRACT_PRICE or MARK_PRICE).
1434    #[serde(default)]
1435    pub working_type: Option<BinanceWorkingType>,
1436    /// Close all position flag.
1437    #[serde(default)]
1438    pub close_position: Option<bool>,
1439    /// Price protection enabled.
1440    #[serde(default)]
1441    pub price_protect: Option<bool>,
1442    /// Reduce-only flag.
1443    #[serde(default)]
1444    pub reduce_only: Option<bool>,
1445    /// Activation price for TRAILING_STOP_MARKET orders.
1446    #[serde(default)]
1447    pub activate_price: Option<String>,
1448    /// Callback rate for TRAILING_STOP_MARKET orders (0.1 to 10, where 1 = 1%).
1449    #[serde(default)]
1450    pub callback_rate: Option<String>,
1451    /// Good till date in milliseconds.
1452    #[serde(default)]
1453    pub good_till_date: Option<i64>,
1454    /// Order creation time in milliseconds.
1455    #[serde(default)]
1456    pub create_time: Option<i64>,
1457    /// Last update time in milliseconds.
1458    #[serde(default)]
1459    pub update_time: Option<i64>,
1460    /// Trigger time in milliseconds (when the algo order triggered).
1461    #[serde(default)]
1462    pub trigger_time: Option<i64>,
1463    /// Order ID in matching engine (populated when algo order is triggered).
1464    #[serde(default)]
1465    pub actual_order_id: Option<String>,
1466    /// Executed quantity in matching engine (populated when algo order is triggered).
1467    #[serde(default, rename = "actualQty", alias = "executedQty")]
1468    pub executed_qty: Option<String>,
1469    /// Average fill price in matching engine (populated when algo order is triggered).
1470    #[serde(default, rename = "actualPrice", alias = "avgPrice")]
1471    pub avg_price: Option<String>,
1472}
1473
1474impl BinanceFuturesAlgoOrder {
1475    /// Converts this Binance algo order to a Nautilus [`OrderStatusReport`].
1476    ///
1477    /// # Errors
1478    ///
1479    /// Returns an error if client order ID, quantity, price, trigger, or trailing fields cannot be
1480    /// parsed.
1481    pub fn to_order_status_report(
1482        &self,
1483        account_id: AccountId,
1484        instrument_id: InstrumentId,
1485        price_precision: u8,
1486        size_precision: u8,
1487        ts_init: UnixNanos,
1488    ) -> anyhow::Result<OrderStatusReport> {
1489        let ts_event = self
1490            .update_time
1491            .or(self.create_time)
1492            .map(|value| parse_millis(value, "Futures algo order time"))
1493            .transpose()?
1494            .unwrap_or(ts_init);
1495        let ts_accepted = self
1496            .create_time
1497            .map(|value| parse_millis(value, "Futures algo order creation time"))
1498            .transpose()?
1499            .unwrap_or(ts_event);
1500
1501        let client_order_id =
1502            decode_client_order_id(&self.client_algo_id, BINANCE_NAUTILUS_FUTURES_BROKER_ID)?;
1503        let venue_order_id = self
1504            .actual_order_id
1505            .as_ref()
1506            .filter(|id| !id.is_empty())
1507            .map_or_else(
1508                || VenueOrderId::new(self.algo_id.to_string()),
1509                |id| VenueOrderId::new(id.clone()),
1510            );
1511
1512        let order_side = match self.side {
1513            BinanceSide::Buy => OrderSide::Buy,
1514            BinanceSide::Sell => OrderSide::Sell,
1515        };
1516
1517        let order_type = self.order_type.to_nautilus_order_type()?;
1518        let time_in_force = self
1519            .time_in_force
1520            .as_ref()
1521            .map(BinanceTimeInForce::to_nautilus_time_in_force)
1522            .transpose()?
1523            .unwrap_or(TimeInForce::Gtc);
1524        let order_status = self.parse_order_status()?;
1525
1526        let quantity: Decimal = self
1527            .quantity
1528            .as_ref()
1529            .map_or(Ok(Decimal::ZERO), |q| q.parse())
1530            .context("invalid quantity")?;
1531        let filled_qty: Decimal = self
1532            .executed_qty
1533            .as_ref()
1534            .map_or(Ok(Decimal::ZERO), |q| q.parse())
1535            .context("invalid executed_qty")?;
1536        let price = if let Some(price) = self.price.as_ref().filter(|price| !price.is_empty()) {
1537            let price: Decimal = price.parse().context("invalid price")?;
1538            if price == Decimal::ZERO {
1539                None
1540            } else {
1541                Some(
1542                    Price::from_decimal_dp(price, price_precision)
1543                        .context("invalid price precision")?,
1544                )
1545            }
1546        } else {
1547            None
1548        };
1549        let avg_px = parse_avg_px(self.avg_price.as_deref(), filled_qty, price_precision)?;
1550        let trigger_price = self.parse_trigger_price(price_precision)?;
1551        let trailing_offset = self.parse_trailing_offset()?;
1552
1553        let mut report = OrderStatusReport::new(
1554            account_id,
1555            instrument_id,
1556            Some(client_order_id),
1557            venue_order_id,
1558            order_side.into(),
1559            order_type,
1560            time_in_force,
1561            order_status,
1562            Quantity::from_decimal_dp(quantity, size_precision)
1563                .context("invalid quantity precision")?,
1564            Quantity::from_decimal_dp(filled_qty, size_precision)
1565                .context("invalid executed_qty precision")?,
1566            ts_accepted,
1567            ts_event,
1568            ts_init,
1569            Some(UUID4::new()),
1570        );
1571
1572        if let Some(price) = price {
1573            report = report.with_price(price);
1574        }
1575
1576        report.avg_px = avg_px;
1577
1578        if let Some(trigger_price) = trigger_price {
1579            report = report
1580                .with_trigger_price(trigger_price)
1581                .with_trigger_type(parse_working_type(self.working_type));
1582        }
1583
1584        if let Some(trailing_offset) = trailing_offset {
1585            report = report
1586                .with_trailing_offset(trailing_offset)
1587                .with_trailing_offset_type(TrailingOffsetType::BasisPoints);
1588        }
1589
1590        if let Some(activation_price) = self
1591            .activate_price
1592            .as_deref()
1593            .map(|price| {
1594                parse_positive_price_at_precision(price, price_precision, "activate_price")
1595            })
1596            .transpose()?
1597            .flatten()
1598        {
1599            report = report.with_activation_price(activation_price);
1600        }
1601
1602        if self.reduce_only == Some(true) || self.close_position == Some(true) {
1603            report = report.with_reduce_only(true);
1604        }
1605
1606        if let Some(expire_time) = parse_good_till_date(self.good_till_date)? {
1607            report = report.with_expire_time(expire_time);
1608        }
1609
1610        if let Some(trigger_time) = self.trigger_time {
1611            report =
1612                report.with_ts_triggered(parse_millis(trigger_time, "Futures algo trigger time")?);
1613        }
1614
1615        Ok(report)
1616    }
1617
1618    /// Converts this algo order to a report enriched with matching-engine execution details.
1619    ///
1620    /// The algo order remains the source of client identity and conditional-order metadata.
1621    /// The matching-engine order is authoritative for status, quantity, fills, average price,
1622    /// venue order identity, and the last update time.
1623    ///
1624    /// # Errors
1625    ///
1626    /// Returns an error if the matching-engine order does not match this algo order or either
1627    /// response contains invalid report data.
1628    #[expect(clippy::too_many_arguments)]
1629    pub fn to_order_status_report_with_actual(
1630        &self,
1631        actual: &BinanceFuturesOrder,
1632        account_id: AccountId,
1633        instrument_id: InstrumentId,
1634        price_precision: u8,
1635        size_precision: u8,
1636        treat_expired_as_canceled: bool,
1637        ts_init: UnixNanos,
1638    ) -> anyhow::Result<OrderStatusReport> {
1639        let expected_actual_order_id = self
1640            .actual_order_id
1641            .as_deref()
1642            .filter(|id| !id.is_empty())
1643            .context("algo order has no actual_order_id")?;
1644
1645        if expected_actual_order_id != actual.order_id.to_string() {
1646            anyhow::bail!(
1647                "actual order ID mismatch: expected {expected_actual_order_id}, was {}",
1648                actual.order_id
1649            );
1650        }
1651
1652        if self.symbol != actual.symbol {
1653            anyhow::bail!(
1654                "actual order symbol mismatch: expected {}, was {}",
1655                self.symbol,
1656                actual.symbol
1657            );
1658        }
1659
1660        if self.side != actual.side {
1661            anyhow::bail!(
1662                "actual order side mismatch: expected {:?}, was {:?}",
1663                self.side,
1664                actual.side
1665            );
1666        }
1667
1668        let mut report = self.to_order_status_report(
1669            account_id,
1670            instrument_id,
1671            price_precision,
1672            size_precision,
1673            ts_init,
1674        )?;
1675        let actual_report = actual.to_order_status_report(
1676            account_id,
1677            instrument_id,
1678            price_precision,
1679            size_precision,
1680            treat_expired_as_canceled,
1681            ts_init,
1682        )?;
1683        report.venue_order_id = actual_report.venue_order_id;
1684        report.order_status = actual_report.order_status;
1685        report.quantity = actual_report.quantity;
1686        report.filled_qty = actual_report.filled_qty;
1687        report.avg_px = actual_report.avg_px.or(report.avg_px);
1688        report.expire_time = report.expire_time.or(actual_report.expire_time);
1689        report.ts_last = actual_report.ts_last;
1690
1691        Ok(report)
1692    }
1693
1694    fn parse_trigger_price(&self, price_precision: u8) -> anyhow::Result<Option<Price>> {
1695        let raw_trigger_price = match self.order_type {
1696            BinanceFuturesOrderType::TrailingStopMarket => self
1697                .trigger_price
1698                .as_deref()
1699                .or(self.activate_price.as_deref()),
1700            _ => self.trigger_price.as_deref(),
1701        };
1702        let trigger_price = raw_trigger_price
1703            .map(|price| parse_positive_price_at_precision(price, price_precision, "trigger_price"))
1704            .transpose()?
1705            .flatten();
1706
1707        if trigger_price.is_none() && requires_algo_trigger_price(self.order_type) {
1708            anyhow::bail!(
1709                "missing positive trigger_price for Binance algo order type {:?}",
1710                self.order_type
1711            );
1712        }
1713
1714        Ok(trigger_price)
1715    }
1716
1717    fn parse_trailing_offset(&self) -> anyhow::Result<Option<Decimal>> {
1718        if self.order_type != BinanceFuturesOrderType::TrailingStopMarket {
1719            return Ok(None);
1720        }
1721
1722        self.callback_rate
1723            .as_deref()
1724            .map(parse_callback_rate_basis_points)
1725            .transpose()
1726            .map(Option::flatten)
1727    }
1728
1729    fn parse_order_status(&self) -> anyhow::Result<OrderStatus> {
1730        Ok(match self.algo_status {
1731            Some(BinanceAlgoStatus::New) => OrderStatus::Accepted,
1732            Some(BinanceAlgoStatus::Triggering) => OrderStatus::Accepted,
1733            Some(BinanceAlgoStatus::Triggered) => self
1734                .executed_qty
1735                .as_deref()
1736                .and_then(|qty| qty.parse::<Decimal>().ok())
1737                .filter(|qty| *qty > Decimal::ZERO)
1738                .map_or(OrderStatus::Accepted, |_| OrderStatus::PartiallyFilled),
1739            Some(BinanceAlgoStatus::Finished) => {
1740                let executed_qty = self
1741                    .executed_qty
1742                    .as_deref()
1743                    .and_then(|qty| qty.parse::<Decimal>().ok());
1744                let quantity = self
1745                    .quantity
1746                    .as_deref()
1747                    .and_then(|qty| qty.parse::<Decimal>().ok());
1748                match (executed_qty, quantity) {
1749                    (Some(actual), Some(total)) if total > Decimal::ZERO && actual >= total => {
1750                        OrderStatus::Filled
1751                    }
1752                    _ => OrderStatus::Canceled,
1753                }
1754            }
1755            Some(BinanceAlgoStatus::Canceled) => OrderStatus::Canceled,
1756            Some(BinanceAlgoStatus::Expired) => OrderStatus::Expired,
1757            Some(BinanceAlgoStatus::Rejected) => OrderStatus::Rejected,
1758            Some(BinanceAlgoStatus::Unknown) => anyhow::bail!("unknown Binance algo order status"),
1759            None => OrderStatus::Initialized,
1760        })
1761    }
1762}
1763
1764fn parse_avg_px(
1765    raw: Option<&str>,
1766    filled_qty: Decimal,
1767    price_precision: u8,
1768) -> anyhow::Result<Option<Decimal>> {
1769    if filled_qty <= Decimal::ZERO {
1770        return Ok(None);
1771    }
1772
1773    raw.filter(|price| !price.is_empty())
1774        .map(|price| parse_positive_price_at_precision(price, price_precision, "avg_price"))
1775        .transpose()
1776        .map(|price| price.flatten().map(|price| price.as_decimal()))
1777}
1778
1779fn parse_positive_price_at_precision(
1780    raw: &str,
1781    precision: u8,
1782    field: &str,
1783) -> anyhow::Result<Option<Price>> {
1784    let decimal = parse_required_decimal(raw, field)?;
1785    if decimal <= Decimal::ZERO {
1786        return Ok(None);
1787    }
1788
1789    Price::from_decimal_dp(decimal, precision)
1790        .map(Some)
1791        .map_err(|e| anyhow::anyhow!("invalid {field} precision: {e}"))
1792}
1793
1794fn parse_callback_rate_basis_points(raw: &str) -> anyhow::Result<Option<Decimal>> {
1795    let rate = parse_required_decimal(raw, "callback_rate")?;
1796    if rate <= Decimal::ZERO {
1797        return Ok(None);
1798    }
1799
1800    rate.checked_mul(Decimal::from(100))
1801        .map(Some)
1802        .ok_or_else(|| anyhow::anyhow!("invalid callback_rate='{raw}': multiplication overflow"))
1803}
1804
1805fn parse_working_type(working_type: Option<BinanceWorkingType>) -> TriggerType {
1806    match working_type {
1807        Some(BinanceWorkingType::ContractPrice) => TriggerType::LastPrice,
1808        Some(BinanceWorkingType::MarkPrice) => TriggerType::MarkPrice,
1809        Some(BinanceWorkingType::Unknown) | None => TriggerType::Default,
1810    }
1811}
1812
1813fn requires_algo_trigger_price(order_type: BinanceFuturesOrderType) -> bool {
1814    matches!(
1815        order_type,
1816        BinanceFuturesOrderType::Stop
1817            | BinanceFuturesOrderType::StopMarket
1818            | BinanceFuturesOrderType::TakeProfit
1819            | BinanceFuturesOrderType::TakeProfitMarket
1820            | BinanceFuturesOrderType::TrailingStopMarket
1821    )
1822}
1823
1824/// Cancel response for algo orders from Binance Futures Algo Service API.
1825#[derive(Clone, Debug, Deserialize)]
1826#[serde(rename_all = "camelCase")]
1827pub struct BinanceFuturesAlgoOrderCancelResponse {
1828    /// Algo order ID that was canceled.
1829    pub algo_id: i64,
1830    /// Client algo order ID.
1831    pub client_algo_id: String,
1832    /// Response code (200 for success).
1833    pub code: String,
1834    /// Response message.
1835    pub msg: String,
1836}
1837
1838#[cfg(test)]
1839mod tests {
1840    use nautilus_model::identifiers::ClientOrderId;
1841    use rstest::rstest;
1842    use rust_decimal_macros::dec;
1843    use zeroize::Zeroize;
1844
1845    use super::*;
1846    use crate::common::testing::load_fixture_string;
1847
1848    #[rstest]
1849    fn test_batch_error_cannot_deserialize_local_send_provenance(
1850        #[values(false, true)] include_not_sent: bool,
1851    ) {
1852        let mut value = serde_json::json!({"code": -2011, "msg": "Unknown order"});
1853        if include_not_sent {
1854            value["not_sent"] = true.into();
1855        }
1856
1857        let error: BatchOrderError = serde_json::from_value(value).unwrap();
1858
1859        assert_eq!(error.code, -2011);
1860        assert_eq!(error.msg, "Unknown order");
1861        assert!(!error.not_sent);
1862    }
1863
1864    fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
1865
1866    #[rstest]
1867    fn test_unknown_order_enums_reject_conversion() {
1868        assert_eq!(
1869            BinanceFuturesOrderType::Unknown
1870                .to_nautilus_order_type()
1871                .unwrap_err()
1872                .to_string(),
1873            "unknown Binance Futures order type",
1874        );
1875        assert_eq!(
1876            BinanceTimeInForce::Unknown
1877                .to_nautilus_time_in_force()
1878                .unwrap_err()
1879                .to_string(),
1880            "unknown Binance time in force",
1881        );
1882        assert_eq!(
1883            BinanceOrderStatus::Unknown
1884                .to_nautilus_order_status(false)
1885                .unwrap_err()
1886                .to_string(),
1887            "unknown Binance order status",
1888        );
1889    }
1890
1891    #[rstest]
1892    fn test_parse_account_info_v2() {
1893        let json = load_fixture_string("futures/http_json/account_info_v2.json");
1894        let account: BinanceFuturesAccountInfo =
1895            serde_json::from_str(&json).expect("Failed to parse account info");
1896
1897        assert_eq!(
1898            account.total_wallet_balance,
1899            Some(Decimal::from_str_exact("23.72469206").unwrap())
1900        );
1901        assert_eq!(account.assets.len(), 1);
1902        assert_eq!(account.assets[0].asset.as_str(), "USDT");
1903        assert_eq!(
1904            account.assets[0].wallet_balance,
1905            Decimal::from_str_exact("23.72469206").unwrap()
1906        );
1907        assert_eq!(account.positions.len(), 1);
1908        assert_eq!(account.positions[0].symbol.as_str(), "BTCUSDT");
1909        assert_eq!(account.positions[0].leverage, Some("100".to_string()));
1910    }
1911
1912    #[rstest]
1913    fn test_account_info_to_account_state_zero_margins() {
1914        let json = load_fixture_string("futures/http_json/account_info_v2.json");
1915        let account: BinanceFuturesAccountInfo =
1916            serde_json::from_str(&json).expect("Failed to parse account info");
1917
1918        let account_id = AccountId::from("BINANCE-001");
1919        let ts_init = UnixNanos::from(1_000_000_000u64);
1920        let state = account.to_account_state(account_id, ts_init).unwrap();
1921
1922        assert_eq!(state.account_id, account_id);
1923        assert_eq!(state.account_type, AccountType::Margin);
1924        assert!(!state.balances.is_empty());
1925        assert_eq!(state.margins.len(), 0);
1926    }
1927
1928    #[rstest]
1929    fn test_account_info_to_account_state_with_margins() {
1930        let json = r#"{
1931            "totalInitialMargin": "500.25000000",
1932            "totalMaintMargin": "250.75000000",
1933            "totalWalletBalance": "10000.00000000",
1934            "assets": [{
1935                "asset": "USDT",
1936                "walletBalance": "10000.00000000",
1937                "availableBalance": "9500.00000000",
1938                "initialMargin": "500.25000000",
1939                "maintMargin": "250.75000000",
1940                "updateTime": 1617939110373
1941            }],
1942            "positions": []
1943        }"#;
1944        let account: BinanceFuturesAccountInfo =
1945            serde_json::from_str(json).expect("Failed to parse account info");
1946
1947        let account_id = AccountId::from("BINANCE-001");
1948        let ts_init = UnixNanos::from(1_000_000_000u64);
1949        let state = account.to_account_state(account_id, ts_init).unwrap();
1950
1951        assert_eq!(state.margins.len(), 1);
1952        let margin = &state.margins[0];
1953        assert!(margin.instrument_id.is_none());
1954        assert_eq!(margin.currency.code, "USDT");
1955        assert_eq!(margin.initial.as_f64(), 500.25);
1956        assert_eq!(margin.maintenance.as_f64(), 250.75);
1957    }
1958
1959    #[rstest]
1960    fn test_account_info_to_account_state_coin_margined_per_base_coin() {
1961        let json = r#"{
1962            "totalWalletBalance": "0.00000000",
1963            "assets": [
1964                {
1965                    "asset": "BTC",
1966                    "walletBalance": "1.50000000",
1967                    "availableBalance": "1.40000000",
1968                    "initialMargin": "0.05000000",
1969                    "maintMargin": "0.02500000",
1970                    "updateTime": 1617939110373
1971                },
1972                {
1973                    "asset": "ETH",
1974                    "walletBalance": "10.00000000",
1975                    "availableBalance": "9.00000000",
1976                    "initialMargin": "0.80000000",
1977                    "maintMargin": "0.40000000",
1978                    "updateTime": 1617939110373
1979                }
1980            ],
1981            "positions": []
1982        }"#;
1983        let account: BinanceFuturesAccountInfo =
1984            serde_json::from_str(json).expect("Failed to parse account info");
1985
1986        let account_id = AccountId::from("BINANCE-001");
1987        let ts_init = UnixNanos::from(1_000_000_000u64);
1988        let state = account.to_account_state(account_id, ts_init).unwrap();
1989
1990        assert_eq!(state.margins.len(), 2);
1991        assert!(state.margins.iter().all(|m| m.instrument_id.is_none()));
1992        let btc = state
1993            .margins
1994            .iter()
1995            .find(|m| m.currency.code == "BTC")
1996            .expect("BTC margin missing");
1997        assert_eq!(btc.initial.as_f64(), 0.05);
1998        assert_eq!(btc.maintenance.as_f64(), 0.025);
1999        let eth = state
2000            .margins
2001            .iter()
2002            .find(|m| m.currency.code == "ETH")
2003            .expect("ETH margin missing");
2004        assert_eq!(eth.initial.as_f64(), 0.8);
2005        assert_eq!(eth.maintenance.as_f64(), 0.4);
2006    }
2007
2008    // Regression for the #3867 bug class: wire values with more decimal places
2009    // than the currency precision (USDT=8) previously tripped the
2010    // `total == locked + free` invariant when Money::new rounded each side
2011    // independently. The `from_total_and_free` constructor must keep the invariant.
2012    #[rstest]
2013    fn test_account_info_to_account_state_precision_drift() {
2014        let json = r#"{
2015            "assets": [{
2016                "asset": "USDT",
2017                "walletBalance": "10.000000034999",
2018                "availableBalance": "9.999999994999",
2019                "updateTime": 1617939110373
2020            }],
2021            "positions": []
2022        }"#;
2023        let account: BinanceFuturesAccountInfo =
2024            serde_json::from_str(json).expect("Failed to parse account info");
2025
2026        let account_id = AccountId::from("BINANCE-001");
2027        let ts_init = UnixNanos::from(1_000_000_000u64);
2028        let state = account.to_account_state(account_id, ts_init).unwrap();
2029
2030        assert_eq!(state.balances.len(), 1);
2031        let balance = &state.balances[0];
2032        assert_eq!(balance.total, balance.locked + balance.free);
2033    }
2034
2035    #[rstest]
2036    fn test_account_info_to_account_state_empty_balance() {
2037        // Empty strings for balance fields (inactive/zero-balance accounts)
2038        let json = r#"{
2039            "assets": [{
2040                "asset": "USDT",
2041                "walletBalance": "",
2042                "availableBalance": "",
2043                "updateTime": 0
2044            }],
2045            "positions": []
2046        }"#;
2047        let account: BinanceFuturesAccountInfo =
2048            serde_json::from_str(json).expect("Failed to parse account info");
2049
2050        let account_id = AccountId::from("BINANCE-001");
2051        let ts_init = UnixNanos::from(1_000_000_000u64);
2052        let state = account.to_account_state(account_id, ts_init).unwrap();
2053
2054        assert_eq!(state.balances.len(), 1);
2055        let balance = &state.balances[0];
2056        assert_eq!(balance.total, Money::new(0.0, Currency::USDT()));
2057        assert_eq!(balance.free, Money::new(0.0, Currency::USDT()));
2058        assert_eq!(balance.locked, Money::new(0.0, Currency::USDT()));
2059    }
2060
2061    #[rstest]
2062    fn test_account_info_to_account_state_empty_assets() {
2063        // No assets at all (completely empty account)
2064        let json = r#"{
2065            "assets": [],
2066            "positions": []
2067        }"#;
2068        let account: BinanceFuturesAccountInfo =
2069            serde_json::from_str(json).expect("Failed to parse account info");
2070
2071        let account_id = AccountId::from("BINANCE-001");
2072        let ts_init = UnixNanos::from(1_000_000_000u64);
2073        let state = account.to_account_state(account_id, ts_init).unwrap();
2074
2075        assert_eq!(state.balances.len(), 1);
2076        let balance = &state.balances[0];
2077        assert_eq!(balance.total, Money::new(0.0, Currency::USDT()));
2078    }
2079
2080    #[rstest]
2081    fn test_parse_position_risk() {
2082        let json = load_fixture_string("futures/http_json/position_risk.json");
2083        let positions: Vec<BinancePositionRisk> =
2084            serde_json::from_str(&json).expect("Failed to parse position risk");
2085
2086        assert_eq!(positions.len(), 1);
2087        assert_eq!(positions[0].symbol.as_str(), "BTCUSDT");
2088        assert_eq!(positions[0].position_amt, "0.001");
2089        assert_eq!(positions[0].mark_price, "51000.0");
2090        assert_eq!(positions[0].leverage, "20");
2091    }
2092
2093    #[rstest]
2094    fn test_parse_balance_with_v1_field() {
2095        // V1 uses 'balance' field
2096        let json = load_fixture_string("futures/http_json/balance.json");
2097        let balances: Vec<BinanceFuturesBalance> =
2098            serde_json::from_str(&json).expect("Failed to parse balance");
2099
2100        assert_eq!(balances.len(), 1);
2101        assert_eq!(balances[0].asset.as_str(), "USDT");
2102        // Uses alias to parse 'balance' into wallet_balance
2103        assert_eq!(
2104            balances[0].wallet_balance,
2105            Decimal::from_str_exact("122.12345678").unwrap()
2106        );
2107        assert_eq!(
2108            balances[0].available_balance,
2109            Decimal::from_str_exact("122.12345678").unwrap()
2110        );
2111    }
2112
2113    #[rstest]
2114    fn test_parse_balance_with_v2_field() {
2115        // V2 uses 'walletBalance' field
2116        let json = r#"{
2117            "asset": "USDT",
2118            "walletBalance": "100.00000000",
2119            "availableBalance": "100.00000000",
2120            "updateTime": 1617939110373
2121        }"#;
2122
2123        let balance: BinanceFuturesBalance =
2124            serde_json::from_str(json).expect("Failed to parse balance");
2125
2126        assert_eq!(balance.asset.as_str(), "USDT");
2127        assert_eq!(
2128            balance.wallet_balance,
2129            Decimal::from_str_exact("100.00000000").unwrap()
2130        );
2131    }
2132
2133    #[rstest]
2134    fn test_parse_order() {
2135        let json = load_fixture_string("futures/http_json/order_response.json");
2136        let order: BinanceFuturesOrder =
2137            serde_json::from_str(&json).expect("Failed to parse order");
2138
2139        assert_eq!(order.order_id, 12345678);
2140        assert_eq!(order.symbol.as_str(), "BTCUSDT");
2141        assert_eq!(order.status, BinanceOrderStatus::New);
2142        assert_eq!(order.time_in_force, BinanceTimeInForce::Gtc);
2143        assert_eq!(order.side, BinanceSide::Buy);
2144        assert_eq!(order.order_type, BinanceFuturesOrderType::Limit);
2145        assert_eq!(order.price_match, Some(BinancePriceMatch::None));
2146        assert_eq!(
2147            order.self_trade_prevention_mode,
2148            Some(BinanceSelfTradePreventionMode::None)
2149        );
2150    }
2151
2152    #[rstest]
2153    fn test_order_to_report_preserves_creation_time_before_fills() {
2154        let json = load_fixture_string("futures/http_json/order_partially_filled.json");
2155        let order: BinanceFuturesOrder = serde_json::from_str(&json).unwrap();
2156        let json = load_fixture_string("futures/http_json/order_partial_fills.json");
2157        let fills: Vec<BinanceUserTrade> = serde_json::from_str(&json).unwrap();
2158        let ts_init = UnixNanos::from_millis(1_790_409_080_000);
2159
2160        let report = order
2161            .to_order_status_report(
2162                AccountId::from("BINANCE-FUTURES-001"),
2163                InstrumentId::from("ETHUSDT-PERP.BINANCE"),
2164                2,
2165                3,
2166                false,
2167                ts_init,
2168            )
2169            .unwrap();
2170
2171        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
2172        assert_eq!(report.quantity, Quantity::from("0.010"));
2173        assert_eq!(report.filled_qty, Quantity::from("0.003"));
2174        assert_eq!(
2175            report.ts_accepted,
2176            UnixNanos::from_millis(1_790_409_068_078)
2177        );
2178        assert_eq!(report.ts_last, UnixNanos::from_millis(1_790_409_076_788));
2179        assert_eq!(report.ts_init, ts_init);
2180        assert_eq!(fills.len(), 2);
2181
2182        for fill in fills {
2183            assert_eq!(fill.order_id, order.order_id);
2184            assert_eq!(fill.symbol, order.symbol);
2185            let ts_fill = UnixNanos::from_millis_checked(fill.time).unwrap();
2186            assert!(report.ts_accepted < ts_fill);
2187            assert!(ts_fill < report.ts_last);
2188        }
2189    }
2190
2191    #[rstest]
2192    fn test_algo_order_to_report_preserves_creation_time() {
2193        let json = load_fixture_string("futures/http_json/algo_order_response.json");
2194        let order: BinanceFuturesAlgoOrder = serde_json::from_str(&json).unwrap();
2195        let ts_init = UnixNanos::from_millis(1_625_474_310_000);
2196
2197        let report = order
2198            .to_order_status_report(
2199                AccountId::from("BINANCE-FUTURES-001"),
2200                InstrumentId::from("BTCUSDT-PERP.BINANCE"),
2201                2,
2202                3,
2203                ts_init,
2204            )
2205            .unwrap();
2206
2207        assert_eq!(
2208            report.ts_accepted,
2209            UnixNanos::from_millis(1_625_474_304_765)
2210        );
2211        assert_eq!(report.ts_last, UnixNanos::from_millis(1_625_474_306_000));
2212        assert_eq!(report.ts_init, ts_init);
2213    }
2214
2215    #[rstest]
2216    #[case(Some(0), Some(2_000), 0, 2_000)]
2217    #[case(None, Some(2_000), 2_000, 2_000)]
2218    #[case(Some(1_000), None, 1_000, 9_000)]
2219    #[case(None, None, 9_000, 9_000)]
2220    fn test_order_to_report_timestamp_fallbacks(
2221        #[case] time: Option<i64>,
2222        #[case] update_time: Option<i64>,
2223        #[case] accepted_ms: u64,
2224        #[case] last_ms: u64,
2225    ) {
2226        let json = load_fixture_string("futures/http_json/order_response.json");
2227        let mut value: Value = serde_json::from_str(&json).unwrap();
2228        value.as_object_mut().unwrap().remove("time");
2229        if let Some(time) = time {
2230            value["time"] = time.into();
2231        }
2232
2233        value["updateTime"] = serde_json::to_value(update_time).unwrap();
2234        let order: BinanceFuturesOrder = serde_json::from_value(value).unwrap();
2235        let ts_init = UnixNanos::from_millis(9_000);
2236
2237        let report = order
2238            .to_order_status_report(
2239                AccountId::from("BINANCE-FUTURES-001"),
2240                InstrumentId::from("BTCUSDT-PERP.BINANCE"),
2241                2,
2242                3,
2243                false,
2244                ts_init,
2245            )
2246            .unwrap();
2247
2248        assert_eq!(report.ts_accepted, UnixNanos::from_millis(accepted_ms));
2249        assert_eq!(report.ts_last, UnixNanos::from_millis(last_ms));
2250        assert_eq!(report.ts_init, ts_init);
2251    }
2252
2253    #[rstest]
2254    #[case(Some(0), Some(2_000), 0, 2_000)]
2255    #[case(None, Some(2_000), 2_000, 2_000)]
2256    #[case(Some(1_000), None, 1_000, 1_000)]
2257    #[case(None, None, 9_000, 9_000)]
2258    fn test_algo_order_to_report_timestamp_fallbacks(
2259        #[case] create_time: Option<i64>,
2260        #[case] update_time: Option<i64>,
2261        #[case] accepted_ms: u64,
2262        #[case] last_ms: u64,
2263    ) {
2264        let mut order = algo_order_with_price(None);
2265        order.create_time = create_time;
2266        order.update_time = update_time;
2267        let ts_init = UnixNanos::from_millis(9_000);
2268
2269        let report = order
2270            .to_order_status_report(
2271                AccountId::from("BINANCE-FUTURES-001"),
2272                InstrumentId::from("BTCUSDT-PERP.BINANCE"),
2273                2,
2274                3,
2275                ts_init,
2276            )
2277            .unwrap();
2278
2279        assert_eq!(report.ts_accepted, UnixNanos::from_millis(accepted_ms));
2280        assert_eq!(report.ts_last, UnixNanos::from_millis(last_ms));
2281        assert_eq!(report.ts_init, ts_init);
2282    }
2283
2284    #[rstest]
2285    #[case(-1, "invalid negative Binance Futures order creation time timestamp: -1")]
2286    #[case(
2287        i64::MAX,
2288        "Binance Futures order creation time timestamp is outside the UnixNanos range: 9223372036854775807"
2289    )]
2290    fn test_order_to_report_rejects_invalid_creation_time(
2291        #[case] time: i64,
2292        #[case] expected_error: &str,
2293    ) {
2294        let mut order = order_with_price("50000.00");
2295        order.time = Some(time);
2296
2297        let result = order.to_order_status_report(
2298            AccountId::from("BINANCE-FUTURES-001"),
2299            InstrumentId::from("BTCUSDT-PERP.BINANCE"),
2300            2,
2301            3,
2302            false,
2303            UnixNanos::from_millis(9_000),
2304        );
2305
2306        assert_eq!(result.unwrap_err().to_string(), expected_error);
2307    }
2308
2309    #[rstest]
2310    #[case(-1, "invalid negative Binance Futures algo order creation time timestamp: -1")]
2311    #[case(
2312        i64::MAX,
2313        "Binance Futures algo order creation time timestamp is outside the UnixNanos range: 9223372036854775807"
2314    )]
2315    fn test_algo_order_to_report_rejects_invalid_creation_time(
2316        #[case] create_time: i64,
2317        #[case] expected_error: &str,
2318    ) {
2319        let mut order = algo_order_with_price(None);
2320        order.create_time = Some(create_time);
2321
2322        let result = order.to_order_status_report(
2323            AccountId::from("BINANCE-FUTURES-001"),
2324            InstrumentId::from("BTCUSDT-PERP.BINANCE"),
2325            2,
2326            3,
2327            UnixNanos::from_millis(9_000),
2328        );
2329
2330        assert_eq!(result.unwrap_err().to_string(), expected_error);
2331    }
2332
2333    #[rstest]
2334    fn test_order_to_report_maps_rpi_to_gtc_post_only() {
2335        let mut order = order_with_price("50000.00");
2336        order.order_type = BinanceFuturesOrderType::Limit;
2337        order.time_in_force = BinanceTimeInForce::Rpi;
2338
2339        let report = order
2340            .to_order_status_report(
2341                AccountId::from("BINANCE-FUTURES-001"),
2342                InstrumentId::from("BTCUSDT-PERP.BINANCE"),
2343                2,
2344                3,
2345                false,
2346                UnixNanos::from(1_000_000_000u64),
2347            )
2348            .unwrap();
2349
2350        assert_eq!(report.time_in_force, TimeInForce::Gtc);
2351        assert!(report.post_only);
2352    }
2353
2354    #[rstest]
2355    fn test_parse_order_defaults_missing_cum_quote_to_zero() {
2356        let json = load_fixture_string("futures/http_json/order_response.json");
2357        let mut value: Value = serde_json::from_str(&json).expect("Failed to parse order fixture");
2358
2359        value
2360            .as_object_mut()
2361            .expect("Order fixture should be a JSON object")
2362            .remove("cumQuote");
2363
2364        let order: BinanceFuturesOrder =
2365            serde_json::from_value(value).expect("Failed to parse order");
2366
2367        assert_eq!(order.cum_quote, "0");
2368    }
2369
2370    #[rstest]
2371    fn test_parse_kline_rejects_non_string_price() {
2372        let value = serde_json::json!([
2373            1_625_474_304_000_i64,
2374            50000.00,
2375            "51000.00",
2376            "49000.00",
2377            "50500.00",
2378            "12.5",
2379            1_625_474_364_000_i64,
2380            "631250.00",
2381            100_i64,
2382            "6.2",
2383            "313100.00"
2384        ]);
2385
2386        let error = serde_json::from_value::<BinanceFuturesKline>(value)
2387            .unwrap_err()
2388            .to_string();
2389
2390        assert!(error.contains("open"));
2391    }
2392
2393    #[rstest]
2394    fn test_parse_hedge_mode_response() {
2395        let json = r#"{"dualSidePosition": true}"#;
2396        let response: BinanceHedgeModeResponse =
2397            serde_json::from_str(json).expect("Failed to parse hedge mode");
2398        assert!(response.dual_side_position);
2399    }
2400
2401    #[rstest]
2402    fn test_parse_leverage_response() {
2403        let json = r#"{"symbol": "BTCUSDT", "leverage": 20, "maxNotionalValue": "250000"}"#;
2404        let response: BinanceLeverageResponse =
2405            serde_json::from_str(json).expect("Failed to parse leverage");
2406        assert_eq!(response.symbol.as_str(), "BTCUSDT");
2407        assert_eq!(response.leverage, 20);
2408    }
2409
2410    #[rstest]
2411    fn test_parse_listen_key_response() {
2412        assert_zeroize_on_drop::<ListenKeyResponse>();
2413
2414        let json =
2415            r#"{"listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"}"#;
2416        let mut response: ListenKeyResponse =
2417            serde_json::from_str(json).expect("Failed to parse listen key");
2418
2419        let debug = format!("{response:?}");
2420        assert_eq!(
2421            response.listen_key.expose_secret(),
2422            "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"
2423        );
2424        assert_eq!(debug, "ListenKeyResponse { listen_key: <redacted> }");
2425        assert!(!debug.contains(response.listen_key.expose_secret()));
2426
2427        response.zeroize();
2428        assert!(response.listen_key.expose_secret().is_empty());
2429    }
2430
2431    #[rstest]
2432    fn test_parse_account_position() {
2433        let json = r#"{
2434            "symbol": "ETHUSDT",
2435            "initialMargin": "100.00",
2436            "maintMargin": "50.00",
2437            "unrealizedProfit": "10.00",
2438            "positionInitialMargin": "100.00",
2439            "openOrderInitialMargin": "0",
2440            "leverage": "10",
2441            "isolated": true,
2442            "entryPrice": "2000.00",
2443            "maxNotional": "100000",
2444            "bidNotional": "0",
2445            "askNotional": "0",
2446            "positionSide": "LONG",
2447            "positionAmt": "0.5",
2448            "updateTime": 1625474304765
2449        }"#;
2450
2451        let position: BinanceAccountPosition =
2452            serde_json::from_str(json).expect("Failed to parse account position");
2453
2454        assert_eq!(position.symbol.as_str(), "ETHUSDT");
2455        assert_eq!(position.leverage, Some("10".to_string()));
2456        assert_eq!(position.isolated, Some(true));
2457        assert_eq!(position.position_side, Some(BinancePositionSide::Long));
2458    }
2459
2460    #[rstest]
2461    fn test_parse_algo_order() {
2462        let json = r#"{
2463            "algoId": 123456789,
2464            "clientAlgoId": "test-algo-order-1",
2465            "algoType": "CONDITIONAL",
2466            "type": "STOP_MARKET",
2467            "symbol": "BTCUSDT",
2468            "side": "BUY",
2469            "positionSide": "BOTH",
2470            "timeInForce": "GTC",
2471            "quantity": "0.001",
2472            "algoStatus": "NEW",
2473            "triggerPrice": "45000.00",
2474            "workingType": "MARK_PRICE",
2475            "reduceOnly": false,
2476            "createTime": 1625474304765,
2477            "updateTime": 1625474304765
2478        }"#;
2479
2480        let order: BinanceFuturesAlgoOrder =
2481            serde_json::from_str(json).expect("Failed to parse algo order");
2482
2483        assert_eq!(order.algo_id, 123456789);
2484        assert_eq!(order.client_algo_id, "test-algo-order-1");
2485        assert_eq!(order.algo_type, BinanceAlgoType::Conditional);
2486        assert_eq!(order.order_type, BinanceFuturesOrderType::StopMarket);
2487        assert_eq!(order.symbol.as_str(), "BTCUSDT");
2488        assert_eq!(order.side, BinanceSide::Buy);
2489        assert_eq!(order.algo_status, Some(BinanceAlgoStatus::New));
2490        assert_eq!(order.trigger_price, Some("45000.00".to_string()));
2491    }
2492
2493    #[rstest]
2494    #[case("actualQty", "actualPrice")]
2495    #[case("executedQty", "avgPrice")]
2496    fn test_parse_algo_order_finished(#[case] quantity_field: &str, #[case] price_field: &str) {
2497        let json = load_fixture_string("futures/http_json/algo_order_response.json")
2498            .replace("actualQty", quantity_field)
2499            .replace("actualPrice", price_field);
2500
2501        let order: BinanceFuturesAlgoOrder =
2502            serde_json::from_str(&json).expect("Failed to parse finished algo order");
2503
2504        assert_eq!(order.algo_status, Some(BinanceAlgoStatus::Finished));
2505        assert_eq!(order.order_type, BinanceFuturesOrderType::StopMarket);
2506        assert_eq!(order.actual_order_id, Some("987654321".to_string()));
2507        assert_eq!(order.executed_qty, Some("0.001".to_string()));
2508        assert_eq!(order.avg_price, Some("50000.00".to_string()));
2509    }
2510
2511    #[rstest]
2512    fn test_parse_algo_order_cancel_response() {
2513        let json = r#"{
2514            "algoId": 123456789,
2515            "clientAlgoId": "test-algo-order-1",
2516            "code": "200",
2517            "msg": "success"
2518        }"#;
2519
2520        let response: BinanceFuturesAlgoOrderCancelResponse =
2521            serde_json::from_str(json).expect("Failed to parse algo cancel response");
2522
2523        assert_eq!(response.algo_id, 123456789);
2524        assert_eq!(response.client_algo_id, "test-algo-order-1");
2525        assert_eq!(response.code, "200");
2526        assert_eq!(response.msg, "success");
2527    }
2528
2529    #[rstest]
2530    fn test_order_to_report_decodes_broker_id() {
2531        let json = r#"{
2532            "orderId": 12345678,
2533            "symbol": "BTCUSDT",
2534            "status": "NEW",
2535            "clientOrderId": "x-aHRE4BCj-T0000000000000",
2536            "price": "50000.00",
2537            "avgPrice": "0.00",
2538            "origQty": "0.001",
2539            "executedQty": "0.000",
2540            "cumQuote": "0.00",
2541            "timeInForce": "GTC",
2542            "type": "LIMIT",
2543            "reduceOnly": false,
2544            "closePosition": false,
2545            "side": "BUY",
2546            "positionSide": "BOTH",
2547            "stopPrice": "0.00",
2548            "workingType": "CONTRACT_PRICE",
2549            "priceProtect": false,
2550            "origType": "LIMIT",
2551            "priceMatch": "NONE",
2552            "selfTradePreventionMode": "NONE",
2553            "goodTillDate": 0,
2554            "time": 1625474304765,
2555            "updateTime": 1625474304765
2556        }"#;
2557
2558        let order: BinanceFuturesOrder = serde_json::from_str(json).unwrap();
2559        let account_id = AccountId::from("BINANCE-FUTURES-001");
2560        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2561        let ts_init = UnixNanos::from(1_000_000_000u64);
2562
2563        let report = order
2564            .to_order_status_report(account_id, instrument_id, 2, 3, false, ts_init)
2565            .unwrap();
2566
2567        assert_eq!(
2568            report.client_order_id,
2569            Some(ClientOrderId::from("O-20200101-000000-000-000-0")),
2570        );
2571        assert_eq!(report.price, Some(Price::from("50000.00")));
2572    }
2573
2574    #[rstest]
2575    fn test_order_to_report_rejects_invalid_client_order_id() {
2576        let mut order = order_with_price("50000.00");
2577        order.client_order_id = String::new();
2578
2579        let result = order.to_order_status_report(
2580            AccountId::from("BINANCE-FUTURES-001"),
2581            InstrumentId::from("BTCUSDT-PERP.BINANCE"),
2582            2,
2583            3,
2584            false,
2585            UnixNanos::from(1_000_000_000u64),
2586        );
2587
2588        assert_eq!(
2589            result.unwrap_err().to_string(),
2590            "invalid Binance client order ID ''"
2591        );
2592    }
2593
2594    #[rstest]
2595    #[case("0")]
2596    #[case("")]
2597    fn test_order_to_report_omits_missing_price(#[case] price: &str) {
2598        let order = order_with_price(price);
2599        let account_id = AccountId::from("BINANCE-FUTURES-001");
2600        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2601        let ts_init = UnixNanos::from(1_000_000_000u64);
2602
2603        let report = order
2604            .to_order_status_report(account_id, instrument_id, 2, 3, false, ts_init)
2605            .unwrap();
2606
2607        assert_eq!(report.price, None);
2608    }
2609
2610    #[rstest]
2611    fn test_order_to_report_sets_avg_px_for_filled_market_order() {
2612        let mut order = order_with_price("0");
2613        order.status = BinanceOrderStatus::Filled;
2614        order.executed_qty = "0.001".to_string();
2615        order.cum_quote = "50.00".to_string();
2616        order.avg_price = Some("50000.00".to_string());
2617        let account_id = AccountId::from("BINANCE-FUTURES-001");
2618        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2619        let ts_init = UnixNanos::from(1_000_000_000u64);
2620
2621        let report = order
2622            .to_order_status_report(account_id, instrument_id, 2, 3, false, ts_init)
2623            .unwrap();
2624
2625        assert_eq!(report.price, None);
2626        assert_eq!(
2627            report.avg_px,
2628            Some(Decimal::from_str_exact("50000.00").unwrap())
2629        );
2630    }
2631
2632    #[rstest]
2633    fn test_order_to_report_omits_avg_px_without_fills() {
2634        let mut order = order_with_price("0");
2635        order.avg_price = Some("50000.00".to_string());
2636        let account_id = AccountId::from("BINANCE-FUTURES-001");
2637        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2638        let ts_init = UnixNanos::from(1_000_000_000u64);
2639
2640        let report = order
2641            .to_order_status_report(account_id, instrument_id, 2, 3, false, ts_init)
2642            .unwrap();
2643
2644        assert_eq!(report.avg_px, None);
2645    }
2646
2647    #[rstest]
2648    fn test_order_to_report_rejects_invalid_avg_px_for_filled_order() {
2649        let mut order = order_with_price("0");
2650        order.executed_qty = "0.001".to_string();
2651        order.avg_price = Some("not-a-number".to_string());
2652        let account_id = AccountId::from("BINANCE-FUTURES-001");
2653        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2654        let ts_init = UnixNanos::from(1_000_000_000u64);
2655
2656        let result = order.to_order_status_report(account_id, instrument_id, 2, 3, false, ts_init);
2657
2658        let error = result.unwrap_err().to_string();
2659        assert!(error.contains("avg_price"));
2660    }
2661
2662    #[rstest]
2663    fn test_close_all_algo_report_with_actual_uses_matching_engine_quantity() {
2664        let mut algo = algo_order_with_price(None);
2665        algo.order_type = BinanceFuturesOrderType::StopMarket;
2666        algo.quantity = None;
2667        algo.close_position = Some(true);
2668        algo.algo_status = Some(BinanceAlgoStatus::Finished);
2669        algo.actual_order_id = Some("987654321".to_string());
2670        algo.executed_qty = Some("0.002".to_string());
2671        algo.avg_price = Some("49000.00".to_string());
2672        algo.reduce_only = Some(true);
2673        algo.trigger_time = Some(1_625_474_305_000);
2674        algo.time_in_force = Some(BinanceTimeInForce::Gtd);
2675        algo.good_till_date = Some(1_700_000_601_000);
2676        algo.update_time = Some(1_625_474_305_500);
2677
2678        let mut actual = order_with_price("0");
2679        actual.order_id = 987654321;
2680        actual.orig_qty = "0.002".to_string();
2681        actual.executed_qty = "0.001".to_string();
2682        actual.avg_price = Some("50000.00".to_string());
2683        actual.status = BinanceOrderStatus::PartiallyFilled;
2684        actual.order_type = BinanceFuturesOrderType::Market;
2685        actual.side = BinanceSide::Sell;
2686        actual.time = Some(1_625_474_305_000);
2687        actual.update_time = Some(1_625_474_306_000);
2688
2689        let account_id = AccountId::from("BINANCE-FUTURES-001");
2690        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2691        let ts_init = UnixNanos::from(1_000_000_000u64);
2692        let report = algo
2693            .to_order_status_report_with_actual(
2694                &actual,
2695                account_id,
2696                instrument_id,
2697                2,
2698                3,
2699                false,
2700                ts_init,
2701            )
2702            .unwrap();
2703
2704        assert_eq!(
2705            report.client_order_id,
2706            Some(ClientOrderId::from("my-algo-order-1"))
2707        );
2708        assert_eq!(report.venue_order_id, VenueOrderId::from("987654321"));
2709        assert_eq!(report.order_type, OrderType::StopMarket);
2710        assert_eq!(report.order_status, OrderStatus::PartiallyFilled);
2711        assert_eq!(report.quantity, Quantity::from("0.002"));
2712        assert_eq!(report.filled_qty, Quantity::from("0.001"));
2713        assert_eq!(report.avg_px, Some(Decimal::from(50000)));
2714        assert_eq!(report.trigger_price, Some(Price::from("45000.00")));
2715        assert_eq!(report.trigger_type, Some(TriggerType::MarkPrice));
2716        assert!(report.reduce_only);
2717        assert_eq!(
2718            report.expire_time,
2719            Some(UnixNanos::from_millis(1_700_000_601_000)),
2720        );
2721        assert_eq!(
2722            report.ts_triggered,
2723            Some(UnixNanos::from_millis(1_625_474_305_000))
2724        );
2725        assert_eq!(
2726            report.ts_accepted,
2727            UnixNanos::from_millis(1_625_474_304_765)
2728        );
2729        assert_eq!(report.ts_last, UnixNanos::from_millis(1_625_474_306_000));
2730    }
2731
2732    #[rstest]
2733    #[case(BinanceAlgoStatus::Finished, Some("0.001"), OrderStatus::Filled)]
2734    #[case(BinanceAlgoStatus::Finished, Some("0.0005"), OrderStatus::Canceled)]
2735    #[case(
2736        BinanceAlgoStatus::Triggered,
2737        Some("0.0005"),
2738        OrderStatus::PartiallyFilled
2739    )]
2740    #[case(BinanceAlgoStatus::Triggered, None, OrderStatus::Accepted)]
2741    fn test_algo_order_status_uses_actual_quantity_conservatively(
2742        #[case] algo_status: BinanceAlgoStatus,
2743        #[case] executed_qty: Option<&str>,
2744        #[case] expected: OrderStatus,
2745    ) {
2746        let mut order = algo_order_with_price(None);
2747        order.algo_status = Some(algo_status);
2748        order.executed_qty = executed_qty.map(str::to_string);
2749
2750        assert_eq!(order.parse_order_status().unwrap(), expected);
2751    }
2752
2753    #[rstest]
2754    fn test_algo_order_to_report_sets_price() {
2755        let order = algo_order_with_price(Some("50000.00"));
2756        let account_id = AccountId::from("BINANCE-FUTURES-001");
2757        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2758        let ts_init = UnixNanos::from(1_000_000_000u64);
2759
2760        let report = order
2761            .to_order_status_report(account_id, instrument_id, 2, 3, ts_init)
2762            .unwrap();
2763
2764        assert_eq!(report.price, Some(Price::from("50000.00")));
2765    }
2766
2767    #[rstest]
2768    fn test_algo_order_to_report_sets_actual_fill_fields() {
2769        let json = load_fixture_string("futures/http_json/algo_order_response.json");
2770        let order: BinanceFuturesAlgoOrder = serde_json::from_str(&json).unwrap();
2771        let account_id = AccountId::from("BINANCE-FUTURES-001");
2772        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2773        let ts_init = UnixNanos::from(1_000_000_000u64);
2774
2775        let report = order
2776            .to_order_status_report(account_id, instrument_id, 2, 3, ts_init)
2777            .unwrap();
2778
2779        assert_eq!(report.order_status, OrderStatus::Filled);
2780        assert_eq!(report.filled_qty.as_decimal(), dec!(0.001));
2781        assert_eq!(report.price, None);
2782        assert_eq!(report.avg_px, Some(dec!(50000.00)));
2783    }
2784
2785    #[rstest]
2786    fn test_algo_order_to_report_omits_avg_price_without_fills() {
2787        let mut order = algo_order_with_price(None);
2788        order.executed_qty = Some("0".to_string());
2789        order.avg_price = Some("not-a-number".to_string());
2790        let account_id = AccountId::from("BINANCE-FUTURES-001");
2791        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2792        let ts_init = UnixNanos::from(1_000_000_000u64);
2793
2794        let report = order
2795            .to_order_status_report(account_id, instrument_id, 2, 3, ts_init)
2796            .unwrap();
2797
2798        assert_eq!(report.filled_qty.as_decimal(), Decimal::ZERO);
2799        assert_eq!(report.avg_px, None);
2800    }
2801
2802    #[rstest]
2803    fn test_algo_order_to_report_sets_trigger_fields() {
2804        let order = algo_order_with_price(Some("44000.00"));
2805        let account_id = AccountId::from("BINANCE-FUTURES-001");
2806        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2807        let ts_init = UnixNanos::from(1_000_000_000u64);
2808
2809        let report = order
2810            .to_order_status_report(account_id, instrument_id, 2, 3, ts_init)
2811            .unwrap();
2812
2813        assert_eq!(report.trigger_price, Some(Price::from("45000.00")));
2814        assert_eq!(report.trigger_type, Some(TriggerType::MarkPrice));
2815    }
2816
2817    #[rstest]
2818    fn test_algo_order_to_report_sets_trailing_fields() {
2819        let mut order = algo_order_with_price(None);
2820        order.order_type = BinanceFuturesOrderType::TrailingStopMarket;
2821        order.trigger_price = None;
2822        order.activate_price = Some("45000.00".to_string());
2823        order.callback_rate = Some("0.25".to_string());
2824        let account_id = AccountId::from("BINANCE-FUTURES-001");
2825        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2826        let ts_init = UnixNanos::from(1_000_000_000u64);
2827
2828        let report = order
2829            .to_order_status_report(account_id, instrument_id, 2, 3, ts_init)
2830            .unwrap();
2831
2832        assert_eq!(report.trigger_price, Some(Price::from("45000.00")));
2833        assert_eq!(report.trigger_type, Some(TriggerType::MarkPrice));
2834        assert_eq!(report.trailing_offset, Some(Decimal::from(25)));
2835        assert_eq!(
2836            report.trailing_offset_type,
2837            Some(TrailingOffsetType::BasisPoints),
2838        );
2839    }
2840
2841    #[rstest]
2842    #[case(None)]
2843    #[case(Some("0"))]
2844    #[case(Some(""))]
2845    fn test_algo_order_to_report_omits_missing_price(#[case] price: Option<&str>) {
2846        let order = algo_order_with_price(price);
2847        let account_id = AccountId::from("BINANCE-FUTURES-001");
2848        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2849        let ts_init = UnixNanos::from(1_000_000_000u64);
2850
2851        let report = order
2852            .to_order_status_report(account_id, instrument_id, 2, 3, ts_init)
2853            .unwrap();
2854
2855        assert_eq!(report.price, None);
2856    }
2857
2858    #[rstest]
2859    fn test_order_to_report_rejects_invalid_price() {
2860        let order = order_with_price("not-a-number");
2861        let account_id = AccountId::from("BINANCE-FUTURES-001");
2862        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2863        let ts_init = UnixNanos::from(1_000_000_000u64);
2864
2865        let result = order.to_order_status_report(account_id, instrument_id, 2, 3, false, ts_init);
2866
2867        let error = result.unwrap_err().to_string();
2868        assert!(error.contains("invalid price"));
2869    }
2870
2871    #[rstest]
2872    fn test_algo_order_to_report_rejects_invalid_trigger_price() {
2873        let mut order = algo_order_with_price(Some("50000.00"));
2874        order.trigger_price = Some("not-a-number".to_string());
2875        let account_id = AccountId::from("BINANCE-FUTURES-001");
2876        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2877        let ts_init = UnixNanos::from(1_000_000_000u64);
2878
2879        let result = order.to_order_status_report(account_id, instrument_id, 2, 3, ts_init);
2880
2881        let error = result.unwrap_err().to_string();
2882        assert!(error.contains("trigger_price"));
2883    }
2884
2885    #[rstest]
2886    fn test_algo_order_to_report_rejects_missing_trigger_price() {
2887        let mut order = algo_order_with_price(None);
2888        order.order_type = BinanceFuturesOrderType::StopMarket;
2889        order.trigger_price = None;
2890        let account_id = AccountId::from("BINANCE-FUTURES-001");
2891        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2892        let ts_init = UnixNanos::from(1_000_000_000u64);
2893
2894        let result = order.to_order_status_report(account_id, instrument_id, 2, 3, ts_init);
2895
2896        let error = result.unwrap_err().to_string();
2897        assert!(error.contains("missing positive trigger_price"));
2898    }
2899
2900    #[rstest]
2901    fn test_algo_order_to_report_rejects_invalid_callback_rate() {
2902        let mut order = algo_order_with_price(None);
2903        order.order_type = BinanceFuturesOrderType::TrailingStopMarket;
2904        order.trigger_price = None;
2905        order.activate_price = Some("45000.00".to_string());
2906        order.callback_rate = Some("not-a-number".to_string());
2907        let account_id = AccountId::from("BINANCE-FUTURES-001");
2908        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2909        let ts_init = UnixNanos::from(1_000_000_000u64);
2910
2911        let result = order.to_order_status_report(account_id, instrument_id, 2, 3, ts_init);
2912
2913        let error = result.unwrap_err().to_string();
2914        assert!(error.contains("callback_rate"));
2915    }
2916
2917    #[rstest]
2918    fn test_algo_order_to_report_rejects_invalid_price() {
2919        let order = algo_order_with_price(Some("not-a-number"));
2920        let account_id = AccountId::from("BINANCE-FUTURES-001");
2921        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2922        let ts_init = UnixNanos::from(1_000_000_000u64);
2923
2924        let result = order.to_order_status_report(account_id, instrument_id, 2, 3, ts_init);
2925
2926        let error = result.unwrap_err().to_string();
2927        assert!(error.contains("invalid price"));
2928    }
2929
2930    #[rstest]
2931    fn test_order_to_report_preserves_good_till_date() {
2932        let mut order = order_with_price("50000.00");
2933        order.time_in_force = BinanceTimeInForce::Gtd;
2934        order.good_till_date = Some(1_700_000_601_000);
2935        let account_id = AccountId::from("BINANCE-FUTURES-001");
2936        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2937        let ts_init = UnixNanos::from(1_000_000_000u64);
2938
2939        let report = order
2940            .to_order_status_report(account_id, instrument_id, 2, 3, false, ts_init)
2941            .unwrap();
2942
2943        assert_eq!(report.time_in_force, TimeInForce::Gtd);
2944        assert_eq!(
2945            report.expire_time,
2946            Some(UnixNanos::from_millis(1_700_000_601_000)),
2947        );
2948    }
2949
2950    #[rstest]
2951    fn test_algo_order_to_report_accepts_position_linked_gtc() {
2952        let json = load_fixture_string("futures/http_json/algo_order_response.json");
2953        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
2954        value["timeInForce"] = "GTE_GTC".into();
2955        value["algoStatus"] = "CANCELED".into();
2956        value["quantity"] = "0.000".into();
2957        value["actualOrderId"] = "".into();
2958        value["actualQty"] = "0.000".into();
2959        value["closePosition"] = true.into();
2960        value["reduceOnly"] = true.into();
2961        let order: BinanceFuturesAlgoOrder = serde_json::from_value(value).unwrap();
2962
2963        let report = order
2964            .to_order_status_report(
2965                AccountId::from("BINANCE-FUTURES-001"),
2966                InstrumentId::from("BTCUSDT-PERP.BINANCE"),
2967                2,
2968                3,
2969                UnixNanos::from(1_000_000_000u64),
2970            )
2971            .unwrap();
2972
2973        assert_eq!(
2974            serde_json::to_string(&order.time_in_force).unwrap(),
2975            "\"GTE_GTC\""
2976        );
2977        assert_eq!(report.time_in_force, TimeInForce::Gtc);
2978        assert_eq!(report.order_type, OrderType::StopMarket);
2979        assert_eq!(report.order_status, OrderStatus::Canceled);
2980        assert_eq!(report.venue_order_id, VenueOrderId::from("123456789"));
2981        assert_eq!(report.quantity, Quantity::from("0.000"));
2982        assert_eq!(report.filled_qty, Quantity::from("0.000"));
2983        assert_eq!(report.expire_time, None);
2984    }
2985
2986    #[rstest]
2987    fn test_algo_order_to_report_preserves_good_till_date() {
2988        let mut order = algo_order_with_price(Some("50000.00"));
2989        order.time_in_force = Some(BinanceTimeInForce::Gtd);
2990        order.good_till_date = Some(1_700_000_601_000);
2991        let account_id = AccountId::from("BINANCE-FUTURES-001");
2992        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
2993        let ts_init = UnixNanos::from(1_000_000_000u64);
2994
2995        let report = order
2996            .to_order_status_report(account_id, instrument_id, 2, 3, ts_init)
2997            .unwrap();
2998
2999        assert_eq!(report.time_in_force, TimeInForce::Gtd);
3000        assert_eq!(
3001            report.expire_time,
3002            Some(UnixNanos::from_millis(1_700_000_601_000)),
3003        );
3004    }
3005
3006    fn order_with_price(price: &str) -> BinanceFuturesOrder {
3007        BinanceFuturesOrder {
3008            symbol: Ustr::from("BTCUSDT"),
3009            order_id: 12345678,
3010            client_order_id: "external-order".to_string(),
3011            orig_qty: "0.001".to_string(),
3012            executed_qty: "0.000".to_string(),
3013            cum_quote: "0.00".to_string(),
3014            price: price.to_string(),
3015            avg_price: Some("0.00".to_string()),
3016            stop_price: Some("0.00".to_string()),
3017            status: BinanceOrderStatus::New,
3018            time_in_force: BinanceTimeInForce::Gtc,
3019            order_type: BinanceFuturesOrderType::Market,
3020            orig_type: Some(BinanceFuturesOrderType::Market),
3021            side: BinanceSide::Buy,
3022            position_side: Some(BinancePositionSide::Both),
3023            reduce_only: Some(false),
3024            close_position: Some(false),
3025            activate_price: None,
3026            price_rate: None,
3027            working_type: Some(BinanceWorkingType::ContractPrice),
3028            price_protect: Some(false),
3029            is_isolated: None,
3030            good_till_date: Some(0),
3031            price_match: Some(BinancePriceMatch::None),
3032            self_trade_prevention_mode: Some(BinanceSelfTradePreventionMode::None),
3033            time: Some(1_625_474_304_000),
3034            update_time: Some(1_625_474_304_765),
3035            working_type_id: None,
3036        }
3037    }
3038
3039    fn algo_order_with_price(price: Option<&str>) -> BinanceFuturesAlgoOrder {
3040        BinanceFuturesAlgoOrder {
3041            algo_id: 123456789,
3042            client_algo_id: "x-aHRE4BCj-Rmy-algo-order-1".to_string(),
3043            algo_type: BinanceAlgoType::Conditional,
3044            order_type: BinanceFuturesOrderType::TakeProfit,
3045            symbol: Ustr::from("BTCUSDT"),
3046            side: BinanceSide::Sell,
3047            position_side: Some(BinancePositionSide::Both),
3048            time_in_force: Some(BinanceTimeInForce::Gtc),
3049            quantity: Some("0.001".to_string()),
3050            algo_status: Some(BinanceAlgoStatus::New),
3051            trigger_price: Some("45000.00".to_string()),
3052            price: price.map(str::to_string),
3053            working_type: Some(BinanceWorkingType::MarkPrice),
3054            close_position: Some(false),
3055            price_protect: None,
3056            reduce_only: Some(false),
3057            activate_price: None,
3058            callback_rate: None,
3059            good_till_date: Some(0),
3060            create_time: Some(1_625_474_304_765),
3061            update_time: Some(1_625_474_304_765),
3062            trigger_time: None,
3063            actual_order_id: None,
3064            executed_qty: None,
3065            avg_price: None,
3066        }
3067    }
3068
3069    #[rstest]
3070    fn test_user_trade_to_fill_report_rejects_invalid_commission() {
3071        let trade = BinanceUserTrade {
3072            symbol: Ustr::from("BTCUSDT"),
3073            id: 100,
3074            order_id: 200,
3075            price: "50000.00".to_string(),
3076            qty: "0.001".to_string(),
3077            quote_qty: None,
3078            realized_pnl: "0".to_string(),
3079            side: BinanceSide::Buy,
3080            position_side: None,
3081            time: 1_625_474_304_000,
3082            buyer: true,
3083            maker: false,
3084            commission: Some("not-a-number".to_string()),
3085            commission_asset: Some(Ustr::from("USDT")),
3086            margin_asset: None,
3087        };
3088
3089        let result = trade.to_fill_report(
3090            AccountId::from("BINANCE-FUTURES-001"),
3091            InstrumentId::from("BTCUSDT-PERP.BINANCE"),
3092            2,
3093            3,
3094            Currency::USDT(),
3095            UnixNanos::from(1_000_000_000u64),
3096        );
3097
3098        let error = result.unwrap_err().to_string();
3099        assert!(error.contains("commission"));
3100    }
3101
3102    #[rstest]
3103    fn test_algo_order_to_report_decodes_broker_id() {
3104        let json = r#"{
3105            "algoId": 123456789,
3106            "clientAlgoId": "x-aHRE4BCj-Rmy-algo-order-1",
3107            "algoType": "CONDITIONAL",
3108            "type": "STOP_MARKET",
3109            "symbol": "BTCUSDT",
3110            "side": "BUY",
3111            "positionSide": "BOTH",
3112            "timeInForce": "GTC",
3113            "quantity": "0.001",
3114            "algoStatus": "NEW",
3115            "triggerPrice": "45000.00",
3116            "workingType": "MARK_PRICE",
3117            "reduceOnly": false,
3118            "createTime": 1625474304765,
3119            "updateTime": 1625474304765
3120        }"#;
3121
3122        let order: BinanceFuturesAlgoOrder = serde_json::from_str(json).unwrap();
3123        let account_id = AccountId::from("BINANCE-FUTURES-001");
3124        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
3125        let ts_init = UnixNanos::from(1_000_000_000u64);
3126
3127        let report = order
3128            .to_order_status_report(account_id, instrument_id, 2, 3, ts_init)
3129            .unwrap();
3130
3131        assert_eq!(
3132            report.client_order_id,
3133            Some(ClientOrderId::from("my-algo-order-1")),
3134        );
3135    }
3136
3137    #[rstest]
3138    fn test_algo_order_to_report_rejects_invalid_client_order_id() {
3139        let mut order = algo_order_with_price(None);
3140        order.client_algo_id = "x-aHRE4BCj-R".to_string();
3141
3142        let result = order.to_order_status_report(
3143            AccountId::from("BINANCE-FUTURES-001"),
3144            InstrumentId::from("BTCUSDT-PERP.BINANCE"),
3145            2,
3146            3,
3147            UnixNanos::from(1_000_000_000u64),
3148        );
3149
3150        assert_eq!(
3151            result.unwrap_err().to_string(),
3152            "missing raw broker client order ID payload"
3153        );
3154    }
3155
3156    #[rstest]
3157    #[case(None, "123456789")]
3158    #[case(Some(""), "123456789")]
3159    #[case(Some("987654321"), "987654321")]
3160    fn test_algo_order_to_report_selects_valid_venue_order_id(
3161        #[case] actual_order_id: Option<&str>,
3162        #[case] expected_venue_order_id: &str,
3163    ) {
3164        let order = BinanceFuturesAlgoOrder {
3165            algo_id: 123456789,
3166            client_algo_id: "x-aHRE4BCj-Rmy-algo-order-1".to_string(),
3167            algo_type: BinanceAlgoType::Conditional,
3168            order_type: BinanceFuturesOrderType::StopMarket,
3169            symbol: Ustr::from("BTCUSDT"),
3170            side: BinanceSide::Buy,
3171            position_side: Some(BinancePositionSide::Both),
3172            time_in_force: Some(BinanceTimeInForce::Gtc),
3173            quantity: Some("0.001".to_string()),
3174            algo_status: Some(BinanceAlgoStatus::New),
3175            trigger_price: Some("45000.00".to_string()),
3176            price: None,
3177            working_type: Some(BinanceWorkingType::MarkPrice),
3178            close_position: Some(false),
3179            price_protect: None,
3180            reduce_only: Some(false),
3181            activate_price: None,
3182            callback_rate: None,
3183            good_till_date: Some(0),
3184            create_time: Some(1_625_474_304_765),
3185            update_time: Some(1_625_474_304_765),
3186            trigger_time: None,
3187            actual_order_id: actual_order_id.map(str::to_string),
3188            executed_qty: None,
3189            avg_price: None,
3190        };
3191        let account_id = AccountId::from("BINANCE-FUTURES-001");
3192        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
3193        let ts_init = UnixNanos::from(1_000_000_000u64);
3194
3195        let report = order
3196            .to_order_status_report(account_id, instrument_id, 2, 3, ts_init)
3197            .unwrap();
3198
3199        assert_eq!(
3200            report.venue_order_id,
3201            VenueOrderId::new(expected_venue_order_id)
3202        );
3203    }
3204
3205    #[rstest]
3206    #[case(BinanceOrderStatus::Expired, false, OrderStatus::Expired)]
3207    #[case(BinanceOrderStatus::Expired, true, OrderStatus::Canceled)]
3208    #[case(BinanceOrderStatus::ExpiredInMatch, false, OrderStatus::Expired)]
3209    #[case(BinanceOrderStatus::ExpiredInMatch, true, OrderStatus::Canceled)]
3210    fn test_to_nautilus_order_status_expired_respects_treat_as_canceled(
3211        #[case] status: BinanceOrderStatus,
3212        #[case] treat_expired_as_canceled: bool,
3213        #[case] expected: OrderStatus,
3214    ) {
3215        let result = status
3216            .to_nautilus_order_status(treat_expired_as_canceled)
3217            .unwrap();
3218        assert_eq!(result, expected);
3219    }
3220}