1use 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#[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 #[builder(default = true)]
55 pub load_all: bool,
56 pub load_ids: Option<Vec<String>>,
58 #[builder(default)]
63 pub filters: HashMap<String, serde_json::Value>,
64 pub filter_callable: Option<String>,
69 #[builder(default = true)]
74 pub log_warnings: bool,
75 #[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 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#[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 Sbe,
195 Json,
197}
198
199#[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 #[builder(default = BinanceProductType::Spot)]
215 pub product_type: BinanceProductType,
216 #[builder(default = BinanceEnvironment::Live)]
218 pub environment: BinanceEnvironment,
219 pub api_key: Option<SecretString>,
221 pub api_secret: Option<SecretString>,
223 pub base_url_http: Option<String>,
225 pub base_url_ws: Option<String>,
230 pub proxy_url: Option<SecretString>,
232 #[builder(default)]
237 pub spot_market_data_mode: BinanceSpotMarketDataMode,
238 #[builder(default)]
245 pub use_usdm_raw_trades: bool,
246 #[builder(default)]
248 pub instrument_provider: BinanceInstrumentProviderConfig,
249 #[builder(default = 3600)]
253 pub instrument_refresh_interval_secs: u64,
254 #[builder(default = 3600)]
257 pub instrument_status_poll_secs: u64,
258 #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
263 pub book_snapshot_timeout_secs: u64,
264 #[builder(default = 5_000)]
266 pub recv_window_ms: u64,
267 #[builder(default = RetryConfig::default().max_retries)]
269 pub max_retries: u32,
270 #[builder(default = RetryConfig::default().initial_delay_ms)]
272 pub retry_delay_initial_ms: u64,
273 #[builder(default = RetryConfig::default().max_delay_ms)]
275 pub retry_delay_max_ms: u64,
276 #[builder(default)]
278 pub us: bool,
279 #[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 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#[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 #[builder(default = AccountId::from("BINANCE-001"))]
380 pub account_id: AccountId,
381 #[builder(default = BinanceProductType::Spot)]
383 pub product_type: BinanceProductType,
384 #[builder(default = BinanceEnvironment::Live)]
386 pub environment: BinanceEnvironment,
387 pub api_key: Option<SecretString>,
389 pub api_secret: Option<SecretString>,
391 pub base_url_http: Option<String>,
393 pub base_url_ws: Option<String>,
397 pub base_url_ws_trading: Option<String>,
399 pub proxy_url: Option<SecretString>,
401 #[builder(default = true)]
403 pub use_ws_trading: bool,
404 #[builder(default = 10_000)]
406 pub ws_trading_setup_timeout_ms: u64,
407 #[builder(default)]
409 pub instrument_provider: BinanceInstrumentProviderConfig,
410 #[builder(default = 3600)]
414 pub instrument_refresh_interval_secs: u64,
415 #[builder(default = true)]
420 pub use_gtd: bool,
421 #[builder(default = true)]
428 pub use_position_ids: bool,
429 pub oms_type: Option<OmsType>,
434 #[builder(default = Decimal::new(4, 4))]
440 pub default_taker_fee: Decimal,
441 #[builder(default = 5_000)]
443 pub recv_window_ms: u64,
444 #[builder(default = RetryConfig::default().max_retries)]
446 pub max_retries: u32,
447 #[builder(default = RetryConfig::default().initial_delay_ms)]
449 pub retry_delay_initial_ms: u64,
450 #[builder(default = RetryConfig::default().max_delay_ms)]
452 pub retry_delay_max_ms: u64,
453 #[builder(default)]
455 pub us: bool,
456 pub futures_leverages: Option<HashMap<String, u32>>,
458 pub futures_margin_types: Option<HashMap<String, BinanceMarginType>>,
460 #[builder(default = Currency::USDT())]
462 pub bnfcr_currency: Currency,
463 #[builder(default = false)]
468 pub treat_expired_as_canceled: bool,
469 #[builder(default = false)]
473 pub use_trade_lite: bool,
474 #[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 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}