Skip to main content

nautilus_bybit/
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//! Configuration structures for the Bybit adapter.
17
18use std::collections::HashMap;
19
20use nautilus_common::config::{ConfigError, ConfigResult, check_unique_values};
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::identifiers::AccountId;
26use nautilus_network::websocket::TransportBackend;
27use serde::{Deserialize, Serialize};
28
29use crate::common::{
30    credential::credential_env_vars,
31    enums::{
32        BybitEnvironment, BybitMarginMode, BybitOrderSmpType, BybitPositionMode, BybitProductType,
33    },
34    parse::deserialize_optional_smp_type,
35    urls::{bybit_http_base_url, bybit_ws_private_url, bybit_ws_public_url, bybit_ws_trade_url},
36};
37
38/// Configuration for the Bybit live data client.
39#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
40#[serde(default, deny_unknown_fields)]
41#[cfg_attr(
42    feature = "python",
43    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
44)]
45#[cfg_attr(
46    feature = "python",
47    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
48)]
49pub struct BybitDataClientConfig {
50    /// API key.
51    ///
52    /// When omitted, the client loads `BYBIT_API_KEY`, `BYBIT_DEMO_API_KEY`, or
53    /// `BYBIT_TESTNET_API_KEY` for the selected [`BybitEnvironment`]. An explicit
54    /// value takes precedence. Public market-data requests stay unsigned.
55    pub api_key: Option<SecretString>,
56    /// API secret.
57    ///
58    /// When omitted, the client loads `BYBIT_API_SECRET`, `BYBIT_DEMO_API_SECRET`,
59    /// or `BYBIT_TESTNET_API_SECRET` for the selected [`BybitEnvironment`]. An
60    /// explicit value takes precedence. A missing key or secret leaves the client
61    /// without credentials.
62    pub api_secret: Option<SecretString>,
63    /// Product types to subscribe to (e.g., Linear, Spot, Inverse, Option).
64    #[builder(default = vec![BybitProductType::Linear])]
65    pub product_types: Vec<BybitProductType>,
66    /// Environment selection (Mainnet, Testnet, Demo).
67    #[builder(default = BybitEnvironment::Mainnet)]
68    pub environment: BybitEnvironment,
69    /// Optional override for the REST base URL.
70    pub base_url_http: Option<String>,
71    /// Optional override for the public WebSocket URL.
72    pub base_url_ws_public: Option<String>,
73    /// Optional override for the private WebSocket URL.
74    pub base_url_ws_private: Option<String>,
75    /// Optional proxy URL for HTTP and WebSocket transports.
76    pub proxy_url: Option<SecretString>,
77    /// REST timeout in seconds.
78    #[builder(default = 60)]
79    pub http_timeout_secs: u64,
80    /// Maximum retry attempts for REST reads.
81    #[builder(default = 3)]
82    pub max_retries: u32,
83    /// Initial retry backoff for REST reads, in milliseconds.
84    #[builder(default = 1_000)]
85    pub retry_delay_initial_ms: u64,
86    /// Maximum retry backoff for REST reads, in milliseconds.
87    #[builder(default = 10_000)]
88    pub retry_delay_max_ms: u64,
89    /// Heartbeat interval in seconds for WebSocket clients.
90    #[builder(default = 20)]
91    pub heartbeat_interval_secs: u64,
92    /// Receive window in milliseconds for signed requests.
93    #[builder(default = 5_000)]
94    pub recv_window_ms: u64,
95    /// Interval in minutes for instrument refresh from REST.
96    /// When `None`, instrument refresh is disabled.
97    pub update_instruments_interval_mins: Option<u64>,
98    /// Interval in seconds for polling instrument definitions and status changes from REST.
99    /// When `None`, instrument/status polling is disabled.
100    pub instrument_poll_interval_secs: Option<u64>,
101    /// Maximum time to wait for an initial, post-reconnect, or recovery order book
102    /// snapshot in seconds. Set to 0 to disable.
103    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
104    pub book_snapshot_timeout_secs: u64,
105    /// WebSocket transport backend (defaults to `Tungstenite`).
106    #[builder(default)]
107    pub transport_backend: TransportBackend,
108    /// Whether bar timestamps use the close time instead of the open time.
109    #[builder(default = true)]
110    pub bars_timestamp_on_close: bool,
111}
112
113#[cfg(feature = "python")]
114nautilus_core::impl_pyo3_config_getters!(BybitDataClientConfig {
115    product_types: Vec<BybitProductType>,
116    environment: BybitEnvironment,
117    base_url_http: Option<String>,
118    base_url_ws_public: Option<String>,
119    base_url_ws_private: Option<String>,
120    http_timeout_secs: u64,
121    max_retries: u32,
122    retry_delay_initial_ms: u64,
123    retry_delay_max_ms: u64,
124    heartbeat_interval_secs: u64,
125    recv_window_ms: u64,
126    update_instruments_interval_mins: Option<u64>,
127    book_snapshot_timeout_secs: u64,
128    transport_backend: TransportBackend,
129    bars_timestamp_on_close: bool,
130});
131
132impl Default for BybitDataClientConfig {
133    fn default() -> Self {
134        Self {
135            update_instruments_interval_mins: Some(60),
136            instrument_poll_interval_secs: Some(60),
137            ..Self::builder().build()
138        }
139    }
140}
141
142impl BybitDataClientConfig {
143    /// Creates a configuration with default values.
144    #[must_use]
145    pub fn new() -> Self {
146        Self::default()
147    }
148
149    /// Validates that configured selections contain no duplicates.
150    ///
151    /// # Errors
152    ///
153    /// Returns an error if `product_types` repeats a value.
154    pub fn validate(&self) -> ConfigResult<()> {
155        check_unique_values("product_types", &self.product_types)
156    }
157
158    /// Returns `true` if both API key and secret fields are set.
159    #[must_use]
160    pub fn has_api_credentials(&self) -> bool {
161        self.api_key.is_some() && self.api_secret.is_some()
162    }
163
164    pub(crate) fn resolved_api_credentials(&self) -> Option<(String, String)> {
165        let (key_var, secret_var) = credential_env_vars(self.environment);
166        // Keep each side in a zeroizing owner until both exist. An incomplete
167        // pair must not leave a plaintext secret on the heap.
168        let key = self
169            .api_key
170            .clone()
171            .or_else(|| std::env::var(key_var).ok().map(SecretString::from))?;
172        let secret = self
173            .api_secret
174            .clone()
175            .or_else(|| std::env::var(secret_var).ok().map(SecretString::from))?;
176        Some((key.into_inner(), secret.into_inner()))
177    }
178
179    /// Returns the REST base URL, considering overrides and environment.
180    #[must_use]
181    pub fn http_base_url(&self) -> String {
182        self.base_url_http
183            .clone()
184            .unwrap_or_else(|| bybit_http_base_url(self.environment).to_string())
185    }
186
187    /// Returns the public WebSocket URL for the given product type.
188    ///
189    /// Falls back to the first product type in the config if multiple are configured.
190    #[must_use]
191    pub fn ws_public_url(&self) -> String {
192        self.base_url_ws_public.clone().unwrap_or_else(|| {
193            let product_type = self
194                .product_types
195                .first()
196                .copied()
197                .unwrap_or(BybitProductType::Linear);
198            bybit_ws_public_url(product_type, self.environment)
199        })
200    }
201
202    /// Returns the public WebSocket URL for a specific product type.
203    #[must_use]
204    pub fn ws_public_url_for(&self, product_type: BybitProductType) -> String {
205        self.base_url_ws_public
206            .clone()
207            .unwrap_or_else(|| bybit_ws_public_url(product_type, self.environment))
208    }
209
210    /// Returns the private WebSocket URL, considering overrides and environment.
211    #[must_use]
212    pub fn ws_private_url(&self) -> String {
213        self.base_url_ws_private
214            .clone()
215            .unwrap_or_else(|| bybit_ws_private_url(self.environment).to_string())
216    }
217
218    /// Returns `true` when private WebSocket connection is required.
219    #[must_use]
220    pub fn requires_private_ws(&self) -> bool {
221        self.has_api_credentials()
222    }
223}
224
225/// Configuration for the Bybit live execution client.
226#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
227#[serde(default, deny_unknown_fields)]
228#[cfg_attr(
229    feature = "python",
230    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
231)]
232#[cfg_attr(
233    feature = "python",
234    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
235)]
236pub struct BybitExecutionClientConfig {
237    /// API key for authenticated requests.
238    pub api_key: Option<SecretString>,
239    /// API secret for authenticated requests.
240    pub api_secret: Option<SecretString>,
241    /// Product types to support (e.g., Linear, Spot, Inverse, Option).
242    #[builder(default = vec![BybitProductType::Linear])]
243    pub product_types: Vec<BybitProductType>,
244    /// Environment selection (Mainnet, Testnet, Demo).
245    #[builder(default = BybitEnvironment::Mainnet)]
246    pub environment: BybitEnvironment,
247    /// Optional override for the REST base URL.
248    pub base_url_http: Option<String>,
249    /// Optional override for the private WebSocket URL.
250    pub base_url_ws_private: Option<String>,
251    /// Optional override for the trade WebSocket URL.
252    pub base_url_ws_trade: Option<String>,
253    /// Optional proxy URL for HTTP and WebSocket transports.
254    pub proxy_url: Option<SecretString>,
255    /// REST timeout in seconds.
256    #[builder(default = 60)]
257    pub http_timeout_secs: u64,
258    /// Maximum retry attempts for REST reads.
259    #[builder(default = 3)]
260    pub max_retries: u32,
261    /// Initial REST read retry backoff, in milliseconds. Also the cancel-all polling interval.
262    #[builder(default = 1_000)]
263    pub retry_delay_initial_ms: u64,
264    /// Maximum retry backoff for REST reads, in milliseconds.
265    #[builder(default = 10_000)]
266    pub retry_delay_max_ms: u64,
267    /// Heartbeat interval in seconds for WebSocket clients.
268    #[builder(default = 20)]
269    pub heartbeat_interval_secs: u64,
270    /// Optional WebSocket authentication wait timeout (seconds), defaulting to
271    /// the client default when unset.
272    pub auth_timeout_secs: Option<u64>,
273    /// Receive window in milliseconds for signed requests.
274    #[builder(default = 5_000)]
275    pub recv_window_ms: u64,
276    /// Optional account identifier to associate with the execution client.
277    pub account_id: Option<AccountId>,
278    /// Whether scoped execution-client SPOT position requests derive positions from wallet
279    /// balances. The HTTP client rejects enabled unscoped SPOT requests because balances cannot be
280    /// attributed to pairs. The execution client omits SPOT from bulk requests and reports its bulk
281    /// coverage as unavailable.
282    #[builder(default)]
283    pub use_spot_position_reports: bool,
284    /// Whether to automatically repay SPOT margin borrows after BUY orders tracked by
285    /// this client and reported on the standard `execution` channel (not `execution.fast`)
286    /// fully fill.
287    #[builder(default)]
288    pub auto_repay_spot_borrows: bool,
289    /// Whether to subscribe to the lower-latency `execution.fast` channel instead of the
290    /// standard `execution` channel. Fast fills derive commissions from cached account fee
291    /// rates on a best-effort basis; derived values are not venue-authoritative. Demo mode
292    /// does not support this option.
293    #[builder(default)]
294    pub use_ws_execution_fast: bool,
295    /// Leverage configuration for futures (symbol -> leverage).
296    pub futures_leverages: Option<HashMap<String, u32>>,
297    /// Position mode configuration for symbols (symbol -> mode).
298    pub position_mode: Option<HashMap<String, BybitPositionMode>>,
299    /// Unified margin mode setting.
300    pub margin_mode: Option<BybitMarginMode>,
301    /// Self-match prevention type sent on every submitted order. The `smp_type` order parameter
302    /// overrides it, and leaving both unset omits the field so the venue default applies.
303    #[serde(deserialize_with = "deserialize_optional_smp_type")]
304    pub smp_type: Option<BybitOrderSmpType>,
305    /// WebSocket transport backend (defaults to `Tungstenite`).
306    #[builder(default)]
307    pub transport_backend: TransportBackend,
308}
309
310#[cfg(feature = "python")]
311nautilus_core::impl_pyo3_config_getters!(BybitExecutionClientConfig {
312    product_types: Vec<BybitProductType>,
313    environment: BybitEnvironment,
314    base_url_http: Option<String>,
315    base_url_ws_private: Option<String>,
316    base_url_ws_trade: Option<String>,
317    http_timeout_secs: u64,
318    max_retries: u32,
319    retry_delay_initial_ms: u64,
320    retry_delay_max_ms: u64,
321    heartbeat_interval_secs: u64,
322    auth_timeout_secs: Option<u64>,
323    recv_window_ms: u64,
324    account_id: Option<AccountId>,
325    use_spot_position_reports: bool,
326    auto_repay_spot_borrows: bool,
327    use_ws_execution_fast: bool,
328    margin_mode: Option<BybitMarginMode>,
329    transport_backend: TransportBackend,
330});
331
332impl Default for BybitExecutionClientConfig {
333    fn default() -> Self {
334        Self::builder().build()
335    }
336}
337
338impl BybitExecutionClientConfig {
339    /// Creates a configuration with default values.
340    #[must_use]
341    pub fn new() -> Self {
342        Self::default()
343    }
344
345    /// Validates configured product types and execution-stream selection.
346    ///
347    /// # Errors
348    ///
349    /// Returns an error if `product_types` repeats a value or fast execution is enabled in Demo
350    /// mode.
351    pub fn validate(&self) -> ConfigResult<()> {
352        if self.use_ws_execution_fast && self.environment == BybitEnvironment::Demo {
353            return Err(ConfigError::unsupported_value(
354                "use_ws_execution_fast",
355                "execution.fast is not supported in demo mode",
356            ));
357        }
358
359        check_unique_values("product_types", &self.product_types)
360    }
361
362    /// Returns `true` if both API key and secret are available.
363    #[must_use]
364    pub fn has_api_credentials(&self) -> bool {
365        self.api_key.is_some() && self.api_secret.is_some()
366    }
367
368    /// Returns the REST base URL, considering overrides and environment.
369    #[must_use]
370    pub fn http_base_url(&self) -> String {
371        self.base_url_http
372            .clone()
373            .unwrap_or_else(|| bybit_http_base_url(self.environment).to_string())
374    }
375
376    /// Returns the private WebSocket URL, considering overrides and environment.
377    #[must_use]
378    pub fn ws_private_url(&self) -> String {
379        self.base_url_ws_private
380            .clone()
381            .unwrap_or_else(|| bybit_ws_private_url(self.environment).to_string())
382    }
383
384    /// Returns the trade WebSocket URL, considering overrides and environment.
385    #[must_use]
386    pub fn ws_trade_url(&self) -> String {
387        self.base_url_ws_trade
388            .clone()
389            .unwrap_or_else(|| bybit_ws_trade_url(self.environment).to_string())
390    }
391}
392#[cfg(test)]
393mod tests {
394    use std::{cell::RefCell, rc::Rc};
395
396    use nautilus_common::{cache::Cache, config::ConfigError};
397    use nautilus_live::ExecutionClientCore;
398    use nautilus_model::{
399        enums::{AccountType, OmsType},
400        identifiers::{ClientId, TraderId, Venue},
401    };
402    use rstest::rstest;
403
404    use super::*;
405    use crate::{data::BybitDataClient, execution::BybitExecutionClient};
406
407    #[rstest]
408    fn test_data_client_rejects_duplicate_types() {
409        let config = BybitDataClientConfig {
410            product_types: vec![BybitProductType::Linear, BybitProductType::Linear],
411            ..Default::default()
412        };
413
414        let error = BybitDataClient::new(ClientId::from("BYBIT"), config)
415            .expect_err("duplicate config must fail before client setup");
416
417        assert_eq!(
418            error.downcast_ref::<ConfigError>(),
419            Some(&ConfigError::duplicate("product_types", None)),
420        );
421    }
422
423    #[rstest]
424    #[case::empty(vec![], false)]
425    #[case::distinct(vec![BybitProductType::Spot, BybitProductType::Linear], false)]
426    #[case::adjacent(vec![BybitProductType::Linear, BybitProductType::Linear], true)]
427    #[case::separated(vec![BybitProductType::Linear, BybitProductType::Spot, BybitProductType::Linear], true)]
428    fn test_config_duplicate_types(#[case] values: Vec<BybitProductType>, #[case] duplicate: bool) {
429        let data = BybitDataClientConfig {
430            product_types: values.clone(),
431            ..Default::default()
432        };
433
434        let execution = BybitExecutionClientConfig {
435            product_types: values.clone(),
436            ..Default::default()
437        };
438
439        let expected = if duplicate {
440            Err(ConfigError::duplicate("product_types", None))
441        } else {
442            Ok(())
443        };
444
445        let data_result = data.validate();
446        let execution_result = execution.validate();
447
448        assert_eq!(data_result, expected);
449        assert_eq!(execution_result, expected);
450        assert_eq!(data.product_types, values);
451        assert_eq!(execution.product_types, values);
452    }
453
454    #[rstest]
455    #[case::demo_fast(BybitEnvironment::Demo, true, true)]
456    #[case::demo_standard(BybitEnvironment::Demo, false, false)]
457    #[case::mainnet_fast(BybitEnvironment::Mainnet, true, false)]
458    #[case::testnet_fast(BybitEnvironment::Testnet, true, false)]
459    fn test_exec_config_fast_environment(
460        #[case] environment: BybitEnvironment,
461        #[case] use_ws_execution_fast: bool,
462        #[case] expect_rejection: bool,
463    ) {
464        let config = BybitExecutionClientConfig {
465            environment,
466            use_ws_execution_fast,
467            ..Default::default()
468        };
469
470        let result = config.validate();
471
472        if expect_rejection {
473            assert_eq!(
474                result,
475                Err(ConfigError::unsupported_value(
476                    "use_ws_execution_fast",
477                    "execution.fast is not supported in demo mode",
478                ))
479            );
480        } else {
481            assert_eq!(result, Ok(()));
482        }
483    }
484
485    #[rstest]
486    fn test_config_debug_redacts_credentials() {
487        let data = BybitDataClientConfig {
488            api_key: Some("data-api-key".into()),
489            api_secret: Some("data-api-secret".into()),
490            proxy_url: Some("http://user:data-proxy@localhost".into()),
491            ..Default::default()
492        };
493        let execution = BybitExecutionClientConfig {
494            api_key: Some("exec-api-key".into()),
495            api_secret: Some("exec-api-secret".into()),
496            proxy_url: Some("http://user:exec-proxy@localhost".into()),
497            ..Default::default()
498        };
499
500        let formatted = format!("{data:?} {execution:?}");
501
502        assert_eq!(formatted.matches(REDACTED).count(), 6);
503
504        for secret in [
505            "data-api-key",
506            "data-api-secret",
507            "data-proxy",
508            "exec-api-key",
509            "exec-api-secret",
510            "exec-proxy",
511        ] {
512            assert!(!formatted.contains(secret));
513        }
514    }
515
516    #[rstest]
517    #[case("None", BybitOrderSmpType::None)]
518    #[case("CancelMaker", BybitOrderSmpType::CancelMaker)]
519    #[case("CancelTaker", BybitOrderSmpType::CancelTaker)]
520    #[case("CancelBoth", BybitOrderSmpType::CancelBoth)]
521    fn test_exec_config_deserializes_smp_type(
522        #[case] value: &str,
523        #[case] expected: BybitOrderSmpType,
524    ) {
525        let json = format!(r#"{{"smp_type": "{value}"}}"#);
526        let config: BybitExecutionClientConfig = serde_json::from_str(&json).unwrap();
527
528        assert_eq!(config.smp_type, Some(expected));
529    }
530
531    #[rstest]
532    #[case(r#"{"smp_type": "Other"}"#)]
533    #[case(r#"{"smp_type": "cancel-maker"}"#)]
534    #[case(r#"{"smp_type": ""}"#)]
535    fn test_exec_config_rejects_invalid_smp_type(#[case] json: &str) {
536        let err = serde_json::from_str::<BybitExecutionClientConfig>(json).unwrap_err();
537
538        assert!(
539            err.to_string().contains("invalid Bybit smp_type"),
540            "expected an smp_type rejection, was '{err}'"
541        );
542    }
543
544    #[rstest]
545    fn test_exec_config_smp_type_defaults_to_none() {
546        let config: BybitExecutionClientConfig = serde_json::from_str("{}").unwrap();
547
548        assert_eq!(config.smp_type, None);
549    }
550
551    #[rstest]
552    fn test_data_config_default() {
553        let config = BybitDataClientConfig::default();
554
555        assert!(config.bars_timestamp_on_close);
556        assert!(!config.has_api_credentials());
557        assert_eq!(config.product_types, vec![BybitProductType::Linear]);
558        assert_eq!(config.http_timeout_secs, 60);
559        assert_eq!(config.heartbeat_interval_secs, 20);
560        assert_eq!(config.book_snapshot_timeout_secs, 10);
561    }
562
563    #[rstest]
564    fn test_data_config_bar_timestamp_builder() {
565        assert!(
566            BybitDataClientConfig::builder()
567                .build()
568                .bars_timestamp_on_close
569        );
570        assert!(
571            serde_json::from_str::<BybitDataClientConfig>("{}")
572                .unwrap()
573                .bars_timestamp_on_close
574        );
575        let config = BybitDataClientConfig::builder()
576            .bars_timestamp_on_close(false)
577            .build();
578        assert!(!config.bars_timestamp_on_close);
579        let config: BybitDataClientConfig =
580            serde_json::from_str(r#"{"bars_timestamp_on_close":false}"#).unwrap();
581        assert!(!config.bars_timestamp_on_close);
582    }
583
584    #[rstest]
585    fn test_data_config_with_credentials() {
586        let config = BybitDataClientConfig {
587            api_key: Some("test_key".into()),
588            api_secret: Some("test_secret".into()),
589            ..Default::default()
590        };
591
592        assert!(config.has_api_credentials());
593        assert!(config.requires_private_ws());
594    }
595
596    #[rstest]
597    fn test_data_config_http_url_mainnet() {
598        let config = BybitDataClientConfig {
599            environment: BybitEnvironment::Mainnet,
600            ..Default::default()
601        };
602
603        assert_eq!(config.http_base_url(), "https://api.bybit.com");
604    }
605
606    #[rstest]
607    fn test_data_config_http_url_testnet() {
608        let config = BybitDataClientConfig {
609            environment: BybitEnvironment::Testnet,
610            ..Default::default()
611        };
612
613        assert_eq!(config.http_base_url(), "https://api-testnet.bybit.com");
614    }
615
616    #[rstest]
617    fn test_data_config_http_url_demo() {
618        let config = BybitDataClientConfig {
619            environment: BybitEnvironment::Demo,
620            ..Default::default()
621        };
622
623        assert_eq!(config.http_base_url(), "https://api-demo.bybit.com");
624    }
625
626    #[rstest]
627    fn test_data_config_http_url_override() {
628        let custom_url = "https://custom.bybit.com";
629        let config = BybitDataClientConfig {
630            base_url_http: Some(custom_url.to_string()),
631            ..Default::default()
632        };
633
634        assert_eq!(config.http_base_url(), custom_url);
635    }
636
637    #[rstest]
638    fn test_data_config_ws_public_url() {
639        let config = BybitDataClientConfig {
640            environment: BybitEnvironment::Mainnet,
641            ..Default::default()
642        };
643
644        assert_eq!(
645            config.ws_public_url(),
646            "wss://stream.bybit.com/v5/public/linear"
647        );
648    }
649
650    #[rstest]
651    fn test_data_config_ws_public_url_for_spot() {
652        let config = BybitDataClientConfig {
653            environment: BybitEnvironment::Mainnet,
654            ..Default::default()
655        };
656
657        assert_eq!(
658            config.ws_public_url_for(BybitProductType::Spot),
659            "wss://stream.bybit.com/v5/public/spot"
660        );
661    }
662
663    #[rstest]
664    fn test_data_config_ws_private_url() {
665        let config = BybitDataClientConfig {
666            environment: BybitEnvironment::Mainnet,
667            ..Default::default()
668        };
669
670        assert_eq!(config.ws_private_url(), "wss://stream.bybit.com/v5/private");
671    }
672
673    #[rstest]
674    fn test_data_config_ws_private_url_testnet() {
675        let config = BybitDataClientConfig {
676            environment: BybitEnvironment::Testnet,
677            ..Default::default()
678        };
679
680        assert_eq!(
681            config.ws_private_url(),
682            "wss://stream-testnet.bybit.com/v5/private"
683        );
684    }
685
686    #[rstest]
687    fn test_exec_config_default() {
688        let config = BybitExecutionClientConfig::default();
689
690        assert!(!config.has_api_credentials());
691        assert_eq!(config.product_types, vec![BybitProductType::Linear]);
692        assert_eq!(config.http_timeout_secs, 60);
693        assert_eq!(config.heartbeat_interval_secs, 20);
694    }
695
696    #[rstest]
697    fn test_exec_config_with_credentials() {
698        let config = BybitExecutionClientConfig {
699            api_key: Some("test_key".into()),
700            api_secret: Some("test_secret".into()),
701            ..Default::default()
702        };
703
704        assert!(config.has_api_credentials());
705    }
706
707    #[rstest]
708    fn test_exec_config_urls() {
709        let config = BybitExecutionClientConfig {
710            environment: BybitEnvironment::Mainnet,
711            ..Default::default()
712        };
713
714        assert_eq!(config.http_base_url(), "https://api.bybit.com");
715        assert_eq!(config.ws_private_url(), "wss://stream.bybit.com/v5/private");
716        assert_eq!(config.ws_trade_url(), "wss://stream.bybit.com/v5/trade");
717    }
718
719    #[rstest]
720    fn test_exec_config_urls_testnet() {
721        let config = BybitExecutionClientConfig {
722            environment: BybitEnvironment::Testnet,
723            ..Default::default()
724        };
725
726        assert_eq!(config.http_base_url(), "https://api-testnet.bybit.com");
727        assert_eq!(
728            config.ws_private_url(),
729            "wss://stream-testnet.bybit.com/v5/private"
730        );
731        assert_eq!(
732            config.ws_trade_url(),
733            "wss://stream-testnet.bybit.com/v5/trade"
734        );
735    }
736
737    #[rstest]
738    fn test_exec_config_custom_urls() {
739        let config = BybitExecutionClientConfig {
740            base_url_http: Some("https://custom-http.bybit.com".to_string()),
741            base_url_ws_private: Some("wss://custom-private.bybit.com".to_string()),
742            base_url_ws_trade: Some("wss://custom-trade.bybit.com".to_string()),
743            ..Default::default()
744        };
745
746        assert_eq!(config.http_base_url(), "https://custom-http.bybit.com");
747        assert_eq!(config.ws_private_url(), "wss://custom-private.bybit.com");
748        assert_eq!(config.ws_trade_url(), "wss://custom-trade.bybit.com");
749    }
750
751    #[rstest]
752    fn test_data_config_toml_minimal() {
753        let config: BybitDataClientConfig = toml::from_str(
754            r#"
755environment = "testnet"
756product_types = ["spot", "linear"]
757http_timeout_secs = 45
758"#,
759        )
760        .unwrap();
761
762        assert_eq!(config.environment, BybitEnvironment::Testnet);
763        assert_eq!(
764            config.product_types,
765            vec![BybitProductType::Spot, BybitProductType::Linear]
766        );
767        assert_eq!(config.http_timeout_secs, 45);
768    }
769
770    #[rstest]
771    fn test_exec_config_toml_empty_uses_defaults() {
772        let config: BybitExecutionClientConfig = toml::from_str("").unwrap();
773        let expected = BybitExecutionClientConfig::default();
774
775        assert_eq!(config.environment, expected.environment);
776        assert_eq!(config.product_types, expected.product_types);
777        assert_eq!(config.http_timeout_secs, expected.http_timeout_secs);
778        assert_eq!(
779            config.heartbeat_interval_secs,
780            expected.heartbeat_interval_secs,
781        );
782        assert_eq!(config.recv_window_ms, expected.recv_window_ms);
783        assert_eq!(config.transport_backend, expected.transport_backend);
784    }
785
786    #[rstest]
787    fn test_execution_client_rejects_duplicate_types() {
788        let core = ExecutionClientCore::new(
789            TraderId::from("TESTER-001"),
790            ClientId::from("BYBIT"),
791            Venue::from("BYBIT"),
792            OmsType::Netting,
793            AccountId::from("BYBIT-001"),
794            AccountType::Margin,
795            None,
796            Rc::new(RefCell::new(Cache::default())),
797        );
798
799        let config = BybitExecutionClientConfig {
800            product_types: vec![BybitProductType::Linear, BybitProductType::Linear],
801            ..Default::default()
802        };
803
804        let error = BybitExecutionClient::new(core, config)
805            .expect_err("duplicate config must fail before credentials or client setup");
806
807        assert_eq!(
808            error.downcast_ref::<ConfigError>(),
809            Some(&ConfigError::duplicate("product_types", None))
810        );
811    }
812}