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