1use 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#[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 pub api_key: Option<SecretString>,
56 pub api_secret: Option<SecretString>,
63 #[builder(default = vec![BybitProductType::Linear])]
65 pub product_types: Vec<BybitProductType>,
66 #[builder(default = BybitEnvironment::Mainnet)]
68 pub environment: BybitEnvironment,
69 pub base_url_http: Option<String>,
71 pub base_url_ws_public: Option<String>,
73 pub base_url_ws_private: Option<String>,
75 pub proxy_url: Option<SecretString>,
77 #[builder(default = 60)]
79 pub http_timeout_secs: u64,
80 #[builder(default = 3)]
82 pub max_retries: u32,
83 #[builder(default = 1_000)]
85 pub retry_delay_initial_ms: u64,
86 #[builder(default = 10_000)]
88 pub retry_delay_max_ms: u64,
89 #[builder(default = 20)]
91 pub heartbeat_interval_secs: u64,
92 #[builder(default = 5_000)]
94 pub recv_window_ms: u64,
95 pub update_instruments_interval_mins: Option<u64>,
98 pub instrument_poll_interval_secs: Option<u64>,
101 #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
104 pub book_snapshot_timeout_secs: u64,
105 #[builder(default)]
107 pub transport_backend: TransportBackend,
108 #[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 #[must_use]
145 pub fn new() -> Self {
146 Self::default()
147 }
148
149 pub fn validate(&self) -> ConfigResult<()> {
155 check_unique_values("product_types", &self.product_types)
156 }
157
158 #[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 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 #[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 #[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 #[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 #[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 #[must_use]
220 pub fn requires_private_ws(&self) -> bool {
221 self.has_api_credentials()
222 }
223}
224
225#[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 pub api_key: Option<SecretString>,
239 pub api_secret: Option<SecretString>,
241 #[builder(default = vec![BybitProductType::Linear])]
243 pub product_types: Vec<BybitProductType>,
244 #[builder(default = BybitEnvironment::Mainnet)]
246 pub environment: BybitEnvironment,
247 pub base_url_http: Option<String>,
249 pub base_url_ws_private: Option<String>,
251 pub base_url_ws_trade: Option<String>,
253 pub proxy_url: Option<SecretString>,
255 #[builder(default = 60)]
257 pub http_timeout_secs: u64,
258 #[builder(default = 3)]
260 pub max_retries: u32,
261 #[builder(default = 1_000)]
263 pub retry_delay_initial_ms: u64,
264 #[builder(default = 10_000)]
266 pub retry_delay_max_ms: u64,
267 #[builder(default = 20)]
269 pub heartbeat_interval_secs: u64,
270 pub auth_timeout_secs: Option<u64>,
273 #[builder(default = 5_000)]
275 pub recv_window_ms: u64,
276 pub account_id: Option<AccountId>,
278 #[builder(default)]
283 pub use_spot_position_reports: bool,
284 #[builder(default)]
288 pub auto_repay_spot_borrows: bool,
289 #[builder(default)]
294 pub use_ws_execution_fast: bool,
295 pub futures_leverages: Option<HashMap<String, u32>>,
297 pub position_mode: Option<HashMap<String, BybitPositionMode>>,
299 pub margin_mode: Option<BybitMarginMode>,
301 #[serde(deserialize_with = "deserialize_optional_smp_type")]
304 pub smp_type: Option<BybitOrderSmpType>,
305 #[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 #[must_use]
341 pub fn new() -> Self {
342 Self::default()
343 }
344
345 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 #[must_use]
364 pub fn has_api_credentials(&self) -> bool {
365 self.api_key.is_some() && self.api_secret.is_some()
366 }
367
368 #[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 #[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 #[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}