Skip to main content

nautilus_binance/common/
enums.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 enumeration types for product types and environments.
17
18use std::fmt::Display;
19
20use nautilus_model::enums::{MarketStatusAction, OrderSide, OrderType, TimeInForce};
21use serde::{Deserialize, Serialize};
22
23/// Binance product type identifier.
24///
25/// Each product type corresponds to a different Binance API domain and
26/// has distinct trading rules and instrument specifications.
27#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
28#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(
32        module = "nautilus_trader.adapters.binance",
33        eq,
34        from_py_object,
35        rename_all = "SCREAMING_SNAKE_CASE"
36    )
37)]
38#[cfg_attr(
39    feature = "python",
40    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.adapters.binance")
41)]
42pub enum BinanceProductType {
43    /// Spot trading (api.binance.com).
44    #[default]
45    Spot,
46    /// Spot Margin trading (uses Spot API with margin endpoints).
47    Margin,
48    /// USD-M Futures - linear perpetuals and delivery futures (fapi.binance.com).
49    UsdM,
50    /// COIN-M Futures - inverse perpetuals and delivery futures (dapi.binance.com).
51    CoinM,
52    /// European Options (eapi.binance.com).
53    Options,
54}
55
56impl BinanceProductType {
57    /// Returns the string representation used in API requests.
58    #[must_use]
59    pub const fn as_str(self) -> &'static str {
60        match self {
61            Self::Spot => "SPOT",
62            Self::Margin => "MARGIN",
63            Self::UsdM => "USD_M",
64            Self::CoinM => "COIN_M",
65            Self::Options => "OPTIONS",
66        }
67    }
68
69    /// Returns the instrument ID suffix for this product type.
70    #[must_use]
71    pub const fn suffix(self) -> &'static str {
72        match self {
73            Self::Spot => "-SPOT",
74            Self::Margin => "-MARGIN",
75            Self::UsdM => "-LINEAR",
76            Self::CoinM => "-INVERSE",
77            Self::Options => "-OPTION",
78        }
79    }
80
81    /// Returns true if this is a spot product (Spot or Margin).
82    #[must_use]
83    pub const fn is_spot(self) -> bool {
84        matches!(self, Self::Spot | Self::Margin)
85    }
86
87    /// Returns true if this is a futures product (USD-M or COIN-M).
88    #[must_use]
89    pub const fn is_futures(self) -> bool {
90        matches!(self, Self::UsdM | Self::CoinM)
91    }
92
93    /// Returns true if this is a linear product (Spot, Margin, or USD-M).
94    #[must_use]
95    pub const fn is_linear(self) -> bool {
96        matches!(self, Self::Spot | Self::Margin | Self::UsdM)
97    }
98
99    /// Returns true if this is an inverse product (COIN-M).
100    #[must_use]
101    pub const fn is_inverse(self) -> bool {
102        matches!(self, Self::CoinM)
103    }
104
105    /// Returns true if this is an options product.
106    #[must_use]
107    pub const fn is_options(self) -> bool {
108        matches!(self, Self::Options)
109    }
110}
111
112impl Display for BinanceProductType {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        write!(f, "{}", self.as_str())
115    }
116}
117
118/// Binance environment type.
119#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
120#[cfg_attr(
121    feature = "python",
122    pyo3::pyclass(
123        module = "nautilus_trader.adapters.binance",
124        eq,
125        from_py_object,
126        rename_all = "SCREAMING_SNAKE_CASE"
127    )
128)]
129#[cfg_attr(
130    feature = "python",
131    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.adapters.binance")
132)]
133pub enum BinanceEnvironment {
134    /// Live exchange environment.
135    #[default]
136    Live,
137    /// Testnet environment.
138    Testnet,
139    /// Demo trading environment.
140    Demo,
141}
142
143impl BinanceEnvironment {
144    /// Returns true if this is the testnet environment.
145    #[must_use]
146    pub const fn is_testnet(self) -> bool {
147        matches!(self, Self::Testnet)
148    }
149
150    /// Returns true for any non-production environment.
151    #[must_use]
152    pub const fn is_sandbox(self) -> bool {
153        matches!(self, Self::Testnet | Self::Demo)
154    }
155}
156
157/// Order side for Binance orders and trades.
158#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
159#[serde(rename_all = "UPPERCASE")]
160pub enum BinanceSide {
161    /// Buy side.
162    Buy,
163    /// Sell side.
164    Sell,
165}
166
167impl TryFrom<OrderSide> for BinanceSide {
168    type Error = anyhow::Error;
169
170    fn try_from(value: OrderSide) -> Result<Self, Self::Error> {
171        match value {
172            OrderSide::Buy => Ok(Self::Buy),
173            OrderSide::Sell => Ok(Self::Sell),
174        }
175    }
176}
177
178impl From<BinanceSide> for OrderSide {
179    fn from(value: BinanceSide) -> Self {
180        match value {
181            BinanceSide::Buy => Self::Buy,
182            BinanceSide::Sell => Self::Sell,
183        }
184    }
185}
186
187/// Position side for dual-side position mode.
188#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
189#[serde(rename_all = "UPPERCASE")]
190#[cfg_attr(
191    feature = "python",
192    pyo3::pyclass(module = "nautilus_trader.adapters.binance", eq, from_py_object)
193)]
194#[cfg_attr(
195    feature = "python",
196    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.adapters.binance")
197)]
198pub enum BinancePositionSide {
199    /// Single position mode (both).
200    Both,
201    /// Long position.
202    Long,
203    /// Short position.
204    Short,
205    /// Unknown or undocumented value.
206    #[serde(other)]
207    Unknown,
208}
209
210/// Margin type applied to a position.
211///
212/// Serializes to the POST format (`CROSSED`/`ISOLATED`) expected by
213/// `/fapi/v1/marginType`. Deserializes from both POST and GET/WS
214/// formats (`cross`/`isolated`) via serde aliases.
215#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
216#[cfg_attr(
217    feature = "python",
218    pyo3::pyclass(
219        module = "nautilus_trader.adapters.binance",
220        eq,
221        from_py_object,
222        rename_all = "SCREAMING_SNAKE_CASE"
223    )
224)]
225#[cfg_attr(
226    feature = "python",
227    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.adapters.binance")
228)]
229pub enum BinanceMarginType {
230    /// Cross margin.
231    #[serde(rename = "CROSSED", alias = "cross")]
232    Cross,
233    /// Isolated margin.
234    #[serde(rename = "ISOLATED", alias = "isolated")]
235    Isolated,
236    /// Unknown or undocumented value.
237    #[default]
238    #[serde(other)]
239    Unknown,
240}
241
242/// Working type for trigger price evaluation.
243#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
244#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
245pub enum BinanceWorkingType {
246    /// Use the contract price.
247    ContractPrice,
248    /// Use the mark price.
249    MarkPrice,
250    /// Unknown or undocumented value.
251    #[serde(other)]
252    Unknown,
253}
254
255/// Order status lifecycle values.
256#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
257#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
258pub enum BinanceOrderStatus {
259    /// Order accepted and working.
260    New,
261    /// Pending new (order list accepted but not yet on book).
262    PendingNew,
263    /// Partially filled.
264    PartiallyFilled,
265    /// Fully filled.
266    Filled,
267    /// Canceled by user or system.
268    Canceled,
269    /// Pending cancel (not commonly used).
270    PendingCancel,
271    /// Rejected by exchange.
272    Rejected,
273    /// Expired.
274    Expired,
275    /// Expired in match (IOC/FOK not executed).
276    ExpiredInMatch,
277    /// Liquidation with insurance fund.
278    NewInsurance,
279    /// Counterparty liquidation (Auto-Deleveraging).
280    NewAdl,
281    /// Unknown or undocumented value.
282    #[serde(other)]
283    Unknown,
284}
285
286/// Algo order status lifecycle values (Binance Futures Algo Service).
287///
288/// These statuses are specific to conditional orders submitted via the
289/// `/fapi/v1/algoOrder` endpoint (STOP_MARKET, STOP_LIMIT, TAKE_PROFIT,
290/// TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET).
291#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
292#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
293pub enum BinanceAlgoStatus {
294    /// Algo order accepted and waiting for trigger condition.
295    New,
296    /// Algo order trigger condition met, forwarding to matching engine.
297    Triggering,
298    /// Algo order successfully placed in matching engine.
299    Triggered,
300    /// Algo order lifecycle completed (check executed qty for fill status).
301    Finished,
302    /// Algo order canceled by user.
303    Canceled,
304    /// Algo order expired (GTD expiration).
305    Expired,
306    /// Algo order rejected by exchange.
307    Rejected,
308    /// Unknown or undocumented value.
309    #[serde(other)]
310    Unknown,
311}
312
313/// Algo order type for Binance Futures Algo Service.
314///
315/// Currently only `Conditional` is supported by Binance.
316#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
317#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
318pub enum BinanceAlgoType {
319    /// Conditional algo order (stop, take-profit, trailing stop).
320    #[default]
321    Conditional,
322    /// Unknown or undocumented value.
323    #[serde(other)]
324    Unknown,
325}
326
327/// Futures order type enumeration.
328#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
329#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
330pub enum BinanceFuturesOrderType {
331    /// Limit order.
332    Limit,
333    /// Market order.
334    Market,
335    /// Stop (stop-limit) order.
336    Stop,
337    /// Stop market order.
338    StopMarket,
339    /// Take profit (limit) order.
340    TakeProfit,
341    /// Take profit market order.
342    TakeProfitMarket,
343    /// Trailing stop market order.
344    TrailingStopMarket,
345    /// Liquidation order created by exchange.
346    Liquidation,
347    /// Auto-deleveraging order created by exchange.
348    Adl,
349    /// Unknown or undocumented value.
350    #[serde(other)]
351    Unknown,
352}
353
354impl TryFrom<BinanceFuturesOrderType> for OrderType {
355    type Error = anyhow::Error;
356
357    fn try_from(value: BinanceFuturesOrderType) -> Result<Self, Self::Error> {
358        Ok(match value {
359            BinanceFuturesOrderType::Limit => Self::Limit,
360            BinanceFuturesOrderType::Market => Self::Market,
361            BinanceFuturesOrderType::Stop => Self::StopLimit,
362            BinanceFuturesOrderType::StopMarket => Self::StopMarket,
363            BinanceFuturesOrderType::TakeProfit => Self::LimitIfTouched,
364            BinanceFuturesOrderType::TakeProfitMarket => Self::MarketIfTouched,
365            BinanceFuturesOrderType::TrailingStopMarket => Self::TrailingStopMarket,
366            BinanceFuturesOrderType::Liquidation | BinanceFuturesOrderType::Adl => Self::Market,
367            BinanceFuturesOrderType::Unknown => anyhow::bail!("unknown Binance Futures order type"),
368        })
369    }
370}
371
372/// Time in force options.
373#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
374#[serde(rename_all = "UPPERCASE")]
375pub enum BinanceTimeInForce {
376    /// Good till canceled.
377    Gtc,
378    /// Good till canceled while the linked position remains open.
379    #[serde(rename = "GTE_GTC")]
380    GteGtc,
381    /// Immediate or cancel.
382    Ioc,
383    /// Fill or kill.
384    Fok,
385    /// Good till crossing (post-only).
386    Gtx,
387    /// Good till date.
388    Gtd,
389    /// Retail Price Improvement (USD-M Futures).
390    Rpi,
391    /// Unknown or undocumented value.
392    #[serde(other)]
393    Unknown,
394}
395
396impl TryFrom<TimeInForce> for BinanceTimeInForce {
397    type Error = anyhow::Error;
398
399    fn try_from(value: TimeInForce) -> Result<Self, Self::Error> {
400        match value {
401            TimeInForce::Gtc => Ok(Self::Gtc),
402            TimeInForce::Ioc => Ok(Self::Ioc),
403            TimeInForce::Fok => Ok(Self::Fok),
404            TimeInForce::Gtd => Ok(Self::Gtd),
405            _ => anyhow::bail!("Unsupported `TimeInForce` for Binance: {value:?}"),
406        }
407    }
408}
409
410/// Income type for account income history.
411#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
412#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
413pub enum BinanceIncomeType {
414    /// Internal transfers.
415    Transfer,
416    /// Welcome bonus.
417    WelcomeBonus,
418    /// Realized profit and loss.
419    RealizedPnl,
420    /// Funding fee payments/receipts.
421    FundingFee,
422    /// Trading commission.
423    Commission,
424    /// Commission rebate.
425    CommissionRebate,
426    /// API rebate.
427    ApiRebate,
428    /// Insurance clear.
429    InsuranceClear,
430    /// Referral kickback.
431    ReferralKickback,
432    /// Contest reward.
433    ContestReward,
434    /// Cross collateral transfer.
435    CrossCollateralTransfer,
436    /// Options premium fee.
437    OptionsPremiumFee,
438    /// Options settle profit.
439    OptionsSettleProfit,
440    /// Internal transfer.
441    InternalTransfer,
442    /// Auto exchange.
443    AutoExchange,
444    /// Delivered settlement.
445    #[serde(rename = "DELIVERED_SETTELMENT")]
446    DeliveredSettlement,
447    /// Coin swap deposit.
448    CoinSwapDeposit,
449    /// Coin swap withdraw.
450    CoinSwapWithdraw,
451    /// Position limit increase fee.
452    PositionLimitIncreaseFee,
453    /// Strategy UM futures transfer.
454    StrategyUmfuturesTransfer,
455    /// Fee return.
456    FeeReturn,
457    /// BFUSD reward.
458    BfusdReward,
459    /// Unknown or undocumented value.
460    #[serde(other)]
461    Unknown,
462}
463
464/// Price match mode for futures maker orders.
465#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
466#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
467pub enum BinancePriceMatch {
468    /// No price match (default).
469    None,
470    /// Match opposing side.
471    Opponent,
472    /// Match opposing side with 5 tick offset.
473    #[serde(rename = "OPPONENT_5")]
474    Opponent5,
475    /// Match opposing side with 10 tick offset.
476    #[serde(rename = "OPPONENT_10")]
477    Opponent10,
478    /// Match opposing side with 20 tick offset.
479    #[serde(rename = "OPPONENT_20")]
480    Opponent20,
481    /// Join current queue on same side.
482    Queue,
483    /// Join queue with 5 tick offset.
484    #[serde(rename = "QUEUE_5")]
485    Queue5,
486    /// Join queue with 10 tick offset.
487    #[serde(rename = "QUEUE_10")]
488    Queue10,
489    /// Join queue with 20 tick offset.
490    #[serde(rename = "QUEUE_20")]
491    Queue20,
492    /// Unknown or undocumented value.
493    #[serde(other)]
494    Unknown,
495}
496
497impl BinancePriceMatch {
498    /// Parses a price match mode from a string param value.
499    ///
500    /// Accepts uppercase Binance API values like `"OPPONENT"`, `"OPPONENT_5"`, `"QUEUE_10"`.
501    ///
502    /// # Errors
503    ///
504    /// Returns an error if the value is not a recognized price match mode.
505    pub fn from_param(s: &str) -> anyhow::Result<Self> {
506        let value = s.to_uppercase();
507        serde_json::from_value(serde_json::Value::String(value))
508            .map_err(|_| anyhow::anyhow!("Invalid price_match value: {s:?}"))
509            .and_then(|pm: Self| {
510                if pm == Self::None || pm == Self::Unknown {
511                    anyhow::bail!("Invalid price_match value: {s:?}")
512                }
513                Ok(pm)
514            })
515    }
516}
517
518/// Self-trade prevention mode.
519#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
520#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
521pub enum BinanceSelfTradePreventionMode {
522    /// No self-trade prevention.
523    None,
524    /// Expire maker orders on self-trade.
525    ExpireMaker,
526    /// Expire taker orders on self-trade.
527    ExpireTaker,
528    /// Expire both sides on self-trade.
529    ExpireBoth,
530    /// Decrement and cancel (spot).
531    Decrement,
532    /// Transfer to sub-account (spot).
533    Transfer,
534    /// Unknown or undocumented value.
535    #[serde(other)]
536    Unknown,
537}
538
539/// Trading status for symbols.
540#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
541#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
542pub enum BinanceTradingStatus {
543    /// Trading is active.
544    Trading,
545    /// Pending activation.
546    PendingTrading,
547    /// Pre-trading session.
548    PreTrading,
549    /// Post-trading session.
550    PostTrading,
551    /// End of day.
552    EndOfDay,
553    /// Trading halted.
554    Halt,
555    /// Auction match.
556    AuctionMatch,
557    /// Break period.
558    Break,
559    /// Pre-delivering.
560    PreDelivering,
561    /// Delivering.
562    Delivering,
563    /// Delivered.
564    Delivered,
565    /// Pre-settlement.
566    PreSettle,
567    /// Settling.
568    Settling,
569    /// Closed.
570    Close,
571    /// Trading is halted for an otherwise active contract.
572    TradingHalt,
573    /// New orders are blocked while cancellation remains available.
574    TradingCancelOnly,
575    /// Unknown or undocumented value.
576    #[serde(other)]
577    Unknown,
578}
579
580impl From<BinanceTradingStatus> for MarketStatusAction {
581    fn from(status: BinanceTradingStatus) -> Self {
582        match status {
583            BinanceTradingStatus::Trading => Self::Trading,
584            BinanceTradingStatus::PendingTrading | BinanceTradingStatus::PreTrading => {
585                Self::PreOpen
586            }
587            BinanceTradingStatus::PostTrading => Self::PostClose,
588            BinanceTradingStatus::EndOfDay => Self::Close,
589            BinanceTradingStatus::Halt => Self::Halt,
590            BinanceTradingStatus::AuctionMatch => Self::Cross,
591            BinanceTradingStatus::Break => Self::Pause,
592            BinanceTradingStatus::PreDelivering | BinanceTradingStatus::PreSettle => Self::PreClose,
593            BinanceTradingStatus::Delivering
594            | BinanceTradingStatus::Delivered
595            | BinanceTradingStatus::Settling
596            | BinanceTradingStatus::Close => Self::Close,
597            BinanceTradingStatus::TradingHalt | BinanceTradingStatus::TradingCancelOnly => {
598                Self::Halt
599            }
600            BinanceTradingStatus::Unknown => Self::NotAvailableForTrading,
601        }
602    }
603}
604
605/// Contract status for coin-margined futures.
606#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
607#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
608pub enum BinanceContractStatus {
609    /// Trading is active.
610    Trading,
611    /// Trading is halted for an otherwise active contract.
612    TradingHalt,
613    /// Pending trading.
614    PendingTrading,
615    /// Pre-delivering.
616    PreDelivering,
617    /// Delivering.
618    Delivering,
619    /// Delivered.
620    Delivered,
621    /// Pre-settle.
622    PreSettle,
623    /// Settling.
624    Settling,
625    /// Closed.
626    Close,
627    /// Pre-delist.
628    PreDelisting,
629    /// Delisting in progress.
630    Delisting,
631    /// Contract down.
632    Down,
633    /// New orders are blocked while cancellation remains available.
634    TradingCancelOnly,
635    /// Unknown or undocumented value.
636    #[serde(other)]
637    Unknown,
638}
639
640impl From<BinanceContractStatus> for MarketStatusAction {
641    fn from(status: BinanceContractStatus) -> Self {
642        match status {
643            BinanceContractStatus::Trading => Self::Trading,
644            BinanceContractStatus::TradingHalt | BinanceContractStatus::TradingCancelOnly => {
645                Self::Halt
646            }
647            BinanceContractStatus::PendingTrading => Self::PreOpen,
648            BinanceContractStatus::PreDelivering
649            | BinanceContractStatus::PreDelisting
650            | BinanceContractStatus::PreSettle => Self::PreClose,
651            BinanceContractStatus::Delivering
652            | BinanceContractStatus::Delivered
653            | BinanceContractStatus::Settling
654            | BinanceContractStatus::Close => Self::Close,
655            BinanceContractStatus::Delisting => Self::Suspend,
656            BinanceContractStatus::Down | BinanceContractStatus::Unknown => {
657                Self::NotAvailableForTrading
658            }
659        }
660    }
661}
662
663/// WebSocket stream event types.
664///
665/// These are the "e" field values in WebSocket JSON messages.
666#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
667#[serde(rename_all = "camelCase")]
668pub enum BinanceWsEventType {
669    /// Aggregate trade event.
670    AggTrade,
671    /// Individual trade event.
672    Trade,
673    /// Book ticker (best bid/ask) event.
674    BookTicker,
675    /// Depth update (order book delta) event.
676    DepthUpdate,
677    /// Mark price update event.
678    MarkPriceUpdate,
679    /// Kline/candlestick event.
680    Kline,
681    /// Forced liquidation order event.
682    ForceOrder,
683    /// 24-hour rolling ticker event.
684    #[serde(rename = "24hrTicker")]
685    Ticker24Hr,
686    /// 24-hour rolling mini ticker event.
687    #[serde(rename = "24hrMiniTicker")]
688    MiniTicker24Hr,
689
690    // User data stream events
691    /// Account update (balance and position changes).
692    #[serde(rename = "ACCOUNT_UPDATE")]
693    AccountUpdate,
694    /// Order/trade update event.
695    #[serde(rename = "ORDER_TRADE_UPDATE")]
696    OrderTradeUpdate,
697    /// Trade Lite event (low-latency fill notification).
698    #[serde(rename = "TRADE_LITE")]
699    TradeLite,
700    /// Algo order update event (Binance Futures Algo Service).
701    #[serde(rename = "ALGO_UPDATE")]
702    AlgoUpdate,
703    /// Margin call warning event.
704    #[serde(rename = "MARGIN_CALL")]
705    MarginCall,
706    /// Account configuration update (leverage change).
707    #[serde(rename = "ACCOUNT_CONFIG_UPDATE")]
708    AccountConfigUpdate,
709    /// Listen key expired event.
710    #[serde(rename = "listenKeyExpired")]
711    ListenKeyExpired,
712
713    /// Unknown or undocumented event type.
714    #[serde(other)]
715    Unknown,
716}
717
718impl BinanceWsEventType {
719    /// Returns the wire format string for this event type.
720    #[must_use]
721    pub const fn as_str(self) -> &'static str {
722        match self {
723            Self::AggTrade => "aggTrade",
724            Self::Trade => "trade",
725            Self::BookTicker => "bookTicker",
726            Self::DepthUpdate => "depthUpdate",
727            Self::MarkPriceUpdate => "markPriceUpdate",
728            Self::Kline => "kline",
729            Self::ForceOrder => "forceOrder",
730            Self::Ticker24Hr => "24hrTicker",
731            Self::MiniTicker24Hr => "24hrMiniTicker",
732            Self::AccountUpdate => "ACCOUNT_UPDATE",
733            Self::OrderTradeUpdate => "ORDER_TRADE_UPDATE",
734            Self::TradeLite => "TRADE_LITE",
735            Self::AlgoUpdate => "ALGO_UPDATE",
736            Self::MarginCall => "MARGIN_CALL",
737            Self::AccountConfigUpdate => "ACCOUNT_CONFIG_UPDATE",
738            Self::ListenKeyExpired => "listenKeyExpired",
739            Self::Unknown => "unknown",
740        }
741    }
742}
743
744impl Display for BinanceWsEventType {
745    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
746        write!(f, "{}", self.as_str())
747    }
748}
749
750/// WebSocket request method (operation type).
751///
752/// Used for subscription requests on both Spot and Futures WebSocket APIs.
753#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
754#[serde(rename_all = "UPPERCASE")]
755pub enum BinanceWsMethod {
756    /// Subscribe to streams.
757    Subscribe,
758    /// Unsubscribe from streams.
759    Unsubscribe,
760}
761
762/// Filter type identifiers returned in exchange info.
763#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
764#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
765pub enum BinanceFilterType {
766    /// Price filter.
767    PriceFilter,
768    /// Percent price filter.
769    PercentPrice,
770    /// Percent price by side filter (spot).
771    PercentPriceBySide,
772    /// Lot size filter.
773    LotSize,
774    /// Market lot size filter.
775    MarketLotSize,
776    /// Notional filter (spot).
777    Notional,
778    /// Min notional filter (futures).
779    MinNotional,
780    /// Iceberg parts filter (spot).
781    IcebergParts,
782    /// Maximum number of orders filter.
783    MaxNumOrders,
784    /// Maximum number of algo orders filter.
785    MaxNumAlgoOrders,
786    /// Maximum number of iceberg orders filter (spot).
787    MaxNumIcebergOrders,
788    /// Maximum position filter (spot).
789    MaxPosition,
790    /// Trailing delta filter (spot).
791    TrailingDelta,
792    /// Maximum number of order amends filter (spot).
793    MaxNumOrderAmends,
794    /// Maximum number of order lists filter (spot).
795    MaxNumOrderLists,
796    /// Maximum asset filter (spot).
797    MaxAsset,
798    /// Exchange-level maximum number of orders.
799    ExchangeMaxNumOrders,
800    /// Exchange-level maximum number of algo orders.
801    ExchangeMaxNumAlgoOrders,
802    /// Exchange-level maximum number of iceberg orders.
803    ExchangeMaxNumIcebergOrders,
804    /// Exchange-level maximum number of order lists.
805    ExchangeMaxNumOrderLists,
806    /// T+1 sell restriction filter (spot).
807    TPlusSell,
808    /// Unknown or undocumented value.
809    #[serde(other)]
810    Unknown,
811}
812
813impl Display for BinanceEnvironment {
814    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
815        match self {
816            Self::Live => write!(f, "Live"),
817            Self::Testnet => write!(f, "Testnet"),
818            Self::Demo => write!(f, "Demo"),
819        }
820    }
821}
822
823/// Rate limit type for API request quotas.
824#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
825#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
826pub enum BinanceRateLimitType {
827    /// Weighted request limit.
828    RequestWeight,
829    /// Order placement limit.
830    Orders,
831    /// Raw request count limit (spot).
832    RawRequests,
833    /// Unknown or undocumented value.
834    #[serde(other)]
835    Unknown,
836}
837
838/// Rate limit time interval.
839#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
840#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
841pub enum BinanceRateLimitInterval {
842    /// One second interval.
843    Second,
844    /// One minute interval.
845    Minute,
846    /// One day interval.
847    Day,
848    /// Unknown or undocumented value.
849    #[serde(other)]
850    Unknown,
851}
852
853/// Kline (candlestick) interval.
854///
855/// # References
856/// - <https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints>
857#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
858pub enum BinanceKlineInterval {
859    /// 1 second (only for spot).
860    #[serde(rename = "1s")]
861    Second1,
862    /// 1 minute.
863    #[default]
864    #[serde(rename = "1m")]
865    Minute1,
866    /// 3 minutes.
867    #[serde(rename = "3m")]
868    Minute3,
869    /// 5 minutes.
870    #[serde(rename = "5m")]
871    Minute5,
872    /// 15 minutes.
873    #[serde(rename = "15m")]
874    Minute15,
875    /// 30 minutes.
876    #[serde(rename = "30m")]
877    Minute30,
878    /// 1 hour.
879    #[serde(rename = "1h")]
880    Hour1,
881    /// 2 hours.
882    #[serde(rename = "2h")]
883    Hour2,
884    /// 4 hours.
885    #[serde(rename = "4h")]
886    Hour4,
887    /// 6 hours.
888    #[serde(rename = "6h")]
889    Hour6,
890    /// 8 hours.
891    #[serde(rename = "8h")]
892    Hour8,
893    /// 12 hours.
894    #[serde(rename = "12h")]
895    Hour12,
896    /// 1 day.
897    #[serde(rename = "1d")]
898    Day1,
899    /// 3 days.
900    #[serde(rename = "3d")]
901    Day3,
902    /// 1 week.
903    #[serde(rename = "1w")]
904    Week1,
905    /// 1 month.
906    #[serde(rename = "1M")]
907    Month1,
908}
909
910impl BinanceKlineInterval {
911    /// Returns the string representation used by Binance API.
912    #[must_use]
913    pub const fn as_str(&self) -> &'static str {
914        match self {
915            Self::Second1 => "1s",
916            Self::Minute1 => "1m",
917            Self::Minute3 => "3m",
918            Self::Minute5 => "5m",
919            Self::Minute15 => "15m",
920            Self::Minute30 => "30m",
921            Self::Hour1 => "1h",
922            Self::Hour2 => "2h",
923            Self::Hour4 => "4h",
924            Self::Hour6 => "6h",
925            Self::Hour8 => "8h",
926            Self::Hour12 => "12h",
927            Self::Day1 => "1d",
928            Self::Day3 => "3d",
929            Self::Week1 => "1w",
930            Self::Month1 => "1M",
931        }
932    }
933}
934
935#[cfg(test)]
936mod tests {
937    use rstest::rstest;
938    use serde_json::json;
939
940    use super::*;
941
942    #[rstest]
943    fn test_product_type_as_str() {
944        assert_eq!(BinanceProductType::Spot.as_str(), "SPOT");
945        assert_eq!(BinanceProductType::Margin.as_str(), "MARGIN");
946        assert_eq!(BinanceProductType::UsdM.as_str(), "USD_M");
947        assert_eq!(BinanceProductType::CoinM.as_str(), "COIN_M");
948        assert_eq!(BinanceProductType::Options.as_str(), "OPTIONS");
949    }
950
951    #[rstest]
952    fn test_product_type_suffix() {
953        assert_eq!(BinanceProductType::Spot.suffix(), "-SPOT");
954        assert_eq!(BinanceProductType::Margin.suffix(), "-MARGIN");
955        assert_eq!(BinanceProductType::UsdM.suffix(), "-LINEAR");
956        assert_eq!(BinanceProductType::CoinM.suffix(), "-INVERSE");
957        assert_eq!(BinanceProductType::Options.suffix(), "-OPTION");
958    }
959
960    #[rstest]
961    fn test_product_type_predicates() {
962        assert!(BinanceProductType::Spot.is_spot());
963        assert!(BinanceProductType::Margin.is_spot());
964        assert!(!BinanceProductType::UsdM.is_spot());
965
966        assert!(BinanceProductType::UsdM.is_futures());
967        assert!(BinanceProductType::CoinM.is_futures());
968        assert!(!BinanceProductType::Spot.is_futures());
969
970        assert!(BinanceProductType::CoinM.is_inverse());
971        assert!(!BinanceProductType::UsdM.is_inverse());
972
973        assert!(BinanceProductType::Options.is_options());
974        assert!(!BinanceProductType::Spot.is_options());
975    }
976
977    #[rstest]
978    #[case("\"REQUEST_WEIGHT\"", BinanceRateLimitType::RequestWeight)]
979    #[case("\"ORDERS\"", BinanceRateLimitType::Orders)]
980    #[case("\"RAW_REQUESTS\"", BinanceRateLimitType::RawRequests)]
981    #[case("\"UNDOCUMENTED\"", BinanceRateLimitType::Unknown)]
982    fn test_rate_limit_type_deserializes(
983        #[case] raw: &str,
984        #[case] expected: BinanceRateLimitType,
985    ) {
986        let value: BinanceRateLimitType = serde_json::from_str(raw).unwrap();
987        assert_eq!(value, expected);
988    }
989
990    #[rstest]
991    #[case("\"SECOND\"", BinanceRateLimitInterval::Second)]
992    #[case("\"MINUTE\"", BinanceRateLimitInterval::Minute)]
993    #[case("\"DAY\"", BinanceRateLimitInterval::Day)]
994    #[case("\"WEEK\"", BinanceRateLimitInterval::Unknown)]
995    fn test_rate_limit_interval_deserializes(
996        #[case] raw: &str,
997        #[case] expected: BinanceRateLimitInterval,
998    ) {
999        let value: BinanceRateLimitInterval = serde_json::from_str(raw).unwrap();
1000        assert_eq!(value, expected);
1001    }
1002
1003    #[rstest]
1004    #[case(BinanceMarginType::Cross, "CROSSED", "cross")]
1005    #[case(BinanceMarginType::Isolated, "ISOLATED", "isolated")]
1006    fn test_margin_type_serde_roundtrip(
1007        #[case] variant: BinanceMarginType,
1008        #[case] post_format: &str,
1009        #[case] get_format: &str,
1010    ) {
1011        let serialized = serde_json::to_value(variant).unwrap();
1012        assert_eq!(serialized, json!(post_format));
1013
1014        let from_post: BinanceMarginType =
1015            serde_json::from_str(&format!("\"{post_format}\"")).unwrap();
1016        assert_eq!(from_post, variant);
1017
1018        let from_get: BinanceMarginType =
1019            serde_json::from_str(&format!("\"{get_format}\"")).unwrap();
1020        assert_eq!(from_get, variant);
1021    }
1022
1023    #[rstest]
1024    fn test_margin_type_unknown_fallback() {
1025        let value: BinanceMarginType = serde_json::from_str("\"SOMETHING_NEW\"").unwrap();
1026        assert_eq!(value, BinanceMarginType::Unknown);
1027    }
1028
1029    #[rstest]
1030    fn test_contract_status_trading_halt_deserializes_and_maps() {
1031        // Binance reports `TRADING_HALT` for a temporarily halted active contract.
1032        // It must deserialize to the explicit variant (not the `Unknown` fallback)
1033        // and map deliberately to `Halt`.
1034        let status: BinanceContractStatus = serde_json::from_str("\"TRADING_HALT\"").unwrap();
1035        assert_eq!(status, BinanceContractStatus::TradingHalt);
1036        assert_eq!(MarketStatusAction::from(status), MarketStatusAction::Halt);
1037    }
1038
1039    #[rstest]
1040    fn test_rate_limit_enums_serialize_to_binance_strings() {
1041        assert_eq!(
1042            serde_json::to_value(BinanceRateLimitType::RequestWeight).unwrap(),
1043            json!("REQUEST_WEIGHT")
1044        );
1045        assert_eq!(
1046            serde_json::to_value(BinanceRateLimitInterval::Minute).unwrap(),
1047            json!("MINUTE")
1048        );
1049    }
1050
1051    #[rstest]
1052    #[case("\"NONE\"", BinancePriceMatch::None)]
1053    #[case("\"OPPONENT\"", BinancePriceMatch::Opponent)]
1054    #[case("\"OPPONENT_5\"", BinancePriceMatch::Opponent5)]
1055    #[case("\"OPPONENT_10\"", BinancePriceMatch::Opponent10)]
1056    #[case("\"OPPONENT_20\"", BinancePriceMatch::Opponent20)]
1057    #[case("\"QUEUE\"", BinancePriceMatch::Queue)]
1058    #[case("\"QUEUE_5\"", BinancePriceMatch::Queue5)]
1059    #[case("\"QUEUE_10\"", BinancePriceMatch::Queue10)]
1060    #[case("\"QUEUE_20\"", BinancePriceMatch::Queue20)]
1061    #[case("\"SOMETHING_NEW\"", BinancePriceMatch::Unknown)]
1062    fn test_price_match_deserializes(#[case] raw: &str, #[case] expected: BinancePriceMatch) {
1063        let value: BinancePriceMatch = serde_json::from_str(raw).unwrap();
1064        assert_eq!(value, expected);
1065    }
1066
1067    #[rstest]
1068    #[case(BinancePriceMatch::None, "NONE")]
1069    #[case(BinancePriceMatch::Opponent, "OPPONENT")]
1070    #[case(BinancePriceMatch::Opponent5, "OPPONENT_5")]
1071    #[case(BinancePriceMatch::Opponent10, "OPPONENT_10")]
1072    #[case(BinancePriceMatch::Opponent20, "OPPONENT_20")]
1073    #[case(BinancePriceMatch::Queue, "QUEUE")]
1074    #[case(BinancePriceMatch::Queue5, "QUEUE_5")]
1075    #[case(BinancePriceMatch::Queue10, "QUEUE_10")]
1076    #[case(BinancePriceMatch::Queue20, "QUEUE_20")]
1077    fn test_price_match_serializes(#[case] variant: BinancePriceMatch, #[case] expected: &str) {
1078        let serialized = serde_json::to_value(variant).unwrap();
1079        assert_eq!(serialized, json!(expected));
1080    }
1081
1082    #[rstest]
1083    #[case("OPPONENT", BinancePriceMatch::Opponent)]
1084    #[case("opponent", BinancePriceMatch::Opponent)]
1085    #[case("OPPONENT_5", BinancePriceMatch::Opponent5)]
1086    #[case("opponent_5", BinancePriceMatch::Opponent5)]
1087    #[case("QUEUE_20", BinancePriceMatch::Queue20)]
1088    #[case("queue_20", BinancePriceMatch::Queue20)]
1089    fn test_price_match_from_param_valid(#[case] input: &str, #[case] expected: BinancePriceMatch) {
1090        let result = BinancePriceMatch::from_param(input).unwrap();
1091        assert_eq!(result, expected);
1092    }
1093
1094    #[rstest]
1095    #[case("NONE")]
1096    #[case("invalid")]
1097    #[case("")]
1098    fn test_price_match_from_param_invalid(#[case] input: &str) {
1099        BinancePriceMatch::from_param(input).unwrap_err();
1100    }
1101}