Skip to main content

nautilus_binance/python/
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//! Python bindings for Binance configuration.
17
18use std::collections::HashMap;
19
20use nautilus_core::{python::to_pyvalue_err, string::secret::SecretString};
21use nautilus_model::{enums::OmsType, identifiers::AccountId, types::Currency};
22use nautilus_network::websocket::TransportBackend;
23use pyo3::{
24    prelude::*,
25    types::{PyDict, PyDictMethods},
26};
27use rust_decimal::Decimal;
28
29use crate::{
30    common::enums::{BinanceEnvironment, BinanceMarginType, BinanceProductType},
31    config::{
32        BinanceDataClientConfig, BinanceExecutionClientConfig, BinanceInstrumentProviderConfig,
33        BinanceSpotMarketDataMode,
34    },
35};
36
37#[pymethods]
38#[pyo3_stub_gen::derive::gen_stub_pymethods]
39impl BinanceInstrumentProviderConfig {
40    /// Configuration for Binance instrument loading.
41    #[new]
42    #[pyo3(signature = (
43        load_all = true,
44        load_ids = None,
45        filters = None,
46        filter_callable = None,
47        log_warnings = true,
48        query_commission_rates = false,
49    ))]
50    fn py_new(
51        load_all: bool,
52        load_ids: Option<Vec<String>>,
53        filters: Option<HashMap<String, Py<PyAny>>>,
54        filter_callable: Option<String>,
55        log_warnings: bool,
56        query_commission_rates: bool,
57    ) -> PyResult<Self> {
58        let filters = filters
59            .map(nautilus_live::python::config::coerce_json_config)
60            .transpose()?
61            .unwrap_or_default();
62
63        let config = Self {
64            load_all,
65            load_ids,
66            filters,
67            filter_callable,
68            log_warnings,
69            query_commission_rates,
70        };
71
72        config.validate_selections().map_err(to_pyvalue_err)?;
73        Ok(config)
74    }
75
76    fn __repr__(&self) -> String {
77        stringify!(BinanceInstrumentProviderConfig).to_string()
78    }
79
80    #[getter]
81    fn load_all(&self) -> bool {
82        self.load_all
83    }
84
85    #[getter]
86    fn load_ids(&self) -> Option<Vec<String>> {
87        self.load_ids.clone()
88    }
89
90    #[getter]
91    fn filters(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
92        let dict = PyDict::new(py);
93        for (key, value) in &self.filters {
94            dict.set_item(
95                key,
96                nautilus_live::python::config::json_value_to_py(py, value)?,
97            )?;
98        }
99        Ok(dict.into_any().unbind())
100    }
101
102    #[getter]
103    fn filter_callable(&self) -> Option<String> {
104        self.filter_callable.clone()
105    }
106
107    #[getter]
108    fn log_warnings(&self) -> bool {
109        self.log_warnings
110    }
111
112    #[getter]
113    fn query_commission_rates(&self) -> bool {
114        self.query_commission_rates
115    }
116}
117
118#[pymethods]
119#[pyo3_stub_gen::derive::gen_stub_pymethods]
120impl BinanceDataClientConfig {
121    /// Configuration for Binance data client.
122    ///
123    /// Ed25519 API keys are required for SBE WebSocket streams.
124    #[new]
125    #[pyo3(signature = (
126        product_type = None,
127        environment = None,
128        base_url_http = None,
129        base_url_ws = None,
130        api_key = None,
131        api_secret = None,
132        spot_market_data_mode = None,
133        instrument_provider = None,
134        instrument_refresh_interval_secs = None,
135        instrument_status_poll_secs = None,
136        proxy_url = None,
137        recv_window_ms = None,
138        us = false,
139        transport_backend = None,
140        max_retries = None,
141        retry_delay_initial_ms = None,
142        retry_delay_max_ms = None,
143        book_snapshot_timeout_secs = None,
144        use_usdm_raw_trades = false,
145    ))]
146    #[expect(clippy::too_many_arguments)]
147    fn py_new(
148        product_type: Option<BinanceProductType>,
149        environment: Option<BinanceEnvironment>,
150        base_url_http: Option<String>,
151        base_url_ws: Option<String>,
152        api_key: Option<String>,
153        api_secret: Option<String>,
154        spot_market_data_mode: Option<BinanceSpotMarketDataMode>,
155        instrument_provider: Option<BinanceInstrumentProviderConfig>,
156        instrument_refresh_interval_secs: Option<u64>,
157        instrument_status_poll_secs: Option<u64>,
158        proxy_url: Option<String>,
159        recv_window_ms: Option<u64>,
160        us: bool,
161        transport_backend: Option<TransportBackend>,
162        max_retries: Option<u32>,
163        retry_delay_initial_ms: Option<u64>,
164        retry_delay_max_ms: Option<u64>,
165        book_snapshot_timeout_secs: Option<u64>,
166        use_usdm_raw_trades: bool,
167    ) -> PyResult<Self> {
168        let defaults = Self::default();
169        let config = Self {
170            product_type: product_type.unwrap_or(defaults.product_type),
171            environment: environment.unwrap_or(defaults.environment),
172            base_url_http: base_url_http.or(defaults.base_url_http),
173            base_url_ws: base_url_ws.or(defaults.base_url_ws),
174            api_key: api_key.map(SecretString::from).or(defaults.api_key),
175            api_secret: api_secret.map(SecretString::from).or(defaults.api_secret),
176            spot_market_data_mode: spot_market_data_mode.unwrap_or(defaults.spot_market_data_mode),
177            use_usdm_raw_trades,
178            instrument_provider: instrument_provider.unwrap_or(defaults.instrument_provider),
179            instrument_refresh_interval_secs: instrument_refresh_interval_secs
180                .unwrap_or(defaults.instrument_refresh_interval_secs),
181            instrument_status_poll_secs: instrument_status_poll_secs
182                .unwrap_or(defaults.instrument_status_poll_secs),
183            book_snapshot_timeout_secs: book_snapshot_timeout_secs
184                .unwrap_or(defaults.book_snapshot_timeout_secs),
185            proxy_url: proxy_url.map(SecretString::from).or(defaults.proxy_url),
186            recv_window_ms: recv_window_ms.unwrap_or(defaults.recv_window_ms),
187            max_retries: max_retries.unwrap_or(defaults.max_retries),
188            retry_delay_initial_ms: retry_delay_initial_ms
189                .unwrap_or(defaults.retry_delay_initial_ms),
190            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
191            us,
192            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
193        };
194        config.validate().map_err(to_pyvalue_err)?;
195        Ok(config)
196    }
197
198    #[getter]
199    const fn has_proxy_url(&self) -> bool {
200        self.proxy_url.is_some()
201    }
202
203    fn __repr__(&self) -> String {
204        stringify!(BinanceDataClientConfig).to_string()
205    }
206}
207
208#[pymethods]
209#[pyo3_stub_gen::derive::gen_stub_pymethods]
210impl BinanceExecutionClientConfig {
211    /// Configuration for Binance execution client.
212    ///
213    /// Global execution uses WebSocket API authentication with Ed25519 credentials.
214    /// Binance US uses HMAC-signed HTTP requests and listen-key user data streams.
215    #[new]
216    #[pyo3(signature = (
217        account_id,
218        product_type = None,
219        environment = None,
220        base_url_http = None,
221        base_url_ws = None,
222        base_url_ws_trading = None,
223        use_ws_trading = true,
224        ws_trading_setup_timeout_ms = None,
225        instrument_provider = None,
226        instrument_refresh_interval_secs = None,
227        use_gtd = true,
228        use_position_ids = true,
229        oms_type = None,
230        default_taker_fee = None,
231        proxy_url = None,
232        recv_window_ms = None,
233        us = false,
234        api_key = None,
235        api_secret = None,
236        futures_leverages = None,
237        futures_margin_types = None,
238        treat_expired_as_canceled = false,
239        use_trade_lite = false,
240        bnfcr_currency = None,
241        transport_backend = None,
242        max_retries = None,
243        retry_delay_initial_ms = None,
244        retry_delay_max_ms = None,
245    ))]
246    #[expect(clippy::too_many_arguments)]
247    fn py_new(
248        account_id: AccountId,
249        product_type: Option<BinanceProductType>,
250        environment: Option<BinanceEnvironment>,
251        base_url_http: Option<String>,
252        base_url_ws: Option<String>,
253        base_url_ws_trading: Option<String>,
254        use_ws_trading: bool,
255        ws_trading_setup_timeout_ms: Option<u64>,
256        instrument_provider: Option<BinanceInstrumentProviderConfig>,
257        instrument_refresh_interval_secs: Option<u64>,
258        use_gtd: bool,
259        use_position_ids: bool,
260        oms_type: Option<OmsType>,
261        default_taker_fee: Option<f64>,
262        proxy_url: Option<String>,
263        recv_window_ms: Option<u64>,
264        us: bool,
265        api_key: Option<String>,
266        api_secret: Option<String>,
267        futures_leverages: Option<HashMap<String, u32>>,
268        futures_margin_types: Option<HashMap<String, BinanceMarginType>>,
269        treat_expired_as_canceled: bool,
270        use_trade_lite: bool,
271        bnfcr_currency: Option<Currency>,
272        transport_backend: Option<TransportBackend>,
273        max_retries: Option<u32>,
274        retry_delay_initial_ms: Option<u64>,
275        retry_delay_max_ms: Option<u64>,
276    ) -> PyResult<Self> {
277        let defaults = Self::default();
278        let config = Self {
279            account_id,
280            product_type: product_type.unwrap_or(defaults.product_type),
281            environment: environment.unwrap_or(defaults.environment),
282            base_url_http: base_url_http.or(defaults.base_url_http),
283            base_url_ws: base_url_ws.or(defaults.base_url_ws),
284            base_url_ws_trading: base_url_ws_trading.or(defaults.base_url_ws_trading),
285            use_ws_trading,
286            ws_trading_setup_timeout_ms: ws_trading_setup_timeout_ms
287                .unwrap_or(defaults.ws_trading_setup_timeout_ms),
288            instrument_provider: instrument_provider.unwrap_or(defaults.instrument_provider),
289            instrument_refresh_interval_secs: instrument_refresh_interval_secs
290                .unwrap_or(defaults.instrument_refresh_interval_secs),
291            use_gtd,
292            use_position_ids,
293            oms_type,
294            default_taker_fee: default_taker_fee
295                .map_or_else(|| Ok(defaults.default_taker_fee), Decimal::try_from)
296                .unwrap_or(defaults.default_taker_fee),
297            proxy_url: proxy_url.map(SecretString::from).or(defaults.proxy_url),
298            recv_window_ms: recv_window_ms.unwrap_or(defaults.recv_window_ms),
299            max_retries: max_retries.unwrap_or(defaults.max_retries),
300            retry_delay_initial_ms: retry_delay_initial_ms
301                .unwrap_or(defaults.retry_delay_initial_ms),
302            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
303            us,
304            api_key: api_key.map(SecretString::from).or(defaults.api_key),
305            api_secret: api_secret.map(SecretString::from).or(defaults.api_secret),
306            futures_leverages,
307            futures_margin_types,
308            bnfcr_currency: bnfcr_currency.unwrap_or(defaults.bnfcr_currency),
309            treat_expired_as_canceled,
310            use_trade_lite,
311            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
312        };
313        config.validate().map_err(to_pyvalue_err)?;
314        Ok(config)
315    }
316
317    #[getter]
318    const fn has_proxy_url(&self) -> bool {
319        self.proxy_url.is_some()
320    }
321
322    fn __repr__(&self) -> String {
323        stringify!(BinanceExecutionClientConfig).to_string()
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use rstest::rstest;
330    use rust_decimal::Decimal;
331
332    use super::*;
333
334    #[rstest]
335    fn test_python_constructors_preserve_existing_positional_arguments() {
336        Python::initialize();
337        Python::attach(|py| {
338            let locals = PyDict::new(py);
339            locals
340                .set_item("DataConfig", py.get_type::<BinanceDataClientConfig>())
341                .unwrap();
342            locals
343                .set_item("ExecConfig", py.get_type::<BinanceExecutionClientConfig>())
344                .unwrap();
345            locals
346                .set_item(
347                    "account_id",
348                    Py::new(py, AccountId::from("BINANCE-001")).unwrap(),
349                )
350                .unwrap();
351            let data = py.eval(
352                c"DataConfig(None, None, None, None, None, None, None, None, None, None, None, None, False, None)",
353                None, Some(&locals),
354            ).unwrap();
355            let execution = py.eval(
356                c"ExecConfig(account_id, None, None, None, None, None, True, None, None, None, True, True, None, None, None, None, False, None, None, None, None, False, False, None, None)",
357                None, Some(&locals),
358            ).unwrap();
359            let data = data.extract::<PyRef<BinanceDataClientConfig>>().unwrap();
360            let execution = execution
361                .extract::<PyRef<BinanceExecutionClientConfig>>()
362                .unwrap();
363
364            assert_eq!(
365                data.max_retries,
366                BinanceDataClientConfig::default().max_retries
367            );
368            assert!(!data.us);
369            assert_eq!(
370                execution.max_retries,
371                BinanceExecutionClientConfig::default().max_retries
372            );
373            assert!(!execution.us);
374            assert_eq!(execution.account_id, AccountId::from("BINANCE-001"));
375        });
376    }
377
378    #[rstest]
379    fn test_data_client_py_new_uses_defaults_for_omitted_fields() {
380        let config = BinanceDataClientConfig::py_new(
381            None, None, None, None, None, None, None, None, None, None, None, None, false, None,
382            None, None, None, None, false,
383        )
384        .unwrap();
385        let defaults = BinanceDataClientConfig::default();
386
387        assert_eq!(config.product_type, defaults.product_type);
388        assert_eq!(config.environment, defaults.environment);
389        assert_eq!(config.base_url_http, defaults.base_url_http);
390        assert_eq!(config.base_url_ws, defaults.base_url_ws);
391        assert_eq!(config.api_key, defaults.api_key);
392        assert_eq!(config.api_secret, defaults.api_secret);
393        assert_eq!(config.spot_market_data_mode, defaults.spot_market_data_mode);
394        assert!(!config.use_usdm_raw_trades);
395        assert_eq!(config.instrument_provider, defaults.instrument_provider);
396        assert_eq!(
397            config.instrument_refresh_interval_secs,
398            defaults.instrument_refresh_interval_secs
399        );
400        assert_eq!(
401            config.instrument_status_poll_secs,
402            defaults.instrument_status_poll_secs
403        );
404        assert_eq!(
405            config.book_snapshot_timeout_secs,
406            defaults.book_snapshot_timeout_secs
407        );
408        assert_eq!(config.proxy_url, defaults.proxy_url);
409        assert_eq!(config.recv_window_ms, defaults.recv_window_ms);
410        assert!(!config.us);
411    }
412
413    #[rstest]
414    fn test_data_client_py_new_uses_explicit_overrides() {
415        let config = BinanceDataClientConfig::py_new(
416            Some(BinanceProductType::UsdM),
417            Some(BinanceEnvironment::Testnet),
418            Some("https://http.example".to_string()),
419            Some("wss://ws.example".to_string()),
420            Some("api-key".to_string()),
421            Some("api-secret".to_string()),
422            Some(BinanceSpotMarketDataMode::Json),
423            None,
424            Some(30),
425            Some(15),
426            Some("http://proxy.example:8080".to_string()),
427            Some(45_000),
428            false,
429            None,
430            Some(7),
431            Some(123),
432            Some(456),
433            Some(0),
434            true,
435        )
436        .unwrap();
437
438        assert_eq!(config.product_type, BinanceProductType::UsdM);
439        assert_eq!(config.environment, BinanceEnvironment::Testnet);
440        assert_eq!(
441            config.base_url_http.as_deref(),
442            Some("https://http.example")
443        );
444        assert_eq!(config.base_url_ws.as_deref(), Some("wss://ws.example"));
445        assert_eq!(
446            config.api_key.as_ref().map(SecretString::expose_secret),
447            Some("api-key"),
448        );
449        assert_eq!(
450            config.api_secret.as_ref().map(SecretString::expose_secret),
451            Some("api-secret"),
452        );
453        assert_eq!(
454            config.spot_market_data_mode,
455            BinanceSpotMarketDataMode::Json
456        );
457        assert!(config.use_usdm_raw_trades);
458        assert_eq!(config.instrument_refresh_interval_secs, 30);
459        assert_eq!(config.instrument_status_poll_secs, 15);
460        assert_eq!(
461            config.proxy_url.as_ref().map(SecretString::expose_secret),
462            Some("http://proxy.example:8080")
463        );
464        assert_eq!(config.recv_window_ms, 45_000);
465        assert_eq!(config.max_retries, 7);
466        assert_eq!(config.retry_delay_initial_ms, 123);
467        assert_eq!(config.retry_delay_max_ms, 456);
468        assert_eq!(config.book_snapshot_timeout_secs, 0);
469    }
470
471    #[rstest]
472    fn test_exec_client_py_new_uses_defaults_for_optional_fields() {
473        let account_id = AccountId::from("BINANCE-001");
474        let config = BinanceExecutionClientConfig::py_new(
475            account_id, None, None, None, None, None, true, None, None, None, true, true, None,
476            None, None, None, false, None, None, None, None, false, false, None, None, None, None,
477            None,
478        )
479        .unwrap();
480        let defaults = BinanceExecutionClientConfig::default();
481
482        assert_eq!(config.account_id, account_id);
483        assert_eq!(config.product_type, defaults.product_type);
484        assert_eq!(config.environment, defaults.environment);
485        assert_eq!(config.base_url_http, defaults.base_url_http);
486        assert_eq!(config.base_url_ws, defaults.base_url_ws);
487        assert_eq!(config.base_url_ws_trading, defaults.base_url_ws_trading);
488        assert!(config.use_ws_trading);
489        assert_eq!(config.ws_trading_setup_timeout_ms, 10_000);
490        assert_eq!(config.instrument_provider, defaults.instrument_provider);
491        assert_eq!(
492            config.instrument_refresh_interval_secs,
493            defaults.instrument_refresh_interval_secs
494        );
495        assert!(config.use_gtd);
496        assert_eq!(config.oms_type, defaults.oms_type);
497        assert_eq!(config.default_taker_fee, defaults.default_taker_fee);
498        assert_eq!(config.proxy_url, defaults.proxy_url);
499        assert_eq!(config.recv_window_ms, defaults.recv_window_ms);
500        assert!(!config.us);
501        assert_eq!(config.api_key, defaults.api_key);
502        assert_eq!(config.api_secret, defaults.api_secret);
503        assert_eq!(config.futures_leverages, defaults.futures_leverages);
504        assert_eq!(config.futures_margin_types, defaults.futures_margin_types);
505        assert_eq!(config.bnfcr_currency, defaults.bnfcr_currency);
506        assert_eq!(config.bnfcr_currency, Currency::USDT());
507        assert_eq!(
508            config.treat_expired_as_canceled,
509            defaults.treat_expired_as_canceled
510        );
511    }
512
513    #[rstest]
514    fn test_exec_client_py_new_preserves_explicit_overrides() {
515        use std::collections::HashMap;
516
517        use crate::common::enums::BinanceMarginType;
518
519        let leverages = HashMap::from([("BTCUSDT".to_string(), 20)]);
520        let margin_types = HashMap::from([("BTCUSDT".to_string(), BinanceMarginType::Cross)]);
521
522        let config = BinanceExecutionClientConfig::py_new(
523            AccountId::from("BINANCE-002"),
524            Some(BinanceProductType::UsdM),
525            Some(BinanceEnvironment::Demo),
526            Some("https://http.example".to_string()),
527            Some("wss://stream.example".to_string()),
528            Some("wss://trade.example".to_string()),
529            false,
530            Some(250),
531            None,
532            Some(45),
533            false,
534            false,
535            Some(OmsType::Hedging),
536            Some(0.0015),
537            Some("http://proxy.example:8080".to_string()),
538            Some(60_000),
539            false,
540            Some("api-key".to_string()),
541            Some("api-secret".to_string()),
542            Some(leverages.clone()),
543            Some(margin_types.clone()),
544            true,
545            true,
546            Some(Currency::USDC()),
547            None,
548            None,
549            None,
550            None,
551        )
552        .unwrap();
553
554        assert_eq!(config.product_type, BinanceProductType::UsdM);
555        assert_eq!(config.environment, BinanceEnvironment::Demo);
556        assert_eq!(
557            config.base_url_http.as_deref(),
558            Some("https://http.example")
559        );
560        assert_eq!(config.base_url_ws.as_deref(), Some("wss://stream.example"));
561        assert_eq!(
562            config.base_url_ws_trading.as_deref(),
563            Some("wss://trade.example")
564        );
565        assert!(!config.use_ws_trading);
566        assert_eq!(config.ws_trading_setup_timeout_ms, 250);
567        assert_eq!(config.instrument_refresh_interval_secs, 45);
568        assert!(!config.use_gtd);
569        assert!(!config.use_position_ids);
570        assert_eq!(config.oms_type, Some(OmsType::Hedging));
571        assert_eq!(config.default_taker_fee, Decimal::try_from(0.0015).unwrap());
572        assert_eq!(
573            config.proxy_url.as_ref().map(SecretString::expose_secret),
574            Some("http://proxy.example:8080")
575        );
576        assert_eq!(config.recv_window_ms, 60_000);
577        assert_eq!(
578            config.api_key.as_ref().map(SecretString::expose_secret),
579            Some("api-key"),
580        );
581        assert_eq!(
582            config.api_secret.as_ref().map(SecretString::expose_secret),
583            Some("api-secret"),
584        );
585        assert_eq!(config.futures_leverages, Some(leverages));
586        assert_eq!(config.futures_margin_types, Some(margin_types));
587        assert_eq!(config.bnfcr_currency, Currency::USDC());
588        assert!(config.treat_expired_as_canceled);
589        assert!(config.use_trade_lite);
590    }
591
592    #[rstest]
593    fn test_exec_client_py_new_uses_default_fee_for_invalid_float() {
594        let defaults = BinanceExecutionClientConfig::default();
595        let config = BinanceExecutionClientConfig::py_new(
596            AccountId::from("BINANCE-003"),
597            None,
598            None,
599            None,
600            None,
601            None,
602            true,
603            None,
604            None,
605            None,
606            true,
607            true,
608            None,
609            Some(f64::NAN),
610            None,
611            None,
612            false,
613            None,
614            None,
615            None,
616            None,
617            false,
618            false,
619            None,
620            None,
621            None,
622            None,
623            None,
624        )
625        .unwrap();
626
627        assert_eq!(config.default_taker_fee, defaults.default_taker_fee);
628    }
629
630    #[rstest]
631    fn test_instrument_provider_py_new_preserves_filters() {
632        Python::initialize();
633        Python::attach(|py| {
634            let symbols = vec!["BTCUSDT", "ETHUSDT"].into_pyobject(py).unwrap();
635            let filters = HashMap::from([("symbols".to_string(), symbols.into_any().unbind())]);
636
637            let config = BinanceInstrumentProviderConfig::py_new(
638                false,
639                Some(vec!["BTCUSDT.BINANCE".to_string()]),
640                Some(filters),
641                None,
642                false,
643                true,
644            )
645            .unwrap();
646
647            assert!(!config.load_all);
648            assert_eq!(config.load_ids, Some(vec!["BTCUSDT.BINANCE".to_string()]));
649            assert_eq!(
650                config.filters["symbols"],
651                serde_json::json!(["BTCUSDT", "ETHUSDT"])
652            );
653            assert!(!config.log_warnings);
654            assert!(config.query_commission_rates);
655        });
656    }
657
658    #[rstest]
659    #[case("load_ids")]
660    #[case("symbols")]
661    #[case("contract_types")]
662    fn test_python_provider_selection_uniqueness(
663        #[case] field: &str,
664        #[values(false, true)] duplicate: bool,
665    ) {
666        Python::initialize();
667        Python::attach(|py| {
668            let mut values = vec!["first", "second"];
669            if duplicate {
670                values.push("first");
671            }
672
673            let kwargs = PyDict::new(py);
674            if field == "load_ids" {
675                kwargs.set_item("load_ids", &values).unwrap();
676            } else {
677                let filters = PyDict::new(py);
678                filters.set_item(field, &values).unwrap();
679                kwargs.set_item("filters", filters).unwrap();
680            }
681
682            let result = py
683                .get_type::<BinanceInstrumentProviderConfig>()
684                .call((), Some(&kwargs));
685
686            if duplicate {
687                let error = result.unwrap_err();
688
689                let expected = if field == "load_ids" {
690                    "instrument_provider.load_ids".to_string()
691                } else {
692                    format!("instrument_provider.filters.{field}")
693                };
694
695                assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
696                assert_eq!(
697                    error.value(py).str().unwrap().to_str().unwrap(),
698                    format!("duplicate {expected}")
699                );
700            } else {
701                let config = result.unwrap();
702                let config = config
703                    .extract::<PyRef<BinanceInstrumentProviderConfig>>()
704                    .unwrap();
705
706                if field == "load_ids" {
707                    assert_eq!(config.load_ids.as_ref().unwrap(), &values);
708                } else {
709                    assert_eq!(config.filters.get(field), Some(&serde_json::json!(values)));
710                }
711            }
712        });
713    }
714
715    #[rstest]
716    #[case("symbols", vec!["BTCUSDT", " btcusdt "])]
717    #[case("bases", vec!["BTC", " btc "])]
718    #[case("quotes", vec!["USDT", " usdt "])]
719    #[case("contract_types", vec!["PERPETUAL", " perpetual "])]
720    fn test_python_provider_rejects_normalized_duplicates(
721        #[case] field: &str,
722        #[case] values: Vec<&str>,
723    ) {
724        Python::initialize();
725        Python::attach(|py| {
726            let filters = PyDict::new(py);
727            filters.set_item(field, values).unwrap();
728            let kwargs = PyDict::new(py);
729            kwargs.set_item("filters", filters).unwrap();
730            let error = py
731                .get_type::<BinanceInstrumentProviderConfig>()
732                .call((), Some(&kwargs))
733                .unwrap_err();
734            assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
735            assert_eq!(
736                error.value(py).str().unwrap().to_str().unwrap(),
737                format!("duplicate instrument_provider.filters.{field}")
738            );
739        });
740    }
741}