Skip to main content

nautilus_deribit/python/
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//! Python bindings for Deribit configuration.
17
18use nautilus_common::python::config_error_to_pyvalue_err;
19use nautilus_core::string::secret::SecretString;
20use nautilus_model::identifiers::{AccountId, InstrumentId};
21use nautilus_network::websocket::TransportBackend;
22use pyo3::prelude::*;
23
24use crate::{
25    common::enums::DeribitEnvironment,
26    config::{DeribitDataClientConfig, DeribitExecutionClientConfig},
27    http::models::DeribitProductType,
28};
29
30#[pymethods]
31#[pyo3_stub_gen::derive::gen_stub_pymethods]
32impl DeribitDataClientConfig {
33    /// Configuration for the Deribit data client.
34    #[new]
35    #[pyo3(signature = (
36        product_types = None,
37        environment = None,
38        api_key = None,
39        api_secret = None,
40        base_url_http = None,
41        base_url_ws = None,
42        proxy_url = None,
43        http_timeout_secs = None,
44        max_retries = None,
45        retry_delay_initial_ms = None,
46        retry_delay_max_ms = None,
47        heartbeat_interval_secs = None,
48        auth_timeout_secs = None,
49        update_instruments_interval_mins = None,
50        auto_load_missing_instruments = None,
51        transport_backend = None,
52        load_ids = None,
53        book_snapshot_timeout_secs = None,
54        book_stale_threshold_secs = None,
55    ))]
56    #[expect(clippy::too_many_arguments)]
57    fn py_new(
58        product_types: Option<Vec<DeribitProductType>>,
59        environment: Option<DeribitEnvironment>,
60        api_key: Option<String>,
61        api_secret: Option<String>,
62        base_url_http: Option<String>,
63        base_url_ws: Option<String>,
64        proxy_url: Option<String>,
65        http_timeout_secs: Option<u64>,
66        max_retries: Option<u32>,
67        retry_delay_initial_ms: Option<u64>,
68        retry_delay_max_ms: Option<u64>,
69        heartbeat_interval_secs: Option<u64>,
70        auth_timeout_secs: Option<u64>,
71        update_instruments_interval_mins: Option<u64>,
72        auto_load_missing_instruments: Option<bool>,
73        transport_backend: Option<TransportBackend>,
74        load_ids: Option<Vec<InstrumentId>>,
75        book_snapshot_timeout_secs: Option<u64>,
76        book_stale_threshold_secs: Option<u64>,
77    ) -> PyResult<Self> {
78        let defaults = Self::default();
79
80        let config = Self {
81            api_key: api_key.map(SecretString::from),
82            api_secret: api_secret.map(SecretString::from),
83            product_types: product_types.unwrap_or(defaults.product_types),
84            base_url_http,
85            base_url_ws,
86            proxy_url: proxy_url.map(SecretString::from),
87            environment: environment.unwrap_or(defaults.environment),
88            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
89            max_retries: max_retries.unwrap_or(defaults.max_retries),
90            retry_delay_initial_ms: retry_delay_initial_ms
91                .unwrap_or(defaults.retry_delay_initial_ms),
92            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
93            heartbeat_interval_secs: heartbeat_interval_secs
94                .unwrap_or(defaults.heartbeat_interval_secs),
95            auth_timeout_secs,
96            update_instruments_interval_mins: update_instruments_interval_mins
97                .unwrap_or(defaults.update_instruments_interval_mins),
98            auto_load_missing_instruments: auto_load_missing_instruments
99                .unwrap_or(defaults.auto_load_missing_instruments),
100            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
101            load_ids,
102            book_snapshot_timeout_secs: book_snapshot_timeout_secs
103                .unwrap_or(defaults.book_snapshot_timeout_secs),
104            book_stale_threshold_secs: book_stale_threshold_secs
105                .unwrap_or(defaults.book_stale_threshold_secs),
106        };
107
108        config.validate().map_err(config_error_to_pyvalue_err)?;
109        Ok(config)
110    }
111
112    #[getter]
113    const fn has_proxy_url(&self) -> bool {
114        self.proxy_url.is_some()
115    }
116
117    fn __repr__(&self) -> String {
118        stringify!(DeribitDataClientConfig).to_string()
119    }
120}
121
122#[pymethods]
123#[pyo3_stub_gen::derive::gen_stub_pymethods]
124impl DeribitExecutionClientConfig {
125    /// Configuration for the Deribit execution client.
126    #[new]
127    #[pyo3(signature = (
128        account_id,
129        product_types = None,
130        environment = None,
131        api_key = None,
132        api_secret = None,
133        base_url_http = None,
134        base_url_ws = None,
135        proxy_url = None,
136        http_timeout_secs = None,
137        max_retries = None,
138        retry_delay_initial_ms = None,
139        retry_delay_max_ms = None,
140        auth_timeout_secs = None,
141        transport_backend = None,
142        load_ids = None,
143    ))]
144    #[expect(clippy::too_many_arguments)]
145    fn py_new(
146        account_id: AccountId,
147        product_types: Option<Vec<DeribitProductType>>,
148        environment: Option<DeribitEnvironment>,
149        api_key: Option<String>,
150        api_secret: Option<String>,
151        base_url_http: Option<String>,
152        base_url_ws: Option<String>,
153        proxy_url: Option<String>,
154        http_timeout_secs: Option<u64>,
155        max_retries: Option<u32>,
156        retry_delay_initial_ms: Option<u64>,
157        retry_delay_max_ms: Option<u64>,
158        auth_timeout_secs: Option<u64>,
159        transport_backend: Option<TransportBackend>,
160        load_ids: Option<Vec<InstrumentId>>,
161    ) -> PyResult<Self> {
162        let defaults = Self::default();
163
164        let config = Self {
165            account_id,
166            api_key: api_key.map(SecretString::from),
167            api_secret: api_secret.map(SecretString::from),
168            product_types: product_types.unwrap_or(defaults.product_types),
169            base_url_http,
170            base_url_ws,
171            proxy_url: proxy_url.map(SecretString::from),
172            environment: environment.unwrap_or(defaults.environment),
173            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
174            max_retries: max_retries.unwrap_or(defaults.max_retries),
175            retry_delay_initial_ms: retry_delay_initial_ms
176                .unwrap_or(defaults.retry_delay_initial_ms),
177            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
178            auth_timeout_secs,
179            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
180            load_ids,
181        };
182
183        config.validate().map_err(config_error_to_pyvalue_err)?;
184        Ok(config)
185    }
186
187    #[getter]
188    const fn has_proxy_url(&self) -> bool {
189        self.proxy_url.is_some()
190    }
191
192    fn __repr__(&self) -> String {
193        stringify!(DeribitExecutionClientConfig).to_string()
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use pyo3::{
200        Python,
201        exceptions::PyValueError,
202        types::{PyDict, PyList},
203    };
204    use rstest::rstest;
205
206    use super::*;
207
208    #[rstest]
209    #[case::data(false)]
210    #[case::execution(true)]
211    fn test_python_config_duplicate_types(
212        #[case] execution: bool,
213        #[values(false, true)] duplicate: bool,
214    ) {
215        Python::initialize();
216        Python::attach(|py| {
217            let values = if duplicate {
218                vec![
219                    DeribitProductType::Future,
220                    DeribitProductType::Option,
221                    DeribitProductType::Future,
222                ]
223            } else {
224                vec![DeribitProductType::Future, DeribitProductType::Option]
225            };
226
227            let objects: Vec<_> = values
228                .iter()
229                .map(|value| Py::new(py, *value).unwrap())
230                .collect();
231            let list = PyList::new(py, objects).unwrap();
232            let kwargs = PyDict::new(py);
233            kwargs.set_item("product_types", list).unwrap();
234            if execution {
235                kwargs
236                    .set_item(
237                        "account_id",
238                        Py::new(py, AccountId::from("DERIBIT-001")).unwrap(),
239                    )
240                    .unwrap();
241            }
242
243            let config_type = if execution {
244                py.get_type::<DeribitExecutionClientConfig>()
245            } else {
246                py.get_type::<DeribitDataClientConfig>()
247            };
248
249            let result = config_type.call((), Some(&kwargs));
250            if duplicate {
251                let error = result.unwrap_err();
252                assert!(error.is_instance_of::<PyValueError>(py));
253                assert_eq!(
254                    error.value(py).str().unwrap().to_str().unwrap(),
255                    "duplicate product_types"
256                );
257            } else {
258                let config = result.unwrap();
259                let actual: Vec<DeribitProductType> =
260                    config.getattr("product_types").unwrap().extract().unwrap();
261                assert_eq!(actual, values);
262            }
263        });
264    }
265}