Skip to main content

nautilus_bybit/http/
models.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//! Data transfer objects for deserializing Bybit HTTP API payloads.
17
18use nautilus_core::{
19    serialization::deserialize_empty_string_as_none, string::secret::SecretString,
20};
21use rust_decimal::Decimal;
22use serde::{Deserialize, Serialize};
23use ustr::Ustr;
24
25use crate::common::{
26    enums::{
27        BybitAccountType, BybitApiKeyType, BybitCancelType, BybitContractType, BybitCreateType,
28        BybitExecType, BybitInnovationFlag, BybitInstrumentStatus, BybitMarginMode,
29        BybitMarginTrading, BybitOptionType, BybitOrderSide, BybitOrderStatus, BybitOrderType,
30        BybitPositionIdx, BybitPositionSide, BybitPositionStatus, BybitProductType,
31        BybitRepayStatus, BybitSmpType, BybitStopOrderType, BybitSymbolType, BybitTimeInForce,
32        BybitTpSlMode, BybitTriggerDirection, BybitTriggerType, BybitUnifiedMarginStatus,
33        BybitWithdrawStatus, BybitWithdrawType,
34    },
35    models::{
36        BybitCursorList, BybitCursorListResponse, BybitListResponse, BybitResponse, LeverageFilter,
37        LinearLotSizeFilter, LinearPriceFilter, OptionLotSizeFilter, SpotLotSizeFilter,
38        SpotPriceFilter,
39    },
40    parse::{
41        bool_or_int, deserialize_decimal_or_zero, deserialize_i32_or_string,
42        deserialize_optional_decimal_or_zero, deserialize_optional_symbol_type,
43        deserialize_string_to_u8, masked_secret, on_off_bool,
44    },
45};
46
47/// Cursor-paginated list of orders for Python bindings.
48#[derive(Clone, Debug, Default, Serialize, Deserialize)]
49#[cfg_attr(
50    feature = "python",
51    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
52)]
53#[cfg_attr(
54    feature = "python",
55    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
56)]
57pub struct BybitOrderCursorList {
58    /// Collection of orders returned by the endpoint.
59    pub list: Vec<BybitOrder>,
60    /// Pagination cursor for the next page.
61    pub next_page_cursor: Option<String>,
62    /// Optional product category when the API includes it.
63    #[serde(default)]
64    pub category: Option<BybitProductType>,
65}
66
67impl From<BybitCursorList<BybitOrder>> for BybitOrderCursorList {
68    fn from(cursor_list: BybitCursorList<BybitOrder>) -> Self {
69        Self {
70            list: cursor_list.list,
71            next_page_cursor: cursor_list.next_page_cursor,
72            category: cursor_list.category,
73        }
74    }
75}
76
77#[cfg(feature = "python")]
78#[pyo3::pymethods]
79impl BybitOrderCursorList {
80    #[getter]
81    #[must_use]
82    pub fn list(&self) -> Vec<BybitOrder> {
83        self.list.clone()
84    }
85
86    #[getter]
87    #[must_use]
88    pub fn next_page_cursor(&self) -> Option<&str> {
89        self.next_page_cursor.as_deref()
90    }
91
92    #[getter]
93    #[must_use]
94    pub fn category(&self) -> Option<BybitProductType> {
95        self.category
96    }
97}
98
99/// Response payload returned by `GET /v5/market/time`.
100///
101/// # References
102/// - <https://bybit-exchange.github.io/docs/v5/market/time>
103#[derive(Clone, Debug, Serialize, Deserialize)]
104#[cfg_attr(
105    feature = "python",
106    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
107)]
108#[cfg_attr(
109    feature = "python",
110    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
111)]
112#[serde(rename_all = "camelCase")]
113pub struct BybitServerTime {
114    /// Server timestamp in seconds represented as string.
115    pub time_second: String,
116    /// Server timestamp in nanoseconds represented as string.
117    pub time_nano: String,
118}
119
120#[cfg(feature = "python")]
121#[pyo3::pymethods]
122impl BybitServerTime {
123    #[getter]
124    #[must_use]
125    pub fn time_second(&self) -> &str {
126        &self.time_second
127    }
128
129    #[getter]
130    #[must_use]
131    pub fn time_nano(&self) -> &str {
132        &self.time_nano
133    }
134}
135
136/// Type alias for the server time response envelope.
137///
138/// # References
139/// - <https://bybit-exchange.github.io/docs/v5/market/time>
140pub type BybitServerTimeResponse = BybitResponse<BybitServerTime>;
141
142/// Ticker payload for spot instruments.
143///
144/// # References
145/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
146#[derive(Clone, Debug, Serialize, Deserialize)]
147#[serde(rename_all = "camelCase")]
148pub struct BybitTickerSpot {
149    pub symbol: Ustr,
150    pub bid1_price: String,
151    pub bid1_size: String,
152    pub ask1_price: String,
153    pub ask1_size: String,
154    pub last_price: String,
155    pub prev_price24h: String,
156    pub price24h_pcnt: String,
157    pub high_price24h: String,
158    pub low_price24h: String,
159    pub turnover24h: String,
160    pub volume24h: String,
161    #[serde(default)]
162    pub usd_index_price: String,
163}
164
165/// Ticker payload for linear and inverse perpetual/futures instruments.
166///
167/// # References
168/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
169#[derive(Clone, Debug, Serialize, Deserialize)]
170#[serde(rename_all = "camelCase")]
171pub struct BybitTickerLinear {
172    pub symbol: Ustr,
173    pub last_price: String,
174    pub index_price: String,
175    pub mark_price: String,
176    pub prev_price24h: String,
177    pub price24h_pcnt: String,
178    pub high_price24h: String,
179    pub low_price24h: String,
180    pub prev_price1h: String,
181    pub open_interest: String,
182    pub open_interest_value: String,
183    pub turnover24h: String,
184    pub volume24h: String,
185    pub funding_rate: String,
186    pub next_funding_time: String,
187    pub predicted_delivery_price: String,
188    pub basis_rate: String,
189    pub delivery_fee_rate: String,
190    pub delivery_time: String,
191    pub ask1_size: String,
192    pub bid1_price: String,
193    pub ask1_price: String,
194    pub bid1_size: String,
195    pub basis: String,
196}
197
198/// Ticker payload for option instruments.
199///
200/// # References
201/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
202#[derive(Clone, Debug, Serialize, Deserialize)]
203#[serde(rename_all = "camelCase")]
204pub struct BybitTickerOption {
205    pub symbol: Ustr,
206    pub bid1_price: String,
207    pub bid1_size: String,
208    pub bid1_iv: String,
209    pub ask1_price: String,
210    pub ask1_size: String,
211    pub ask1_iv: String,
212    pub last_price: String,
213    pub high_price24h: String,
214    pub low_price24h: String,
215    pub mark_price: String,
216    pub index_price: String,
217    pub mark_iv: String,
218    pub underlying_price: String,
219    pub open_interest: String,
220    pub turnover24h: String,
221    pub volume24h: String,
222    pub total_volume: String,
223    pub total_turnover: String,
224    pub delta: String,
225    pub gamma: String,
226    pub vega: String,
227    pub theta: String,
228    pub predicted_delivery_price: String,
229    pub change24h: String,
230}
231
232/// Response alias for spot ticker requests.
233///
234/// # References
235/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
236pub type BybitTickersSpotResponse = BybitListResponse<BybitTickerSpot>;
237/// Response alias for linear/inverse ticker requests.
238///
239/// # References
240/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
241pub type BybitTickersLinearResponse = BybitListResponse<BybitTickerLinear>;
242/// Response alias for option ticker requests.
243///
244/// # References
245/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
246pub type BybitTickersOptionResponse = BybitListResponse<BybitTickerOption>;
247
248/// Unified ticker data structure containing common fields across all product types.
249///
250/// This simplified ticker structure is designed to work across SPOT, LINEAR, and OPTION products,
251/// containing only the most commonly used fields.
252#[derive(Clone, Debug, Serialize, Deserialize)]
253#[serde(rename_all = "camelCase")]
254#[cfg_attr(
255    feature = "python",
256    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
257)]
258#[cfg_attr(
259    feature = "python",
260    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
261)]
262pub struct BybitTickerData {
263    pub symbol: Ustr,
264    pub bid1_price: String,
265    pub bid1_size: String,
266    pub ask1_price: String,
267    pub ask1_size: String,
268    pub last_price: String,
269    pub high_price24h: String,
270    pub low_price24h: String,
271    pub turnover24h: String,
272    pub volume24h: String,
273    #[serde(default)]
274    pub open_interest: Option<String>,
275    #[serde(default)]
276    pub funding_rate: Option<String>,
277    #[serde(default)]
278    pub next_funding_time: Option<String>,
279    #[serde(default)]
280    pub mark_price: Option<String>,
281    #[serde(default)]
282    pub index_price: Option<String>,
283}
284
285#[cfg(feature = "python")]
286#[pyo3::pymethods]
287impl BybitTickerData {
288    #[getter]
289    #[must_use]
290    pub fn symbol(&self) -> &str {
291        self.symbol.as_str()
292    }
293
294    #[getter]
295    #[must_use]
296    pub fn bid1_price(&self) -> &str {
297        &self.bid1_price
298    }
299
300    #[getter]
301    #[must_use]
302    pub fn bid1_size(&self) -> &str {
303        &self.bid1_size
304    }
305
306    #[getter]
307    #[must_use]
308    pub fn ask1_price(&self) -> &str {
309        &self.ask1_price
310    }
311
312    #[getter]
313    #[must_use]
314    pub fn ask1_size(&self) -> &str {
315        &self.ask1_size
316    }
317
318    #[getter]
319    #[must_use]
320    pub fn last_price(&self) -> &str {
321        &self.last_price
322    }
323
324    #[getter]
325    #[must_use]
326    pub fn high_price24h(&self) -> &str {
327        &self.high_price24h
328    }
329
330    #[getter]
331    #[must_use]
332    pub fn low_price24h(&self) -> &str {
333        &self.low_price24h
334    }
335
336    #[getter]
337    #[must_use]
338    pub fn turnover24h(&self) -> &str {
339        &self.turnover24h
340    }
341
342    #[getter]
343    #[must_use]
344    pub fn volume24h(&self) -> &str {
345        &self.volume24h
346    }
347
348    #[getter]
349    #[must_use]
350    pub fn open_interest(&self) -> Option<&str> {
351        self.open_interest.as_deref()
352    }
353
354    #[getter]
355    #[must_use]
356    pub fn funding_rate(&self) -> Option<&str> {
357        self.funding_rate.as_deref()
358    }
359
360    #[getter]
361    #[must_use]
362    pub fn next_funding_time(&self) -> Option<&str> {
363        self.next_funding_time.as_deref()
364    }
365
366    #[getter]
367    #[must_use]
368    pub fn mark_price(&self) -> Option<&str> {
369        self.mark_price.as_deref()
370    }
371
372    #[getter]
373    #[must_use]
374    pub fn index_price(&self) -> Option<&str> {
375        self.index_price.as_deref()
376    }
377}
378
379impl From<BybitTickerSpot> for BybitTickerData {
380    fn from(ticker: BybitTickerSpot) -> Self {
381        Self {
382            symbol: ticker.symbol,
383            bid1_price: ticker.bid1_price,
384            bid1_size: ticker.bid1_size,
385            ask1_price: ticker.ask1_price,
386            ask1_size: ticker.ask1_size,
387            last_price: ticker.last_price,
388            high_price24h: ticker.high_price24h,
389            low_price24h: ticker.low_price24h,
390            turnover24h: ticker.turnover24h,
391            volume24h: ticker.volume24h,
392            open_interest: None,
393            funding_rate: None,
394            next_funding_time: None,
395            mark_price: None,
396            index_price: None,
397        }
398    }
399}
400
401impl From<BybitTickerLinear> for BybitTickerData {
402    fn from(ticker: BybitTickerLinear) -> Self {
403        Self {
404            symbol: ticker.symbol,
405            bid1_price: ticker.bid1_price,
406            bid1_size: ticker.bid1_size,
407            ask1_price: ticker.ask1_price,
408            ask1_size: ticker.ask1_size,
409            last_price: ticker.last_price,
410            high_price24h: ticker.high_price24h,
411            low_price24h: ticker.low_price24h,
412            turnover24h: ticker.turnover24h,
413            volume24h: ticker.volume24h,
414            open_interest: Some(ticker.open_interest),
415            funding_rate: Some(ticker.funding_rate),
416            next_funding_time: Some(ticker.next_funding_time),
417            mark_price: Some(ticker.mark_price),
418            index_price: Some(ticker.index_price),
419        }
420    }
421}
422
423impl From<BybitTickerOption> for BybitTickerData {
424    fn from(ticker: BybitTickerOption) -> Self {
425        Self {
426            symbol: ticker.symbol,
427            bid1_price: ticker.bid1_price,
428            bid1_size: ticker.bid1_size,
429            ask1_price: ticker.ask1_price,
430            ask1_size: ticker.ask1_size,
431            last_price: ticker.last_price,
432            high_price24h: ticker.high_price24h,
433            low_price24h: ticker.low_price24h,
434            turnover24h: ticker.turnover24h,
435            volume24h: ticker.volume24h,
436            open_interest: Some(ticker.open_interest),
437            funding_rate: None,
438            next_funding_time: None,
439            mark_price: Some(ticker.mark_price),
440            index_price: Some(ticker.index_price),
441        }
442    }
443}
444
445/// Kline/candlestick entry returned by `GET /v5/market/kline`.
446///
447/// Bybit returns klines as arrays with 7 elements:
448/// [startTime, openPrice, highPrice, lowPrice, closePrice, volume, turnover]
449///
450/// # References
451/// - <https://bybit-exchange.github.io/docs/v5/market/kline>
452#[derive(Clone, Debug, Serialize)]
453pub struct BybitKline {
454    pub start: String,
455    pub open: String,
456    pub high: String,
457    pub low: String,
458    pub close: String,
459    pub volume: String,
460    pub turnover: String,
461}
462
463impl<'de> Deserialize<'de> for BybitKline {
464    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
465    where
466        D: serde::Deserializer<'de>,
467    {
468        let [start, open, high, low, close, volume, turnover]: [String; 7] =
469            Deserialize::deserialize(deserializer)?;
470        Ok(Self {
471            start,
472            open,
473            high,
474            low,
475            close,
476            volume,
477            turnover,
478        })
479    }
480}
481
482/// Kline list result returned by Bybit.
483///
484/// # References
485/// - <https://bybit-exchange.github.io/docs/v5/market/kline>
486#[derive(Clone, Debug, Serialize, Deserialize)]
487#[serde(rename_all = "camelCase")]
488pub struct BybitKlineResult {
489    pub category: BybitProductType,
490    pub symbol: Ustr,
491    pub list: Vec<BybitKline>,
492}
493
494/// Response alias for kline history requests.
495///
496/// # References
497/// - <https://bybit-exchange.github.io/docs/v5/market/kline>
498pub type BybitKlinesResponse = BybitResponse<BybitKlineResult>;
499
500/// Trade entry returned by `GET /v5/market/recent-trade`.
501///
502/// # References
503/// - <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
504#[derive(Clone, Debug, Serialize, Deserialize)]
505#[serde(rename_all = "camelCase")]
506pub struct BybitTrade {
507    pub exec_id: String,
508    pub symbol: Ustr,
509    pub price: String,
510    pub size: String,
511    pub side: BybitOrderSide,
512    pub time: String,
513    pub is_block_trade: bool,
514    #[serde(default)]
515    pub m_p: Option<String>,
516    #[serde(default)]
517    pub i_p: Option<String>,
518    #[serde(default)]
519    pub mlv: Option<String>,
520    #[serde(default)]
521    pub iv: Option<String>,
522}
523
524/// Trade list result returned by Bybit.
525///
526/// # References
527/// - <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
528#[derive(Clone, Debug, Serialize, Deserialize)]
529#[serde(rename_all = "camelCase")]
530pub struct BybitTradeResult {
531    pub category: BybitProductType,
532    pub list: Vec<BybitTrade>,
533}
534
535/// Response alias for recent trades requests.
536///
537/// # References
538/// - <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
539pub type BybitTradesResponse = BybitResponse<BybitTradeResult>;
540
541/// Funding entry returned by `GET /v5/market/funding/history`.
542///
543/// # References
544/// - <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
545#[derive(Clone, Debug, Serialize, Deserialize)]
546#[serde(rename_all = "camelCase")]
547pub struct BybitFunding {
548    pub symbol: Ustr,
549    pub funding_rate: String,
550    pub funding_rate_timestamp: String,
551}
552
553/// Funding list result returned by Bybit.
554///
555/// # References
556/// - <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
557#[derive(Clone, Debug, Serialize, Deserialize)]
558#[serde(rename_all = "camelCase")]
559pub struct BybitFundingResult {
560    pub category: BybitProductType,
561    pub list: Vec<BybitFunding>,
562}
563
564/// Response alias for historical funding requests.
565///
566/// # References
567/// - <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
568pub type BybitFundingResponse = BybitResponse<BybitFundingResult>;
569
570/// Orderbook result returned by Bybit.
571///
572/// # References
573/// - <https://bybit-exchange.github.io/docs/v5/market/orderbook>
574#[derive(Clone, Debug, Serialize, Deserialize)]
575#[serde(rename_all = "camelCase")]
576pub struct BybitOrderbookResult {
577    /// Symbol.
578    pub s: Ustr,
579    /// Bid levels represented as `[price, size]` string pairs.
580    pub b: Vec<[String; 2]>,
581    /// Ask levels represented as `[price, size]` string pairs.
582    pub a: Vec<[String; 2]>,
583    pub ts: i64,
584    /// Update identifier.
585    pub u: i64,
586    /// Cross sequence number.
587    pub seq: i64,
588    pub cts: i64,
589}
590
591/// Response alias for orderbook requests.
592///
593/// # References
594/// - <https://bybit-exchange.github.io/docs/v5/market/orderbook>
595pub type BybitOrderbookResponse = BybitResponse<BybitOrderbookResult>;
596
597/// Instrument definition for spot symbols.
598///
599/// # References
600/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
601#[derive(Clone, Debug, Serialize, Deserialize)]
602#[serde(rename_all = "camelCase")]
603pub struct BybitInstrumentSpot {
604    pub symbol: Ustr,
605    pub base_coin: Ustr,
606    pub quote_coin: Ustr,
607    pub innovation: BybitInnovationFlag,
608    pub status: BybitInstrumentStatus,
609    pub margin_trading: BybitMarginTrading,
610    pub lot_size_filter: SpotLotSizeFilter,
611    pub price_filter: SpotPriceFilter,
612    #[serde(default)]
613    pub symbol_id: Option<i64>,
614    #[serde(default, deserialize_with = "deserialize_optional_symbol_type")]
615    pub symbol_type: Option<BybitSymbolType>,
616    #[serde(default)]
617    pub xstock_multiplier: Option<String>,
618}
619
620/// Instrument definition for linear contracts.
621///
622/// # References
623/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
624#[derive(Clone, Debug, Serialize, Deserialize)]
625#[serde(rename_all = "camelCase")]
626pub struct BybitInstrumentLinear {
627    pub symbol: Ustr,
628    pub contract_type: BybitContractType,
629    pub status: BybitInstrumentStatus,
630    pub base_coin: Ustr,
631    pub quote_coin: Ustr,
632    pub launch_time: String,
633    pub delivery_time: String,
634    pub delivery_fee_rate: String,
635    pub price_scale: String,
636    pub leverage_filter: LeverageFilter,
637    pub price_filter: LinearPriceFilter,
638    pub lot_size_filter: LinearLotSizeFilter,
639    pub unified_margin_trade: bool,
640    pub funding_interval: i64,
641    pub settle_coin: Ustr,
642    #[serde(default)]
643    pub symbol_id: Option<i64>,
644    #[serde(default, deserialize_with = "deserialize_optional_symbol_type")]
645    pub symbol_type: Option<BybitSymbolType>,
646    /// Ticker of the underlying in its native market (TradFi only).
647    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
648    pub underlying_ticker: Option<String>,
649    /// Full name of the underlying asset.
650    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
651    pub full_name: Option<String>,
652    /// Market region of the underlying, which sets its trading calendar (TradFi only).
653    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
654    pub market_region: Option<String>,
655}
656
657/// Instrument definition for inverse contracts.
658///
659/// # References
660/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
661#[derive(Clone, Debug, Serialize, Deserialize)]
662#[serde(rename_all = "camelCase")]
663pub struct BybitInstrumentInverse {
664    pub symbol: Ustr,
665    pub contract_type: BybitContractType,
666    pub status: BybitInstrumentStatus,
667    pub base_coin: Ustr,
668    pub quote_coin: Ustr,
669    pub launch_time: String,
670    pub delivery_time: String,
671    pub delivery_fee_rate: String,
672    pub price_scale: String,
673    pub leverage_filter: LeverageFilter,
674    pub price_filter: LinearPriceFilter,
675    pub lot_size_filter: LinearLotSizeFilter,
676    pub unified_margin_trade: bool,
677    pub funding_interval: i64,
678    pub settle_coin: Ustr,
679    #[serde(default)]
680    pub symbol_id: Option<i64>,
681    #[serde(default, deserialize_with = "deserialize_optional_symbol_type")]
682    pub symbol_type: Option<BybitSymbolType>,
683}
684
685/// Instrument definition for option contracts.
686///
687/// # References
688/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
689#[derive(Clone, Debug, Serialize, Deserialize)]
690#[serde(rename_all = "camelCase")]
691pub struct BybitInstrumentOption {
692    pub symbol: Ustr,
693    pub status: BybitInstrumentStatus,
694    pub base_coin: Ustr,
695    pub quote_coin: Ustr,
696    pub settle_coin: Ustr,
697    pub options_type: BybitOptionType,
698    pub launch_time: String,
699    pub delivery_time: String,
700    pub delivery_fee_rate: String,
701    pub price_filter: LinearPriceFilter,
702    pub lot_size_filter: OptionLotSizeFilter,
703    #[serde(default)]
704    pub symbol_id: Option<i64>,
705}
706
707/// Response alias for instrument info requests that return spot instruments.
708///
709/// # References
710/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
711pub type BybitInstrumentSpotResponse = BybitCursorListResponse<BybitInstrumentSpot>;
712/// Response alias for instrument info requests that return linear contracts.
713///
714/// # References
715/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
716pub type BybitInstrumentLinearResponse = BybitCursorListResponse<BybitInstrumentLinear>;
717/// Response alias for instrument info requests that return inverse contracts.
718///
719/// # References
720/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
721pub type BybitInstrumentInverseResponse = BybitCursorListResponse<BybitInstrumentInverse>;
722/// Response alias for instrument info requests that return option contracts.
723///
724/// # References
725/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
726pub type BybitInstrumentOptionResponse = BybitCursorListResponse<BybitInstrumentOption>;
727
728/// Fee rate structure returned by `GET /v5/account/fee-rate`.
729///
730/// # References
731/// - <https://bybit-exchange.github.io/docs/v5/account/fee-rate>
732#[derive(Clone, Debug, Serialize, Deserialize)]
733#[serde(rename_all = "camelCase")]
734#[cfg_attr(
735    feature = "python",
736    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
737)]
738#[cfg_attr(
739    feature = "python",
740    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
741)]
742pub struct BybitFeeRate {
743    pub symbol: Ustr,
744    pub taker_fee_rate: String,
745    pub maker_fee_rate: String,
746    #[serde(default)]
747    pub base_coin: Option<Ustr>,
748}
749
750#[cfg(feature = "python")]
751#[pyo3::pymethods]
752impl BybitFeeRate {
753    #[getter]
754    #[must_use]
755    pub fn symbol(&self) -> &str {
756        self.symbol.as_str()
757    }
758
759    #[getter]
760    #[must_use]
761    pub fn taker_fee_rate(&self) -> &str {
762        &self.taker_fee_rate
763    }
764
765    #[getter]
766    #[must_use]
767    pub fn maker_fee_rate(&self) -> &str {
768        &self.maker_fee_rate
769    }
770
771    #[getter]
772    #[must_use]
773    pub fn base_coin(&self) -> Option<&str> {
774        self.base_coin.as_ref().map(|u| u.as_str())
775    }
776}
777
778/// Response alias for fee rate requests.
779///
780/// # References
781/// - <https://bybit-exchange.github.io/docs/v5/account/fee-rate>
782pub type BybitFeeRateResponse = BybitListResponse<BybitFeeRate>;
783
784/// Account balance snapshot coin entry.
785///
786/// # References
787/// - <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
788#[derive(Clone, Debug, Serialize, Deserialize)]
789#[serde(rename_all = "camelCase")]
790pub struct BybitCoinBalance {
791    pub available_to_borrow: String,
792    pub bonus: String,
793    pub accrued_interest: String,
794    pub available_to_withdraw: String,
795    #[serde(default, rename = "totalOrderIM")]
796    pub total_order_im: Option<String>,
797    pub equity: String,
798    pub usd_value: String,
799    pub borrow_amount: String,
800    #[serde(default, rename = "totalPositionMM")]
801    pub total_position_mm: Option<String>,
802    #[serde(default, rename = "totalPositionIM")]
803    pub total_position_im: Option<String>,
804    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
805    pub wallet_balance: Decimal,
806    pub unrealised_pnl: String,
807    pub cum_realised_pnl: String,
808    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
809    pub locked: Decimal,
810    pub collateral_switch: bool,
811    pub margin_collateral: bool,
812    pub coin: Ustr,
813    #[serde(default)]
814    pub spot_hedging_qty: Option<String>,
815    #[serde(default, deserialize_with = "deserialize_optional_decimal_or_zero")]
816    pub spot_borrow: Decimal,
817}
818
819/// Wallet balance snapshot containing per-coin balances.
820///
821/// # References
822/// - <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
823#[derive(Clone, Debug, Serialize, Deserialize)]
824#[serde(rename_all = "camelCase")]
825pub struct BybitWalletBalance {
826    pub total_equity: String,
827    #[serde(rename = "accountIMRate")]
828    pub account_im_rate: String,
829    pub total_margin_balance: String,
830    pub total_initial_margin: String,
831    pub account_type: BybitAccountType,
832    pub total_available_balance: String,
833    #[serde(rename = "accountMMRate")]
834    pub account_mm_rate: String,
835    #[serde(rename = "totalPerpUPL")]
836    pub total_perp_upl: String,
837    pub total_wallet_balance: String,
838    #[serde(rename = "accountLTV")]
839    pub account_ltv: String,
840    pub total_maintenance_margin: String,
841    pub coin: Vec<BybitCoinBalance>,
842}
843
844/// Response alias for wallet balance requests.
845///
846/// # References
847/// - <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
848pub type BybitWalletBalanceResponse = BybitListResponse<BybitWalletBalance>;
849
850/// Account-level configuration returned by `GET /v5/account/info`.
851///
852/// # References
853/// - <https://bybit-exchange.github.io/docs/v5/account/account-info>
854#[derive(Clone, Debug, Serialize, Deserialize)]
855#[serde(rename_all = "camelCase")]
856pub struct BybitAccountInfo {
857    pub unified_margin_status: BybitUnifiedMarginStatus,
858    pub margin_mode: BybitMarginMode,
859    pub is_master_trader: bool,
860    #[serde(with = "on_off_bool")]
861    pub spot_hedging_status: bool,
862    pub updated_time: String,
863    // `dcp_status`, `time_window`, and `smp_group` are absent from responses
864    // for accounts that predate the disconnection-protection feature.
865    #[serde(default, with = "on_off_bool")]
866    pub dcp_status: bool,
867    #[serde(default, deserialize_with = "deserialize_i32_or_string")]
868    pub time_window: i32,
869    #[serde(default, deserialize_with = "deserialize_i32_or_string")]
870    pub smp_group: i32,
871}
872
873/// Response alias for account info requests.
874///
875/// # References
876/// - <https://bybit-exchange.github.io/docs/v5/account/account-info>
877pub type BybitAccountInfoResponse = BybitResponse<BybitAccountInfo>;
878
879/// Order representation as returned by order-related endpoints.
880///
881/// # References
882/// - <https://bybit-exchange.github.io/docs/v5/order/order-list>
883#[derive(Clone, Debug, Serialize, Deserialize)]
884#[cfg_attr(
885    feature = "python",
886    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
887)]
888#[cfg_attr(
889    feature = "python",
890    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
891)]
892#[serde(rename_all = "camelCase")]
893pub struct BybitOrder {
894    pub order_id: Ustr,
895    pub order_link_id: Ustr,
896    pub block_trade_id: Option<Ustr>,
897    pub symbol: Ustr,
898    pub price: String,
899    pub qty: String,
900    pub side: BybitOrderSide,
901    pub is_leverage: String,
902    #[serde(deserialize_with = "deserialize_i32_or_string")]
903    pub position_idx: i32,
904    pub order_status: BybitOrderStatus,
905    pub cancel_type: BybitCancelType,
906    pub reject_reason: Ustr,
907    pub avg_price: Option<String>,
908    pub leaves_qty: String,
909    pub leaves_value: String,
910    pub cum_exec_qty: String,
911    pub cum_exec_value: String,
912    pub cum_exec_fee: String,
913    pub time_in_force: BybitTimeInForce,
914    pub order_type: BybitOrderType,
915    pub stop_order_type: BybitStopOrderType,
916    pub order_iv: Option<String>,
917    pub trigger_price: String,
918    pub take_profit: String,
919    pub stop_loss: String,
920    pub tp_trigger_by: BybitTriggerType,
921    pub sl_trigger_by: BybitTriggerType,
922    pub trigger_direction: BybitTriggerDirection,
923    pub trigger_by: BybitTriggerType,
924    pub last_price_on_created: String,
925    pub reduce_only: bool,
926    pub close_on_trigger: bool,
927    pub smp_type: BybitSmpType,
928    #[serde(deserialize_with = "deserialize_i32_or_string")]
929    pub smp_group: i32,
930    pub smp_order_id: Ustr,
931    pub tpsl_mode: Option<BybitTpSlMode>,
932    #[serde(default)]
933    pub tp_limit_price: String,
934    #[serde(default)]
935    pub sl_limit_price: String,
936    pub place_type: Ustr,
937    pub created_time: String,
938    pub updated_time: String,
939}
940
941#[cfg(feature = "python")]
942#[pyo3::pymethods]
943impl BybitOrder {
944    #[getter]
945    #[must_use]
946    pub fn order_id(&self) -> &str {
947        self.order_id.as_str()
948    }
949
950    #[getter]
951    #[must_use]
952    pub fn order_link_id(&self) -> &str {
953        self.order_link_id.as_str()
954    }
955
956    #[getter]
957    #[must_use]
958    pub fn block_trade_id(&self) -> Option<&str> {
959        self.block_trade_id.as_ref().map(|s| s.as_str())
960    }
961
962    #[getter]
963    #[must_use]
964    pub fn symbol(&self) -> &str {
965        self.symbol.as_str()
966    }
967
968    #[getter]
969    #[must_use]
970    pub fn price(&self) -> &str {
971        &self.price
972    }
973
974    #[getter]
975    #[must_use]
976    pub fn qty(&self) -> &str {
977        &self.qty
978    }
979
980    #[getter]
981    #[must_use]
982    pub fn side(&self) -> BybitOrderSide {
983        self.side
984    }
985
986    #[getter]
987    #[must_use]
988    pub fn is_leverage(&self) -> &str {
989        &self.is_leverage
990    }
991
992    #[getter]
993    #[must_use]
994    pub fn position_idx(&self) -> i32 {
995        self.position_idx
996    }
997
998    #[getter]
999    #[must_use]
1000    pub fn order_status(&self) -> BybitOrderStatus {
1001        self.order_status
1002    }
1003
1004    #[getter]
1005    #[must_use]
1006    pub fn cancel_type(&self) -> BybitCancelType {
1007        self.cancel_type
1008    }
1009
1010    #[getter]
1011    #[must_use]
1012    pub fn reject_reason(&self) -> &str {
1013        self.reject_reason.as_str()
1014    }
1015
1016    #[getter]
1017    #[must_use]
1018    pub fn avg_price(&self) -> Option<&str> {
1019        self.avg_price.as_deref()
1020    }
1021
1022    #[getter]
1023    #[must_use]
1024    pub fn leaves_qty(&self) -> &str {
1025        &self.leaves_qty
1026    }
1027
1028    #[getter]
1029    #[must_use]
1030    pub fn leaves_value(&self) -> &str {
1031        &self.leaves_value
1032    }
1033
1034    #[getter]
1035    #[must_use]
1036    pub fn cum_exec_qty(&self) -> &str {
1037        &self.cum_exec_qty
1038    }
1039
1040    #[getter]
1041    #[must_use]
1042    pub fn cum_exec_value(&self) -> &str {
1043        &self.cum_exec_value
1044    }
1045
1046    #[getter]
1047    #[must_use]
1048    pub fn cum_exec_fee(&self) -> &str {
1049        &self.cum_exec_fee
1050    }
1051
1052    #[getter]
1053    #[must_use]
1054    pub fn time_in_force(&self) -> BybitTimeInForce {
1055        self.time_in_force
1056    }
1057
1058    #[getter]
1059    #[must_use]
1060    pub fn order_type(&self) -> BybitOrderType {
1061        self.order_type
1062    }
1063
1064    #[getter]
1065    #[must_use]
1066    pub fn stop_order_type(&self) -> BybitStopOrderType {
1067        self.stop_order_type
1068    }
1069
1070    #[getter]
1071    #[must_use]
1072    pub fn order_iv(&self) -> Option<&str> {
1073        self.order_iv.as_deref()
1074    }
1075
1076    #[getter]
1077    #[must_use]
1078    pub fn trigger_price(&self) -> &str {
1079        &self.trigger_price
1080    }
1081
1082    #[getter]
1083    #[must_use]
1084    pub fn take_profit(&self) -> &str {
1085        &self.take_profit
1086    }
1087
1088    #[getter]
1089    #[must_use]
1090    pub fn stop_loss(&self) -> &str {
1091        &self.stop_loss
1092    }
1093
1094    #[getter]
1095    #[must_use]
1096    pub fn tp_trigger_by(&self) -> BybitTriggerType {
1097        self.tp_trigger_by
1098    }
1099
1100    #[getter]
1101    #[must_use]
1102    pub fn sl_trigger_by(&self) -> BybitTriggerType {
1103        self.sl_trigger_by
1104    }
1105
1106    #[getter]
1107    #[must_use]
1108    pub fn trigger_direction(&self) -> BybitTriggerDirection {
1109        self.trigger_direction
1110    }
1111
1112    #[getter]
1113    #[must_use]
1114    pub fn trigger_by(&self) -> BybitTriggerType {
1115        self.trigger_by
1116    }
1117
1118    #[getter]
1119    #[must_use]
1120    pub fn last_price_on_created(&self) -> &str {
1121        &self.last_price_on_created
1122    }
1123
1124    #[getter]
1125    #[must_use]
1126    pub fn reduce_only(&self) -> bool {
1127        self.reduce_only
1128    }
1129
1130    #[getter]
1131    #[must_use]
1132    pub fn close_on_trigger(&self) -> bool {
1133        self.close_on_trigger
1134    }
1135
1136    #[getter]
1137    #[must_use]
1138    #[expect(
1139        clippy::missing_panics_doc,
1140        reason = "serialization of a simple enum cannot fail"
1141    )]
1142    pub fn smp_type(&self) -> String {
1143        serde_json::to_string(&self.smp_type)
1144            .expect("Failed to serialize BybitSmpType")
1145            .trim_matches('"')
1146            .to_string()
1147    }
1148
1149    #[getter]
1150    #[must_use]
1151    pub fn smp_group(&self) -> i32 {
1152        self.smp_group
1153    }
1154
1155    #[getter]
1156    #[must_use]
1157    pub fn smp_order_id(&self) -> &str {
1158        self.smp_order_id.as_str()
1159    }
1160
1161    #[getter]
1162    #[must_use]
1163    pub fn tpsl_mode(&self) -> Option<BybitTpSlMode> {
1164        self.tpsl_mode
1165    }
1166
1167    #[getter]
1168    #[must_use]
1169    pub fn tp_limit_price(&self) -> &str {
1170        &self.tp_limit_price
1171    }
1172
1173    #[getter]
1174    #[must_use]
1175    pub fn sl_limit_price(&self) -> &str {
1176        &self.sl_limit_price
1177    }
1178
1179    #[getter]
1180    #[must_use]
1181    pub fn place_type(&self) -> &str {
1182        self.place_type.as_str()
1183    }
1184
1185    #[getter]
1186    #[must_use]
1187    pub fn created_time(&self) -> &str {
1188        &self.created_time
1189    }
1190
1191    #[getter]
1192    #[must_use]
1193    pub fn updated_time(&self) -> &str {
1194        &self.updated_time
1195    }
1196}
1197
1198/// Response alias for open order queries.
1199///
1200/// # References
1201/// - <https://bybit-exchange.github.io/docs/v5/order/order-list>
1202pub type BybitOpenOrdersResponse = BybitCursorListResponse<BybitOrder>;
1203/// Response alias for order history queries with pagination.
1204///
1205/// # References
1206/// - <https://bybit-exchange.github.io/docs/v5/order/order-list>
1207pub type BybitOrderHistoryResponse = BybitCursorListResponse<BybitOrder>;
1208
1209/// Payload returned after placing a single order.
1210///
1211/// # References
1212/// - <https://bybit-exchange.github.io/docs/v5/order/create-order>
1213#[derive(Clone, Debug, Serialize, Deserialize)]
1214#[serde(rename_all = "camelCase")]
1215pub struct BybitPlaceOrderResult {
1216    pub order_id: Option<Ustr>,
1217    pub order_link_id: Option<Ustr>,
1218}
1219
1220/// Response alias for order placement endpoints.
1221///
1222/// # References
1223/// - <https://bybit-exchange.github.io/docs/v5/order/create-order>
1224pub type BybitPlaceOrderResponse = BybitResponse<BybitPlaceOrderResult>;
1225
1226/// Payload returned after cancelling a single order.
1227///
1228/// # References
1229/// - <https://bybit-exchange.github.io/docs/v5/order/cancel-order>
1230#[derive(Clone, Debug, Serialize, Deserialize)]
1231#[serde(rename_all = "camelCase")]
1232pub struct BybitCancelOrderResult {
1233    pub order_id: Option<Ustr>,
1234    pub order_link_id: Option<Ustr>,
1235}
1236
1237/// Response alias for order cancellation endpoints.
1238///
1239/// # References
1240/// - <https://bybit-exchange.github.io/docs/v5/order/cancel-order>
1241pub type BybitCancelOrderResponse = BybitResponse<BybitCancelOrderResult>;
1242
1243/// Execution/Fill payload returned by `GET /v5/execution/list`.
1244///
1245/// # References
1246/// - <https://bybit-exchange.github.io/docs/v5/order/execution>
1247#[derive(Clone, Debug, Serialize, Deserialize)]
1248#[serde(rename_all = "camelCase")]
1249pub struct BybitExecution {
1250    pub symbol: Ustr,
1251    pub order_id: Ustr,
1252    pub order_link_id: Ustr,
1253    pub side: BybitOrderSide,
1254    pub order_price: String,
1255    pub order_qty: String,
1256    pub leaves_qty: String,
1257    pub create_type: Option<BybitCreateType>,
1258    pub order_type: BybitOrderType,
1259    pub stop_order_type: Option<BybitStopOrderType>,
1260    pub exec_fee: String,
1261    pub exec_id: String,
1262    pub exec_price: String,
1263    pub exec_qty: String,
1264    pub exec_type: BybitExecType,
1265    pub exec_value: String,
1266    pub exec_time: String,
1267    pub fee_currency: Ustr,
1268    pub is_maker: bool,
1269    pub fee_rate: String,
1270    pub trade_iv: String,
1271    pub mark_iv: String,
1272    pub mark_price: String,
1273    pub index_price: String,
1274    pub underlying_price: String,
1275    pub block_trade_id: String,
1276    pub closed_size: String,
1277    pub seq: i64,
1278}
1279
1280/// Response alias for trade history requests.
1281///
1282/// # References
1283/// - <https://bybit-exchange.github.io/docs/v5/order/execution>
1284pub type BybitTradeHistoryResponse = BybitCursorListResponse<BybitExecution>;
1285
1286/// Represents a position returned by the Bybit API.
1287///
1288/// # References
1289/// - <https://bybit-exchange.github.io/docs/v5/position>
1290#[derive(Clone, Debug, Serialize, Deserialize)]
1291#[serde(rename_all = "camelCase")]
1292pub struct BybitPosition {
1293    pub position_idx: BybitPositionIdx,
1294    #[serde(deserialize_with = "deserialize_i32_or_string")]
1295    pub risk_id: i32,
1296    pub risk_limit_value: String,
1297    pub symbol: Ustr,
1298    pub side: BybitPositionSide,
1299    pub size: String,
1300    pub avg_price: String,
1301    pub position_value: String,
1302    #[serde(deserialize_with = "deserialize_i32_or_string")]
1303    pub trade_mode: i32,
1304    pub position_status: BybitPositionStatus,
1305    #[serde(deserialize_with = "deserialize_i32_or_string")]
1306    pub auto_add_margin: i32,
1307    #[serde(deserialize_with = "deserialize_i32_or_string")]
1308    pub adl_rank_indicator: i32,
1309    pub leverage: String,
1310    pub position_balance: String,
1311    pub mark_price: String,
1312    pub liq_price: String,
1313    pub bust_price: String,
1314    #[serde(rename = "positionMM")]
1315    pub position_mm: String,
1316    #[serde(rename = "positionIM")]
1317    pub position_im: String,
1318    pub tpsl_mode: BybitTpSlMode,
1319    pub take_profit: String,
1320    pub stop_loss: String,
1321    pub trailing_stop: String,
1322    pub unrealised_pnl: String,
1323    pub cur_realised_pnl: String,
1324    pub cum_realised_pnl: String,
1325    #[serde(default = "default_position_seq")]
1326    pub seq: i64,
1327    #[serde(default)]
1328    pub is_reduce_only: bool,
1329    #[serde(default)]
1330    pub mmr_sys_updated_time: String,
1331    #[serde(default)]
1332    pub leverage_sys_updated_time: String,
1333    pub created_time: String,
1334    pub updated_time: String,
1335    #[serde(default)]
1336    pub open_time: i64,
1337}
1338
1339const fn default_position_seq() -> i64 {
1340    -1
1341}
1342
1343/// Response alias for position list requests.
1344///
1345/// # References
1346/// - <https://bybit-exchange.github.io/docs/v5/position>
1347pub type BybitPositionListResponse = BybitCursorListResponse<BybitPosition>;
1348
1349/// Reason detail for set margin mode failures.
1350///
1351/// # References
1352/// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
1353#[derive(Clone, Debug, Serialize, Deserialize)]
1354#[serde(rename_all = "camelCase")]
1355pub struct BybitSetMarginModeReason {
1356    pub reason_code: String,
1357    pub reason_msg: String,
1358}
1359
1360/// Result payload for set margin mode operation.
1361///
1362/// # References
1363/// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
1364#[derive(Clone, Debug, Serialize, Deserialize)]
1365#[serde(rename_all = "camelCase")]
1366pub struct BybitSetMarginModeResult {
1367    #[serde(default)]
1368    pub reasons: Vec<BybitSetMarginModeReason>,
1369}
1370
1371/// Response alias for set margin mode requests.
1372///
1373/// # References
1374/// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
1375pub type BybitSetMarginModeResponse = BybitResponse<BybitSetMarginModeResult>;
1376
1377/// Empty result for set leverage operation.
1378#[derive(Clone, Debug, Serialize, Deserialize)]
1379pub struct BybitSetLeverageResult {}
1380
1381/// Response alias for set leverage requests.
1382///
1383/// # References
1384/// - <https://bybit-exchange.github.io/docs/v5/position/leverage>
1385pub type BybitSetLeverageResponse = BybitResponse<BybitSetLeverageResult>;
1386
1387/// Empty result for switch mode operation.
1388#[derive(Clone, Debug, Serialize, Deserialize)]
1389pub struct BybitSwitchModeResult {}
1390
1391/// Response alias for switch mode requests.
1392///
1393/// # References
1394/// - <https://bybit-exchange.github.io/docs/v5/position/position-mode>
1395pub type BybitSwitchModeResponse = BybitResponse<BybitSwitchModeResult>;
1396
1397/// Empty result for set trading stop operation.
1398#[derive(Clone, Debug, Serialize, Deserialize)]
1399pub struct BybitSetTradingStopResult {}
1400
1401/// Response alias for set trading stop requests.
1402///
1403/// # References
1404/// - <https://bybit-exchange.github.io/docs/v5/position/trading-stop>
1405pub type BybitSetTradingStopResponse = BybitResponse<BybitSetTradingStopResult>;
1406
1407/// Result from manual borrow operation.
1408#[derive(Clone, Debug, Serialize, Deserialize)]
1409#[serde(rename_all = "camelCase")]
1410pub struct BybitBorrowResult {
1411    pub coin: Ustr,
1412    pub amount: String,
1413}
1414
1415/// Response alias for manual borrow requests.
1416///
1417/// # References
1418///
1419/// - <https://bybit-exchange.github.io/docs/v5/account/borrow>
1420pub type BybitBorrowResponse = BybitResponse<BybitBorrowResult>;
1421
1422/// Result from no-convert repay operation.
1423#[derive(Clone, Debug, Serialize, Deserialize)]
1424#[serde(rename_all = "camelCase")]
1425pub struct BybitNoConvertRepayResult {
1426    pub result_status: BybitRepayStatus,
1427}
1428
1429/// Response alias for no-convert repay requests.
1430///
1431/// # References
1432///
1433/// - <https://bybit-exchange.github.io/docs/v5/account/no-convert-repay>
1434pub type BybitNoConvertRepayResponse = BybitResponse<BybitNoConvertRepayResult>;
1435
1436/// Result from a manual repay (with conversion) operation.
1437#[derive(Clone, Debug, Serialize, Deserialize)]
1438#[serde(rename_all = "camelCase")]
1439pub struct BybitRepayResult {
1440    pub result_status: BybitRepayStatus,
1441}
1442
1443/// Response alias for manual repay requests.
1444///
1445/// # References
1446///
1447/// - <https://bybit-exchange.github.io/docs/v5/account/repay>
1448pub type BybitRepayResponse = BybitResponse<BybitRepayResult>;
1449
1450/// Result from a withdrawal request.
1451#[derive(Clone, Debug, Serialize, Deserialize)]
1452pub struct BybitWithdrawResult {
1453    pub id: String,
1454}
1455
1456/// Response alias for withdrawal requests.
1457///
1458/// # References
1459///
1460/// - <https://bybit-exchange.github.io/docs/v5/asset/withdraw>
1461pub type BybitWithdrawResponse = BybitResponse<BybitWithdrawResult>;
1462
1463/// A single withdrawal record.
1464///
1465/// # References
1466///
1467/// - <https://bybit-exchange.github.io/docs/v5/asset/withdraw/withdraw-record>
1468#[derive(Clone, Debug, Serialize, Deserialize)]
1469#[serde(rename_all = "camelCase")]
1470pub struct BybitWithdrawalRecord {
1471    pub withdraw_id: String,
1472    #[serde(rename = "txID")]
1473    pub tx_id: String,
1474    pub coin: Ustr,
1475    pub chain: String,
1476    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1477    pub amount: Decimal,
1478    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1479    pub withdraw_fee: Decimal,
1480    pub status: BybitWithdrawStatus,
1481    pub to_address: String,
1482    #[serde(default)]
1483    pub tag: String,
1484    pub withdraw_type: BybitWithdrawType,
1485    pub create_time: String,
1486    pub update_time: String,
1487    #[serde(default)]
1488    pub tax: String,
1489    #[serde(default)]
1490    pub tax_rate: String,
1491    #[serde(default)]
1492    pub tax_type: String,
1493}
1494
1495/// Result payload for `GET /v5/asset/withdraw/query-record`.
1496#[derive(Clone, Debug, Serialize, Deserialize)]
1497#[serde(rename_all = "camelCase")]
1498pub struct BybitWithdrawalRecordsResult {
1499    #[serde(default)]
1500    pub rows: Vec<BybitWithdrawalRecord>,
1501    #[serde(default)]
1502    pub next_page_cursor: Option<String>,
1503}
1504
1505impl BybitWithdrawalRecordsResult {
1506    /// Returns the cursor to use for the next page, or `None` when the final
1507    /// page has been fetched.
1508    ///
1509    /// Treats both an empty and a missing cursor as end-of-pages.
1510    #[must_use]
1511    pub fn continuation_cursor(&self) -> Option<&str> {
1512        match self.next_page_cursor.as_deref() {
1513            None | Some("") => None,
1514            Some(cursor) => Some(cursor),
1515        }
1516    }
1517}
1518
1519/// Response alias for withdrawal records queries.
1520///
1521/// # References
1522///
1523/// - <https://bybit-exchange.github.io/docs/v5/asset/withdraw/withdraw-record>
1524pub type BybitWithdrawalRecordsResponse = BybitResponse<BybitWithdrawalRecordsResult>;
1525
1526/// API key permissions.
1527#[derive(Clone, Debug, Serialize, Deserialize)]
1528#[cfg_attr(
1529    feature = "python",
1530    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
1531)]
1532#[cfg_attr(
1533    feature = "python",
1534    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
1535)]
1536#[serde(rename_all = "PascalCase")]
1537pub struct BybitApiKeyPermissions {
1538    #[serde(default)]
1539    pub contract_trade: Vec<String>,
1540    #[serde(default)]
1541    pub spot: Vec<String>,
1542    #[serde(default)]
1543    pub wallet: Vec<String>,
1544    #[serde(default)]
1545    pub options: Vec<String>,
1546    #[serde(default)]
1547    pub derivatives: Vec<String>,
1548    #[serde(default)]
1549    pub exchange: Vec<String>,
1550    #[serde(default)]
1551    pub copy_trading: Vec<String>,
1552    #[serde(default)]
1553    pub block_trade: Vec<String>,
1554    // Bybit ships this key uppercase (`"NFT"`); the struct-level PascalCase
1555    // rule would otherwise serialize it as `"Nft"` and silently drop values.
1556    #[serde(rename = "NFT", default)]
1557    pub nft: Vec<String>,
1558    #[serde(default)]
1559    pub affiliate: Vec<String>,
1560    // Newer permission buckets. Master-account responses populate them, sub-key
1561    // responses typically omit or return empty arrays - both cases deserialize
1562    // to an empty `Vec` via `serde(default)`.
1563    #[serde(default)]
1564    pub earn: Vec<String>,
1565    // Bybit uses `"FiatP2P"` - PascalCase rename would emit `"FiatP2p"`.
1566    #[serde(rename = "FiatP2P", default)]
1567    pub fiat_p2p: Vec<String>,
1568    #[serde(default)]
1569    pub fiat_bybit_pay: Vec<String>,
1570    #[serde(default)]
1571    pub fiat_bit_pay: Vec<String>,
1572    #[serde(default)]
1573    pub fiat_global_pay: Vec<String>,
1574    #[serde(default)]
1575    pub fiat_convert_broker: Vec<String>,
1576    #[serde(default)]
1577    pub bit_card: Vec<String>,
1578    // Bybit uses `"ByXPost"` - PascalCase rename would emit `"ByxPost"`.
1579    #[serde(rename = "ByXPost", default)]
1580    pub byx_post: Vec<String>,
1581}
1582
1583/// Account details from API key info.
1584#[derive(Debug, Clone, Serialize, Deserialize)]
1585#[cfg_attr(
1586    feature = "python",
1587    pyo3::pyclass(module = "nautilus_trader.adapters.bybit", from_py_object)
1588)]
1589#[cfg_attr(
1590    feature = "python",
1591    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.bybit")
1592)]
1593#[serde(rename_all = "camelCase")]
1594pub struct BybitAccountDetails {
1595    pub id: String,
1596    pub note: String,
1597    pub api_key: SecretString,
1598    pub read_only: u8,
1599    pub secret: SecretString,
1600    #[serde(rename = "type")]
1601    pub key_type: u8,
1602    pub permissions: BybitApiKeyPermissions,
1603    pub ips: Vec<String>,
1604    #[serde(default)]
1605    pub user_id: Option<u64>,
1606    #[serde(default)]
1607    pub inviter_id: Option<u64>,
1608    pub vip_level: String,
1609    #[serde(deserialize_with = "deserialize_string_to_u8", default)]
1610    pub mkt_maker_level: u8,
1611    #[serde(default)]
1612    pub affiliate_id: Option<u64>,
1613    pub rsa_public_key: String,
1614    pub is_master: bool,
1615    pub parent_uid: String,
1616    pub uta: u8,
1617    pub kyc_level: String,
1618    pub kyc_region: String,
1619    #[serde(default)]
1620    pub unified: Option<i32>,
1621    #[serde(default)]
1622    pub deadline_day: i64,
1623    #[serde(default)]
1624    pub expired_at: Option<String>,
1625    pub created_at: String,
1626}
1627
1628#[cfg(feature = "python")]
1629#[pyo3::pymethods]
1630impl BybitAccountDetails {
1631    #[getter]
1632    #[must_use]
1633    pub fn id(&self) -> &str {
1634        &self.id
1635    }
1636
1637    #[getter]
1638    #[must_use]
1639    pub fn note(&self) -> &str {
1640        &self.note
1641    }
1642
1643    #[getter]
1644    #[must_use]
1645    pub fn api_key(&self) -> &str {
1646        self.api_key.expose_secret()
1647    }
1648
1649    #[getter]
1650    #[must_use]
1651    pub fn read_only(&self) -> u8 {
1652        self.read_only
1653    }
1654
1655    #[getter]
1656    #[must_use]
1657    pub fn key_type(&self) -> u8 {
1658        self.key_type
1659    }
1660
1661    #[getter]
1662    #[must_use]
1663    pub fn user_id(&self) -> Option<u64> {
1664        self.user_id
1665    }
1666
1667    #[getter]
1668    #[must_use]
1669    pub fn inviter_id(&self) -> Option<u64> {
1670        self.inviter_id
1671    }
1672
1673    #[getter]
1674    #[must_use]
1675    pub fn vip_level(&self) -> &str {
1676        &self.vip_level
1677    }
1678
1679    #[getter]
1680    #[must_use]
1681    pub fn mkt_maker_level(&self) -> u8 {
1682        self.mkt_maker_level
1683    }
1684
1685    #[getter]
1686    #[must_use]
1687    pub fn affiliate_id(&self) -> Option<u64> {
1688        self.affiliate_id
1689    }
1690
1691    #[getter]
1692    #[must_use]
1693    pub fn rsa_public_key(&self) -> &str {
1694        &self.rsa_public_key
1695    }
1696
1697    #[getter]
1698    #[must_use]
1699    pub fn is_master(&self) -> bool {
1700        self.is_master
1701    }
1702
1703    #[getter]
1704    #[must_use]
1705    pub fn parent_uid(&self) -> &str {
1706        &self.parent_uid
1707    }
1708
1709    #[getter]
1710    #[must_use]
1711    pub fn uta(&self) -> u8 {
1712        self.uta
1713    }
1714
1715    #[getter]
1716    #[must_use]
1717    pub fn kyc_level(&self) -> &str {
1718        &self.kyc_level
1719    }
1720
1721    #[getter]
1722    #[must_use]
1723    pub fn kyc_region(&self) -> &str {
1724        &self.kyc_region
1725    }
1726
1727    #[getter]
1728    #[must_use]
1729    pub fn deadline_day(&self) -> i64 {
1730        self.deadline_day
1731    }
1732
1733    #[getter]
1734    #[must_use]
1735    pub fn expired_at(&self) -> Option<&str> {
1736        self.expired_at.as_deref()
1737    }
1738
1739    #[getter]
1740    #[must_use]
1741    pub fn created_at(&self) -> &str {
1742        &self.created_at
1743    }
1744}
1745
1746/// Response alias for API key info requests.
1747///
1748/// # References
1749///
1750/// - <https://bybit-exchange.github.io/docs/v5/user/apikey-info>
1751pub type BybitAccountDetailsResponse = BybitResponse<BybitAccountDetails>;
1752
1753/// Basic information about a sub-account member.
1754///
1755/// `member_type`, `status`, and `account_mode` use raw integer codes whose valid
1756/// ranges differ per endpoint; values are kept as-is rather than mapped to Rust
1757/// enums, consistent with other venue-raw fields in this module.
1758///
1759/// # References
1760///
1761/// - <https://bybit-exchange.github.io/docs/v5/user/subuid-list>
1762/// - <https://bybit-exchange.github.io/docs/v5/user/page-subuid>
1763/// - <https://bybit-exchange.github.io/docs/v5/user/fund-subuid-list>
1764#[derive(Clone, Debug, Serialize, Deserialize)]
1765#[serde(rename_all = "camelCase")]
1766pub struct BybitSubMember {
1767    pub uid: String,
1768    pub username: String,
1769    pub member_type: i32,
1770    pub status: i32,
1771    pub account_mode: i32,
1772    #[serde(default)]
1773    pub remark: String,
1774}
1775
1776/// Result payload for `GET /v5/user/query-sub-members`.
1777#[derive(Clone, Debug, Serialize, Deserialize)]
1778#[serde(rename_all = "camelCase")]
1779pub struct BybitSubMembersResult {
1780    #[serde(default)]
1781    pub sub_members: Vec<BybitSubMember>,
1782}
1783
1784/// Response alias for the non-paginated sub-UID list.
1785///
1786/// # References
1787///
1788/// - <https://bybit-exchange.github.io/docs/v5/user/subuid-list>
1789pub type BybitSubMembersResponse = BybitResponse<BybitSubMembersResult>;
1790
1791/// Result payload for cursor-paginated sub-account listings.
1792///
1793/// The inner array is named `subMembers` and the cursor field is `nextCursor`
1794/// (with `"0"` as the end-of-pages sentinel), so the standard
1795/// `BybitCursorListResponse<T>` (which expects `list` / `nextPageCursor`)
1796/// cannot be reused here. Callers treat `"0"` or an empty string as the
1797/// termination sentinel.
1798#[derive(Clone, Debug, Serialize, Deserialize)]
1799#[serde(rename_all = "camelCase")]
1800pub struct BybitSubMembersPagedResult {
1801    #[serde(default)]
1802    pub sub_members: Vec<BybitSubMember>,
1803    #[serde(default)]
1804    pub next_cursor: Option<String>,
1805}
1806
1807impl BybitSubMembersPagedResult {
1808    /// Returns the cursor to use for the next page, or `None` when the final
1809    /// page has been fetched.
1810    ///
1811    /// Bybit signals end-of-pages either by omitting the cursor or returning
1812    /// `"0"`/`""`; both cases collapse to `None` here so callers can treat any
1813    /// non-`None` return value as a live cursor.
1814    #[must_use]
1815    pub fn continuation_cursor(&self) -> Option<&str> {
1816        match self.next_cursor.as_deref() {
1817            None | Some("" | "0") => None,
1818            Some(cursor) => Some(cursor),
1819        }
1820    }
1821
1822    /// Returns `true` when the result has more pages to fetch.
1823    #[must_use]
1824    pub fn has_more_pages(&self) -> bool {
1825        self.continuation_cursor().is_some()
1826    }
1827}
1828
1829/// Response alias for paginated sub-UID list (`/v5/user/submembers`).
1830///
1831/// # References
1832///
1833/// - <https://bybit-exchange.github.io/docs/v5/user/page-subuid>
1834pub type BybitSubMembersPagedResponse = BybitResponse<BybitSubMembersPagedResult>;
1835
1836/// Response alias for the escrow (fund-custodial) sub-account list
1837/// (`/v5/user/escrow_sub_members`); shares the paginated sub-member shape.
1838///
1839/// # References
1840///
1841/// - <https://bybit-exchange.github.io/docs/v5/user/fund-subuid-list>
1842pub type BybitEscrowSubMembersResponse = BybitResponse<BybitSubMembersPagedResult>;
1843
1844/// Information about a single sub-account API key.
1845///
1846/// Deliberately not shared with [`BybitAccountDetails`]: master-level fields
1847/// such as `is_master`, `parent_uid`, `uta`, and the KYC block are absent.
1848///
1849/// # References
1850///
1851/// - <https://bybit-exchange.github.io/docs/v5/user/list-sub-apikeys>
1852#[derive(Debug, Clone, Serialize, Deserialize)]
1853#[serde(rename_all = "camelCase")]
1854pub struct BybitSubApiKeyInfo {
1855    pub id: String,
1856    #[serde(default)]
1857    pub ips: Vec<String>,
1858    pub api_key: SecretString,
1859    #[serde(default)]
1860    pub note: String,
1861    pub status: i32,
1862    #[serde(default)]
1863    pub expired_at: Option<String>,
1864    pub created_at: String,
1865    #[serde(rename = "type")]
1866    pub key_type: BybitApiKeyType,
1867    #[serde(with = "masked_secret")]
1868    pub secret: Option<SecretString>,
1869    #[serde(with = "bool_or_int")]
1870    pub read_only: bool,
1871    #[serde(default)]
1872    pub deadline_day: Option<i64>,
1873    #[serde(default)]
1874    pub flag: String,
1875    pub permissions: BybitApiKeyPermissions,
1876}
1877
1878/// Result payload for `GET /v5/user/sub-apikeys`.
1879///
1880/// The inner array field is named `result` (nested inside the outer
1881/// `retCode/retMsg/result` envelope) rather than the usual `list`, so the
1882/// standard `BybitCursorListResponse<T>` cannot be reused here.
1883#[derive(Clone, Debug, Serialize, Deserialize)]
1884#[serde(rename_all = "camelCase")]
1885pub struct BybitSubApiKeysResult {
1886    #[serde(rename = "result", default)]
1887    pub keys: Vec<BybitSubApiKeyInfo>,
1888    #[serde(default)]
1889    pub next_page_cursor: Option<String>,
1890}
1891
1892impl BybitSubApiKeysResult {
1893    /// Returns the cursor to use for the next page, or `None` when the final
1894    /// page has been fetched.
1895    ///
1896    /// The end-of-pages sentinel on this endpoint is an empty string rather
1897    /// than `"0"`; both that and a missing cursor collapse to `None`.
1898    #[must_use]
1899    pub fn continuation_cursor(&self) -> Option<&str> {
1900        match self.next_page_cursor.as_deref() {
1901            None | Some("") => None,
1902            Some(cursor) => Some(cursor),
1903        }
1904    }
1905
1906    /// Returns `true` when the result has more pages to fetch.
1907    #[must_use]
1908    pub fn has_more_pages(&self) -> bool {
1909        self.continuation_cursor().is_some()
1910    }
1911}
1912
1913/// Response alias for sub-account API keys list.
1914///
1915/// # References
1916///
1917/// - <https://bybit-exchange.github.io/docs/v5/user/list-sub-apikeys>
1918pub type BybitSubApiKeysResponse = BybitResponse<BybitSubApiKeysResult>;
1919
1920/// Shared result payload for API-key update endpoints (sub or master).
1921///
1922/// `/v5/user/update-sub-api` and `/v5/user/update-api` return the same field
1923/// set; only the number of permission buckets populated inside `permissions`
1924/// differs. Because [`BybitApiKeyPermissions`] covers the superset of both,
1925/// the two endpoints reuse a single DTO.
1926#[derive(Debug, Clone, Serialize, Deserialize)]
1927#[serde(rename_all = "camelCase")]
1928pub struct BybitApiKeyUpdateResult {
1929    pub id: String,
1930    #[serde(default)]
1931    pub note: String,
1932    pub api_key: SecretString,
1933    #[serde(with = "bool_or_int")]
1934    pub read_only: bool,
1935    #[serde(with = "masked_secret")]
1936    pub secret: Option<SecretString>,
1937    pub permissions: BybitApiKeyPermissions,
1938    #[serde(default)]
1939    pub ips: Vec<String>,
1940}
1941
1942/// Response alias for `POST /v5/user/update-sub-api`.
1943///
1944/// # References
1945///
1946/// - <https://bybit-exchange.github.io/docs/v5/user/modify-sub-apikey>
1947pub type BybitUpdateSubApiResponse = BybitResponse<BybitApiKeyUpdateResult>;
1948
1949/// Response alias for `POST /v5/user/update-api`.
1950///
1951/// # References
1952///
1953/// - <https://bybit-exchange.github.io/docs/v5/user/modify-master-apikey>
1954pub type BybitUpdateMasterApiResponse = BybitResponse<BybitApiKeyUpdateResult>;
1955
1956#[cfg(test)]
1957mod tests {
1958    use nautilus_core::UnixNanos;
1959    use nautilus_model::identifiers::AccountId;
1960    use rstest::rstest;
1961    use rust_decimal::Decimal;
1962    use rust_decimal_macros::dec;
1963
1964    use super::*;
1965    use crate::common::testing::load_test_json;
1966
1967    #[rstest]
1968    fn deserialize_spot_instrument_uses_enums() {
1969        let json = load_test_json("http_get_instruments_spot.json");
1970        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
1971        let instrument = &response.result.list[0];
1972
1973        assert_eq!(instrument.status, BybitInstrumentStatus::Trading);
1974        assert_eq!(instrument.innovation, BybitInnovationFlag::Standard);
1975        assert_eq!(instrument.margin_trading, BybitMarginTrading::UtaOnly);
1976    }
1977
1978    #[rstest]
1979    fn deserialize_linear_instrument_status() {
1980        let json = load_test_json("http_get_instruments_linear.json");
1981        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
1982        let instrument = &response.result.list[0];
1983
1984        assert_eq!(instrument.status, BybitInstrumentStatus::Trading);
1985        assert_eq!(instrument.contract_type, BybitContractType::LinearPerpetual);
1986    }
1987
1988    #[rstest]
1989    fn deserialize_spot_instrument_with_xstock_fields() {
1990        let json = load_test_json("http_get_instruments_spot_xstocks.json");
1991        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
1992        let instrument = &response.result.list[0];
1993
1994        assert_eq!(instrument.symbol_id, Some(42));
1995        assert_eq!(instrument.symbol_type, Some(BybitSymbolType::Xstocks));
1996        assert_eq!(instrument.xstock_multiplier.as_deref(), Some("0.1"));
1997    }
1998
1999    #[rstest]
2000    fn deserialize_linear_instrument_with_symbol_type_and_id() {
2001        let json = load_test_json("http_get_instruments_linear_symbol_type.json");
2002        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
2003        let instrument = &response.result.list[0];
2004
2005        assert_eq!(instrument.symbol_id, Some(7));
2006        assert_eq!(instrument.symbol_type, Some(BybitSymbolType::Stock));
2007        assert_eq!(instrument.underlying_ticker.as_deref(), Some("AMD"));
2008        assert_eq!(
2009            instrument.full_name.as_deref(),
2010            Some("Advanced Micro Devices")
2011        );
2012        assert_eq!(instrument.market_region.as_deref(), Some("US"));
2013    }
2014
2015    #[rstest]
2016    fn deserialize_linear_instrument_maps_empty_strings_to_none() {
2017        let json = load_test_json("http_get_instruments_linear_symbol_type.json")
2018            .replace(r#""symbolType": "stock""#, r#""symbolType": """#)
2019            .replace(r#""underlyingTicker": "AMD""#, r#""underlyingTicker": """#)
2020            .replace(
2021                r#""fullName": "Advanced Micro Devices""#,
2022                r#""fullName": """#,
2023            )
2024            .replace(r#""marketRegion": "US""#, r#""marketRegion": """#);
2025        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
2026        let instrument = &response.result.list[0];
2027
2028        assert_eq!(instrument.symbol_type, None);
2029        assert_eq!(instrument.underlying_ticker, None);
2030        assert_eq!(instrument.full_name, None);
2031        assert_eq!(instrument.market_region, None);
2032    }
2033
2034    #[derive(Deserialize)]
2035    struct SymbolTypeWrap {
2036        #[serde(rename = "symbolType")]
2037        t: BybitSymbolType,
2038    }
2039
2040    #[rstest]
2041    fn deserialize_symbol_type_falls_back_to_other_for_unknown() {
2042        let json = r#"{"symbolType": "newthing"}"#;
2043        let parsed: SymbolTypeWrap = serde_json::from_str(json).unwrap();
2044        assert_eq!(parsed.t, BybitSymbolType::Other);
2045    }
2046
2047    #[rstest]
2048    fn deserialize_account_info_response() {
2049        let json = load_test_json("http_get_account_info.json");
2050        let response: BybitAccountInfoResponse = serde_json::from_str(&json).unwrap();
2051
2052        assert_eq!(response.result.margin_mode, BybitMarginMode::RegularMargin);
2053        assert_eq!(
2054            response.result.unified_margin_status,
2055            BybitUnifiedMarginStatus::UnifiedTradingAccount10Pro
2056        );
2057        assert!(!response.result.is_master_trader);
2058        assert!(!response.result.spot_hedging_status);
2059        assert!(!response.result.dcp_status);
2060        assert_eq!(response.result.time_window, 10);
2061        assert_eq!(response.result.smp_group, 0);
2062    }
2063
2064    #[rstest]
2065    fn deserialize_account_info_without_deprecated_fields() {
2066        let json = r#"{
2067            "retCode": 0,
2068            "retMsg": "OK",
2069            "result": {
2070                "marginMode": "PORTFOLIO_MARGIN",
2071                "updatedTime": "1697078946000",
2072                "unifiedMarginStatus": 5,
2073                "isMasterTrader": true,
2074                "spotHedgingStatus": "ON"
2075            }
2076        }"#;
2077        let response: BybitAccountInfoResponse = serde_json::from_str(json).unwrap();
2078
2079        assert_eq!(
2080            response.result.margin_mode,
2081            BybitMarginMode::PortfolioMargin
2082        );
2083        assert_eq!(
2084            response.result.unified_margin_status,
2085            BybitUnifiedMarginStatus::UnifiedTradingAccount20
2086        );
2087        assert!(response.result.is_master_trader);
2088        assert!(response.result.spot_hedging_status);
2089        assert!(!response.result.dcp_status);
2090        assert_eq!(response.result.time_window, 0);
2091        assert_eq!(response.result.smp_group, 0);
2092    }
2093
2094    #[rstest]
2095    fn deserialize_account_info_accepts_string_time_window_and_smp_group() {
2096        let mut json: serde_json::Value =
2097            serde_json::from_str(&load_test_json("http_get_account_info.json")).unwrap();
2098        json["result"]["timeWindow"] = serde_json::Value::String("10".to_string());
2099        json["result"]["smpGroup"] = serde_json::Value::String("1234".to_string());
2100
2101        let response: BybitAccountInfoResponse = serde_json::from_value(json).unwrap();
2102
2103        assert_eq!(response.result.time_window, 10);
2104        assert_eq!(response.result.smp_group, 1234);
2105    }
2106
2107    #[rstest]
2108    fn deserialize_order_response_maps_enums() {
2109        let json = load_test_json("http_get_orders_history.json");
2110        let response: BybitOrderHistoryResponse = serde_json::from_str(&json).unwrap();
2111        let order = &response.result.list[0];
2112
2113        assert_eq!(order.cancel_type, BybitCancelType::CancelByUser);
2114        assert_eq!(order.tp_trigger_by, BybitTriggerType::MarkPrice);
2115        assert_eq!(order.sl_trigger_by, BybitTriggerType::LastPrice);
2116        assert_eq!(order.tpsl_mode, Some(BybitTpSlMode::Full));
2117        assert_eq!(order.order_type, BybitOrderType::Limit);
2118        assert_eq!(order.smp_type, BybitSmpType::None);
2119        assert_eq!(order.smp_group, 0);
2120    }
2121
2122    #[rstest]
2123    #[case::both_missing(true, true)]
2124    #[case::tp_missing(true, false)]
2125    #[case::sl_missing(false, true)]
2126    fn deserialize_option_order_response_without_tp_sl_limit_prices(
2127        #[case] omit_tp_limit_price: bool,
2128        #[case] omit_sl_limit_price: bool,
2129    ) {
2130        let mut json: serde_json::Value =
2131            serde_json::from_str(&load_test_json("http_get_orders_history.json")).unwrap();
2132        let order = json["result"]["list"][0].as_object_mut().unwrap();
2133        order.insert(
2134            "symbol".to_string(),
2135            serde_json::json!("BTC-25SEP26-86500-C-USDT"),
2136        );
2137        order.insert("orderIv".to_string(), serde_json::json!("0.45"));
2138        order.insert("tpLimitPrice".to_string(), serde_json::json!("31000"));
2139        order.insert("slLimitPrice".to_string(), serde_json::json!("29000"));
2140        if omit_tp_limit_price {
2141            order.remove("tpLimitPrice");
2142        }
2143
2144        if omit_sl_limit_price {
2145            order.remove("slLimitPrice");
2146        }
2147
2148        let mut expected = serde_json::Value::Object(order.clone());
2149        expected["tpLimitPrice"] =
2150            serde_json::json!(if omit_tp_limit_price { "" } else { "31000" });
2151        expected["slLimitPrice"] =
2152            serde_json::json!(if omit_sl_limit_price { "" } else { "29000" });
2153
2154        let response: BybitOrderHistoryResponse = serde_json::from_value(json).unwrap();
2155        let actual = serde_json::to_value(&response.result.list[0]).unwrap();
2156
2157        assert_eq!(response.result.list.len(), 1);
2158        assert_eq!(actual, expected);
2159    }
2160
2161    #[rstest]
2162    fn deserialize_order_response_accepts_string_smp_group() {
2163        let mut json: serde_json::Value =
2164            serde_json::from_str(&load_test_json("http_get_orders_history.json")).unwrap();
2165        json["result"]["list"][0]["smpGroup"] = serde_json::Value::String("123456789".to_string());
2166
2167        let response: BybitOrderHistoryResponse = serde_json::from_value(json).unwrap();
2168
2169        assert_eq!(response.result.list[0].smp_group, 123_456_789);
2170    }
2171
2172    #[rstest]
2173    fn deserialize_order_response_accepts_string_position_idx() {
2174        let mut json: serde_json::Value =
2175            serde_json::from_str(&load_test_json("http_get_orders_history.json")).unwrap();
2176        json["result"]["list"][0]["positionIdx"] = serde_json::Value::String("1".to_string());
2177
2178        let response: BybitOrderHistoryResponse = serde_json::from_value(json).unwrap();
2179
2180        assert_eq!(response.result.list[0].position_idx, 1);
2181    }
2182
2183    #[rstest]
2184    #[case::malformed(
2185        "invalid",
2186        "expected i32, received \"invalid\": invalid digit found in string"
2187    )]
2188    #[case::out_of_range(
2189        "2147483648",
2190        "expected i32, received \"2147483648\": number too large to fit in target type"
2191    )]
2192    fn deserialize_order_response_rejects_invalid_string_smp_group(
2193        #[case] value: &str,
2194        #[case] expected: &str,
2195    ) {
2196        let mut json: serde_json::Value =
2197            serde_json::from_str(&load_test_json("http_get_orders_history.json")).unwrap();
2198        json["result"]["list"][0]["smpGroup"] = serde_json::Value::String(value.to_string());
2199
2200        let result: Result<BybitOrderHistoryResponse, _> = serde_json::from_value(json);
2201
2202        assert_eq!(result.unwrap_err().to_string(), expected);
2203    }
2204
2205    #[rstest]
2206    fn deserialize_wallet_balance_without_optional_fields() {
2207        let json = r#"{
2208            "retCode": 0,
2209            "retMsg": "OK",
2210            "result": {
2211                "list": [{
2212                    "totalEquity": "1000.00",
2213                    "accountIMRate": "0",
2214                    "totalMarginBalance": "1000.00",
2215                    "totalInitialMargin": "0",
2216                    "accountType": "UNIFIED",
2217                    "totalAvailableBalance": "1000.00",
2218                    "accountMMRate": "0",
2219                    "totalPerpUPL": "0",
2220                    "totalWalletBalance": "1000.00",
2221                    "accountLTV": "0",
2222                    "totalMaintenanceMargin": "0",
2223                    "coin": [{
2224                        "availableToBorrow": "0",
2225                        "bonus": "0",
2226                        "accruedInterest": "0",
2227                        "availableToWithdraw": "1000.00",
2228                        "equity": "1000.00",
2229                        "usdValue": "1000.00",
2230                        "borrowAmount": "0",
2231                        "totalPositionIM": "0",
2232                        "walletBalance": "1000.00",
2233                        "unrealisedPnl": "0",
2234                        "cumRealisedPnl": "0",
2235                        "locked": "0",
2236                        "collateralSwitch": true,
2237                        "marginCollateral": true,
2238                        "coin": "USDT"
2239                    }]
2240                }]
2241            }
2242        }"#;
2243
2244        let response: BybitWalletBalanceResponse = serde_json::from_str(json)
2245            .expect("Failed to parse wallet balance without optional fields");
2246
2247        assert_eq!(response.ret_code, 0);
2248        assert_eq!(response.result.list[0].coin[0].total_order_im, None);
2249        assert_eq!(response.result.list[0].coin[0].total_position_mm, None);
2250    }
2251
2252    #[rstest]
2253    fn deserialize_wallet_balance_from_docs() {
2254        let json = include_str!("../../test_data/http_get_wallet_balance.json");
2255
2256        let response: BybitWalletBalanceResponse = serde_json::from_str(json)
2257            .expect("Failed to parse wallet balance from Bybit docs example");
2258
2259        assert_eq!(response.ret_code, 0);
2260        assert_eq!(response.ret_msg, "OK");
2261
2262        let wallet = &response.result.list[0];
2263        assert_eq!(wallet.total_equity, "3.31216591");
2264        assert_eq!(wallet.account_im_rate, "0");
2265        assert_eq!(wallet.account_mm_rate, "0");
2266        assert_eq!(wallet.total_perp_upl, "0");
2267        assert_eq!(wallet.account_ltv, "0");
2268
2269        // Check BTC coin
2270        let btc = &wallet.coin[0];
2271        assert_eq!(btc.coin, "BTC");
2272        assert_eq!(btc.available_to_borrow, "3");
2273        assert_eq!(btc.total_order_im, Some("0".to_string()));
2274        assert_eq!(btc.total_position_mm, Some("0".to_string()));
2275        assert_eq!(btc.total_position_im, Some("0".to_string()));
2276
2277        // Check USDT coin (without optional IM/MM fields)
2278        let usdt = &wallet.coin[1];
2279        assert_eq!(usdt.coin, "USDT");
2280        assert_eq!(usdt.wallet_balance, dec!(1000.50));
2281        assert_eq!(usdt.total_order_im, None);
2282        assert_eq!(usdt.total_position_mm, None);
2283        assert_eq!(usdt.total_position_im, None);
2284        assert_eq!(btc.spot_borrow, Decimal::ZERO);
2285        assert_eq!(usdt.spot_borrow, Decimal::ZERO);
2286    }
2287
2288    #[rstest]
2289    fn test_parse_wallet_balance_with_spot_borrow() {
2290        let json = include_str!("../../test_data/http_get_wallet_balance_with_spot_borrow.json");
2291        let response: BybitWalletBalanceResponse =
2292            serde_json::from_str(json).expect("Failed to parse wallet balance with spotBorrow");
2293
2294        let wallet = &response.result.list[0];
2295        let usdt = &wallet.coin[0];
2296
2297        assert_eq!(usdt.coin, "USDT");
2298        assert_eq!(usdt.wallet_balance, dec!(1200.00));
2299        assert_eq!(usdt.spot_borrow, dec!(200.00));
2300        assert_eq!(usdt.borrow_amount, "200.00");
2301
2302        // Verify calculation: actual_balance = walletBalance - spotBorrow = 1200 - 200 = 1000
2303        let account_id = crate::common::parse::parse_account_state(
2304            wallet,
2305            AccountId::new("BYBIT-001"),
2306            UnixNanos::default(),
2307        )
2308        .expect("Failed to parse account state");
2309
2310        let balance = &account_id.balances[0];
2311        assert_eq!(balance.total.as_f64(), 1000.0);
2312    }
2313
2314    #[rstest]
2315    fn test_parse_wallet_balance_spot_short() {
2316        let json = include_str!("../../test_data/http_get_wallet_balance_spot_short.json");
2317        let response: BybitWalletBalanceResponse = serde_json::from_str(json)
2318            .expect("Failed to parse wallet balance with SHORT SPOT position");
2319
2320        let wallet = &response.result.list[0];
2321        let eth = &wallet.coin[0];
2322
2323        assert_eq!(eth.coin, "ETH");
2324        assert_eq!(eth.wallet_balance, dec!(0));
2325        assert_eq!(eth.spot_borrow, dec!(0.06142));
2326        assert_eq!(eth.borrow_amount, "0.06142");
2327
2328        let account_state = crate::common::parse::parse_account_state(
2329            wallet,
2330            AccountId::new("BYBIT-001"),
2331            UnixNanos::default(),
2332        )
2333        .expect("Failed to parse account state");
2334
2335        let eth_balance = account_state
2336            .balances
2337            .iter()
2338            .find(|b| b.currency.code == "ETH")
2339            .expect("ETH balance not found");
2340
2341        // Negative balance represents SHORT position (borrowed ETH)
2342        assert_eq!(eth_balance.total.as_f64(), -0.06142);
2343    }
2344
2345    #[rstest]
2346    fn deserialize_borrow_response() {
2347        let json = r#"{
2348            "retCode": 0,
2349            "retMsg": "success",
2350            "result": {
2351                "coin": "BTC",
2352                "amount": "0.01"
2353            },
2354            "retExtInfo": {},
2355            "time": 1756197991955
2356        }"#;
2357
2358        let response: BybitBorrowResponse = serde_json::from_str(json).unwrap();
2359
2360        assert_eq!(response.ret_code, 0);
2361        assert_eq!(response.ret_msg, "success");
2362        assert_eq!(response.result.coin, "BTC");
2363        assert_eq!(response.result.amount, "0.01");
2364    }
2365
2366    #[rstest]
2367    fn deserialize_no_convert_repay_response() {
2368        let json = r#"{
2369            "retCode": 0,
2370            "retMsg": "OK",
2371            "result": {
2372                "resultStatus": "SU"
2373            },
2374            "retExtInfo": {},
2375            "time": 1234567890
2376        }"#;
2377
2378        let response: BybitNoConvertRepayResponse = serde_json::from_str(json).unwrap();
2379
2380        assert_eq!(response.ret_code, 0);
2381        assert_eq!(response.ret_msg, "OK");
2382        assert_eq!(response.result.result_status, BybitRepayStatus::Success);
2383    }
2384
2385    #[rstest]
2386    fn deserialize_repay_response() {
2387        let json = r#"{
2388            "retCode": 0,
2389            "retMsg": "success",
2390            "result": {
2391                "resultStatus": "P"
2392            },
2393            "retExtInfo": {},
2394            "time": 1756295680801
2395        }"#;
2396
2397        let response: BybitRepayResponse = serde_json::from_str(json).unwrap();
2398
2399        assert_eq!(response.ret_code, 0);
2400        assert_eq!(response.ret_msg, "success");
2401        assert_eq!(response.result.result_status, BybitRepayStatus::Processing);
2402    }
2403
2404    #[rstest]
2405    fn deserialize_position_without_conditional_fields() {
2406        // Bybit v5 docs mark `isReduceOnly`, `mmrSysUpdatedTime`, `leverageSysUpdatedTime`
2407        // and `seq` as conditional fields that may be absent, e.g. once a position has been
2408        // closed through the UI (see issue #3836).
2409        let json = r#"{
2410            "retCode": 0,
2411            "retMsg": "OK",
2412            "result": {
2413                "list": [{
2414                    "positionIdx": 0,
2415                    "riskId": 1,
2416                    "riskLimitValue": "150",
2417                    "symbol": "LTCUSDT",
2418                    "side": "",
2419                    "size": "0",
2420                    "avgPrice": "0",
2421                    "positionValue": "0",
2422                    "tradeMode": 0,
2423                    "positionStatus": "Normal",
2424                    "autoAddMargin": 0,
2425                    "adlRankIndicator": 0,
2426                    "leverage": "10",
2427                    "positionBalance": "0",
2428                    "markPrice": "70.00",
2429                    "liqPrice": "",
2430                    "bustPrice": "",
2431                    "positionMM": "0",
2432                    "positionIM": "0",
2433                    "tpslMode": "Full",
2434                    "takeProfit": "0",
2435                    "stopLoss": "0",
2436                    "trailingStop": "0",
2437                    "unrealisedPnl": "0",
2438                    "curRealisedPnl": "0",
2439                    "cumRealisedPnl": "0",
2440                    "createdTime": "1676538056258",
2441                    "updatedTime": "1697673600012"
2442                }],
2443                "nextPageCursor": "",
2444                "category": "linear"
2445            },
2446            "retExtInfo": {},
2447            "time": 1697673900000
2448        }"#;
2449
2450        let response: BybitPositionListResponse = serde_json::from_str(json)
2451            .expect("Failed to parse position list with missing conditional fields");
2452
2453        let position = &response.result.list[0];
2454        assert!(!position.is_reduce_only);
2455        assert_eq!(position.seq, -1);
2456        assert_eq!(position.mmr_sys_updated_time, "");
2457        assert_eq!(position.leverage_sys_updated_time, "");
2458        assert_eq!(position.open_time, 0);
2459    }
2460
2461    #[rstest]
2462    #[case(0_i64)]
2463    #[case(1_700_000_000_123_i64)]
2464    fn deserialize_position_with_open_time_integer(#[case] expected: i64) {
2465        // Bybit position info added `openTime` (integer, ms; default 0) effective 2026-04-21.
2466        let mut value: serde_json::Value =
2467            serde_json::from_str(&load_test_json("http_get_positions_with_open_time.json"))
2468                .unwrap();
2469        value["result"]["list"][0]["openTime"] = serde_json::json!(expected);
2470
2471        let response: BybitPositionListResponse = serde_json::from_value(value)
2472            .expect("Failed to parse position list with integer openTime");
2473
2474        assert_eq!(response.result.list[0].open_time, expected);
2475    }
2476
2477    #[rstest]
2478    fn deserialize_position_response_accepts_string_integer_fields() {
2479        let mut json: serde_json::Value =
2480            serde_json::from_str(&load_test_json("http_get_positions.json")).unwrap();
2481        let position = &mut json["result"]["list"][0];
2482        position["riskId"] = serde_json::Value::String("1234".to_string());
2483        position["tradeMode"] = serde_json::Value::String("1".to_string());
2484        position["autoAddMargin"] = serde_json::Value::String("2".to_string());
2485        position["adlRankIndicator"] = serde_json::Value::String("35".to_string());
2486
2487        let response: BybitPositionListResponse = serde_json::from_value(json).unwrap();
2488
2489        let position = &response.result.list[0];
2490        assert_eq!(position.risk_id, 1234);
2491        assert_eq!(position.trade_mode, 1);
2492        assert_eq!(position.auto_add_margin, 2);
2493        assert_eq!(position.adl_rank_indicator, 35);
2494    }
2495
2496    #[rstest]
2497    fn deserialize_inverse_instrument_with_symbol_type_and_id() {
2498        let json = load_test_json("http_get_instruments_inverse_symbol_type.json");
2499        let response: BybitInstrumentInverseResponse = serde_json::from_str(&json).unwrap();
2500        let instrument = &response.result.list[0];
2501
2502        assert_eq!(instrument.symbol_id, Some(11));
2503        assert_eq!(instrument.symbol_type, Some(BybitSymbolType::Commodity));
2504    }
2505
2506    #[rstest]
2507    fn deserialize_option_instrument_with_symbol_id() {
2508        let json = load_test_json("http_get_instruments_option_symbol_id.json");
2509        let response: BybitInstrumentOptionResponse = serde_json::from_str(&json).unwrap();
2510        let instrument = &response.result.list[0];
2511
2512        assert_eq!(instrument.symbol_id, Some(99));
2513    }
2514
2515    #[rstest]
2516    fn deserialize_sub_members_response() {
2517        let json = load_test_json("http_get_user_sub_members.json");
2518        let response: BybitSubMembersResponse =
2519            serde_json::from_str(&json).expect("parse sub members");
2520        assert_eq!(response.ret_code, 0);
2521        assert_eq!(response.result.sub_members.len(), 2);
2522        let first = &response.result.sub_members[0];
2523        assert_eq!(first.uid, "106314365");
2524        assert_eq!(first.username, "xxxx02");
2525        assert_eq!(first.member_type, 1);
2526        assert_eq!(first.status, 1);
2527        assert_eq!(first.account_mode, 5);
2528        assert_eq!(first.remark, "");
2529        let second = &response.result.sub_members[1];
2530        assert_eq!(second.uid, "106279879");
2531        assert_eq!(second.account_mode, 6);
2532    }
2533
2534    #[rstest]
2535    fn deserialize_sub_members_paged_response() {
2536        // The final-page sentinel is `"0"`; both `"0"` and `None` collapse to
2537        // `continuation_cursor() == None` through the method.
2538        let json = load_test_json("http_get_user_sub_members_paged.json");
2539        let response: BybitSubMembersPagedResponse =
2540            serde_json::from_str(&json).expect("parse paged sub members");
2541        assert_eq!(response.result.sub_members.len(), 2);
2542        assert_eq!(response.result.next_cursor.as_deref(), Some("0"));
2543        assert!(!response.result.has_more_pages());
2544        assert_eq!(response.result.continuation_cursor(), None);
2545    }
2546
2547    #[rstest]
2548    fn deserialize_escrow_sub_members_response_uses_same_shape() {
2549        // The escrow alias must decode into the same shape as the paginated
2550        // sub-member list; a non-`"0"` cursor indicates more pages to fetch.
2551        let json = load_test_json("http_get_user_escrow_sub_members.json");
2552        let response: BybitEscrowSubMembersResponse =
2553            serde_json::from_str(&json).expect("parse escrow sub members");
2554        assert_eq!(response.result.sub_members.len(), 2);
2555        assert_eq!(response.result.sub_members[0].member_type, 12);
2556        assert_eq!(response.result.sub_members[0].remark, "earn fund");
2557        assert_eq!(response.result.next_cursor.as_deref(), Some("344"));
2558        assert!(response.result.has_more_pages());
2559        assert_eq!(response.result.continuation_cursor(), Some("344"));
2560    }
2561
2562    #[rstest]
2563    fn deserialize_sub_api_keys_response() {
2564        // `readOnly` arrives as a bool here; the masked `"******"` secret
2565        // collapses to `None` through the `masked_secret` Serde adapter.
2566        let json = load_test_json("http_get_user_sub_apikeys.json");
2567        let response: BybitSubApiKeysResponse =
2568            serde_json::from_str(&json).expect("parse sub apikeys");
2569        assert_eq!(response.result.keys.len(), 1);
2570        let key = &response.result.keys[0];
2571        let debug = format!("{key:?}");
2572
2573        assert!(!key.read_only);
2574        assert_eq!(key.secret, None);
2575        assert_eq!(key.key_type, BybitApiKeyType::Hmac);
2576        assert_eq!(key.flag, "hmac");
2577        assert_eq!(key.deadline_day, Some(21));
2578        assert_eq!(key.permissions.contract_trade, vec!["Order", "Position"]);
2579        assert_eq!(key.permissions.spot, vec!["SpotTrade"]);
2580        assert!(key.permissions.earn.is_empty());
2581        assert_eq!(response.result.next_page_cursor.as_deref(), Some(""));
2582        assert!(!response.result.has_more_pages());
2583        assert!(debug.contains("api_key: <redacted>"));
2584        assert!(debug.contains("secret: None"));
2585        assert!(!debug.contains("XXXXXX"));
2586    }
2587
2588    #[rstest]
2589    fn deserialize_update_sub_api_response() {
2590        let json = load_test_json("http_post_user_update_sub_api.json");
2591        let response: BybitUpdateSubApiResponse =
2592            serde_json::from_str(&json).expect("parse update sub api");
2593        let debug = format!("{:?}", response.result);
2594
2595        assert!(!response.result.read_only);
2596        assert_eq!(response.result.secret, None);
2597        assert_eq!(response.result.ips, vec!["*"]);
2598        assert_eq!(response.result.permissions.spot, vec!["SpotTrade"]);
2599        assert_eq!(response.result.permissions.wallet, vec!["AccountTransfer"]);
2600        assert!(debug.contains("api_key: <redacted>"));
2601        assert!(debug.contains("secret: None"));
2602        assert!(!debug.contains("xxxxxx"));
2603    }
2604
2605    #[rstest]
2606    fn deserialize_update_master_api_response() {
2607        // Asserts on non-empty permission buckets so the test actually verifies
2608        // deserialisation (an empty `Vec` would be indistinguishable from a
2609        // `#[serde(default)]` fallback). In particular, `nft` exercises the
2610        // explicit `#[serde(rename = "NFT")]` attribute.
2611        let json = load_test_json("http_post_user_update_master_api.json");
2612        let response: BybitUpdateMasterApiResponse =
2613            serde_json::from_str(&json).expect("parse update master api");
2614        assert!(!response.result.read_only);
2615        assert_eq!(response.result.ips, vec!["*"]);
2616        let perms = &response.result.permissions;
2617        assert_eq!(perms.contract_trade, vec!["Order", "Position"]);
2618        assert_eq!(perms.copy_trading, vec!["CopyTrading"]);
2619        assert!(perms.earn.is_empty());
2620        assert_eq!(perms.nft, vec!["NFTQueryProductList"]);
2621    }
2622
2623    #[rstest]
2624    fn deserialize_permissions_renamed_buckets_preserve_values() {
2625        // Regression guard for `#[serde(rename = ...)]` on permission keys
2626        // whose Bybit casing (`NFT`, `FiatP2P`, `ByXPost`) differs from
2627        // serde's `PascalCase` default (`Nft`, `FiatP2p`, `ByxPost`). Using
2628        // non-empty values ensures a rename regression causes a failure
2629        // rather than silently falling through to `serde(default)`.
2630        let json = r#"{
2631            "NFT": ["NFTQueryProductList"],
2632            "FiatP2P": ["P2PDeposit"],
2633            "ByXPost": ["PostContent"]
2634        }"#;
2635        let perms: BybitApiKeyPermissions =
2636            serde_json::from_str(json).expect("parse renamed buckets");
2637        assert_eq!(perms.nft, vec!["NFTQueryProductList"]);
2638        assert_eq!(perms.fiat_p2p, vec!["P2PDeposit"]);
2639        assert_eq!(perms.byx_post, vec!["PostContent"]);
2640    }
2641
2642    #[rstest]
2643    fn deserialize_account_details_response_with_current_docs_example() {
2644        let json = load_test_json("http_get_user_query_api.json");
2645        let response: BybitAccountDetailsResponse =
2646            serde_json::from_str(&json).expect("parse account details");
2647        let debug = format!("{:?}", response.result);
2648
2649        assert_eq!(
2650            response.result.permissions.fiat_global_pay,
2651            Vec::<String>::new()
2652        );
2653        assert_eq!(
2654            response.result.permissions.fiat_bit_pay,
2655            vec!["FaitPayOrder"]
2656        );
2657        assert_eq!(response.result.permissions.bit_card, vec!["BitCard"]);
2658        assert_eq!(response.result.permissions.byx_post, vec!["ByXPost"]);
2659        assert_eq!(response.result.unified, Some(0));
2660        assert!(debug.contains("api_key: <redacted>"));
2661        assert!(debug.contains("secret: <redacted>"));
2662        assert!(!debug.contains("api_key: \"XXXXXXXX\""));
2663    }
2664}