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, InstrumentId};
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        load_ids = None,
158    ))]
159    #[expect(clippy::too_many_arguments)]
160    fn py_new(
161        product_types: Option<Vec<BybitProductType>>,
162        environment: Option<BybitEnvironment>,
163        api_key: Option<String>,
164        api_secret: Option<String>,
165        base_url_http: Option<String>,
166        base_url_ws_private: Option<String>,
167        base_url_ws_trade: Option<String>,
168        proxy_url: Option<String>,
169        http_timeout_secs: Option<u64>,
170        max_retries: Option<u32>,
171        retry_delay_initial_ms: Option<u64>,
172        retry_delay_max_ms: Option<u64>,
173        heartbeat_interval_secs: Option<u64>,
174        auth_timeout_secs: Option<u64>,
175        recv_window_ms: Option<u64>,
176        account_id: Option<AccountId>,
177        use_spot_position_reports: Option<bool>,
178        auto_repay_spot_borrows: Option<bool>,
179        margin_mode: Option<BybitMarginMode>,
180        smp_type: Option<String>,
181        transport_backend: Option<TransportBackend>,
182        use_ws_execution_fast: Option<bool>,
183        load_ids: Option<Vec<InstrumentId>>,
184    ) -> PyResult<Self> {
185        let smp_type = smp_type
186            .map(|value| parse_smp_type(&value))
187            .transpose()
188            .map_err(to_pyvalue_err)?;
189
190        let defaults = Self::default();
191
192        let config = Self {
193            api_key: api_key.map(SecretString::from),
194            api_secret: api_secret.map(SecretString::from),
195            product_types: product_types.unwrap_or(defaults.product_types),
196            environment: environment.unwrap_or(defaults.environment),
197            base_url_http,
198            base_url_ws_private,
199            base_url_ws_trade,
200            proxy_url: proxy_url.map(SecretString::from),
201            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
202            max_retries: max_retries.unwrap_or(defaults.max_retries),
203            retry_delay_initial_ms: retry_delay_initial_ms
204                .unwrap_or(defaults.retry_delay_initial_ms),
205            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
206            heartbeat_interval_secs: heartbeat_interval_secs
207                .unwrap_or(defaults.heartbeat_interval_secs),
208            auth_timeout_secs,
209            recv_window_ms: recv_window_ms.unwrap_or(defaults.recv_window_ms),
210            account_id,
211            use_spot_position_reports: use_spot_position_reports
212                .unwrap_or(defaults.use_spot_position_reports),
213            auto_repay_spot_borrows: auto_repay_spot_borrows
214                .unwrap_or(defaults.auto_repay_spot_borrows),
215            use_ws_execution_fast: use_ws_execution_fast.unwrap_or(defaults.use_ws_execution_fast),
216            futures_leverages: None,
217            position_mode: None,
218            margin_mode,
219            smp_type,
220            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
221            load_ids,
222        };
223
224        config.validate().map_err(config_error_to_pyvalue_err)?;
225        Ok(config)
226    }
227
228    #[getter]
229    #[pyo3(name = "smp_type")]
230    fn py_smp_type(&self) -> Option<String> {
231        self.smp_type.map(|smp_type| smp_type.as_ref().to_string())
232    }
233
234    #[getter]
235    const fn has_proxy_url(&self) -> bool {
236        self.proxy_url.is_some()
237    }
238
239    fn __repr__(&self) -> String {
240        stringify!(BybitExecutionClientConfig).to_string()
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    use pyo3::{
247        Python,
248        exceptions::PyValueError,
249        prelude::*,
250        types::{PyDict, PyList},
251    };
252    use rstest::rstest;
253
254    use super::*;
255
256    #[rstest]
257    #[case::valid("ETHUSDT-LINEAR.BYBIT", true)]
258    #[case::invalid("ETHUSDT-LINEAR.BINANCE", false)]
259    #[case::empty_symbol("-LINEAR.BYBIT", false)]
260    fn test_python_execution_config_load_ids(#[case] id: &str, #[case] valid: bool) {
261        Python::initialize();
262        Python::attach(|py| {
263            let instrument_id = InstrumentId::from(id);
264            let list = PyList::new(py, [Py::new(py, instrument_id).unwrap()]).unwrap();
265            let kwargs = PyDict::new(py);
266            kwargs.set_item("load_ids", list).unwrap();
267            let result = py
268                .get_type::<BybitExecutionClientConfig>()
269                .call((), Some(&kwargs));
270
271            if valid {
272                let actual: Option<Vec<InstrumentId>> = result
273                    .unwrap()
274                    .getattr("load_ids")
275                    .unwrap()
276                    .extract()
277                    .unwrap();
278                assert_eq!(actual, Some(vec![instrument_id]));
279            } else {
280                let error = result.unwrap_err();
281                assert!(error.is_instance_of::<PyValueError>(py));
282                assert_eq!(
283                    error.value(py).str().unwrap().to_str().unwrap(),
284                    format!(
285                        "invalid load_ids: {id} is not an uppercase BYBIT instrument in a configured product type"
286                    )
287                );
288            }
289        });
290    }
291
292    #[rstest]
293    #[case::data(false)]
294    #[case::execution(true)]
295    fn test_python_config_duplicate_types(
296        #[case] execution: bool,
297        #[values(false, true)] duplicate: bool,
298    ) {
299        Python::initialize();
300        Python::attach(|py| {
301            let values = if duplicate {
302                vec![
303                    BybitProductType::Linear,
304                    BybitProductType::Spot,
305                    BybitProductType::Linear,
306                ]
307            } else {
308                vec![BybitProductType::Linear, BybitProductType::Spot]
309            };
310
311            let objects: Vec<_> = values
312                .iter()
313                .map(|value| Py::new(py, *value).unwrap())
314                .collect();
315            let list = PyList::new(py, objects).unwrap();
316            let kwargs = PyDict::new(py);
317            kwargs.set_item("product_types", list).unwrap();
318            if execution {
319                kwargs
320                    .set_item(
321                        "account_id",
322                        Py::new(py, AccountId::from("BYBIT-001")).unwrap(),
323                    )
324                    .unwrap();
325            }
326
327            let config_type = if execution {
328                py.get_type::<BybitExecutionClientConfig>()
329            } else {
330                py.get_type::<BybitDataClientConfig>()
331            };
332
333            let result = config_type.call((), Some(&kwargs));
334            if duplicate {
335                let error = result.unwrap_err();
336                assert!(error.is_instance_of::<PyValueError>(py));
337                assert_eq!(
338                    error.value(py).str().unwrap().to_str().unwrap(),
339                    "duplicate product_types"
340                );
341            } else {
342                let config = result.unwrap();
343                let actual: Vec<BybitProductType> =
344                    config.getattr("product_types").unwrap().extract().unwrap();
345                assert_eq!(actual, values);
346            }
347        });
348    }
349
350    #[rstest]
351    #[case::default(None, false)]
352    #[case::enabled(Some(true), true)]
353    #[case::disabled(Some(false), false)]
354    fn test_python_execution_config_fast_selection(
355        #[case] configured: Option<bool>,
356        #[case] expected: bool,
357    ) {
358        Python::initialize();
359        Python::attach(|py| {
360            let kwargs = PyDict::new(py);
361            if let Some(configured) = configured {
362                kwargs
363                    .set_item("use_ws_execution_fast", configured)
364                    .unwrap();
365            }
366
367            let config = py
368                .get_type::<BybitExecutionClientConfig>()
369                .call((), Some(&kwargs))
370                .unwrap();
371            let actual = config
372                .getattr("use_ws_execution_fast")
373                .unwrap()
374                .extract::<bool>()
375                .unwrap();
376            assert_eq!(actual, expected);
377        });
378    }
379
380    #[rstest]
381    fn test_python_execution_config_parameter_order() {
382        Python::initialize();
383        Python::attach(|py| {
384            let inspect = py.import("inspect").unwrap();
385            let signature = inspect
386                .call_method1("signature", (py.get_type::<BybitExecutionClientConfig>(),))
387                .unwrap();
388            let parameters = signature.getattr("parameters").unwrap();
389            let keys = parameters.call_method0("keys").unwrap();
390            let names = py
391                .import("builtins")
392                .unwrap()
393                .call_method1("list", (keys,))
394                .unwrap()
395                .extract::<Vec<String>>()
396                .unwrap();
397
398            assert_eq!(
399                names,
400                [
401                    "product_types",
402                    "environment",
403                    "api_key",
404                    "api_secret",
405                    "base_url_http",
406                    "base_url_ws_private",
407                    "base_url_ws_trade",
408                    "proxy_url",
409                    "http_timeout_secs",
410                    "max_retries",
411                    "retry_delay_initial_ms",
412                    "retry_delay_max_ms",
413                    "heartbeat_interval_secs",
414                    "auth_timeout_secs",
415                    "recv_window_ms",
416                    "account_id",
417                    "use_spot_position_reports",
418                    "auto_repay_spot_borrows",
419                    "margin_mode",
420                    "smp_type",
421                    "transport_backend",
422                    "use_ws_execution_fast",
423                    "load_ids",
424                ],
425            );
426        });
427    }
428}