Skip to main content

nautilus_binance/
config.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 adapter configuration structures.
17
18use std::{any::Any, collections::HashMap, fmt::Debug, str::FromStr, time::Duration};
19
20use nautilus_common::{config::check_unique_values, factories::ClientConfig};
21#[cfg(test)]
22use nautilus_core::string::secret::REDACTED;
23use nautilus_core::string::secret::SecretString;
24use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
25use nautilus_model::{
26    enums::OmsType,
27    identifiers::{AccountId, InstrumentId},
28    types::Currency,
29};
30use nautilus_network::{
31    backoff::ExponentialBackoff, retry::RetryConfig, websocket::TransportBackend,
32};
33use rust_decimal::Decimal;
34use serde::{Deserialize, Serialize};
35
36use crate::common::{
37    enums::{BinanceEnvironment, BinanceMarginType, BinanceProductType},
38    instruments::filter_values,
39};
40
41/// Configuration for Binance instrument loading.
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, bon::Builder)]
43#[serde(default, deny_unknown_fields)]
44#[cfg_attr(
45    feature = "python",
46    pyo3::pyclass(module = "nautilus_trader.adapters.binance", from_py_object)
47)]
48#[cfg_attr(
49    feature = "python",
50    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.binance")
51)]
52pub struct BinanceInstrumentProviderConfig {
53    /// Whether to load all instruments on startup.
54    #[builder(default = true)]
55    pub load_all: bool,
56    /// Specific Nautilus instrument IDs to load when `load_all` is false.
57    pub load_ids: Option<Vec<String>>,
58    /// Venue filters applied while loading instruments.
59    ///
60    /// Supported keys are `symbols`, `bases`, `quotes`, and, for Futures,
61    /// `contract_types`. Each value may be a string or an array of strings.
62    #[builder(default)]
63    pub filters: HashMap<String, serde_json::Value>,
64    /// Fully qualified Python callable path requested by legacy configuration.
65    ///
66    /// Binance v2 rejects this field because the legacy Binance provider never
67    /// applied it and Rust live clients cannot safely invoke arbitrary Python.
68    pub filter_callable: Option<String>,
69    /// Whether instrument parser failures should be logged as warnings.
70    ///
71    /// Non-trading symbols skipped during bulk loads always log at debug;
72    /// this flag applies to explicitly selected symbols and unexpected failures.
73    #[builder(default = true)]
74    pub log_warnings: bool,
75    /// Whether to query account-specific commission rates for every loaded symbol.
76    #[builder(default)]
77    pub query_commission_rates: bool,
78}
79
80impl Default for BinanceInstrumentProviderConfig {
81    fn default() -> Self {
82        Self::builder().build()
83    }
84}
85
86impl BinanceInstrumentProviderConfig {
87    /// Validates instrument loading configuration.
88    ///
89    /// Filter selection uniqueness uses trimmed, uppercase values.
90    ///
91    /// # Errors
92    ///
93    /// Returns an error if IDs are malformed, selections contain duplicates, filters are
94    /// unsupported, or a legacy callable filter cannot run safely in Binance v2.
95    pub fn validate(&self, product_type: BinanceProductType) -> anyhow::Result<()> {
96        if let Some(filter_callable) = self
97            .filter_callable
98            .as_deref()
99            .map(str::trim)
100            .filter(|value| !value.is_empty())
101        {
102            anyhow::bail!(
103                "Binance v2 does not support instrument filter_callable {filter_callable:?}; \
104                 the legacy Binance provider never applied callable filters"
105            );
106        }
107
108        if let Some(load_ids) = &self.load_ids {
109            for raw in load_ids {
110                let instrument_id = InstrumentId::from_str(raw)
111                    .map_err(|e| anyhow::anyhow!("invalid Binance load_ids value {raw:?}: {e}"))?;
112                anyhow::ensure!(
113                    instrument_id.venue.as_str() == "BINANCE",
114                    "Binance load_ids value {raw:?} must use venue BINANCE"
115                );
116            }
117        }
118
119        for (key, value) in &self.filters {
120            let supported = matches!(key.as_str(), "symbols" | "bases" | "quotes")
121                || key == "contract_types"
122                    && matches!(
123                        product_type,
124                        BinanceProductType::UsdM | BinanceProductType::CoinM
125                    );
126            anyhow::ensure!(
127                supported,
128                "unsupported Binance instrument filter {key:?} for {product_type:?}"
129            );
130            validate_filter_strings(key, value)?;
131        }
132
133        self.validate_selections()?;
134        Ok(())
135    }
136
137    pub(crate) fn validate_selections(&self) -> anyhow::Result<()> {
138        if let Some(values) = &self.load_ids {
139            check_unique_values("instrument_provider.load_ids", values)?;
140        }
141
142        for (name, value) in &self.filters {
143            if value.is_array() {
144                filter_values(self, name)?;
145            }
146        }
147
148        Ok(())
149    }
150
151    pub(crate) fn excludes(&self, instrument_id: InstrumentId) -> bool {
152        !self.load_all
153            && self.load_ids.as_ref().is_some_and(|load_ids| {
154                load_ids
155                    .iter()
156                    .all(|raw_id| InstrumentId::from(raw_id.as_str()) != instrument_id)
157            })
158    }
159}
160
161fn validate_filter_strings(name: &str, value: &serde_json::Value) -> anyhow::Result<()> {
162    let valid = match value {
163        serde_json::Value::String(value) => !value.trim().is_empty(),
164        serde_json::Value::Array(values) => {
165            !values.is_empty()
166                && values
167                    .iter()
168                    .all(|value| value.as_str().is_some_and(|value| !value.trim().is_empty()))
169        }
170        _ => false,
171    };
172
173    anyhow::ensure!(
174        valid,
175        "Binance instrument filter {name:?} must be a non-empty string or array of strings"
176    );
177
178    Ok(())
179}
180
181/// Spot market-data transport mode.
182#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
183#[cfg_attr(
184    feature = "python",
185    pyo3::pyclass(module = "nautilus_trader.adapters.binance", eq, from_py_object)
186)]
187#[cfg_attr(
188    feature = "python",
189    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.adapters.binance")
190)]
191pub enum BinanceSpotMarketDataMode {
192    #[default]
193    /// Spot SBE streams (requires Ed25519 credentials).
194    Sbe,
195    /// Force Spot public JSON streams (does not require credentials).
196    Json,
197}
198
199/// Configuration for Binance data client.
200///
201/// Ed25519 API keys are required for SBE WebSocket streams.
202#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
203#[serde(default, deny_unknown_fields)]
204#[cfg_attr(
205    feature = "python",
206    pyo3::pyclass(module = "nautilus_trader.adapters.binance", from_py_object)
207)]
208#[cfg_attr(
209    feature = "python",
210    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.binance")
211)]
212pub struct BinanceDataClientConfig {
213    /// Product type to subscribe to.
214    #[builder(default = BinanceProductType::Spot)]
215    pub product_type: BinanceProductType,
216    /// Environment (live, testnet, or demo).
217    #[builder(default = BinanceEnvironment::Live)]
218    pub environment: BinanceEnvironment,
219    /// API key (Ed25519).
220    pub api_key: Option<SecretString>,
221    /// API secret (Ed25519 base64-encoded or PEM).
222    pub api_secret: Option<SecretString>,
223    /// Optional base URL override for HTTP API.
224    pub base_url_http: Option<String>,
225    /// Optional base URL override for WebSocket.
226    ///
227    /// Live USD-M Futures data overrides are normalized onto the matching
228    /// `/market/ws` and `/public/ws` routes.
229    pub base_url_ws: Option<String>,
230    /// Optional proxy URL for HTTP and WebSocket transports.
231    pub proxy_url: Option<SecretString>,
232    /// Spot market-data transport mode.
233    ///
234    /// - `Sbe` uses SBE streams and requires Ed25519 credentials.
235    /// - `Json` forces public JSON streams with no credentials.
236    #[builder(default)]
237    pub spot_market_data_mode: BinanceSpotMarketDataMode,
238    /// Whether USD-M Futures trade subscriptions use the raw `<symbol>@trade` stream.
239    ///
240    /// When false, trades come from `<symbol>@aggTrade`. When true, each order book trade
241    /// emits one `TradeTick` with the venue trade ID instead of the aggregate trade ID.
242    /// Binance serves the raw stream on the public route but does not list it in the
243    /// USD-M market stream documentation. Supported for USD-M Futures clients only.
244    #[builder(default)]
245    pub use_usdm_raw_trades: bool,
246    /// Instrument loading and fee configuration.
247    #[builder(default)]
248    pub instrument_provider: BinanceInstrumentProviderConfig,
249    /// Interval in seconds for a full instrument catalog refresh.
250    ///
251    /// Set to 0 to disable. Defaults to 3600 (60 minutes).
252    #[builder(default = 3600)]
253    pub instrument_refresh_interval_secs: u64,
254    /// Interval in seconds for polling exchange info to detect instrument status
255    /// changes (e.g. Trading -> Halt). Set to 0 to disable. Defaults to 3600 (60 minutes).
256    #[builder(default = 3600)]
257    pub instrument_status_poll_secs: u64,
258    /// Maximum time to wait for an initial, post-reconnect, or recovery order book
259    /// snapshot in seconds.
260    ///
261    /// Bounds each REST depth snapshot request for diff depth books. Set to 0 to disable.
262    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
263    pub book_snapshot_timeout_secs: u64,
264    /// Receive window in milliseconds for signed HTTP requests.
265    #[builder(default = 5_000)]
266    pub recv_window_ms: u64,
267    /// Maximum retries for HTTP GET requests. Mutating requests are sent once.
268    #[builder(default = RetryConfig::default().max_retries)]
269    pub max_retries: u32,
270    /// Initial HTTP retry delay in milliseconds.
271    #[builder(default = RetryConfig::default().initial_delay_ms)]
272    pub retry_delay_initial_ms: u64,
273    /// Maximum exponential HTTP retry delay in milliseconds.
274    #[builder(default = RetryConfig::default().max_delay_ms)]
275    pub retry_delay_max_ms: u64,
276    /// Whether to route this Spot client to Binance US.
277    #[builder(default)]
278    pub us: bool,
279    /// WebSocket transport backend (defaults to `Tungstenite`).
280    #[builder(default)]
281    pub transport_backend: TransportBackend,
282}
283
284#[cfg(feature = "python")]
285nautilus_core::impl_pyo3_config_getters!(BinanceDataClientConfig {
286    product_type: BinanceProductType,
287    environment: BinanceEnvironment,
288    base_url_http: Option<String>,
289    base_url_ws: Option<String>,
290    spot_market_data_mode: BinanceSpotMarketDataMode,
291    use_usdm_raw_trades: bool,
292    instrument_provider: BinanceInstrumentProviderConfig,
293    instrument_refresh_interval_secs: u64,
294    instrument_status_poll_secs: u64,
295    book_snapshot_timeout_secs: u64,
296    recv_window_ms: u64,
297    max_retries: u32,
298    retry_delay_initial_ms: u64,
299    retry_delay_max_ms: u64,
300    us: bool,
301    transport_backend: TransportBackend,
302});
303
304impl Default for BinanceDataClientConfig {
305    fn default() -> Self {
306        Self::builder().build()
307    }
308}
309
310impl BinanceDataClientConfig {
311    /// Validates Binance data client configuration.
312    ///
313    /// # Errors
314    ///
315    /// Returns an error if the receive-window, provider, raw trade, or Binance US settings are
316    /// invalid.
317    pub fn validate(&self) -> anyhow::Result<()> {
318        validate_recv_window(self.recv_window_ms)?;
319        validate_retry_config(&self.retry_config())?;
320        self.instrument_provider.validate(self.product_type)?;
321
322        if self.use_usdm_raw_trades {
323            anyhow::ensure!(
324                self.product_type == BinanceProductType::UsdM,
325                "use_usdm_raw_trades supports USD-M Futures clients only"
326            );
327        }
328
329        if self.us {
330            anyhow::ensure!(
331                self.product_type == BinanceProductType::Spot,
332                "Binance US supports Spot clients only"
333            );
334            anyhow::ensure!(
335                self.environment == BinanceEnvironment::Live,
336                "Binance US supports the Live environment only"
337            );
338            anyhow::ensure!(
339                self.spot_market_data_mode == BinanceSpotMarketDataMode::Json,
340                "Binance US market data requires spot_market_data_mode=Json"
341            );
342        }
343
344        Ok(())
345    }
346
347    pub(crate) fn retry_config(&self) -> RetryConfig {
348        RetryConfig {
349            max_retries: self.max_retries,
350            initial_delay_ms: self.retry_delay_initial_ms,
351            max_delay_ms: self.retry_delay_max_ms,
352            ..crate::common::http::retry_config()
353        }
354    }
355}
356
357impl ClientConfig for BinanceDataClientConfig {
358    fn as_any(&self) -> &dyn Any {
359        self
360    }
361}
362
363/// Configuration for Binance execution client.
364///
365/// Global execution uses WebSocket API authentication with Ed25519 credentials.
366/// Binance US uses HMAC-signed HTTP requests and listen-key user data streams.
367#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
368#[serde(default, deny_unknown_fields)]
369#[cfg_attr(
370    feature = "python",
371    pyo3::pyclass(module = "nautilus_trader.adapters.binance", from_py_object)
372)]
373#[cfg_attr(
374    feature = "python",
375    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.binance")
376)]
377pub struct BinanceExecutionClientConfig {
378    /// Account ID for the client.
379    #[builder(default = AccountId::from("BINANCE-001"))]
380    pub account_id: AccountId,
381    /// Product type to trade.
382    #[builder(default = BinanceProductType::Spot)]
383    pub product_type: BinanceProductType,
384    /// Environment (live, testnet, or demo).
385    #[builder(default = BinanceEnvironment::Live)]
386    pub environment: BinanceEnvironment,
387    /// API key (uses an environment variable if not provided).
388    pub api_key: Option<SecretString>,
389    /// API secret (Ed25519 for Global or HMAC for Binance US).
390    pub api_secret: Option<SecretString>,
391    /// Optional base URL override for HTTP API.
392    pub base_url_http: Option<String>,
393    /// Optional base URL override for WebSocket user data stream.
394    ///
395    /// Live USD-M Futures stream overrides are normalized onto the `/private/ws` route.
396    pub base_url_ws: Option<String>,
397    /// Optional base URL override for WebSocket trading API (Spot and USD-M Futures).
398    pub base_url_ws_trading: Option<String>,
399    /// Optional proxy URL for HTTP and WebSocket transports.
400    pub proxy_url: Option<SecretString>,
401    /// Whether to use the WebSocket trading API for order operations (Spot and USD-M Futures).
402    #[builder(default = true)]
403    pub use_ws_trading: bool,
404    /// Timeout in milliseconds for each Binance Spot WS trading setup response.
405    #[builder(default = 10_000)]
406    pub ws_trading_setup_timeout_ms: u64,
407    /// Instrument loading and fee configuration.
408    #[builder(default)]
409    pub instrument_provider: BinanceInstrumentProviderConfig,
410    /// Interval in seconds for refreshing the execution instrument cache.
411    ///
412    /// Set to 0 to disable. Defaults to 3600 (60 minutes).
413    #[builder(default = 3600)]
414    pub instrument_refresh_interval_secs: u64,
415    /// Whether to use Binance-native GTD orders.
416    ///
417    /// Set to false only when the strategy manages GTD expiry locally. The adapter then maps GTD
418    /// to GTC and the strategy must enable `manage_gtd_expiry`.
419    #[builder(default = true)]
420    pub use_gtd: bool,
421    /// Whether to use canonical Binance Futures position IDs.
422    ///
423    /// When true, Futures hedge-mode order and fill reports include a `venue_position_id` derived
424    /// from the instrument and Binance position side (e.g. `ETHUSDT-PERP.BINANCE-LONG`). Hedge-mode
425    /// REST position reports use the same IDs. One-way `BOTH` reports remain unkeyed. When false,
426    /// `venue_position_id` is None, allowing virtual positions with `OmsType::Hedging`.
427    #[builder(default = true)]
428    pub use_position_ids: bool,
429    /// Optional OMS type override for Binance Futures accounts.
430    ///
431    /// Set to `Hedging` when the account uses dual-side position mode. When
432    /// `None`, Binance Futures clients use `Netting`. Ignored for Spot clients.
433    pub oms_type: Option<OmsType>,
434    /// Default taker fee rate for commission estimation.
435    ///
436    /// Used as a fallback when the venue omits commission fields in
437    /// exchange-generated fills (liquidation, ADL, settlement).
438    /// Standard Binance Futures taker fee is 0.0004 (0.04%).
439    #[builder(default = Decimal::new(4, 4))]
440    pub default_taker_fee: Decimal,
441    /// Receive window in milliseconds for signed HTTP requests.
442    #[builder(default = 5_000)]
443    pub recv_window_ms: u64,
444    /// Maximum retries for HTTP GET requests. Mutating requests are sent once.
445    #[builder(default = RetryConfig::default().max_retries)]
446    pub max_retries: u32,
447    /// Initial HTTP retry delay in milliseconds.
448    #[builder(default = RetryConfig::default().initial_delay_ms)]
449    pub retry_delay_initial_ms: u64,
450    /// Maximum exponential HTTP retry delay in milliseconds.
451    #[builder(default = RetryConfig::default().max_delay_ms)]
452    pub retry_delay_max_ms: u64,
453    /// Whether to route this Spot client to Binance US.
454    #[builder(default)]
455    pub us: bool,
456    /// Initial leverage per Binance symbol (e.g. BTCUSDT -> 20), applied during connect.
457    pub futures_leverages: Option<HashMap<String, u32>>,
458    /// Margin type per Binance symbol (e.g. BTCUSDT -> Cross), applied during connect.
459    pub futures_margin_types: Option<HashMap<String, BinanceMarginType>>,
460    /// Currency that Binance Futures Credits (`BNFCR`) balances and fees resolve to (defaults to USDT).
461    #[builder(default = Currency::USDT())]
462    pub bnfcr_currency: Currency,
463    /// If true, the EXPIRED execution type emits `OrderCanceled` instead of `OrderExpired`.
464    ///
465    /// Binance uses EXPIRED for certain cancel scenarios depending on order type
466    /// and time-in-force combination.
467    #[builder(default = false)]
468    pub treat_expired_as_canceled: bool,
469    /// If true, drive fills from the lower-latency `TRADE_LITE` user data event
470    /// and dedup the matching fill portion of `ORDER_TRADE_UPDATE`. If false,
471    /// `TRADE_LITE` events are ignored and fills come from `ORDER_TRADE_UPDATE`.
472    #[builder(default = false)]
473    pub use_trade_lite: bool,
474    /// WebSocket transport backend (defaults to `Tungstenite`).
475    #[builder(default)]
476    pub transport_backend: TransportBackend,
477}
478
479#[cfg(feature = "python")]
480nautilus_core::impl_pyo3_config_getters!(BinanceExecutionClientConfig {
481    account_id: AccountId,
482    product_type: BinanceProductType,
483    environment: BinanceEnvironment,
484    base_url_http: Option<String>,
485    base_url_ws: Option<String>,
486    base_url_ws_trading: Option<String>,
487    use_ws_trading: bool,
488    ws_trading_setup_timeout_ms: u64,
489    instrument_provider: BinanceInstrumentProviderConfig,
490    instrument_refresh_interval_secs: u64,
491    use_gtd: bool,
492    use_position_ids: bool,
493    oms_type: Option<OmsType>,
494    default_taker_fee: Decimal,
495    recv_window_ms: u64,
496    max_retries: u32,
497    retry_delay_initial_ms: u64,
498    retry_delay_max_ms: u64,
499    us: bool,
500    futures_leverages: Option<HashMap<String, u32>>,
501    futures_margin_types: Option<HashMap<String, BinanceMarginType>>,
502    treat_expired_as_canceled: bool,
503    use_trade_lite: bool,
504    bnfcr_currency: Currency,
505    transport_backend: TransportBackend,
506});
507
508impl Default for BinanceExecutionClientConfig {
509    fn default() -> Self {
510        Self::builder().build()
511    }
512}
513
514impl BinanceExecutionClientConfig {
515    /// Validates Binance execution client configuration.
516    ///
517    /// # Errors
518    ///
519    /// Returns an error if the receive-window, WS trading setup timeout, provider, or Binance US
520    /// settings are invalid.
521    pub fn validate(&self) -> anyhow::Result<()> {
522        validate_recv_window(self.recv_window_ms)?;
523        validate_retry_config(&self.retry_config())?;
524        anyhow::ensure!(
525            self.ws_trading_setup_timeout_ms > 0,
526            "ws_trading_setup_timeout_ms must be greater than 0, was {}",
527            self.ws_trading_setup_timeout_ms
528        );
529        self.instrument_provider.validate(self.product_type)?;
530
531        if self.us {
532            anyhow::ensure!(
533                self.product_type == BinanceProductType::Spot,
534                "Binance US supports Spot clients only"
535            );
536            anyhow::ensure!(
537                self.environment == BinanceEnvironment::Live,
538                "Binance US supports the Live environment only"
539            );
540        }
541
542        Ok(())
543    }
544
545    pub(crate) fn retry_config(&self) -> RetryConfig {
546        RetryConfig {
547            max_retries: self.max_retries,
548            initial_delay_ms: self.retry_delay_initial_ms,
549            max_delay_ms: self.retry_delay_max_ms,
550            ..crate::common::http::retry_config()
551        }
552    }
553}
554
555fn validate_retry_config(config: &RetryConfig) -> anyhow::Result<()> {
556    ExponentialBackoff::new(
557        Duration::from_millis(config.initial_delay_ms),
558        Duration::from_millis(config.max_delay_ms),
559        config.backoff_factor,
560        config.jitter_ms,
561        config.immediate_first,
562    )?;
563    Ok(())
564}
565
566fn validate_recv_window(recv_window_ms: u64) -> anyhow::Result<()> {
567    anyhow::ensure!(
568        (1..=60_000).contains(&recv_window_ms),
569        "recv_window_ms must be in the inclusive range 1..=60000, was {recv_window_ms}"
570    );
571    Ok(())
572}
573
574impl ClientConfig for BinanceExecutionClientConfig {
575    fn as_any(&self) -> &dyn Any {
576        self
577    }
578}
579
580#[cfg(test)]
581mod tests {
582    use nautilus_common::config::ConfigError;
583    use rstest::rstest;
584
585    use super::*;
586
587    #[rstest]
588    fn test_config_debug_redacts_credentials() {
589        let data = BinanceDataClientConfig {
590            api_key: Some("data-api-key".into()),
591            api_secret: Some("data-api-secret".into()),
592            proxy_url: Some("http://user:data-proxy@localhost".into()),
593            ..Default::default()
594        };
595        let execution = BinanceExecutionClientConfig {
596            api_key: Some("exec-api-key".into()),
597            api_secret: Some("exec-api-secret".into()),
598            proxy_url: Some("http://user:exec-proxy@localhost".into()),
599            ..Default::default()
600        };
601
602        let formatted = format!("{data:?} {execution:?}");
603
604        assert_eq!(formatted.matches(REDACTED).count(), 6);
605
606        for secret in [
607            "data-api-key",
608            "data-api-secret",
609            "data-proxy",
610            "exec-api-key",
611            "exec-api-secret",
612            "exec-proxy",
613        ] {
614            assert!(!formatted.contains(secret));
615        }
616    }
617
618    #[rstest]
619    fn test_data_config_toml_minimal() {
620        let config: BinanceDataClientConfig = toml::from_str(
621            r#"
622environment = "Testnet"
623product_type = "USD_M"
624instrument_status_poll_secs = 600
625"#,
626        )
627        .unwrap();
628
629        assert_eq!(config.environment, BinanceEnvironment::Testnet);
630        assert_eq!(config.product_type, BinanceProductType::UsdM);
631        assert_eq!(config.spot_market_data_mode, BinanceSpotMarketDataMode::Sbe);
632        assert!(!config.use_usdm_raw_trades);
633        assert_eq!(config.instrument_status_poll_secs, 600);
634        assert_eq!(config.book_snapshot_timeout_secs, 10);
635    }
636
637    #[rstest]
638    fn test_data_config_toml_spot_market_data_mode_override() {
639        let config: BinanceDataClientConfig = toml::from_str(
640            r#"
641spot_market_data_mode = "Json"
642"#,
643        )
644        .unwrap();
645
646        assert_eq!(
647            config.spot_market_data_mode,
648            BinanceSpotMarketDataMode::Json
649        );
650    }
651
652    #[rstest]
653    fn test_data_config_toml_use_usdm_raw_trades_override() {
654        let config: BinanceDataClientConfig = toml::from_str(
655            r#"
656product_type = "USD_M"
657use_usdm_raw_trades = true
658"#,
659        )
660        .unwrap();
661
662        assert!(config.use_usdm_raw_trades);
663        assert!(config.validate().is_ok());
664    }
665
666    #[rstest]
667    #[case(BinanceProductType::Spot)]
668    #[case(BinanceProductType::CoinM)]
669    fn test_data_config_rejects_raw_trades_outside_usdm(#[case] product_type: BinanceProductType) {
670        let config = BinanceDataClientConfig {
671            product_type,
672            use_usdm_raw_trades: true,
673            ..Default::default()
674        };
675
676        assert_eq!(
677            config.validate().unwrap_err().to_string(),
678            "use_usdm_raw_trades supports USD-M Futures clients only"
679        );
680    }
681
682    #[rstest]
683    fn test_data_config_toml_rejects_plural_product_types() {
684        let result = toml::from_str::<BinanceDataClientConfig>(
685            r#"
686product_types = ["SPOT", "USD_M"]
687"#,
688        );
689
690        let message = result.unwrap_err().to_string();
691        assert!(message.contains("unknown field `product_types`"));
692    }
693
694    #[rstest]
695    fn test_exec_config_toml_empty_uses_defaults() {
696        let config: BinanceExecutionClientConfig = toml::from_str("").unwrap();
697        let expected = BinanceExecutionClientConfig::default();
698
699        assert_eq!(config.environment, expected.environment);
700        assert_eq!(config.product_type, expected.product_type);
701        assert_eq!(config.use_ws_trading, expected.use_ws_trading);
702        assert_eq!(config.ws_trading_setup_timeout_ms, 10_000);
703        assert_eq!(config.instrument_provider, expected.instrument_provider);
704        assert_eq!(
705            config.instrument_refresh_interval_secs,
706            expected.instrument_refresh_interval_secs
707        );
708        assert_eq!(config.use_gtd, expected.use_gtd);
709        assert_eq!(config.use_position_ids, expected.use_position_ids);
710        assert_eq!(config.oms_type, expected.oms_type);
711        assert_eq!(config.default_taker_fee, expected.default_taker_fee);
712        assert_eq!(config.proxy_url, expected.proxy_url);
713        assert_eq!(config.recv_window_ms, expected.recv_window_ms);
714        assert_eq!(config.us, expected.us);
715        assert_eq!(
716            config.treat_expired_as_canceled,
717            expected.treat_expired_as_canceled,
718        );
719        assert_eq!(config.use_trade_lite, expected.use_trade_lite);
720        assert_eq!(config.transport_backend, expected.transport_backend);
721    }
722
723    #[rstest]
724    fn test_exec_config_toml_oms_type_override() {
725        let config: BinanceExecutionClientConfig = toml::from_str(
726            r#"
727oms_type = "Hedging"
728"#,
729        )
730        .unwrap();
731
732        assert_eq!(config.oms_type, Some(OmsType::Hedging));
733    }
734
735    #[rstest]
736    fn test_exec_config_toml_use_gtd_override() {
737        let config: BinanceExecutionClientConfig = toml::from_str("use_gtd = false").unwrap();
738
739        assert!(!config.use_gtd);
740    }
741
742    #[rstest]
743    fn test_exec_config_toml_ws_trading_setup_timeout_override() {
744        let config: BinanceExecutionClientConfig =
745            toml::from_str("ws_trading_setup_timeout_ms = 250").unwrap();
746
747        assert_eq!(config.ws_trading_setup_timeout_ms, 250);
748    }
749
750    #[rstest]
751    #[case(0)]
752    #[case(60_001)]
753    fn test_data_config_rejects_recv_window_out_of_bounds(#[case] recv_window_ms: u64) {
754        let config = BinanceDataClientConfig {
755            recv_window_ms,
756            ..Default::default()
757        };
758
759        let message = config.validate().unwrap_err().to_string();
760
761        assert_eq!(
762            message,
763            format!(
764                "recv_window_ms must be in the inclusive range 1..=60000, was {recv_window_ms}"
765            )
766        );
767    }
768
769    #[rstest]
770    fn test_exec_config_rejects_zero_ws_trading_setup_timeout() {
771        let config = BinanceExecutionClientConfig {
772            ws_trading_setup_timeout_ms: 0,
773            ..Default::default()
774        };
775
776        let message = config.validate().unwrap_err().to_string();
777
778        assert_eq!(
779            message,
780            "ws_trading_setup_timeout_ms must be greater than 0, was 0"
781        );
782    }
783
784    #[rstest]
785    #[case(1)]
786    #[case(60_000)]
787    fn test_exec_config_accepts_recv_window_bounds(#[case] recv_window_ms: u64) {
788        let config = BinanceExecutionClientConfig {
789            recv_window_ms,
790            ..Default::default()
791        };
792
793        assert!(config.validate().is_ok());
794    }
795
796    #[rstest]
797    #[case(
798        BinanceProductType::UsdM,
799        BinanceEnvironment::Live,
800        BinanceSpotMarketDataMode::Json,
801        "Binance US supports Spot clients only"
802    )]
803    #[case(
804        BinanceProductType::Spot,
805        BinanceEnvironment::Testnet,
806        BinanceSpotMarketDataMode::Json,
807        "Binance US supports the Live environment only"
808    )]
809    #[case(
810        BinanceProductType::Spot,
811        BinanceEnvironment::Live,
812        BinanceSpotMarketDataMode::Sbe,
813        "Binance US market data requires spot_market_data_mode=Json"
814    )]
815    fn test_data_config_rejects_unsupported_binance_us_combinations(
816        #[case] product_type: BinanceProductType,
817        #[case] environment: BinanceEnvironment,
818        #[case] spot_market_data_mode: BinanceSpotMarketDataMode,
819        #[case] expected: &str,
820    ) {
821        let config = BinanceDataClientConfig {
822            product_type,
823            environment,
824            spot_market_data_mode,
825            us: true,
826            ..Default::default()
827        };
828
829        assert_eq!(config.validate().unwrap_err().to_string(), expected);
830    }
831
832    #[rstest]
833    #[case(
834        BinanceProductType::CoinM,
835        BinanceEnvironment::Live,
836        "Binance US supports Spot clients only"
837    )]
838    #[case(
839        BinanceProductType::Spot,
840        BinanceEnvironment::Demo,
841        "Binance US supports the Live environment only"
842    )]
843    fn test_exec_config_rejects_unsupported_binance_us_combinations(
844        #[case] product_type: BinanceProductType,
845        #[case] environment: BinanceEnvironment,
846        #[case] expected: &str,
847    ) {
848        let config = BinanceExecutionClientConfig {
849            product_type,
850            environment,
851            us: true,
852            ..Default::default()
853        };
854
855        assert_eq!(config.validate().unwrap_err().to_string(), expected);
856    }
857
858    #[rstest]
859    fn test_instrument_provider_rejects_callable_and_spot_contract_filter() {
860        let callable = BinanceInstrumentProviderConfig {
861            filter_callable: Some("package.module:predicate".to_string()),
862            ..Default::default()
863        };
864        let contract_filter = BinanceInstrumentProviderConfig {
865            filters: HashMap::from([(
866                "contract_types".to_string(),
867                serde_json::json!("PERPETUAL"),
868            )]),
869            ..Default::default()
870        };
871
872        assert_eq!(
873            callable
874                .validate(BinanceProductType::Spot)
875                .unwrap_err()
876                .to_string(),
877            "Binance v2 does not support instrument filter_callable \"package.module:predicate\"; the legacy Binance provider never applied callable filters"
878        );
879        assert_eq!(
880            contract_filter
881                .validate(BinanceProductType::Spot)
882                .unwrap_err()
883                .to_string(),
884            "unsupported Binance instrument filter \"contract_types\" for Spot"
885        );
886    }
887
888    #[rstest]
889    fn test_instrument_provider_rejects_empty_and_non_string_filter_values() {
890        for value in [serde_json::json!([]), serde_json::json!(["BTC", 7])] {
891            let config = BinanceInstrumentProviderConfig {
892                filters: HashMap::from([("bases".to_string(), value)]),
893                ..Default::default()
894            };
895
896            assert_eq!(
897                config
898                    .validate(BinanceProductType::UsdM)
899                    .unwrap_err()
900                    .to_string(),
901                "Binance instrument filter \"bases\" must be a non-empty string or array of strings"
902            );
903        }
904    }
905
906    #[rstest]
907    #[case("load_ids", serde_json::json!(["BTCUSDT.BINANCE", "ETHUSDT.BINANCE"]))]
908    fn test_instrument_provider_selection_uniqueness(
909        #[case] field: &str,
910        #[case] mut values: serde_json::Value,
911        #[values(false, true)] duplicate: bool,
912    ) {
913        if duplicate {
914            let entries = values.as_array_mut().unwrap();
915            entries.push(entries[0].clone());
916        }
917
918        let mut input = serde_json::to_value(BinanceInstrumentProviderConfig::default()).unwrap();
919        input[field] = values;
920        let config: BinanceInstrumentProviderConfig = serde_json::from_value(input).unwrap();
921        let original = serde_json::to_value(&config).unwrap();
922
923        let expected = if duplicate {
924            Err(ConfigError::duplicate(
925                format!("instrument_provider.{field}"),
926                None,
927            ))
928        } else {
929            Ok(())
930        };
931
932        let result = config
933            .validate(BinanceProductType::Spot)
934            .map_err(|e| e.downcast::<ConfigError>().unwrap());
935
936        assert_eq!(result, expected);
937        assert_eq!(serde_json::to_value(&config).unwrap(), original);
938    }
939
940    #[rstest]
941    #[case("symbols")]
942    #[case("bases")]
943    #[case("quotes")]
944    #[case("contract_types")]
945    fn test_filter_arrays_reject_duplicates(#[case] field: &str) {
946        let mut config = BinanceInstrumentProviderConfig::default();
947        config.filters.insert(
948            field.to_string(),
949            serde_json::json!(["first", "second", "first"]),
950        );
951        let error = config.validate(BinanceProductType::UsdM).unwrap_err();
952
953        assert_eq!(
954            error.downcast_ref::<ConfigError>(),
955            Some(&ConfigError::duplicate(
956                format!("instrument_provider.filters.{field}"),
957                None
958            ))
959        );
960    }
961
962    #[rstest]
963    #[case("symbols", serde_json::json!(["BTCUSDT", " btcusdt "]))]
964    #[case("bases", serde_json::json!(["BTC", " btc "]))]
965    #[case("quotes", serde_json::json!(["USDT", " usdt "]))]
966    #[case("contract_types", serde_json::json!(["PERPETUAL", " perpetual "]))]
967    fn test_filter_arrays_reject_normalized_duplicates(
968        #[case] field: &str,
969        #[case] values: serde_json::Value,
970    ) {
971        let mut config = BinanceInstrumentProviderConfig::default();
972        config.filters.insert(field.to_string(), values.clone());
973        let error = config.validate(BinanceProductType::UsdM).unwrap_err();
974        assert_eq!(
975            error.downcast_ref::<ConfigError>(),
976            Some(&ConfigError::duplicate(
977                format!("instrument_provider.filters.{field}"),
978                None
979            ))
980        );
981        assert_eq!(config.filters.get(field), Some(&values));
982    }
983}