Skip to main content

nautilus_bybit/
data_types.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//! Bybit-specific custom data types.
17//!
18//! These types carry Bybit domain data to subscribing actors as
19//! [`CustomData`](nautilus_model::data::CustomData): liquidations flow through the data
20//! engine, and margin results through the execution event channel.
21
22use nautilus_core::UnixNanos;
23use nautilus_model::{
24    custom_data,
25    enums::PositionSide,
26    identifiers::InstrumentId,
27    types::{Price, Quantity},
28};
29#[cfg(feature = "arrow")]
30use nautilus_serialization::arrow_custom_data;
31
32/// Bybit public liquidation from the `allLiquidation` WebSocket stream.
33///
34/// Bybit publishes this stream for linear and inverse contracts only.
35#[cfg_attr(
36    feature = "arrow",
37    arrow_custom_data(pyo3, stub_module = "nautilus_trader.adapters.bybit")
38)]
39#[custom_data(pyo3, stub_module = "nautilus_trader.adapters.bybit")]
40pub struct BybitLiquidation {
41    /// The instrument for this liquidation event.
42    pub instrument_id: InstrumentId,
43    /// The side of the liquidated position (Bybit `Buy` means a long position was liquidated).
44    #[custom_data_field(native_enum)]
45    pub position_side: PositionSide,
46    /// The bankruptcy price of the liquidated position.
47    pub bankruptcy_price: Price,
48    /// The executed liquidation size.
49    pub quantity: Quantity,
50    /// UNIX timestamp (nanoseconds) when the data event occurred.
51    pub ts_event: UnixNanos,
52    /// UNIX timestamp (nanoseconds) when the instance was initialized.
53    pub ts_init: UnixNanos,
54}
55
56/// Result from a manual Bybit spot margin borrow operation.
57#[cfg_attr(
58    feature = "arrow",
59    arrow_custom_data(pyo3, stub_module = "nautilus_trader.adapters.bybit")
60)]
61#[custom_data(pyo3, stub_module = "nautilus_trader.adapters.bybit")]
62pub struct BybitMarginBorrowResult {
63    /// The coin the borrow targeted.
64    pub coin: String,
65    /// The requested amount.
66    pub amount: String,
67    /// Whether the borrow operation was successful.
68    pub success: bool,
69    /// Error message if the operation failed.
70    pub message: String,
71    /// UNIX timestamp (nanoseconds) when the event occurred.
72    pub ts_event: UnixNanos,
73    /// UNIX timestamp (nanoseconds) when the instance was initialized.
74    pub ts_init: UnixNanos,
75}
76
77/// Result from a manual Bybit spot margin repay operation.
78#[cfg_attr(
79    feature = "arrow",
80    arrow_custom_data(pyo3, stub_module = "nautilus_trader.adapters.bybit")
81)]
82#[custom_data(pyo3, stub_module = "nautilus_trader.adapters.bybit")]
83pub struct BybitMarginRepayResult {
84    /// The coin the repay targeted.
85    pub coin: String,
86    /// The requested amount (None if repaying all).
87    #[custom_data_field(serde)]
88    pub amount: Option<String>,
89    /// Whether the repay operation was successful.
90    pub success: bool,
91    /// The venue result status on success, or the client-side `FAIL` marker on failure.
92    pub result_status: String,
93    /// Error message if the operation failed.
94    pub message: String,
95    /// UNIX timestamp (nanoseconds) when the event occurred.
96    pub ts_event: UnixNanos,
97    /// UNIX timestamp (nanoseconds) when the instance was initialized.
98    pub ts_init: UnixNanos,
99}
100
101/// Current borrowed amount on Bybit for a coin.
102#[cfg_attr(
103    feature = "arrow",
104    arrow_custom_data(pyo3, stub_module = "nautilus_trader.adapters.bybit")
105)]
106#[custom_data(pyo3, stub_module = "nautilus_trader.adapters.bybit")]
107pub struct BybitMarginStatusResult {
108    /// The coin being queried.
109    pub coin: String,
110    /// The current borrowed amount.
111    pub borrow_amount: String,
112    /// UNIX timestamp (nanoseconds) when the event occurred.
113    pub ts_event: UnixNanos,
114    /// UNIX timestamp (nanoseconds) when the instance was initialized.
115    pub ts_init: UnixNanos,
116}
117
118/// Registers Bybit custom data types.
119///
120/// Safe to call multiple times (idempotent via internal `Once` guards).
121pub fn register_bybit_custom_data() {
122    macro_rules! register {
123        ($ty:ty) => {
124            #[cfg(feature = "arrow")]
125            {
126                nautilus_serialization::ensure_custom_data_registered::<$ty>();
127            }
128
129            #[cfg(not(feature = "arrow"))]
130            {
131                let _ = nautilus_model::data::ensure_custom_data_json_registered::<$ty>();
132            }
133        };
134    }
135
136    register!(BybitLiquidation);
137    register!(BybitMarginBorrowResult);
138    register!(BybitMarginRepayResult);
139    register!(BybitMarginStatusResult);
140}
141
142#[cfg(test)]
143mod tests {
144    use nautilus_model::data::{custom::CustomDataTrait, register_custom_data_json};
145    use rstest::rstest;
146
147    use super::*;
148
149    fn liquidation() -> BybitLiquidation {
150        BybitLiquidation::new(
151            InstrumentId::from("BTCUSDT-LINEAR.BYBIT"),
152            PositionSide::Short,
153            Price::from("97410.5"),
154            Quantity::from("1.250"),
155            UnixNanos::from(1_739_502_302_929_000_000),
156            UnixNanos::from(1_739_502_303_500_000_000),
157        )
158    }
159
160    #[rstest]
161    fn test_register_bybit_custom_data_is_idempotent() {
162        register_bybit_custom_data();
163        register_bybit_custom_data();
164    }
165
166    #[rstest]
167    fn test_register_bybit_custom_data_registers_json_deserializer() {
168        register_bybit_custom_data();
169
170        let err = register_custom_data_json::<BybitLiquidation>().unwrap_err();
171
172        assert_eq!(
173            err.to_string(),
174            "Custom data type \"BybitLiquidation\" is already registered for JSON",
175        );
176    }
177
178    #[rstest]
179    fn test_bybit_liquidation_json_round_trip() {
180        let original = liquidation();
181
182        let value: serde_json::Value = serde_json::from_str(&original.to_json().unwrap()).unwrap();
183        let restored = <BybitLiquidation as CustomDataTrait>::from_json(value).unwrap();
184        let restored = restored
185            .as_any()
186            .downcast_ref::<BybitLiquidation>()
187            .unwrap();
188
189        assert_eq!(restored, &original);
190        assert_eq!(restored.instrument_id, original.instrument_id);
191        assert_eq!(restored.position_side, PositionSide::Short);
192        assert_eq!(restored.bankruptcy_price, Price::from("97410.5"));
193        assert_eq!(restored.quantity, Quantity::from("1.250"));
194        assert_eq!(restored.ts_event, original.ts_event);
195        assert_eq!(restored.ts_init, original.ts_init);
196    }
197
198    #[cfg(feature = "arrow")]
199    #[rstest]
200    fn test_bybit_liquidation_arrow_schema_uses_native_types() {
201        use arrow::datatypes::DataType;
202        use nautilus_serialization::arrow::ArrowSchemaProvider;
203
204        let schema = BybitLiquidation::get_schema(None);
205        let names: Vec<_> = schema.fields().iter().map(|f| f.name().as_str()).collect();
206
207        assert_eq!(
208            names,
209            vec![
210                "instrument_id",
211                "position_side",
212                "bankruptcy_price",
213                "quantity",
214                "ts_event",
215                "ts_init",
216            ],
217        );
218        assert!(matches!(
219            schema.field(0).data_type(),
220            DataType::Utf8 | DataType::Utf8View
221        ));
222        assert_eq!(
223            schema.field(1).data_type(),
224            &nautilus_serialization::arrow::enum_dictionary_data_type(),
225        );
226        assert_eq!(schema.field(2).data_type(), &DataType::Decimal128(38, 16));
227        assert_eq!(schema.field(3).data_type(), &DataType::Decimal128(38, 16));
228        assert_eq!(
229            schema.field(4).data_type(),
230            &nautilus_serialization::arrow::timestamp_data_type(),
231        );
232        assert_eq!(
233            schema.field(5).data_type(),
234            &nautilus_serialization::arrow::timestamp_data_type(),
235        );
236    }
237}