Skip to main content

nautilus_bybit/python/
mod.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 from `pyo3`.
17
18pub mod config;
19pub mod enums;
20pub mod factories;
21pub mod http;
22pub mod params;
23
24use nautilus_common::factories::{ClientConfig, DataClientFactory, ExecutionClientFactory};
25use nautilus_core::python::{to_pyruntime_err, to_pyvalue_err};
26use nautilus_model::{
27    data::ensure_rust_extractor_registered,
28    enums::{BarAggregation, OrderSide},
29};
30use nautilus_system::get_global_pyo3_registry;
31use pyo3::prelude::*;
32
33use crate::{
34    common::{
35        consts::{BYBIT, BYBIT_CLIENT_ID, BYBIT_VENUE},
36        enums::{BybitOrderSide, BybitPositionIdx, BybitPositionMode},
37        parse::{bar_spec_to_bybit_interval, extract_raw_symbol, resolve_position_idx},
38        symbol::BybitSymbol,
39    },
40    config::{BybitDataClientConfig, BybitExecutionClientConfig},
41    data_types::{
42        BybitLiquidation, BybitMarginBorrowResult, BybitMarginRepayResult, BybitMarginStatusResult,
43        register_bybit_custom_data,
44    },
45    factories::{BybitDataClientFactory, BybitExecutionClientFactory},
46};
47
48/// Extracts the raw symbol from a Bybit symbol by removing the product type suffix.
49///
50/// # Examples
51/// - `"ETHUSDT-LINEAR"` → `"ETHUSDT"`
52/// - `"BTCUSDT-SPOT"` → `"BTCUSDT"`
53/// - `"ETHUSDT"` → `"ETHUSDT"` (no suffix)
54#[pyfunction]
55#[pyo3_stub_gen::derive::gen_stub_pyfunction(module = "nautilus_trader.adapters.bybit")]
56#[pyo3(name = "bybit_extract_raw_symbol")]
57fn py_bybit_extract_raw_symbol(symbol: &str) -> &str {
58    extract_raw_symbol(symbol)
59}
60
61/// Converts a Nautilus bar aggregation and step to a Bybit kline interval string.
62///
63/// # Errors
64///
65/// Returns an error if the aggregation type or step is not supported by Bybit.
66#[pyfunction]
67#[pyo3_stub_gen::derive::gen_stub_pyfunction(module = "nautilus_trader.adapters.bybit")]
68#[pyo3(name = "bybit_bar_spec_to_interval")]
69fn py_bybit_bar_spec_to_interval(aggregation: BarAggregation, step: u64) -> PyResult<String> {
70    let interval = bar_spec_to_bybit_interval(aggregation, step).map_err(to_pyvalue_err)?;
71    Ok(interval.to_string())
72}
73
74/// Extracts the product type from a Bybit symbol.
75///
76/// # Examples
77/// - `"ETHUSDT-LINEAR"` → `BybitProductType.LINEAR`
78/// - `"BTCUSDT-SPOT"` → `BybitProductType.SPOT`
79/// - `"BTCUSD-INVERSE"` → `BybitProductType.INVERSE`
80/// - `"ETH-26JUN26-16000-P-OPTION"` → `BybitProductType.OPTION`
81///
82/// # Errors
83///
84/// Returns an error if the symbol does not contain a valid Bybit product type suffix.
85#[pyfunction]
86#[pyo3_stub_gen::derive::gen_stub_pyfunction(module = "nautilus_trader.adapters.bybit")]
87#[pyo3(name = "bybit_product_type_from_symbol")]
88fn py_bybit_product_type_from_symbol(
89    symbol: &str,
90) -> PyResult<crate::common::enums::BybitProductType> {
91    let bybit_symbol = BybitSymbol::new(symbol).map_err(to_pyvalue_err)?;
92    Ok(bybit_symbol.product_type())
93}
94
95/// Resolves the Bybit `positionIdx` for an outgoing order.
96///
97/// Returns `None` when no position mode is configured. Otherwise returns the
98/// hedge-mode index for the position being affected (long or short), accounting
99/// for `is_reduce_only`. A `manual_override` always wins.
100#[pyfunction]
101#[pyo3_stub_gen::derive::gen_stub_pyfunction(module = "nautilus_trader.adapters.bybit")]
102#[pyo3(name = "bybit_resolve_position_idx")]
103#[pyo3(signature = (position_mode, order_side, is_reduce_only, manual_override=None))]
104fn py_bybit_resolve_position_idx(
105    position_mode: Option<BybitPositionMode>,
106    order_side: OrderSide,
107    is_reduce_only: bool,
108    manual_override: Option<BybitPositionIdx>,
109) -> Option<BybitPositionIdx> {
110    let bybit_side = BybitOrderSide::from(order_side);
111    resolve_position_idx(position_mode, bybit_side, is_reduce_only, manual_override)
112}
113
114#[expect(clippy::needless_pass_by_value)]
115fn extract_bybit_data_factory(
116    py: Python<'_>,
117    factory: Py<PyAny>,
118) -> PyResult<Box<dyn DataClientFactory>> {
119    match factory.extract::<BybitDataClientFactory>(py) {
120        Ok(f) => Ok(Box::new(f)),
121        Err(e) => Err(to_pyvalue_err(format!(
122            "Failed to extract BybitDataClientFactory: {e}"
123        ))),
124    }
125}
126
127#[expect(clippy::needless_pass_by_value)]
128fn extract_bybit_exec_factory(
129    py: Python<'_>,
130    factory: Py<PyAny>,
131) -> PyResult<Box<dyn ExecutionClientFactory>> {
132    match factory.extract::<BybitExecutionClientFactory>(py) {
133        Ok(f) => Ok(Box::new(f)),
134        Err(e) => Err(to_pyvalue_err(format!(
135            "Failed to extract BybitExecutionClientFactory: {e}"
136        ))),
137    }
138}
139
140#[expect(clippy::needless_pass_by_value)]
141fn extract_bybit_data_config(py: Python<'_>, config: Py<PyAny>) -> PyResult<Box<dyn ClientConfig>> {
142    match config.extract::<BybitDataClientConfig>(py) {
143        Ok(c) => Ok(Box::new(c)),
144        Err(e) => Err(to_pyvalue_err(format!(
145            "Failed to extract BybitDataClientConfig: {e}"
146        ))),
147    }
148}
149
150#[expect(clippy::needless_pass_by_value)]
151fn extract_bybit_exec_config(py: Python<'_>, config: Py<PyAny>) -> PyResult<Box<dyn ClientConfig>> {
152    match config.extract::<BybitExecutionClientConfig>(py) {
153        Ok(c) => Ok(Box::new(c)),
154        Err(e) => Err(to_pyvalue_err(format!(
155            "Failed to extract BybitExecutionClientConfig: {e}"
156        ))),
157    }
158}
159
160/// Exposed through `nautilus_trader.adapters.bybit`.
161///
162/// # Errors
163///
164/// Returns an error if any bindings fail to register with the Python module.
165#[pymodule]
166#[rustfmt::skip]
167pub fn bybit(_: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
168    m.add(stringify!(BYBIT), BYBIT)?;
169    m.add(stringify!(BYBIT_CLIENT_ID), *BYBIT_CLIENT_ID)?;
170    m.add(stringify!(BYBIT_VENUE), *BYBIT_VENUE)?;
171    m.add_class::<crate::common::enums::BybitAccountType>()?;
172    m.add_class::<crate::common::enums::BybitCancelType>()?;
173    m.add_class::<crate::common::enums::BybitEnvironment>()?;
174    m.add_class::<crate::common::enums::BybitMarginAction>()?;
175    m.add_class::<crate::common::enums::BybitMarginMode>()?;
176    m.add_class::<crate::common::enums::BybitOpenOnly>()?;
177    m.add_class::<crate::common::enums::BybitOrderFilter>()?;
178    m.add_class::<crate::common::enums::BybitOrderSide>()?;
179    m.add_class::<crate::common::enums::BybitOrderStatus>()?;
180    m.add_class::<crate::common::enums::BybitOrderType>()?;
181    m.add_class::<crate::common::enums::BybitPositionIdx>()?;
182    m.add_class::<crate::common::enums::BybitPositionMode>()?;
183    m.add_class::<crate::common::enums::BybitProductType>()?;
184    m.add_class::<crate::common::enums::BybitStopOrderType>()?;
185    m.add_class::<crate::common::enums::BybitTimeInForce>()?;
186    m.add_class::<crate::common::enums::BybitTpSlMode>()?;
187    m.add_class::<crate::common::enums::BybitTriggerDirection>()?;
188    m.add_class::<crate::common::enums::BybitTriggerType>()?;
189    m.add_class::<crate::http::client::BybitHttpClient>()?;
190    m.add_class::<crate::http::client::BybitRawHttpClient>()?;
191    m.add_class::<crate::http::models::BybitServerTime>()?;
192    m.add_class::<crate::http::models::BybitAccountDetails>()?;
193    m.add_class::<crate::http::models::BybitApiKeyPermissions>()?;
194    m.add_class::<crate::http::models::BybitFeeRate>()?;
195    m.add_class::<crate::http::models::BybitOrder>()?;
196    m.add_class::<crate::http::models::BybitOrderCursorList>()?;
197    m.add_class::<crate::http::models::BybitTickerData>()?;
198    m.add_class::<crate::data_types::BybitMarginBorrowResult>()?;
199    m.add_class::<crate::data_types::BybitMarginRepayResult>()?;
200    m.add_class::<crate::data_types::BybitMarginStatusResult>()?;
201    m.add_class::<params::BybitTickersParams>()?;
202    m.add_class::<params::BybitNativeTpSlParams>()?;
203    m.add_class::<BybitLiquidation>()?;
204    m.add_class::<BybitDataClientConfig>()?;
205    m.add_class::<BybitDataClientFactory>()?;
206    m.add_class::<BybitExecutionClientConfig>()?;
207    m.add_class::<BybitExecutionClientFactory>()?;
208    m.add_function(wrap_pyfunction!(py_bybit_extract_raw_symbol, m)?)?;
209    m.add_function(wrap_pyfunction!(py_bybit_bar_spec_to_interval, m)?)?;
210    m.add_function(wrap_pyfunction!(py_bybit_product_type_from_symbol, m)?)?;
211    m.add_function(wrap_pyfunction!(py_bybit_resolve_position_idx, m)?)?;
212
213    let registry = get_global_pyo3_registry();
214
215    if let Err(e) =
216        registry.register_factory_extractor(BYBIT.to_string(), extract_bybit_data_factory)
217    {
218        return Err(to_pyruntime_err(format!(
219            "Failed to register Bybit data factory extractor: {e}"
220        )));
221    }
222
223    if let Err(e) = registry
224        .register_exec_factory_extractor(BYBIT.to_string(), extract_bybit_exec_factory)
225    {
226        return Err(to_pyruntime_err(format!(
227            "Failed to register Bybit exec factory extractor: {e}"
228        )));
229    }
230
231    if let Err(e) = registry.register_config_extractor(
232        "BybitDataClientConfig".to_string(),
233        extract_bybit_data_config,
234    ) {
235        return Err(to_pyruntime_err(format!(
236            "Failed to register Bybit data config extractor: {e}"
237        )));
238    }
239
240    if let Err(e) = registry.register_config_extractor(
241        "BybitExecutionClientConfig".to_string(),
242        extract_bybit_exec_config,
243    ) {
244        return Err(to_pyruntime_err(format!(
245            "Failed to register Bybit exec config extractor: {e}"
246        )));
247    }
248
249    register_bybit_custom_data();
250    let _ = ensure_rust_extractor_registered::<BybitLiquidation>();
251    let _ = ensure_rust_extractor_registered::<BybitMarginBorrowResult>();
252    let _ = ensure_rust_extractor_registered::<BybitMarginRepayResult>();
253    let _ = ensure_rust_extractor_registered::<BybitMarginStatusResult>();
254
255    Ok(())
256}