Skip to main content

nautilus_deribit/
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 Deribit adapter.
17
18use nautilus_common::config::{ConfigError, ConfigResult, check_unique_values};
19#[cfg(test)]
20use nautilus_core::string::secret::REDACTED;
21use nautilus_core::string::secret::SecretString;
22use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
23use nautilus_model::identifiers::{AccountId, InstrumentId};
24use nautilus_network::websocket::TransportBackend;
25use serde::{Deserialize, Serialize};
26
27use crate::{
28    common::{
29        consts::DERIBIT_VENUE,
30        credential::credential_env_vars,
31        enums::DeribitEnvironment,
32        urls::{get_http_base_url, get_ws_url},
33    },
34    http::models::DeribitProductType,
35};
36
37fn validate_load_ids(load_ids: Option<&[InstrumentId]>) -> ConfigResult<()> {
38    let Some(load_ids) = load_ids else {
39        return Ok(());
40    };
41
42    check_unique_values("load_ids", load_ids)?;
43    for instrument_id in load_ids {
44        if instrument_id.venue != *DERIBIT_VENUE {
45            return Err(ConfigError::invalid_value(
46                "load_ids",
47                format!("{instrument_id} is not a DERIBIT instrument"),
48            ));
49        }
50    }
51
52    Ok(())
53}
54
55/// Configuration for the Deribit data client.
56#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
57#[serde(default, deny_unknown_fields)]
58#[cfg_attr(
59    feature = "python",
60    pyo3::pyclass(module = "nautilus_trader.adapters.deribit", from_py_object)
61)]
62#[cfg_attr(
63    feature = "python",
64    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.deribit")
65)]
66pub struct DeribitDataClientConfig {
67    /// Optional API key for authenticated endpoints.
68    pub api_key: Option<SecretString>,
69    /// Optional API secret for authenticated endpoints.
70    pub api_secret: Option<SecretString>,
71    /// Product types to load (e.g., Future, Option, Spot).
72    #[builder(default = vec![DeribitProductType::Future])]
73    pub product_types: Vec<DeribitProductType>,
74    /// The Deribit environment (mainnet or testnet).
75    #[builder(default)]
76    pub environment: DeribitEnvironment,
77    /// Optional override for the HTTP base URL.
78    pub base_url_http: Option<String>,
79    /// Optional override for the WebSocket URL.
80    pub base_url_ws: Option<String>,
81    /// Optional proxy URL for HTTP and WebSocket transports.
82    pub proxy_url: Option<SecretString>,
83    /// HTTP timeout in seconds.
84    #[builder(default = 60)]
85    pub http_timeout_secs: u64,
86    /// Maximum retry attempts for requests.
87    #[builder(default = 3)]
88    pub max_retries: u32,
89    /// Initial retry delay in milliseconds.
90    #[builder(default = 1_000)]
91    pub retry_delay_initial_ms: u64,
92    /// Maximum retry delay in milliseconds.
93    #[builder(default = 10_000)]
94    pub retry_delay_max_ms: u64,
95    /// Heartbeat interval in seconds for WebSocket connection.
96    #[builder(default = 30)]
97    pub heartbeat_interval_secs: u64,
98    /// Optional WebSocket authentication timeout (seconds), defaulting to
99    /// `AUTHENTICATION_TIMEOUT_SECS` when unset.
100    pub auth_timeout_secs: Option<u64>,
101    /// Interval in minutes for refreshing instruments of the configured product types.
102    /// A zero value disables periodic refresh.
103    #[builder(default = 60)]
104    pub update_instruments_interval_mins: u64,
105    /// If `true`, subscribes for uncached instruments lazy-load via HTTP; otherwise fail fast.
106    #[builder(default = false)]
107    pub auto_load_missing_instruments: bool,
108    /// WebSocket transport backend (defaults to `Tungstenite`).
109    #[builder(default)]
110    pub transport_backend: TransportBackend,
111    /// Extra instruments to load on connect.
112    ///
113    /// `None` or empty adds none. Set the same value on the execution client. That client uses
114    /// the value as the reconciliation scope.
115    pub load_ids: Option<Vec<InstrumentId>>,
116    /// Maximum wait for an initial, post-reconnect, or recovery book snapshot, in seconds.
117    /// A zero value disables snapshot deadlines.
118    #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
119    pub book_snapshot_timeout_secs: u64,
120    /// Maximum receive age of accepted book frames before recovery, in seconds.
121    /// A zero value disables stale book recovery.
122    #[builder(default = 120)]
123    pub book_stale_threshold_secs: u64,
124}
125
126#[cfg(feature = "python")]
127nautilus_core::impl_pyo3_config_getters!(DeribitDataClientConfig {
128    product_types: Vec<DeribitProductType>,
129    environment: DeribitEnvironment,
130    base_url_http: Option<String>,
131    base_url_ws: Option<String>,
132    http_timeout_secs: u64,
133    max_retries: u32,
134    retry_delay_initial_ms: u64,
135    retry_delay_max_ms: u64,
136    heartbeat_interval_secs: u64,
137    auth_timeout_secs: Option<u64>,
138    update_instruments_interval_mins: u64,
139    auto_load_missing_instruments: bool,
140    transport_backend: TransportBackend,
141    load_ids: Option<Vec<InstrumentId>>,
142    book_snapshot_timeout_secs: u64,
143    book_stale_threshold_secs: u64,
144});
145
146impl Default for DeribitDataClientConfig {
147    fn default() -> Self {
148        Self::builder().build()
149    }
150}
151
152impl DeribitDataClientConfig {
153    /// Creates a new configuration with default settings.
154    #[must_use]
155    pub fn new() -> Self {
156        Self::default()
157    }
158
159    /// Validates that configured selections contain no duplicates.
160    ///
161    /// # Errors
162    ///
163    /// Returns an error if `product_types` or `load_ids` repeats a value, or a `load_ids` entry
164    /// is not a DERIBIT instrument.
165    pub fn validate(&self) -> ConfigResult<()> {
166        check_unique_values("product_types", &self.product_types)?;
167        validate_load_ids(self.load_ids.as_deref())
168    }
169
170    /// Returns `true` when API credentials are available (in config or env vars).
171    #[must_use]
172    pub fn has_api_credentials(&self) -> bool {
173        let (key_env, secret_env) = credential_env_vars(self.environment);
174        let has_key = self.api_key.is_some() || std::env::var(key_env).is_ok();
175        let has_secret = self.api_secret.is_some() || std::env::var(secret_env).is_ok();
176        has_key && has_secret
177    }
178
179    /// Returns the HTTP base URL, falling back to the default when unset.
180    #[must_use]
181    pub fn http_base_url(&self) -> String {
182        self.base_url_http
183            .clone()
184            .unwrap_or_else(|| get_http_base_url(self.environment).to_string())
185    }
186
187    /// Returns the WebSocket URL, respecting the environment and overrides.
188    #[must_use]
189    pub fn ws_url(&self) -> String {
190        self.base_url_ws
191            .clone()
192            .unwrap_or_else(|| get_ws_url(self.environment).to_string())
193    }
194}
195
196/// Configuration for the Deribit execution client.
197#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
198#[serde(default, deny_unknown_fields)]
199#[cfg_attr(
200    feature = "python",
201    pyo3::pyclass(module = "nautilus_trader.adapters.deribit", from_py_object)
202)]
203#[cfg_attr(
204    feature = "python",
205    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.deribit")
206)]
207pub struct DeribitExecutionClientConfig {
208    /// The account ID for this client.
209    #[builder(default = AccountId::from("DERIBIT-001"))]
210    pub account_id: AccountId,
211    /// Optional API key for authenticated endpoints.
212    pub api_key: Option<SecretString>,
213    /// Optional API secret for authenticated endpoints.
214    pub api_secret: Option<SecretString>,
215    /// Product types to load (e.g., Future, Option, Spot).
216    #[builder(default = vec![DeribitProductType::Future])]
217    pub product_types: Vec<DeribitProductType>,
218    /// The Deribit environment (mainnet or testnet).
219    #[builder(default)]
220    pub environment: DeribitEnvironment,
221    /// Optional override for the HTTP base URL.
222    pub base_url_http: Option<String>,
223    /// Optional override for the WebSocket URL.
224    pub base_url_ws: Option<String>,
225    /// Optional proxy URL for HTTP and WebSocket transports.
226    pub proxy_url: Option<SecretString>,
227    /// HTTP timeout in seconds.
228    #[builder(default = 60)]
229    pub http_timeout_secs: u64,
230    /// Maximum retry attempts for requests.
231    #[builder(default = 3)]
232    pub max_retries: u32,
233    /// Initial retry delay in milliseconds.
234    #[builder(default = 1_000)]
235    pub retry_delay_initial_ms: u64,
236    /// Maximum retry delay in milliseconds.
237    #[builder(default = 10_000)]
238    pub retry_delay_max_ms: u64,
239    /// Optional WebSocket authentication timeout (seconds), defaulting to
240    /// `AUTHENTICATION_TIMEOUT_SECS` when unset.
241    pub auth_timeout_secs: Option<u64>,
242    /// WebSocket transport backend (defaults to `Tungstenite`).
243    #[builder(default)]
244    pub transport_backend: TransportBackend,
245    /// Instruments this node loads during connect and reconciles.
246    ///
247    /// `None` or empty means every instrument is in scope. A non-empty set is the only
248    /// reconciliation scope. Set the same value on the data and execution clients, and set
249    /// `reconciliation_instrument_ids` to that set so continuous checks do not treat an omitted
250    /// position as flat.
251    pub load_ids: Option<Vec<InstrumentId>>,
252}
253
254#[cfg(feature = "python")]
255nautilus_core::impl_pyo3_config_getters!(DeribitExecutionClientConfig {
256    account_id: AccountId,
257    product_types: Vec<DeribitProductType>,
258    environment: DeribitEnvironment,
259    base_url_http: Option<String>,
260    base_url_ws: Option<String>,
261    http_timeout_secs: u64,
262    max_retries: u32,
263    retry_delay_initial_ms: u64,
264    retry_delay_max_ms: u64,
265    auth_timeout_secs: Option<u64>,
266    transport_backend: TransportBackend,
267    load_ids: Option<Vec<InstrumentId>>,
268});
269
270impl Default for DeribitExecutionClientConfig {
271    fn default() -> Self {
272        Self::builder().build()
273    }
274}
275
276impl DeribitExecutionClientConfig {
277    /// Validates that configured selections contain no duplicates.
278    ///
279    /// # Errors
280    ///
281    /// Returns an error if `product_types` or `load_ids` repeats a value, or a `load_ids` entry
282    /// is not a DERIBIT instrument.
283    pub fn validate(&self) -> ConfigResult<()> {
284        check_unique_values("product_types", &self.product_types)?;
285        validate_load_ids(self.load_ids.as_deref())
286    }
287
288    /// Returns `true` when API credentials are available (in config or env vars).
289    #[must_use]
290    pub fn has_api_credentials(&self) -> bool {
291        let (key_env, secret_env) = credential_env_vars(self.environment);
292        let has_key = self.api_key.is_some() || std::env::var(key_env).is_ok();
293        let has_secret = self.api_secret.is_some() || std::env::var(secret_env).is_ok();
294        has_key && has_secret
295    }
296
297    /// Returns the HTTP base URL, falling back to the default when unset.
298    #[must_use]
299    pub fn http_base_url(&self) -> String {
300        self.base_url_http
301            .clone()
302            .unwrap_or_else(|| get_http_base_url(self.environment).to_string())
303    }
304
305    /// Returns the WebSocket URL, respecting the environment and overrides.
306    #[must_use]
307    pub fn ws_url(&self) -> String {
308        self.base_url_ws
309            .clone()
310            .unwrap_or_else(|| get_ws_url(self.environment).to_string())
311    }
312}
313
314#[cfg(test)]
315mod tests {
316    use std::{cell::RefCell, rc::Rc};
317
318    use nautilus_common::{cache::Cache, config::ConfigError};
319    use nautilus_live::ExecutionClientCore;
320    use nautilus_model::{
321        enums::{AccountType, OmsType},
322        identifiers::{ClientId, TraderId, Venue},
323    };
324    use rstest::rstest;
325
326    use super::*;
327    use crate::{data::DeribitDataClient, execution::DeribitExecutionClient};
328
329    #[rstest]
330    fn test_data_client_rejects_duplicate_types() {
331        let config = DeribitDataClientConfig {
332            product_types: vec![DeribitProductType::Future, DeribitProductType::Future],
333            ..Default::default()
334        };
335
336        let error = DeribitDataClient::new(ClientId::from("DERIBIT"), config)
337            .expect_err("duplicate config must fail before client setup");
338
339        assert_eq!(
340            error.downcast_ref::<ConfigError>(),
341            Some(&ConfigError::duplicate("product_types", None)),
342        );
343    }
344
345    #[rstest]
346    #[case::empty(vec![], false)]
347    #[case::distinct(vec![DeribitProductType::Option, DeribitProductType::Future], false)]
348    #[case::adjacent(vec![DeribitProductType::Future, DeribitProductType::Future], true)]
349    #[case::separated(vec![DeribitProductType::Future, DeribitProductType::Option, DeribitProductType::Future], true)]
350    fn test_config_duplicate_types(
351        #[case] values: Vec<DeribitProductType>,
352        #[case] duplicate: bool,
353    ) {
354        let data = DeribitDataClientConfig {
355            product_types: values.clone(),
356            ..Default::default()
357        };
358
359        let execution = DeribitExecutionClientConfig {
360            product_types: values.clone(),
361            ..Default::default()
362        };
363
364        let expected = if duplicate {
365            Err(ConfigError::duplicate("product_types", None))
366        } else {
367            Ok(())
368        };
369
370        let data_result = data.validate();
371        let execution_result = execution.validate();
372
373        assert_eq!(data_result, expected);
374        assert_eq!(execution_result, expected);
375        assert_eq!(data.product_types, values);
376        assert_eq!(execution.product_types, values);
377    }
378
379    #[rstest]
380    fn test_config_debug_redacts_credentials() {
381        let data = DeribitDataClientConfig {
382            api_key: Some("data-api-key".into()),
383            api_secret: Some("data-api-secret".into()),
384            proxy_url: Some("http://user:data-proxy@localhost".into()),
385            ..Default::default()
386        };
387        let execution = DeribitExecutionClientConfig {
388            api_key: Some("exec-api-key".into()),
389            api_secret: Some("exec-api-secret".into()),
390            proxy_url: Some("http://user:exec-proxy@localhost".into()),
391            ..Default::default()
392        };
393
394        let formatted = format!("{data:?} {execution:?}");
395
396        assert_eq!(formatted.matches(REDACTED).count(), 6);
397
398        for secret in [
399            "data-api-key",
400            "data-api-secret",
401            "data-proxy",
402            "exec-api-key",
403            "exec-api-secret",
404            "exec-proxy",
405        ] {
406            assert!(!formatted.contains(secret));
407        }
408    }
409
410    #[rstest]
411    fn test_default_config() {
412        let config = DeribitDataClientConfig::default();
413        assert_eq!(config.environment, DeribitEnvironment::Mainnet);
414        assert_eq!(config.product_types.len(), 1);
415        assert_eq!(config.http_timeout_secs, 60);
416        assert_eq!(config.book_snapshot_timeout_secs, 10);
417        assert_eq!(config.book_stale_threshold_secs, 120);
418    }
419
420    #[rstest]
421    fn test_book_timers_deserialize_with_defaults() {
422        let mut value = serde_json::to_value(DeribitDataClientConfig::default())
423            .expect("default config serializes");
424        let object = value.as_object_mut().expect("config is an object");
425        object.remove("book_snapshot_timeout_secs");
426        object.remove("book_stale_threshold_secs");
427
428        let config: DeribitDataClientConfig =
429            serde_json::from_value(value).expect("legacy config deserializes");
430
431        assert_eq!(config.book_snapshot_timeout_secs, 10);
432        assert_eq!(config.book_stale_threshold_secs, 120);
433    }
434
435    #[rstest]
436    fn test_http_base_url_default() {
437        let config = DeribitDataClientConfig::default();
438        assert_eq!(config.http_base_url(), "https://www.deribit.com");
439    }
440
441    #[rstest]
442    fn test_http_base_url_testnet() {
443        let config = DeribitDataClientConfig {
444            environment: DeribitEnvironment::Testnet,
445            ..Default::default()
446        };
447        assert_eq!(config.http_base_url(), "https://test.deribit.com");
448    }
449
450    #[rstest]
451    fn test_ws_url_default() {
452        let config = DeribitDataClientConfig::default();
453        assert_eq!(config.ws_url(), "wss://www.deribit.com/ws/api/v2");
454    }
455
456    #[rstest]
457    fn test_ws_url_testnet() {
458        let config = DeribitDataClientConfig {
459            environment: DeribitEnvironment::Testnet,
460            ..Default::default()
461        };
462        assert_eq!(config.ws_url(), "wss://test.deribit.com/ws/api/v2");
463    }
464
465    #[rstest]
466    fn test_load_ids_reject_duplicates_and_other_venues() {
467        let duplicate = DeribitExecutionClientConfig {
468            load_ids: Some(vec![
469                InstrumentId::from("BTC-PERPETUAL.DERIBIT"),
470                InstrumentId::from("BTC-PERPETUAL.DERIBIT"),
471            ]),
472            ..Default::default()
473        };
474
475        let other_venue = DeribitDataClientConfig {
476            load_ids: Some(vec![InstrumentId::from("BTC-PERPETUAL.BINANCE")]),
477            ..Default::default()
478        };
479
480        assert_eq!(
481            duplicate.validate(),
482            Err(ConfigError::duplicate("load_ids", None)),
483        );
484        assert_eq!(
485            other_venue.validate().expect_err("other venue").to_string(),
486            ConfigError::invalid_value(
487                "load_ids",
488                "BTC-PERPETUAL.BINANCE is not a DERIBIT instrument",
489            )
490            .to_string(),
491        );
492    }
493
494    #[rstest]
495    fn test_has_api_credentials_in_config() {
496        let config = DeribitDataClientConfig {
497            api_key: Some("test_key".into()),
498            api_secret: Some("test_secret".into()),
499            ..Default::default()
500        };
501        assert!(config.has_api_credentials());
502    }
503
504    #[rstest]
505    fn test_data_config_toml_minimal() {
506        let config: DeribitDataClientConfig = toml::from_str(
507            r#"
508environment = "testnet"
509product_types = ["future", "option"]
510heartbeat_interval_secs = 15
511auto_load_missing_instruments = true
512"#,
513        )
514        .unwrap();
515
516        assert_eq!(config.environment, DeribitEnvironment::Testnet);
517        assert_eq!(
518            config.product_types,
519            vec![DeribitProductType::Future, DeribitProductType::Option]
520        );
521        assert_eq!(config.heartbeat_interval_secs, 15);
522        assert!(config.auto_load_missing_instruments);
523    }
524
525    #[rstest]
526    fn test_exec_config_toml_empty_uses_defaults() {
527        let config: DeribitExecutionClientConfig = toml::from_str("").unwrap();
528        let expected = DeribitExecutionClientConfig::default();
529        assert_eq!(config.account_id, expected.account_id);
530        assert_eq!(config.environment, expected.environment);
531        assert_eq!(config.product_types, expected.product_types);
532        assert_eq!(config.http_timeout_secs, expected.http_timeout_secs);
533        assert_eq!(config.max_retries, expected.max_retries);
534        assert_eq!(config.transport_backend, expected.transport_backend);
535    }
536
537    #[rstest]
538    fn test_execution_client_rejects_duplicate_types() {
539        let core = ExecutionClientCore::new(
540            TraderId::from("TESTER-001"),
541            ClientId::from("DERIBIT"),
542            Venue::from("DERIBIT"),
543            OmsType::Netting,
544            AccountId::from("DERIBIT-001"),
545            AccountType::Margin,
546            None,
547            Rc::new(RefCell::new(Cache::default())),
548        );
549
550        let config = DeribitExecutionClientConfig {
551            product_types: vec![DeribitProductType::Future, DeribitProductType::Future],
552            ..Default::default()
553        };
554
555        let error = DeribitExecutionClient::new(core, config)
556            .expect_err("duplicate config must fail before credentials or client setup");
557
558        assert_eq!(
559            error.downcast_ref::<ConfigError>(),
560            Some(&ConfigError::duplicate("product_types", None))
561        );
562    }
563}