Skip to main content

nautilus_bybit/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 Bybit configuration.
17
18use nautilus_common::python::config_error_to_pyvalue_err;
19use nautilus_core::{python::to_pyvalue_err, string::secret::SecretString};
20use nautilus_model::identifiers::AccountId;
21use nautilus_network::websocket::TransportBackend;
22use pyo3::{PyResult, pymethods};
23
24use crate::{
25    common::{
26        enums::{BybitEnvironment, BybitMarginMode, BybitProductType},
27        parse::parse_smp_type,
28    },
29    config::{BybitDataClientConfig, BybitExecutionClientConfig},
30};
31
32#[pymethods]
33#[pyo3_stub_gen::derive::gen_stub_pymethods]
34impl BybitDataClientConfig {
35    /// Configuration for the Bybit live data client.
36    #[new]
37    #[pyo3(signature = (
38        product_types = None,
39        environment = None,
40        api_key = None,
41        api_secret = None,
42        base_url_http = None,
43        base_url_ws_public = None,
44        base_url_ws_private = None,
45        proxy_url = None,
46        http_timeout_secs = None,
47        max_retries = None,
48        retry_delay_initial_ms = None,
49        retry_delay_max_ms = None,
50        heartbeat_interval_secs = None,
51        recv_window_ms = None,
52        update_instruments_interval_mins = None,
53        instrument_status_poll_secs = None,
54        transport_backend = None,
55        book_snapshot_timeout_secs = None,
56        bars_timestamp_on_close = None,
57    ))]
58    #[expect(clippy::too_many_arguments)]
59    fn py_new(
60        product_types: Option<Vec<BybitProductType>>,
61        environment: Option<BybitEnvironment>,
62        api_key: Option<String>,
63        api_secret: Option<String>,
64        base_url_http: Option<String>,
65        base_url_ws_public: Option<String>,
66        base_url_ws_private: Option<String>,
67        proxy_url: Option<String>,
68        http_timeout_secs: Option<u64>,
69        max_retries: Option<u32>,
70        retry_delay_initial_ms: Option<u64>,
71        retry_delay_max_ms: Option<u64>,
72        heartbeat_interval_secs: Option<u64>,
73        recv_window_ms: Option<u64>,
74        update_instruments_interval_mins: Option<u64>,
75        instrument_status_poll_secs: Option<u64>,
76        transport_backend: Option<TransportBackend>,
77        book_snapshot_timeout_secs: Option<u64>,
78        bars_timestamp_on_close: Option<bool>,
79    ) -> PyResult<Self> {
80        let defaults = Self::default();
81
82        let config = Self {
83            api_key: api_key.map(SecretString::from),
84            api_secret: api_secret.map(SecretString::from),
85            product_types: product_types.unwrap_or(defaults.product_types),
86            environment: environment.unwrap_or(defaults.environment),
87            base_url_http,
88            base_url_ws_public,
89            base_url_ws_private,
90            proxy_url: proxy_url.map(SecretString::from),
91            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
92            max_retries: max_retries.unwrap_or(defaults.max_retries),
93            retry_delay_initial_ms: retry_delay_initial_ms
94                .unwrap_or(defaults.retry_delay_initial_ms),
95            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
96            heartbeat_interval_secs: heartbeat_interval_secs
97                .unwrap_or(defaults.heartbeat_interval_secs),
98            recv_window_ms: recv_window_ms.unwrap_or(defaults.recv_window_ms),
99            update_instruments_interval_mins: update_instruments_interval_mins
100                .or(defaults.update_instruments_interval_mins),
101            instrument_poll_interval_secs: instrument_status_poll_secs
102                .or(defaults.instrument_poll_interval_secs),
103            book_snapshot_timeout_secs: book_snapshot_timeout_secs
104                .unwrap_or(defaults.book_snapshot_timeout_secs),
105            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
106            bars_timestamp_on_close: bars_timestamp_on_close
107                .unwrap_or(defaults.bars_timestamp_on_close),
108        };
109
110        config.validate().map_err(config_error_to_pyvalue_err)?;
111        Ok(config)
112    }
113
114    #[getter]
115    const fn instrument_status_poll_secs(&self) -> Option<u64> {
116        self.instrument_poll_interval_secs
117    }
118
119    #[getter]
120    const fn has_proxy_url(&self) -> bool {
121        self.proxy_url.is_some()
122    }
123
124    fn __repr__(&self) -> String {
125        stringify!(BybitDataClientConfig).to_string()
126    }
127}
128
129#[pymethods]
130#[pyo3_stub_gen::derive::gen_stub_pymethods]
131impl BybitExecutionClientConfig {
132    /// Configuration for the Bybit live execution client.
133    #[new]
134    #[pyo3(signature = (
135        product_types = None,
136        environment = None,
137        api_key = None,
138        api_secret = None,
139        base_url_http = None,
140        base_url_ws_private = None,
141        base_url_ws_trade = None,
142        proxy_url = None,
143        http_timeout_secs = None,
144        max_retries = None,
145        retry_delay_initial_ms = None,
146        retry_delay_max_ms = None,
147        heartbeat_interval_secs = None,
148        auth_timeout_secs = None,
149        recv_window_ms = None,
150        account_id = None,
151        use_spot_position_reports = None,
152        auto_repay_spot_borrows = None,
153        margin_mode = None,
154        smp_type = None,
155        transport_backend = None,
156        use_ws_execution_fast = None,
157    ))]
158    #[expect(clippy::too_many_arguments)]
159    fn py_new(
160        product_types: Option<Vec<BybitProductType>>,
161        environment: Option<BybitEnvironment>,
162        api_key: Option<String>,
163        api_secret: Option<String>,
164        base_url_http: Option<String>,
165        base_url_ws_private: Option<String>,
166        base_url_ws_trade: Option<String>,
167        proxy_url: Option<String>,
168        http_timeout_secs: Option<u64>,
169        max_retries: Option<u32>,
170        retry_delay_initial_ms: Option<u64>,
171        retry_delay_max_ms: Option<u64>,
172        heartbeat_interval_secs: Option<u64>,
173        auth_timeout_secs: Option<u64>,
174        recv_window_ms: Option<u64>,
175        account_id: Option<AccountId>,
176        use_spot_position_reports: Option<bool>,
177        auto_repay_spot_borrows: Option<bool>,
178        margin_mode: Option<BybitMarginMode>,
179        smp_type: Option<String>,
180        transport_backend: Option<TransportBackend>,
181        use_ws_execution_fast: Option<bool>,
182    ) -> PyResult<Self> {
183        let smp_type = smp_type
184            .map(|value| parse_smp_type(&value))
185            .transpose()
186            .map_err(to_pyvalue_err)?;
187
188        let defaults = Self::default();
189
190        let config = Self {
191            api_key: api_key.map(SecretString::from),
192            api_secret: api_secret.map(SecretString::from),
193            product_types: product_types.unwrap_or(defaults.product_types),
194            environment: environment.unwrap_or(defaults.environment),
195            base_url_http,
196            base_url_ws_private,
197            base_url_ws_trade,
198            proxy_url: proxy_url.map(SecretString::from),
199            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
200            max_retries: max_retries.unwrap_or(defaults.max_retries),
201            retry_delay_initial_ms: retry_delay_initial_ms
202                .unwrap_or(defaults.retry_delay_initial_ms),
203            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
204            heartbeat_interval_secs: heartbeat_interval_secs
205                .unwrap_or(defaults.heartbeat_interval_secs),
206            auth_timeout_secs,
207            recv_window_ms: recv_window_ms.unwrap_or(defaults.recv_window_ms),
208            account_id,
209            use_spot_position_reports: use_spot_position_reports
210                .unwrap_or(defaults.use_spot_position_reports),
211            auto_repay_spot_borrows: auto_repay_spot_borrows
212                .unwrap_or(defaults.auto_repay_spot_borrows),
213            use_ws_execution_fast: use_ws_execution_fast.unwrap_or(defaults.use_ws_execution_fast),
214            futures_leverages: None,
215            position_mode: None,
216            margin_mode,
217            smp_type,
218            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
219        };
220
221        config.validate().map_err(config_error_to_pyvalue_err)?;
222        Ok(config)
223    }
224
225    #[getter]
226    #[pyo3(name = "smp_type")]
227    fn py_smp_type(&self) -> Option<String> {
228        self.smp_type.map(|smp_type| smp_type.as_ref().to_string())
229    }
230
231    #[getter]
232    const fn has_proxy_url(&self) -> bool {
233        self.proxy_url.is_some()
234    }
235
236    fn __repr__(&self) -> String {
237        stringify!(BybitExecutionClientConfig).to_string()
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use pyo3::{
244        Python,
245        exceptions::PyValueError,
246        prelude::*,
247        types::{PyDict, PyList},
248    };
249    use rstest::rstest;
250
251    use super::*;
252
253    #[rstest]
254    #[case::data(false)]
255    #[case::execution(true)]
256    fn test_python_config_duplicate_types(
257        #[case] execution: bool,
258        #[values(false, true)] duplicate: bool,
259    ) {
260        Python::initialize();
261        Python::attach(|py| {
262            let values = if duplicate {
263                vec![
264                    BybitProductType::Linear,
265                    BybitProductType::Spot,
266                    BybitProductType::Linear,
267                ]
268            } else {
269                vec![BybitProductType::Linear, BybitProductType::Spot]
270            };
271
272            let objects: Vec<_> = values
273                .iter()
274                .map(|value| Py::new(py, *value).unwrap())
275                .collect();
276            let list = PyList::new(py, objects).unwrap();
277            let kwargs = PyDict::new(py);
278            kwargs.set_item("product_types", list).unwrap();
279            if execution {
280                kwargs
281                    .set_item(
282                        "account_id",
283                        Py::new(py, AccountId::from("BYBIT-001")).unwrap(),
284                    )
285                    .unwrap();
286            }
287
288            let config_type = if execution {
289                py.get_type::<BybitExecutionClientConfig>()
290            } else {
291                py.get_type::<BybitDataClientConfig>()
292            };
293
294            let result = config_type.call((), Some(&kwargs));
295            if duplicate {
296                let error = result.unwrap_err();
297                assert!(error.is_instance_of::<PyValueError>(py));
298                assert_eq!(
299                    error.value(py).str().unwrap().to_str().unwrap(),
300                    "duplicate product_types"
301                );
302            } else {
303                let config = result.unwrap();
304                let actual: Vec<BybitProductType> =
305                    config.getattr("product_types").unwrap().extract().unwrap();
306                assert_eq!(actual, values);
307            }
308        });
309    }
310
311    #[rstest]
312    #[case::default(None, false)]
313    #[case::enabled(Some(true), true)]
314    #[case::disabled(Some(false), false)]
315    fn test_python_execution_config_fast_selection(
316        #[case] configured: Option<bool>,
317        #[case] expected: bool,
318    ) {
319        Python::initialize();
320        Python::attach(|py| {
321            let kwargs = PyDict::new(py);
322            if let Some(configured) = configured {
323                kwargs
324                    .set_item("use_ws_execution_fast", configured)
325                    .unwrap();
326            }
327
328            let config = py
329                .get_type::<BybitExecutionClientConfig>()
330                .call((), Some(&kwargs))
331                .unwrap();
332            let actual = config
333                .getattr("use_ws_execution_fast")
334                .unwrap()
335                .extract::<bool>()
336                .unwrap();
337            assert_eq!(actual, expected);
338        });
339    }
340
341    #[rstest]
342    fn test_python_execution_config_fast_parameter_is_last() {
343        Python::initialize();
344        Python::attach(|py| {
345            let inspect = py.import("inspect").unwrap();
346            let signature = inspect
347                .call_method1("signature", (py.get_type::<BybitExecutionClientConfig>(),))
348                .unwrap();
349            let parameters = signature.getattr("parameters").unwrap();
350            let keys = parameters.call_method0("keys").unwrap();
351            let names = py
352                .import("builtins")
353                .unwrap()
354                .call_method1("list", (keys,))
355                .unwrap()
356                .extract::<Vec<String>>()
357                .unwrap();
358
359            assert_eq!(
360                names.last().map(String::as_str),
361                Some("use_ws_execution_fast")
362            );
363            assert_eq!(
364                names.get(names.len() - 2).map(String::as_str),
365                Some("transport_backend")
366            );
367        });
368    }
369}