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/// Trade type in the `X` field of USD-M Futures `<symbol>@trade` stream messages.
751///
752/// Binance does not document the USD-M raw trade stream. Its aggregate trade stream
753/// excludes insurance fund and ADL trades.
754#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
755#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
756pub enum BinanceFuturesTradeType {
757    /// Order book trade.
758    Market,
759    /// Order book trade against a Retail Price Improvement order.
760    Rpi,
761    /// Insurance fund trade.
762    InsuranceFund,
763    /// Auto-deleveraging trade.
764    Adl,
765    /// Not a trade; the message carries zero price and quantity.
766    Na,
767    /// Unknown or undocumented value.
768    #[serde(other)]
769    Unknown,
770}
771
772/// WebSocket request method (operation type).
773///
774/// Used for subscription requests on both Spot and Futures WebSocket APIs.
775#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
776#[serde(rename_all = "UPPERCASE")]
777pub enum BinanceWsMethod {
778    /// Subscribe to streams.
779    Subscribe,
780    /// Unsubscribe from streams.
781    Unsubscribe,
782}
783
784/// Filter type identifiers returned in exchange info.
785#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
786#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
787pub enum BinanceFilterType {
788    /// Price filter.
789    PriceFilter,
790    /// Percent price filter.
791    PercentPrice,
792    /// Percent price by side filter (spot).
793    PercentPriceBySide,
794    /// Lot size filter.
795    LotSize,
796    /// Market lot size filter.
797    MarketLotSize,
798    /// Notional filter (spot).
799    Notional,
800    /// Min notional filter (futures).
801    MinNotional,
802    /// Iceberg parts filter (spot).
803    IcebergParts,
804    /// Maximum number of orders filter.
805    MaxNumOrders,
806    /// Maximum number of algo orders filter.
807    MaxNumAlgoOrders,
808    /// Maximum number of iceberg orders filter (spot).
809    MaxNumIcebergOrders,
810    /// Maximum position filter (spot).
811    MaxPosition,
812    /// Trailing delta filter (spot).
813    TrailingDelta,
814    /// Maximum number of order amends filter (spot).
815    MaxNumOrderAmends,
816    /// Maximum number of order lists filter (spot).
817    MaxNumOrderLists,
818    /// Maximum asset filter (spot).
819    MaxAsset,
820    /// Exchange-level maximum number of orders.
821    ExchangeMaxNumOrders,
822    /// Exchange-level maximum number of algo orders.
823    ExchangeMaxNumAlgoOrders,
824    /// Exchange-level maximum number of iceberg orders.
825    ExchangeMaxNumIcebergOrders,
826    /// Exchange-level maximum number of order lists.
827    ExchangeMaxNumOrderLists,
828    /// T+1 sell restriction filter (spot).
829    TPlusSell,
830    /// Unknown or undocumented value.
831    #[serde(other)]
832    Unknown,
833}
834
835impl Display for BinanceEnvironment {
836    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
837        match self {
838            Self::Live => write!(f, "Live"),
839            Self::Testnet => write!(f, "Testnet"),
840            Self::Demo => write!(f, "Demo"),
841        }
842    }
843}
844
845/// Rate limit type for API request quotas.
846#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
847#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
848pub enum BinanceRateLimitType {
849    /// Weighted request limit.
850    RequestWeight,
851    /// Order placement limit.
852    Orders,
853    /// Raw request count limit (spot).
854    RawRequests,
855    /// Unknown or undocumented value.
856    #[serde(other)]
857    Unknown,
858}
859
860/// Rate limit time interval.
861#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
862#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
863pub enum BinanceRateLimitInterval {
864    /// One second interval.
865    Second,
866    /// One minute interval.
867    Minute,
868    /// One day interval.
869    Day,
870    /// Unknown or undocumented value.
871    #[serde(other)]
872    Unknown,
873}
874
875/// Kline (candlestick) interval.
876///
877/// # References
878/// - <https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints>
879#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
880pub enum BinanceKlineInterval {
881    /// 1 second (only for spot).
882    #[serde(rename = "1s")]
883    Second1,
884    /// 1 minute.
885    #[default]
886    #[serde(rename = "1m")]
887    Minute1,
888    /// 3 minutes.
889    #[serde(rename = "3m")]
890    Minute3,
891    /// 5 minutes.
892    #[serde(rename = "5m")]
893    Minute5,
894    /// 15 minutes.
895    #[serde(rename = "15m")]
896    Minute15,
897    /// 30 minutes.
898    #[serde(rename = "30m")]
899    Minute30,
900    /// 1 hour.
901    #[serde(rename = "1h")]
902    Hour1,
903    /// 2 hours.
904    #[serde(rename = "2h")]
905    Hour2,
906    /// 4 hours.
907    #[serde(rename = "4h")]
908    Hour4,
909    /// 6 hours.
910    #[serde(rename = "6h")]
911    Hour6,
912    /// 8 hours.
913    #[serde(rename = "8h")]
914    Hour8,
915    /// 12 hours.
916    #[serde(rename = "12h")]
917    Hour12,
918    /// 1 day.
919    #[serde(rename = "1d")]
920    Day1,
921    /// 3 days.
922    #[serde(rename = "3d")]
923    Day3,
924    /// 1 week.
925    #[serde(rename = "1w")]
926    Week1,
927    /// 1 month.
928    #[serde(rename = "1M")]
929    Month1,
930}
931
932impl BinanceKlineInterval {
933    /// Returns the string representation used by Binance API.
934    #[must_use]
935    pub const fn as_str(&self) -> &'static str {
936        match self {
937            Self::Second1 => "1s",
938            Self::Minute1 => "1m",
939            Self::Minute3 => "3m",
940            Self::Minute5 => "5m",
941            Self::Minute15 => "15m",
942            Self::Minute30 => "30m",
943            Self::Hour1 => "1h",
944            Self::Hour2 => "2h",
945            Self::Hour4 => "4h",
946            Self::Hour6 => "6h",
947            Self::Hour8 => "8h",
948            Self::Hour12 => "12h",
949            Self::Day1 => "1d",
950            Self::Day3 => "3d",
951            Self::Week1 => "1w",
952            Self::Month1 => "1M",
953        }
954    }
955}
956
957#[cfg(test)]
958mod tests {
959    use rstest::rstest;
960    use serde_json::json;
961
962    use super::*;
963
964    #[rstest]
965    fn test_product_type_as_str() {
966        assert_eq!(BinanceProductType::Spot.as_str(), "SPOT");
967        assert_eq!(BinanceProductType::Margin.as_str(), "MARGIN");
968        assert_eq!(BinanceProductType::UsdM.as_str(), "USD_M");
969        assert_eq!(BinanceProductType::CoinM.as_str(), "COIN_M");
970        assert_eq!(BinanceProductType::Options.as_str(), "OPTIONS");
971    }
972
973    #[rstest]
974    fn test_product_type_suffix() {
975        assert_eq!(BinanceProductType::Spot.suffix(), "-SPOT");
976        assert_eq!(BinanceProductType::Margin.suffix(), "-MARGIN");
977        assert_eq!(BinanceProductType::UsdM.suffix(), "-LINEAR");
978        assert_eq!(BinanceProductType::CoinM.suffix(), "-INVERSE");
979        assert_eq!(BinanceProductType::Options.suffix(), "-OPTION");
980    }
981
982    #[rstest]
983    fn test_product_type_predicates() {
984        assert!(BinanceProductType::Spot.is_spot());
985        assert!(BinanceProductType::Margin.is_spot());
986        assert!(!BinanceProductType::UsdM.is_spot());
987
988        assert!(BinanceProductType::UsdM.is_futures());
989        assert!(BinanceProductType::CoinM.is_futures());
990        assert!(!BinanceProductType::Spot.is_futures());
991
992        assert!(BinanceProductType::CoinM.is_inverse());
993        assert!(!BinanceProductType::UsdM.is_inverse());
994
995        assert!(BinanceProductType::Options.is_options());
996        assert!(!BinanceProductType::Spot.is_options());
997    }
998
999    #[rstest]
1000    #[case("\"REQUEST_WEIGHT\"", BinanceRateLimitType::RequestWeight)]
1001    #[case("\"ORDERS\"", BinanceRateLimitType::Orders)]
1002    #[case("\"RAW_REQUESTS\"", BinanceRateLimitType::RawRequests)]
1003    #[case("\"UNDOCUMENTED\"", BinanceRateLimitType::Unknown)]
1004    fn test_rate_limit_type_deserializes(
1005        #[case] raw: &str,
1006        #[case] expected: BinanceRateLimitType,
1007    ) {
1008        let value: BinanceRateLimitType = serde_json::from_str(raw).unwrap();
1009        assert_eq!(value, expected);
1010    }
1011
1012    #[rstest]
1013    #[case("\"MARKET\"", BinanceFuturesTradeType::Market)]
1014    #[case("\"RPI\"", BinanceFuturesTradeType::Rpi)]
1015    #[case("\"INSURANCE_FUND\"", BinanceFuturesTradeType::InsuranceFund)]
1016    #[case("\"ADL\"", BinanceFuturesTradeType::Adl)]
1017    #[case("\"NA\"", BinanceFuturesTradeType::Na)]
1018    #[case("\"UNDOCUMENTED\"", BinanceFuturesTradeType::Unknown)]
1019    fn test_futures_trade_type_deserializes(
1020        #[case] raw: &str,
1021        #[case] expected: BinanceFuturesTradeType,
1022    ) {
1023        let value: BinanceFuturesTradeType = serde_json::from_str(raw).unwrap();
1024        assert_eq!(value, expected);
1025    }
1026
1027    #[rstest]
1028    #[case("\"SECOND\"", BinanceRateLimitInterval::Second)]
1029    #[case("\"MINUTE\"", BinanceRateLimitInterval::Minute)]
1030    #[case("\"DAY\"", BinanceRateLimitInterval::Day)]
1031    #[case("\"WEEK\"", BinanceRateLimitInterval::Unknown)]
1032    fn test_rate_limit_interval_deserializes(
1033        #[case] raw: &str,
1034        #[case] expected: BinanceRateLimitInterval,
1035    ) {
1036        let value: BinanceRateLimitInterval = serde_json::from_str(raw).unwrap();
1037        assert_eq!(value, expected);
1038    }
1039
1040    #[rstest]
1041    #[case(BinanceMarginType::Cross, "CROSSED", "cross")]
1042    #[case(BinanceMarginType::Isolated, "ISOLATED", "isolated")]
1043    fn test_margin_type_serde_roundtrip(
1044        #[case] variant: BinanceMarginType,
1045        #[case] post_format: &str,
1046        #[case] get_format: &str,
1047    ) {
1048        let serialized = serde_json::to_value(variant).unwrap();
1049        assert_eq!(serialized, json!(post_format));
1050
1051        let from_post: BinanceMarginType =
1052            serde_json::from_str(&format!("\"{post_format}\"")).unwrap();
1053        assert_eq!(from_post, variant);
1054
1055        let from_get: BinanceMarginType =
1056            serde_json::from_str(&format!("\"{get_format}\"")).unwrap();
1057        assert_eq!(from_get, variant);
1058    }
1059
1060    #[rstest]
1061    fn test_margin_type_unknown_fallback() {
1062        let value: BinanceMarginType = serde_json::from_str("\"SOMETHING_NEW\"").unwrap();
1063        assert_eq!(value, BinanceMarginType::Unknown);
1064    }
1065
1066    #[rstest]
1067    fn test_contract_status_trading_halt_deserializes_and_maps() {
1068        // Binance reports `TRADING_HALT` for a temporarily halted active contract.
1069        // It must deserialize to the explicit variant (not the `Unknown` fallback)
1070        // and map deliberately to `Halt`.
1071        let status: BinanceContractStatus = serde_json::from_str("\"TRADING_HALT\"").unwrap();
1072        assert_eq!(status, BinanceContractStatus::TradingHalt);
1073        assert_eq!(MarketStatusAction::from(status), MarketStatusAction::Halt);
1074    }
1075
1076    #[rstest]
1077    fn test_rate_limit_enums_serialize_to_binance_strings() {
1078        assert_eq!(
1079            serde_json::to_value(BinanceRateLimitType::RequestWeight).unwrap(),
1080            json!("REQUEST_WEIGHT")
1081        );
1082        assert_eq!(
1083            serde_json::to_value(BinanceRateLimitInterval::Minute).unwrap(),
1084            json!("MINUTE")
1085        );
1086    }
1087
1088    #[rstest]
1089    #[case("\"NONE\"", BinancePriceMatch::None)]
1090    #[case("\"OPPONENT\"", BinancePriceMatch::Opponent)]
1091    #[case("\"OPPONENT_5\"", BinancePriceMatch::Opponent5)]
1092    #[case("\"OPPONENT_10\"", BinancePriceMatch::Opponent10)]
1093    #[case("\"OPPONENT_20\"", BinancePriceMatch::Opponent20)]
1094    #[case("\"QUEUE\"", BinancePriceMatch::Queue)]
1095    #[case("\"QUEUE_5\"", BinancePriceMatch::Queue5)]
1096    #[case("\"QUEUE_10\"", BinancePriceMatch::Queue10)]
1097    #[case("\"QUEUE_20\"", BinancePriceMatch::Queue20)]
1098    #[case("\"SOMETHING_NEW\"", BinancePriceMatch::Unknown)]
1099    fn test_price_match_deserializes(#[case] raw: &str, #[case] expected: BinancePriceMatch) {
1100        let value: BinancePriceMatch = serde_json::from_str(raw).unwrap();
1101        assert_eq!(value, expected);
1102    }
1103
1104    #[rstest]
1105    #[case(BinancePriceMatch::None, "NONE")]
1106    #[case(BinancePriceMatch::Opponent, "OPPONENT")]
1107    #[case(BinancePriceMatch::Opponent5, "OPPONENT_5")]
1108    #[case(BinancePriceMatch::Opponent10, "OPPONENT_10")]
1109    #[case(BinancePriceMatch::Opponent20, "OPPONENT_20")]
1110    #[case(BinancePriceMatch::Queue, "QUEUE")]
1111    #[case(BinancePriceMatch::Queue5, "QUEUE_5")]
1112    #[case(BinancePriceMatch::Queue10, "QUEUE_10")]
1113    #[case(BinancePriceMatch::Queue20, "QUEUE_20")]
1114    fn test_price_match_serializes(#[case] variant: BinancePriceMatch, #[case] expected: &str) {
1115        let serialized = serde_json::to_value(variant).unwrap();
1116        assert_eq!(serialized, json!(expected));
1117    }
1118
1119    #[rstest]
1120    #[case("OPPONENT", BinancePriceMatch::Opponent)]
1121    #[case("opponent", BinancePriceMatch::Opponent)]
1122    #[case("OPPONENT_5", BinancePriceMatch::Opponent5)]
1123    #[case("opponent_5", BinancePriceMatch::Opponent5)]
1124    #[case("QUEUE_20", BinancePriceMatch::Queue20)]
1125    #[case("queue_20", BinancePriceMatch::Queue20)]
1126    fn test_price_match_from_param_valid(#[case] input: &str, #[case] expected: BinancePriceMatch) {
1127        let result = BinancePriceMatch::from_param(input).unwrap();
1128        assert_eq!(result, expected);
1129    }
1130
1131    #[rstest]
1132    #[case("NONE")]
1133    #[case("invalid")]
1134    #[case("")]
1135    fn test_price_match_from_param_invalid(#[case] input: &str) {
1136        BinancePriceMatch::from_param(input).unwrap_err();
1137    }
1138}