Skip to main content

nautilus_bybit/common/
parse.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//! Conversion functions that translate Bybit API schemas into Nautilus instruments.
17
18use std::{convert::TryFrom, str::FromStr};
19
20use anyhow::Context;
21use indexmap::IndexMap;
22pub use nautilus_core::serialization::{
23    deserialize_decimal_or_zero, deserialize_optional_decimal_or_zero,
24    deserialize_optional_decimal_str, deserialize_string_to_u8,
25};
26use serde::{Deserialize, de::Error};
27
28/// Serde adapter for Bybit `ON`/`OFF` string fields that represent booleans.
29///
30/// Use as `#[serde(with = "on_off_bool")]`. Unknown values deserialize as an
31/// error rather than silently coercing, so field renames surface rather than
32/// decoding to the wrong value.
33pub mod on_off_bool {
34    use serde::{Deserialize, Deserializer, Serializer, de::Error};
35
36    pub fn serialize<S: Serializer>(value: &bool, s: S) -> Result<S::Ok, S::Error> {
37        s.serialize_str(if *value { "ON" } else { "OFF" })
38    }
39
40    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
41        let raw = String::deserialize(d)?;
42        match raw.as_str() {
43            "ON" => Ok(true),
44            "OFF" => Ok(false),
45            other => Err(D::Error::custom(format!(
46                "expected 'ON' or 'OFF', received {other:?}"
47            ))),
48        }
49    }
50}
51
52/// Serde adapter that accepts `readOnly` as either a bool or `0`/`1` integer.
53///
54/// Bybit returns `readOnly` as a bool on `/v5/user/list-sub-apikeys` and as an
55/// integer on `/v5/user/query-api` and the two update endpoints. Deserializing
56/// through this module keeps the Rust field a plain `bool` across all DTOs.
57pub mod bool_or_int {
58    use serde::{Deserialize, Deserializer, Serializer, de::Error};
59
60    pub fn serialize<S: Serializer>(value: &bool, s: S) -> Result<S::Ok, S::Error> {
61        s.serialize_bool(*value)
62    }
63
64    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
65        #[derive(Deserialize)]
66        #[serde(untagged)]
67        enum BoolOrInt {
68            Bool(bool),
69            Int(i64),
70        }
71
72        match BoolOrInt::deserialize(d)? {
73            BoolOrInt::Bool(b) => Ok(b),
74            BoolOrInt::Int(0) => Ok(false),
75            BoolOrInt::Int(1) => Ok(true),
76            BoolOrInt::Int(n) => Err(D::Error::custom(format!(
77                "expected bool or 0/1, received {n}"
78            ))),
79        }
80    }
81}
82
83/// Deserializes an integer from either a JSON integer or base-10 integer string.
84///
85/// Bybit responses can encode the same integer field in both forms.
86pub(crate) fn deserialize_int_or_string<'de, T, D>(d: D) -> Result<T, D::Error>
87where
88    T: serde::Deserialize<'de> + std::str::FromStr,
89    T::Err: std::fmt::Display,
90    D: serde::Deserializer<'de>,
91{
92    #[derive(serde::Deserialize)]
93    #[serde(untagged)]
94    enum IntOrString<T> {
95        Int(T),
96        Str(String),
97    }
98
99    match IntOrString::<T>::deserialize(d)? {
100        IntOrString::Int(value) => Ok(value),
101        IntOrString::Str(value) => value.parse().map_err(|e| {
102            D::Error::custom(format!(
103                "expected {}, received {value:?}: {e}",
104                std::any::type_name::<T>()
105            ))
106        }),
107    }
108}
109
110/// Deserializes an `i32` from either a JSON integer or base-10 integer string.
111///
112/// Bybit order responses can encode `smpGroup` in both forms.
113pub(crate) fn deserialize_i32_or_string<'de, D: serde::Deserializer<'de>>(
114    d: D,
115) -> Result<i32, D::Error> {
116    deserialize_int_or_string(d)
117}
118
119/// Deserializes an `i64` from either a JSON integer or base-10 integer string.
120///
121/// Bybit position responses can encode `riskId` in both forms.
122pub(crate) fn deserialize_i64_or_string<'de, D: serde::Deserializer<'de>>(
123    d: D,
124) -> Result<i64, D::Error> {
125    deserialize_int_or_string(d)
126}
127
128/// Deserializes an optional [`BybitSymbolType`], treating an empty string as `None`.
129///
130/// Bybit sends `symbolType: ""` for regular symbols, which would otherwise decode as
131/// [`BybitSymbolType::Other`].
132pub(crate) fn deserialize_optional_symbol_type<'de, D: serde::Deserializer<'de>>(
133    d: D,
134) -> Result<Option<BybitSymbolType>, D::Error> {
135    let Some(value) = Option::<String>::deserialize(d)?.filter(|value| !value.is_empty()) else {
136        return Ok(None);
137    };
138
139    BybitSymbolType::deserialize(serde::de::IntoDeserializer::<D::Error>::into_deserializer(
140        value,
141    ))
142    .map(Some)
143}
144
145/// Round-trips `Option<bool>` as `0`/`1` integers for Bybit request bodies
146/// that advertise `readOnly` as an integer on the wire.
147pub mod opt_bool_as_int {
148    use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
149
150    pub fn serialize<S: Serializer>(value: &Option<bool>, s: S) -> Result<S::Ok, S::Error> {
151        value.map(i32::from).serialize(s)
152    }
153
154    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
155        match Option::<i32>::deserialize(d)? {
156            None => Ok(None),
157            Some(0) => Ok(Some(false)),
158            Some(1) => Ok(Some(true)),
159            Some(n) => Err(D::Error::custom(format!("expected 0 or 1, received {n}"))),
160        }
161    }
162}
163
164/// Serde adapter that treats the masked secret literal (`"******"`) and empty
165/// strings as `None`, preserving real values as `Some`.
166///
167/// Bybit responses never expose a usable secret: `list-sub-apikeys` returns
168/// `"******"`, while the update endpoints return `""`. Surfacing `Option<String>`
169/// keeps callers from accidentally treating the sentinel as a real credential.
170pub mod masked_secret {
171    use nautilus_core::string::secret::SecretString;
172    use serde::{Deserialize, Deserializer, Serialize, Serializer};
173
174    pub fn serialize<S: Serializer>(value: &Option<SecretString>, s: S) -> Result<S::Ok, S::Error> {
175        match value {
176            Some(v) => v.serialize(s),
177            None => "".serialize(s),
178        }
179    }
180
181    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<SecretString>, D::Error> {
182        let raw = Option::<String>::deserialize(d)?;
183        Ok(match raw.as_deref() {
184            None | Some("" | "******") => None,
185            Some(_) => raw.map(SecretString::from),
186        })
187    }
188}
189use nautilus_core::{
190    Params, UUID4,
191    datetime::{NANOSECONDS_IN_MILLISECOND, nanos_to_millis as nanos_to_millis_u64},
192    nanos::UnixNanos,
193    serialization::decimal,
194};
195use nautilus_model::{
196    data::{
197        Bar, BarType, BookOrder, FundingRateUpdate, OrderBookDelta, OrderBookDeltas, TradeTick,
198    },
199    enums::{
200        AccountType, AggressorSide, AssetClass, BarAggregation, BookAction, ExerciseStyle,
201        LiquiditySide, OptionKind, OrderSide, OrderStatus, OrderType, PositionSide, RecordFlag,
202        SettlementType, TimeInForce, TriggerType,
203    },
204    events::account::state::AccountState,
205    identifiers::{
206        AccountId, ClientOrderId, InstrumentId, PositionId, Symbol, TradeId, VenueOrderId,
207    },
208    instruments::{
209        Instrument, any::InstrumentAny, crypto_future::CryptoFuture, crypto_option::CryptoOption,
210        crypto_perpetual::CryptoPerpetual, currency_pair::CurrencyPair,
211        perpetual_contract::PerpetualContract, tokenized_asset::TokenizedAsset,
212    },
213    reports::{FillReport, OrderStatusReport, PositionStatusReport},
214    types::{AccountBalance, Currency, MarginBalance, Money, Price, QUANTITY_MAX, Quantity},
215};
216use rust_decimal::Decimal;
217use ustr::Ustr;
218
219use crate::{
220    common::{
221        enums::{
222            BybitBboSideType, BybitContractType, BybitKlineInterval, BybitMarginAction,
223            BybitMarginTrading, BybitMarketUnit, BybitOptionType, BybitOrderSide,
224            BybitOrderSmpType, BybitOrderStatus, BybitOrderType, BybitPositionIdx,
225            BybitPositionMode, BybitPositionSide, BybitProductType, BybitStopOrderType,
226            BybitSymbolType, BybitTimeInForce, BybitTpSlMode, BybitTriggerDirection,
227            BybitTriggerType,
228        },
229        symbol::BybitSymbol,
230    },
231    http::{
232        models::{
233            BybitExecution, BybitFunding, BybitInstrumentInverse, BybitInstrumentLinear,
234            BybitInstrumentOption, BybitInstrumentSpot, BybitKline, BybitOrderbookResult,
235            BybitPosition, BybitTrade, BybitWalletBalance,
236        },
237        query::BybitNativeTpSlParams,
238    },
239    websocket::parse::parse_millis_i64,
240};
241
242const BYBIT_HOUR_INTERVALS: &[u64] = &[1, 2, 4, 6, 12];
243
244const BYBIT_POST_ONLY_REJECT_REASON: &str = "EC_PostOnlyWillTakeLiquidity";
245
246/// Returns whether a Bybit rejection reason indicates a post-only order that
247/// would have taken liquidity (crossed the book).
248#[must_use]
249pub fn bybit_rejection_due_post_only(reason: &str) -> bool {
250    reason.contains(BYBIT_POST_ONLY_REJECT_REASON)
251}
252
253/// Extracts the raw symbol from a Bybit symbol by removing the product type suffix.
254#[must_use]
255pub fn extract_raw_symbol(symbol: &str) -> &str {
256    symbol.rsplit_once('-').map_or(symbol, |(prefix, _)| prefix)
257}
258
259/// Extracts the base coin from a Bybit option symbol.
260///
261/// For example, `"BTC-27MAR26-70000-P"` returns `"BTC"`.
262#[must_use]
263pub fn extract_base_coin(symbol: &str) -> &str {
264    symbol.split_once('-').map_or(symbol, |(base, _)| base)
265}
266
267/// Constructs a full Bybit symbol from a raw symbol and product type.
268///
269/// Returns a `Ustr` for efficient string interning and comparisons.
270#[must_use]
271pub fn make_bybit_symbol<S: AsRef<str>>(raw_symbol: S, product_type: BybitProductType) -> Ustr {
272    let raw = raw_symbol.as_ref();
273    Ustr::from(&format!("{raw}{}", product_type.suffix()))
274}
275
276/// Converts a Bybit kline interval string to a Nautilus bar aggregation and step.
277///
278/// Bybit interval strings: 1, 3, 5, 15, 30, 60, 120, 240, 360, 720 (minutes/hours), D, W, M
279#[must_use]
280pub fn bybit_interval_to_bar_spec(interval: &str) -> Option<(usize, BarAggregation)> {
281    match interval {
282        "1" => Some((1, BarAggregation::Minute)),
283        "3" => Some((3, BarAggregation::Minute)),
284        "5" => Some((5, BarAggregation::Minute)),
285        "15" => Some((15, BarAggregation::Minute)),
286        "30" => Some((30, BarAggregation::Minute)),
287        "60" => Some((1, BarAggregation::Hour)),
288        "120" => Some((2, BarAggregation::Hour)),
289        "240" => Some((4, BarAggregation::Hour)),
290        "360" => Some((6, BarAggregation::Hour)),
291        "720" => Some((12, BarAggregation::Hour)),
292        "D" => Some((1, BarAggregation::Day)),
293        "W" => Some((1, BarAggregation::Week)),
294        "M" => Some((1, BarAggregation::Month)),
295        _ => None,
296    }
297}
298
299/// Converts a Nautilus bar aggregation and step to a Bybit kline interval.
300///
301/// Bybit supported intervals: 1, 3, 5, 15, 30, 60, 120, 240, 360, 720 (minutes), D, W, M
302///
303/// # Errors
304///
305/// Returns an error if the aggregation type or step is not supported by Bybit.
306pub fn bar_spec_to_bybit_interval(
307    aggregation: BarAggregation,
308    step: u64,
309) -> anyhow::Result<BybitKlineInterval> {
310    match aggregation {
311        BarAggregation::Minute => match step {
312            1 => Ok(BybitKlineInterval::Minute1),
313            3 => Ok(BybitKlineInterval::Minute3),
314            5 => Ok(BybitKlineInterval::Minute5),
315            15 => Ok(BybitKlineInterval::Minute15),
316            30 => Ok(BybitKlineInterval::Minute30),
317            _ => anyhow::bail!(
318                "Bybit only supports minute intervals 1, 3, 5, 15, 30 (use HOUR for >= 60)"
319            ),
320        },
321        BarAggregation::Hour => match step {
322            1 => Ok(BybitKlineInterval::Hour1),
323            2 => Ok(BybitKlineInterval::Hour2),
324            4 => Ok(BybitKlineInterval::Hour4),
325            6 => Ok(BybitKlineInterval::Hour6),
326            12 => Ok(BybitKlineInterval::Hour12),
327            _ => anyhow::bail!(
328                "Bybit only supports the following hour intervals: {BYBIT_HOUR_INTERVALS:?}"
329            ),
330        },
331        BarAggregation::Day => {
332            if step != 1 {
333                anyhow::bail!("Bybit only supports 1 DAY interval bars");
334            }
335            Ok(BybitKlineInterval::Day1)
336        }
337        BarAggregation::Week => {
338            if step != 1 {
339                anyhow::bail!("Bybit only supports 1 WEEK interval bars");
340            }
341            Ok(BybitKlineInterval::Week1)
342        }
343        BarAggregation::Month => {
344            if step != 1 {
345                anyhow::bail!("Bybit only supports 1 MONTH interval bars");
346            }
347            Ok(BybitKlineInterval::Month1)
348        }
349        _ => {
350            anyhow::bail!("Bybit does not support {aggregation:?} bars");
351        }
352    }
353}
354
355fn default_margin() -> Decimal {
356    Decimal::new(1, 1)
357}
358
359/// Parses a spot instrument definition returned by Bybit into a Nautilus currency pair, or a
360/// tokenized asset for tokenized real-world assets (such as xStocks).
361///
362/// # Panics
363///
364/// Panics if the constructed instrument fails validation.
365pub fn parse_spot_instrument(
366    definition: &BybitInstrumentSpot,
367    ts_event: UnixNanos,
368    ts_init: UnixNanos,
369) -> anyhow::Result<InstrumentAny> {
370    let base_currency = get_currency(definition.base_coin.as_str());
371    let quote_currency = get_currency(definition.quote_coin.as_str());
372
373    let symbol = BybitSymbol::new(format!("{}-SPOT", definition.symbol))?;
374    let instrument_id = symbol.to_instrument_id();
375    let raw_symbol = Symbol::new(symbol.raw_symbol());
376
377    let price_increment = parse_price(&definition.price_filter.tick_size, "priceFilter.tickSize")?;
378    let size_increment = parse_quantity(
379        &definition.lot_size_filter.base_precision,
380        "lotSizeFilter.basePrecision",
381    )?;
382    let lot_size = Some(size_increment);
383    let max_quantity = parse_max_quantity(
384        &definition.lot_size_filter.max_order_qty,
385        "lotSizeFilter.maxOrderQty",
386    )?;
387    let min_quantity = Some(parse_quantity(
388        &definition.lot_size_filter.min_order_qty,
389        "lotSizeFilter.minOrderQty",
390    )?);
391    let min_notional = Some(Money::from_decimal(
392        parse_decimal(
393            &definition.lot_size_filter.min_order_amt,
394            "lotSizeFilter.minOrderAmt",
395        )?,
396        quote_currency,
397    )?);
398
399    let margin_trading_supported = matches!(
400        definition.margin_trading,
401        BybitMarginTrading::Both | BybitMarginTrading::UtaOnly
402    );
403
404    let mut info = build_instrument_info(
405        definition.symbol_type,
406        definition.xstock_multiplier.as_deref(),
407        None,
408        None,
409    )
410    .unwrap_or_default();
411    info.insert(
412        "margin_trading".to_string(),
413        serde_json::Value::Bool(margin_trading_supported),
414    );
415    let info = Params::new(info);
416
417    let asset_class = definition
418        .symbol_type
419        .map_or(AssetClass::Cryptocurrency, AssetClass::from);
420
421    if asset_class != AssetClass::Cryptocurrency {
422        // `xstockMultiplier` converts token to stock price, not contract size, so it stays in
423        // `info` and the instrument multiplier remains 1
424        let instrument = TokenizedAsset::builder()
425            .instrument_id(instrument_id)
426            .raw_symbol(raw_symbol)
427            .asset_class(asset_class)
428            .base_currency(base_currency)
429            .quote_currency(quote_currency)
430            .price_precision(price_increment.precision)
431            .size_precision(size_increment.precision)
432            .price_increment(price_increment)
433            .size_increment(size_increment)
434            .maybe_lot_size(lot_size)
435            .maybe_max_quantity(max_quantity)
436            .maybe_min_quantity(min_quantity)
437            .maybe_min_notional(min_notional)
438            .margin_init(default_margin())
439            .margin_maint(default_margin())
440            .info(info)
441            .ts_event(ts_event)
442            .ts_init(ts_init)
443            .build()?;
444        return Ok(InstrumentAny::TokenizedAsset(instrument));
445    }
446
447    let instrument = CurrencyPair::builder()
448        .instrument_id(instrument_id)
449        .raw_symbol(raw_symbol)
450        .base_currency(base_currency)
451        .quote_currency(quote_currency)
452        .price_precision(price_increment.precision)
453        .size_precision(size_increment.precision)
454        .price_increment(price_increment)
455        .size_increment(size_increment)
456        .maybe_lot_size(lot_size)
457        .maybe_max_quantity(max_quantity)
458        .maybe_min_quantity(min_quantity)
459        .maybe_min_notional(min_notional)
460        .margin_init(default_margin())
461        .margin_maint(default_margin())
462        .info(info)
463        .ts_event(ts_event)
464        .ts_init(ts_init)
465        .build()
466        .unwrap();
467
468    Ok(InstrumentAny::CurrencyPair(instrument))
469}
470
471/// Parses a linear contract definition (perpetual or dated future) into a Nautilus instrument.
472///
473/// # Panics
474///
475/// Panics if the constructed instrument fails validation.
476pub fn parse_linear_instrument(
477    definition: &BybitInstrumentLinear,
478    ts_event: UnixNanos,
479    ts_init: UnixNanos,
480) -> anyhow::Result<InstrumentAny> {
481    // Validate required fields
482    anyhow::ensure!(
483        !definition.base_coin.is_empty(),
484        "base_coin is empty for symbol '{}'",
485        definition.symbol
486    );
487    anyhow::ensure!(
488        !definition.quote_coin.is_empty(),
489        "quote_coin is empty for symbol '{}'",
490        definition.symbol
491    );
492
493    let base_currency = get_currency(definition.base_coin.as_str());
494    let quote_currency = get_currency(definition.quote_coin.as_str());
495    let settlement_currency = resolve_settlement_currency(
496        definition.settle_coin.as_str(),
497        base_currency,
498        quote_currency,
499    )?;
500
501    let symbol = BybitSymbol::new(format!("{}-LINEAR", definition.symbol))?;
502    let instrument_id = symbol.to_instrument_id();
503    let raw_symbol = Symbol::new(symbol.raw_symbol());
504
505    let price_increment = parse_price(&definition.price_filter.tick_size, "priceFilter.tickSize")?;
506    let size_increment = parse_quantity(
507        &definition.lot_size_filter.qty_step,
508        "lotSizeFilter.qtyStep",
509    )?;
510    let lot_size = Some(size_increment);
511    let max_quantity = parse_max_quantity(
512        &definition.lot_size_filter.max_order_qty,
513        "lotSizeFilter.maxOrderQty",
514    )?;
515    let min_quantity = Some(parse_quantity(
516        &definition.lot_size_filter.min_order_qty,
517        "lotSizeFilter.minOrderQty",
518    )?);
519    let max_price = Some(parse_price(
520        &definition.price_filter.max_price,
521        "priceFilter.maxPrice",
522    )?);
523    let min_price = Some(parse_price(
524        &definition.price_filter.min_price,
525        "priceFilter.minPrice",
526    )?);
527    let min_notional = parse_optional_notional(
528        definition.lot_size_filter.min_notional_value.as_deref(),
529        quote_currency,
530        "lotSizeFilter.minNotionalValue",
531    )?;
532
533    let info = build_instrument_info(
534        definition.symbol_type,
535        None,
536        definition.full_name.as_deref(),
537        definition.market_region.as_deref(),
538    )
539    .map(Params::new);
540
541    let asset_class = definition
542        .symbol_type
543        .map_or(AssetClass::Cryptocurrency, AssetClass::from);
544
545    match definition.contract_type {
546        BybitContractType::LinearPerpetual if asset_class != AssetClass::Cryptocurrency => {
547            // Bybit leaves `underlyingTicker` empty for commodity and forex
548            let underlying = definition
549                .underlying_ticker
550                .as_deref()
551                .unwrap_or(definition.base_coin.as_str());
552
553            let instrument = PerpetualContract::builder()
554                .instrument_id(instrument_id)
555                .raw_symbol(raw_symbol)
556                .underlying(Ustr::from(underlying))
557                .asset_class(asset_class)
558                .quote_currency(quote_currency)
559                .settlement_currency(settlement_currency)
560                .is_inverse(false)
561                .price_precision(price_increment.precision)
562                .size_precision(size_increment.precision)
563                .price_increment(price_increment)
564                .size_increment(size_increment)
565                .maybe_lot_size(lot_size)
566                .maybe_max_quantity(max_quantity)
567                .maybe_min_quantity(min_quantity)
568                .maybe_min_notional(min_notional)
569                .maybe_max_price(max_price)
570                .maybe_min_price(min_price)
571                .margin_init(default_margin())
572                .margin_maint(default_margin())
573                .maybe_info(info)
574                .ts_event(ts_event)
575                .ts_init(ts_init)
576                .build()?;
577            Ok(InstrumentAny::PerpetualContract(instrument))
578        }
579        BybitContractType::LinearPerpetual => {
580            let instrument = CryptoPerpetual::builder()
581                .instrument_id(instrument_id)
582                .raw_symbol(raw_symbol)
583                .base_currency(base_currency)
584                .quote_currency(quote_currency)
585                .settlement_currency(settlement_currency)
586                .is_inverse(false)
587                .price_precision(price_increment.precision)
588                .size_precision(size_increment.precision)
589                .price_increment(price_increment)
590                .size_increment(size_increment)
591                .maybe_lot_size(lot_size)
592                .maybe_max_quantity(max_quantity)
593                .maybe_min_quantity(min_quantity)
594                .maybe_min_notional(min_notional)
595                .maybe_max_price(max_price)
596                .maybe_min_price(min_price)
597                .margin_init(default_margin())
598                .margin_maint(default_margin())
599                .maybe_info(info)
600                .ts_event(ts_event)
601                .ts_init(ts_init)
602                .build()
603                .unwrap();
604            Ok(InstrumentAny::CryptoPerpetual(instrument))
605        }
606        BybitContractType::LinearFutures => {
607            let activation_ns = parse_millis_timestamp(&definition.launch_time, "launchTime")?;
608            let expiration_ns = parse_millis_timestamp(&definition.delivery_time, "deliveryTime")?;
609            let instrument = CryptoFuture::builder()
610                .instrument_id(instrument_id)
611                .raw_symbol(raw_symbol)
612                .underlying(base_currency)
613                .quote_currency(quote_currency)
614                .settlement_currency(settlement_currency)
615                .is_inverse(false)
616                .activation_ns(activation_ns)
617                .expiration_ns(expiration_ns)
618                .price_precision(price_increment.precision)
619                .size_precision(size_increment.precision)
620                .price_increment(price_increment)
621                .size_increment(size_increment)
622                .maybe_lot_size(lot_size)
623                .maybe_max_quantity(max_quantity)
624                .maybe_min_quantity(min_quantity)
625                .maybe_min_notional(min_notional)
626                .maybe_max_price(max_price)
627                .maybe_min_price(min_price)
628                .margin_init(default_margin())
629                .margin_maint(default_margin())
630                .maybe_info(info)
631                .ts_event(ts_event)
632                .ts_init(ts_init)
633                .build()
634                .unwrap();
635            Ok(InstrumentAny::CryptoFuture(instrument))
636        }
637        other => Err(anyhow::anyhow!(
638            "unsupported linear contract variant: {other:?}"
639        )),
640    }
641}
642
643/// Parses Bybit's `minNotionalValue` string (when present) into a `Money` value
644/// denominated in the instrument's quote currency. Returns `Ok(None)` if the
645/// field is absent or an empty string.
646fn parse_optional_notional(
647    raw: Option<&str>,
648    currency: Currency,
649    field: &str,
650) -> anyhow::Result<Option<Money>> {
651    let Some(s) = raw.map(str::trim).filter(|s| !s.is_empty()) else {
652        return Ok(None);
653    };
654
655    let amount = decimal::parse(s).with_context(|| format!("invalid {field}: {s:?}"))?;
656    let notional = Money::from_decimal(amount, currency)?;
657    anyhow::ensure!(notional.is_positive(), "{field} must be positive, was {s}");
658
659    Ok(Some(notional))
660}
661
662/// Parses an inverse contract definition into a Nautilus instrument.
663///
664/// # Panics
665///
666/// Panics if the constructed instrument fails validation.
667pub fn parse_inverse_instrument(
668    definition: &BybitInstrumentInverse,
669    ts_event: UnixNanos,
670    ts_init: UnixNanos,
671) -> anyhow::Result<InstrumentAny> {
672    // Validate required fields
673    anyhow::ensure!(
674        !definition.base_coin.is_empty(),
675        "base_coin is empty for symbol '{}'",
676        definition.symbol
677    );
678    anyhow::ensure!(
679        !definition.quote_coin.is_empty(),
680        "quote_coin is empty for symbol '{}'",
681        definition.symbol
682    );
683
684    let base_currency = get_currency(definition.base_coin.as_str());
685    let quote_currency = get_currency(definition.quote_coin.as_str());
686    let settlement_currency = resolve_settlement_currency(
687        definition.settle_coin.as_str(),
688        base_currency,
689        quote_currency,
690    )?;
691
692    let symbol = BybitSymbol::new(format!("{}-INVERSE", definition.symbol))?;
693    let instrument_id = symbol.to_instrument_id();
694    let raw_symbol = Symbol::new(symbol.raw_symbol());
695
696    let price_increment = parse_price(&definition.price_filter.tick_size, "priceFilter.tickSize")?;
697    let size_increment = parse_quantity(
698        &definition.lot_size_filter.qty_step,
699        "lotSizeFilter.qtyStep",
700    )?;
701    let lot_size = Some(size_increment);
702    let max_quantity = parse_max_quantity(
703        &definition.lot_size_filter.max_order_qty,
704        "lotSizeFilter.maxOrderQty",
705    )?;
706    let min_quantity = Some(parse_quantity(
707        &definition.lot_size_filter.min_order_qty,
708        "lotSizeFilter.minOrderQty",
709    )?);
710    let max_price = Some(parse_price(
711        &definition.price_filter.max_price,
712        "priceFilter.maxPrice",
713    )?);
714    let min_price = Some(parse_price(
715        &definition.price_filter.min_price,
716        "priceFilter.minPrice",
717    )?);
718    let min_notional = parse_optional_notional(
719        definition.lot_size_filter.min_notional_value.as_deref(),
720        quote_currency,
721        "lotSizeFilter.minNotionalValue",
722    )?;
723
724    let info = build_instrument_info(definition.symbol_type, None, None, None).map(Params::new);
725
726    match definition.contract_type {
727        BybitContractType::InversePerpetual => {
728            let instrument = CryptoPerpetual::builder()
729                .instrument_id(instrument_id)
730                .raw_symbol(raw_symbol)
731                .base_currency(base_currency)
732                .quote_currency(quote_currency)
733                .settlement_currency(settlement_currency)
734                .is_inverse(true)
735                .price_precision(price_increment.precision)
736                .size_precision(size_increment.precision)
737                .price_increment(price_increment)
738                .size_increment(size_increment)
739                .maybe_lot_size(lot_size)
740                .maybe_max_quantity(max_quantity)
741                .maybe_min_quantity(min_quantity)
742                .maybe_min_notional(min_notional)
743                .maybe_max_price(max_price)
744                .maybe_min_price(min_price)
745                .margin_init(default_margin())
746                .margin_maint(default_margin())
747                .maybe_info(info)
748                .ts_event(ts_event)
749                .ts_init(ts_init)
750                .build()
751                .unwrap();
752            Ok(InstrumentAny::CryptoPerpetual(instrument))
753        }
754        BybitContractType::InverseFutures => {
755            let activation_ns = parse_millis_timestamp(&definition.launch_time, "launchTime")?;
756            let expiration_ns = parse_millis_timestamp(&definition.delivery_time, "deliveryTime")?;
757            let instrument = CryptoFuture::builder()
758                .instrument_id(instrument_id)
759                .raw_symbol(raw_symbol)
760                .underlying(base_currency)
761                .quote_currency(quote_currency)
762                .settlement_currency(settlement_currency)
763                .is_inverse(true)
764                .activation_ns(activation_ns)
765                .expiration_ns(expiration_ns)
766                .price_precision(price_increment.precision)
767                .size_precision(size_increment.precision)
768                .price_increment(price_increment)
769                .size_increment(size_increment)
770                .maybe_lot_size(lot_size)
771                .maybe_max_quantity(max_quantity)
772                .maybe_min_quantity(min_quantity)
773                .maybe_min_notional(min_notional)
774                .maybe_max_price(max_price)
775                .maybe_min_price(min_price)
776                .margin_init(default_margin())
777                .margin_maint(default_margin())
778                .maybe_info(info)
779                .ts_event(ts_event)
780                .ts_init(ts_init)
781                .build()
782                .unwrap();
783            Ok(InstrumentAny::CryptoFuture(instrument))
784        }
785        other => Err(anyhow::anyhow!(
786            "unsupported inverse contract variant: {other:?}"
787        )),
788    }
789}
790
791fn build_instrument_info(
792    symbol_type: Option<BybitSymbolType>,
793    xstock_multiplier: Option<&str>,
794    full_name: Option<&str>,
795    market_region: Option<&str>,
796) -> Option<IndexMap<String, serde_json::Value>> {
797    let symbol_type = symbol_type?;
798    let value = symbol_type.as_str()?;
799    let mut info = IndexMap::from([(
800        "symbol_type".to_string(),
801        serde_json::Value::String(value.to_string()),
802    )]);
803
804    if symbol_type == BybitSymbolType::Xstocks
805        && let Some(multiplier) = xstock_multiplier.filter(|value| !value.is_empty())
806    {
807        info.insert(
808            "xstock_multiplier".to_string(),
809            serde_json::Value::String(multiplier.to_string()),
810        );
811    }
812
813    for (key, value) in [("full_name", full_name), ("market_region", market_region)] {
814        if let Some(value) = value {
815            info.insert(
816                key.to_string(),
817                serde_json::Value::String(value.to_string()),
818            );
819        }
820    }
821
822    Some(info)
823}
824
825/// Parses a Bybit option contract definition into a Nautilus [`CryptoOption`].
826///
827/// # Panics
828///
829/// Panics if the constructed instrument fails validation.
830pub fn parse_option_instrument(
831    definition: &BybitInstrumentOption,
832    ts_event: UnixNanos,
833    ts_init: UnixNanos,
834) -> anyhow::Result<InstrumentAny> {
835    let symbol = BybitSymbol::new(format!("{}-OPTION", definition.symbol))?;
836    let instrument_id = symbol.to_instrument_id();
837    let raw_symbol = Symbol::new(symbol.raw_symbol());
838    let underlying = get_currency(definition.base_coin.as_str());
839    let quote_currency = get_currency(definition.quote_coin.as_str());
840    let settlement_currency = get_currency(definition.settle_coin.as_str());
841    // Bybit Options are linear contracts - they are margined and settled in stablecoins
842    let is_inverse = false;
843
844    let price_increment = parse_price(&definition.price_filter.tick_size, "priceFilter.tickSize")?;
845    let max_price = Some(parse_price(
846        &definition.price_filter.max_price,
847        "priceFilter.maxPrice",
848    )?);
849    let min_price = Some(parse_price(
850        &definition.price_filter.min_price,
851        "priceFilter.minPrice",
852    )?);
853    let lot_size = parse_quantity(
854        &definition.lot_size_filter.qty_step,
855        "lotSizeFilter.qtyStep",
856    )?;
857    let max_quantity = parse_max_quantity(
858        &definition.lot_size_filter.max_order_qty,
859        "lotSizeFilter.maxOrderQty",
860    )?;
861    let min_quantity = Some(parse_quantity(
862        &definition.lot_size_filter.min_order_qty,
863        "lotSizeFilter.minOrderQty",
864    )?);
865
866    let option_kind = match definition.options_type {
867        BybitOptionType::Call => OptionKind::Call,
868        BybitOptionType::Put => OptionKind::Put,
869    };
870
871    let strike_price = extract_strike_from_symbol(&definition.symbol)?;
872    let activation_ns = parse_millis_timestamp(&definition.launch_time, "launchTime")?;
873    let expiration_ns = parse_millis_timestamp(&definition.delivery_time, "deliveryTime")?;
874
875    let instrument = CryptoOption::builder()
876        .instrument_id(instrument_id)
877        .raw_symbol(raw_symbol)
878        .underlying(underlying)
879        .quote_currency(quote_currency)
880        .settlement_currency(settlement_currency)
881        .is_inverse(is_inverse)
882        .option_kind(option_kind)
883        .strike_price(strike_price)
884        .activation_ns(activation_ns)
885        .expiration_ns(expiration_ns)
886        .price_precision(price_increment.precision)
887        .size_precision(lot_size.precision)
888        .price_increment(price_increment)
889        // Lot size represents size increment.
890        .size_increment(lot_size)
891        .multiplier(Quantity::from(1_u32))
892        .lot_size(lot_size)
893        .maybe_max_quantity(max_quantity)
894        .maybe_min_quantity(min_quantity)
895        .maybe_max_price(max_price)
896        .maybe_min_price(min_price)
897        // Fixed by the Bybit contract specification; the payload carries neither
898        .exercise_style(ExerciseStyle::European)
899        .settlement_type(SettlementType::Cash)
900        .ts_event(ts_event)
901        .ts_init(ts_init)
902        .build()
903        .unwrap();
904
905    Ok(InstrumentAny::CryptoOption(instrument))
906}
907
908/// Parses a REST trade payload into a [`TradeTick`].
909pub fn parse_trade_tick(
910    trade: &BybitTrade,
911    instrument: &InstrumentAny,
912    ts_init: Option<UnixNanos>,
913) -> anyhow::Result<TradeTick> {
914    let price =
915        parse_price_with_precision(&trade.price, instrument.price_precision(), "trade.price")?;
916    let size =
917        parse_quantity_with_precision(&trade.size, instrument.size_precision(), "trade.size")?;
918    let aggressor: AggressorSide = trade.side.into();
919    let trade_id = TradeId::new_checked(trade.exec_id.as_str())
920        .context("invalid exec_id in Bybit trade payload")?;
921    let ts_event = parse_millis_timestamp(&trade.time, "trade.time")?;
922    let ts_init = ts_init.unwrap_or(ts_event);
923
924    TradeTick::new_checked(
925        instrument.id(),
926        price,
927        size,
928        aggressor,
929        trade_id,
930        ts_event,
931        ts_init,
932    )
933    .context("failed to construct TradeTick from Bybit trade payload")
934}
935
936/// Parses a REST funding payload into a [`FundingRateUpdate`].
937pub fn parse_funding_rate(
938    funding: &BybitFunding,
939    instrument: &InstrumentAny,
940    interval_millis: Option<i64>,
941) -> anyhow::Result<FundingRateUpdate> {
942    let rate = parse_decimal(&funding.funding_rate, "funding.rate")?;
943    let ts_event = parse_millis_timestamp(&funding.funding_rate_timestamp, "funding.timestamp")?;
944    let interval = interval_millis
945        .map(|ms| u16::try_from(ms / 60_000).context("interval milliseconds out of bounds"))
946        .transpose()?;
947
948    Ok(FundingRateUpdate::new(
949        instrument.id(),
950        rate,
951        interval,
952        None, // next_funding_ns not provided with historical funding rates
953        ts_event,
954        ts_event,
955    ))
956}
957
958/// Parses an order book response into [`OrderBookDeltas`].
959pub fn parse_orderbook(
960    result: &BybitOrderbookResult,
961    instrument: &InstrumentAny,
962    ts_init: Option<UnixNanos>,
963) -> anyhow::Result<OrderBookDeltas> {
964    let ts_event = parse_millis_i64(result.ts, "orderbook.timestamp")?;
965    let ts_init = ts_init.unwrap_or(ts_event);
966
967    let instrument_id = instrument.id();
968    let price_precision = instrument.price_precision();
969    let size_precision = instrument.size_precision();
970    let update_id = u64::try_from(result.u)
971        .context("received negative update id in Bybit order book message")?;
972    let sequence = u64::try_from(result.seq)
973        .context("received negative sequence in Bybit order book message")?;
974
975    let total_levels = result.b.len() + result.a.len();
976    let mut deltas = Vec::with_capacity(total_levels + 1);
977
978    let mut clear = OrderBookDelta::clear(instrument_id, sequence, ts_event, ts_init);
979
980    if total_levels == 0 {
981        clear.flags |= RecordFlag::F_LAST as u8;
982    }
983    deltas.push(clear);
984
985    let mut processed = 0_usize;
986
987    let mut push_level = |values: &[String], side: OrderSide| -> anyhow::Result<()> {
988        let (price, size) = parse_book_level(values, price_precision, size_precision, "orderbook")?;
989
990        processed += 1;
991        let mut flags = RecordFlag::F_MBP as u8;
992
993        if processed == total_levels {
994            flags |= RecordFlag::F_LAST as u8;
995        }
996
997        let order = BookOrder::new(side, price, size, update_id);
998        let delta = OrderBookDelta::new_checked(
999            instrument_id,
1000            BookAction::Add,
1001            order,
1002            flags,
1003            sequence,
1004            ts_event,
1005            ts_init,
1006        )
1007        .context("failed to construct OrderBookDelta from Bybit book level")?;
1008        deltas.push(delta);
1009        Ok(())
1010    };
1011
1012    for level in &result.b {
1013        push_level(level, OrderSide::Buy)?;
1014    }
1015
1016    for level in &result.a {
1017        push_level(level, OrderSide::Sell)?;
1018    }
1019
1020    OrderBookDeltas::new_checked(instrument_id, deltas)
1021        .context("failed to assemble OrderBookDeltas from Bybit message")
1022}
1023
1024pub fn parse_book_level(
1025    level: &[String],
1026    price_precision: u8,
1027    size_precision: u8,
1028    label: &str,
1029) -> anyhow::Result<(Price, Quantity)> {
1030    let price_str = level
1031        .first()
1032        .ok_or_else(|| anyhow::anyhow!("missing price component in {label} level"))?;
1033    let size_str = level
1034        .get(1)
1035        .ok_or_else(|| anyhow::anyhow!("missing size component in {label} level"))?;
1036    let price = parse_price_with_precision(price_str, price_precision, label)?;
1037    let size = parse_quantity_with_precision(size_str, size_precision, label)?;
1038    Ok((price, size))
1039}
1040
1041/// Parses a kline entry into a [`Bar`].
1042pub fn parse_kline_bar(
1043    kline: &BybitKline,
1044    instrument: &InstrumentAny,
1045    bar_type: BarType,
1046    timestamp_on_close: bool,
1047    ts_init: Option<UnixNanos>,
1048) -> anyhow::Result<Bar> {
1049    let price_precision = instrument.price_precision();
1050    let size_precision = instrument.size_precision();
1051
1052    let open = parse_price_with_precision(&kline.open, price_precision, "kline.open")?;
1053    let high = parse_price_with_precision(&kline.high, price_precision, "kline.high")?;
1054    let low = parse_price_with_precision(&kline.low, price_precision, "kline.low")?;
1055    let close = parse_price_with_precision(&kline.close, price_precision, "kline.close")?;
1056    let volume = parse_quantity_with_precision(&kline.volume, size_precision, "kline.volume")?;
1057
1058    let ts_open = parse_millis_timestamp(&kline.start, "kline.start")?;
1059    let interval_ns = bar_type.spec().timedelta().as_nanos();
1060    let interval_ns = u64::try_from(interval_ns)
1061        .context("bar interval overflowed the u64 range for nanoseconds")?;
1062    let ts_close = ts_open
1063        .as_u64()
1064        .checked_add(interval_ns)
1065        .map(UnixNanos::from)
1066        .context("bar timestamp overflowed when adjusting to close time")?;
1067
1068    let ts_event = if timestamp_on_close {
1069        ts_close
1070    } else {
1071        ts_open
1072    };
1073    let ts_init = ts_init.unwrap_or(ts_close); // Received time or close time
1074
1075    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
1076        .context("failed to construct Bar from Bybit kline entry")
1077}
1078
1079/// Constructs a venue position ID from an instrument and Bybit position index.
1080///
1081/// Position index values: 0 = one-way mode, 1 = buy-side hedge, 2 = sell-side hedge.
1082#[must_use]
1083pub fn make_venue_position_id(instrument_id: InstrumentId, position_idx: i32) -> PositionId {
1084    let side = match position_idx {
1085        0 => "ONEWAY",
1086        1 => "LONG",
1087        2 => "SHORT",
1088        _ => "UNKNOWN",
1089    };
1090    PositionId::new(format!("{instrument_id}-{side}"))
1091}
1092
1093/// Constructs a venue position ID only for hedge-mode Bybit position indexes.
1094#[must_use]
1095pub fn make_hedge_venue_position_id(
1096    instrument_id: InstrumentId,
1097    position_idx: i32,
1098) -> Option<PositionId> {
1099    match position_idx {
1100        1 | 2 => Some(make_venue_position_id(instrument_id, position_idx)),
1101        _ => None,
1102    }
1103}
1104
1105/// Resolves the `positionIdx` to send with an order under a given position mode.
1106///
1107/// In hedge mode `positionIdx` identifies the position being affected (1 = long,
1108/// 2 = short), not the trade direction. A reduce-only sell closes a long position
1109/// and a reduce-only buy closes a short position. A manual override always wins.
1110#[must_use]
1111pub fn resolve_position_idx(
1112    position_mode: Option<BybitPositionMode>,
1113    order_side: BybitOrderSide,
1114    is_reduce_only: bool,
1115    manual_override: Option<BybitPositionIdx>,
1116) -> Option<BybitPositionIdx> {
1117    if manual_override.is_some() {
1118        return manual_override;
1119    }
1120
1121    let mode = position_mode?;
1122    match mode {
1123        BybitPositionMode::BothSides => Some(match (order_side, is_reduce_only) {
1124            (BybitOrderSide::Buy, false) | (BybitOrderSide::Sell, true) => {
1125                BybitPositionIdx::BuyHedge
1126            }
1127            (BybitOrderSide::Sell, false) | (BybitOrderSide::Buy, true) => {
1128                BybitPositionIdx::SellHedge
1129            }
1130            (BybitOrderSide::Unknown, _) => BybitPositionIdx::OneWay,
1131        }),
1132        BybitPositionMode::MergedSingle => Some(BybitPositionIdx::OneWay),
1133    }
1134}
1135
1136/// Parses a Bybit execution into a Nautilus FillReport.
1137///
1138/// # Errors
1139///
1140/// Returns an error if:
1141/// - Required price or quantity fields cannot be parsed.
1142/// - The execution timestamp cannot be parsed.
1143/// - Numeric conversions fail.
1144pub fn parse_fill_report(
1145    execution: &BybitExecution,
1146    account_id: AccountId,
1147    instrument: &InstrumentAny,
1148    ts_init: UnixNanos,
1149) -> anyhow::Result<FillReport> {
1150    let instrument_id = instrument.id();
1151    let venue_order_id = VenueOrderId::new(execution.order_id);
1152    let trade_id = TradeId::new_checked(execution.exec_id.as_str())
1153        .context("invalid execId in Bybit execution payload")?;
1154
1155    let order_side = OrderSide::try_from(execution.side)?;
1156
1157    let last_px = parse_price_with_precision(
1158        &execution.exec_price,
1159        instrument.price_precision(),
1160        "execution.execPrice",
1161    )?;
1162
1163    let last_qty = parse_quantity_with_precision(
1164        &execution.exec_qty,
1165        instrument.size_precision(),
1166        "execution.execQty",
1167    )?;
1168
1169    let fee_decimal: Decimal = execution
1170        .exec_fee
1171        .parse()
1172        .with_context(|| format!("Failed to parse execFee='{}'", execution.exec_fee))?;
1173    let currency = get_currency(&execution.fee_currency);
1174    let commission = Money::from_decimal(fee_decimal, currency).with_context(|| {
1175        format!(
1176            "Failed to create commission from execFee='{}'",
1177            execution.exec_fee
1178        )
1179    })?;
1180
1181    // Determine liquidity side from is_maker flag
1182    let liquidity_side = if execution.is_maker {
1183        LiquiditySide::Maker
1184    } else {
1185        LiquiditySide::Taker
1186    };
1187
1188    let ts_event = parse_millis_timestamp(&execution.exec_time, "execution.execTime")?;
1189
1190    // Parse client_order_id if present
1191    let client_order_id = if execution.order_link_id.is_empty() {
1192        None
1193    } else {
1194        Some(ClientOrderId::new(execution.order_link_id))
1195    };
1196
1197    Ok(FillReport::new(
1198        account_id,
1199        instrument_id,
1200        venue_order_id,
1201        trade_id,
1202        order_side,
1203        last_qty,
1204        last_px,
1205        commission,
1206        liquidity_side,
1207        client_order_id,
1208        None, // venue_position_id: execution data lacks position_idx
1209        ts_event,
1210        ts_init,
1211        None, // Will generate a new UUID4
1212    ))
1213}
1214
1215/// Parses a Bybit position into a Nautilus PositionStatusReport.
1216///
1217/// # Errors
1218///
1219/// Returns an error if:
1220/// - Position quantity or price fields cannot be parsed.
1221/// - The position timestamp cannot be parsed.
1222/// - Numeric conversions fail.
1223pub fn parse_position_status_report(
1224    position: &BybitPosition,
1225    account_id: AccountId,
1226    instrument: &InstrumentAny,
1227    ts_init: UnixNanos,
1228) -> anyhow::Result<PositionStatusReport> {
1229    let instrument_id = instrument.id();
1230
1231    let size = parse_quantity_with_precision(
1232        &position.size,
1233        instrument.size_precision(),
1234        "position.size",
1235    )?;
1236
1237    // Determine position side and quantity
1238    let (position_side, quantity) = match position.side {
1239        BybitPositionSide::Buy => (PositionSide::Long, size),
1240        BybitPositionSide::Sell => (PositionSide::Short, size),
1241        BybitPositionSide::Flat => {
1242            let qty = Quantity::zero(instrument.size_precision());
1243            (PositionSide::Flat, qty)
1244        }
1245    };
1246
1247    // Parse average entry price
1248    let avg_px_open = if position.avg_price.is_empty() || position.avg_price == "0" {
1249        None
1250    } else {
1251        Some(Decimal::from_str(&position.avg_price)?)
1252    };
1253
1254    // Use ts_init if updatedTime is empty (initial/flat positions)
1255    let ts_last = if position.updated_time.is_empty() {
1256        ts_init
1257    } else {
1258        parse_millis_timestamp(&position.updated_time, "position.updatedTime")?
1259    };
1260
1261    // Bybit ranks open positions 1-5 by ADL priority (5 = next to be deleveraged);
1262    // 0 means the account has no open position or is flat.
1263    if position.adl_rank_indicator >= 4 {
1264        log::warn!(
1265            "Elevated ADL risk: {} position size={} adl_rank={}",
1266            instrument_id,
1267            position.size,
1268            position.adl_rank_indicator,
1269        );
1270    }
1271
1272    let venue_position_id =
1273        make_hedge_venue_position_id(instrument_id, position.position_idx as i32);
1274
1275    Ok(PositionStatusReport::new(
1276        account_id,
1277        instrument_id,
1278        position_side,
1279        quantity,
1280        ts_last,
1281        ts_init,
1282        None, // Will generate a new UUID4
1283        venue_position_id,
1284        avg_px_open,
1285    ))
1286}
1287
1288/// Parses a Bybit wallet balance into a Nautilus account state.
1289///
1290/// # Errors
1291///
1292/// Returns an error if:
1293/// - Balance data cannot be parsed.
1294/// - Currency is invalid.
1295pub fn parse_account_state(
1296    wallet_balance: &BybitWalletBalance,
1297    account_id: AccountId,
1298    ts_init: UnixNanos,
1299) -> anyhow::Result<AccountState> {
1300    let mut balances = Vec::new();
1301
1302    for coin in &wallet_balance.coin {
1303        let total_dec = coin.wallet_balance - coin.spot_borrow;
1304        let locked_dec = coin.locked;
1305
1306        let currency = get_currency(&coin.coin);
1307        balances.push(AccountBalance::from_total_and_locked(
1308            total_dec, locked_dec, currency,
1309        )?);
1310    }
1311
1312    let mut margins = Vec::new();
1313
1314    for coin in &wallet_balance.coin {
1315        // Position IM is reserved against open positions; order IM is reserved against
1316        // pending orders. Sum both so an account that only has open orders still
1317        // reports a non-zero initial margin.
1318        let position_im_dec = match &coin.total_position_im {
1319            Some(im) if !im.is_empty() => decimal::parse(im).context("invalid totalPositionIM")?,
1320            _ => Decimal::ZERO,
1321        };
1322
1323        let order_im_dec = match &coin.total_order_im {
1324            Some(im) if !im.is_empty() => decimal::parse(im).context("invalid totalOrderIM")?,
1325            _ => Decimal::ZERO,
1326        };
1327
1328        let initial_margin_dec = position_im_dec
1329            .checked_add(order_im_dec)
1330            .context("initial margin overflowed")?;
1331
1332        let maintenance_margin_dec = match &coin.total_position_mm {
1333            Some(mm) if !mm.is_empty() => decimal::parse(mm).context("invalid totalPositionMM")?,
1334            _ => Decimal::ZERO,
1335        };
1336
1337        anyhow::ensure!(
1338            position_im_dec >= Decimal::ZERO
1339                && order_im_dec >= Decimal::ZERO
1340                && maintenance_margin_dec >= Decimal::ZERO,
1341            "margin must be non-negative"
1342        );
1343
1344        if initial_margin_dec.is_zero() && maintenance_margin_dec.is_zero() {
1345            continue;
1346        }
1347
1348        let currency = get_currency(&coin.coin);
1349        let initial_margin = Money::from_decimal(initial_margin_dec, currency)?;
1350        let maintenance_margin = Money::from_decimal(maintenance_margin_dec, currency)?;
1351
1352        margins.push(MarginBalance::new(initial_margin, maintenance_margin, None));
1353    }
1354
1355    let account_type = AccountType::Margin;
1356    let is_reported = true;
1357    let event_id = UUID4::new();
1358
1359    // Use current time as ts_event since Bybit doesn't provide this in wallet balance
1360    let ts_event = ts_init;
1361
1362    Ok(AccountState::new(
1363        account_id,
1364        account_type,
1365        balances,
1366        margins,
1367        is_reported,
1368        event_id,
1369        ts_event,
1370        ts_init,
1371        None,
1372    ))
1373}
1374
1375pub(crate) fn parse_price_with_precision(
1376    value: &str,
1377    precision: u8,
1378    field: &str,
1379) -> anyhow::Result<Price> {
1380    let parsed = parse_decimal(value, field)?;
1381    Price::from_decimal_dp(parsed, precision).with_context(|| {
1382        format!("Failed to construct Price for {field} with precision {precision}")
1383    })
1384}
1385
1386pub(crate) fn parse_quantity_with_precision(
1387    value: &str,
1388    precision: u8,
1389    field: &str,
1390) -> anyhow::Result<Quantity> {
1391    let parsed = parse_decimal(value, field)?;
1392    Quantity::from_decimal_dp(parsed, precision).with_context(|| {
1393        format!("Failed to construct Quantity for {field} with precision {precision}")
1394    })
1395}
1396
1397pub(crate) fn parse_price(value: &str, field: &str) -> anyhow::Result<Price> {
1398    Price::from_str(value).map_err(|e| anyhow::anyhow!("Failed to parse {field}='{value}': {e}"))
1399}
1400
1401pub(crate) fn parse_quantity(value: &str, field: &str) -> anyhow::Result<Quantity> {
1402    Quantity::from_str(value).map_err(|e| anyhow::anyhow!("Failed to parse {field}='{value}': {e}"))
1403}
1404
1405/// Parses an order size limit, returning `None` when it exceeds [`QUANTITY_MAX`].
1406pub(crate) fn parse_max_quantity(value: &str, field: &str) -> anyhow::Result<Option<Quantity>> {
1407    if parse_decimal(value, field)? > Decimal::try_from(QUANTITY_MAX)? {
1408        return Ok(None);
1409    }
1410
1411    parse_quantity(value, field).map(Some)
1412}
1413
1414pub(crate) fn parse_decimal(value: &str, field: &str) -> anyhow::Result<Decimal> {
1415    Decimal::from_str(value)
1416        .map_err(|e| anyhow::anyhow!("Failed to parse {field}='{value}' as Decimal: {e}"))
1417}
1418
1419pub(crate) fn parse_millis_timestamp(value: &str, field: &str) -> anyhow::Result<UnixNanos> {
1420    let millis: u64 = value
1421        .parse()
1422        .with_context(|| format!("Failed to parse {field}='{value}' as u64 millis"))?;
1423    let nanos = millis
1424        .checked_mul(NANOSECONDS_IN_MILLISECOND)
1425        .context("millisecond timestamp overflowed when converting to nanoseconds")?;
1426    Ok(UnixNanos::from(nanos))
1427}
1428
1429fn resolve_settlement_currency(
1430    settle_coin: &str,
1431    base_currency: Currency,
1432    quote_currency: Currency,
1433) -> anyhow::Result<Currency> {
1434    if settle_coin.eq_ignore_ascii_case(base_currency.code.as_str()) {
1435        Ok(base_currency)
1436    } else if settle_coin.eq_ignore_ascii_case(quote_currency.code.as_str()) {
1437        Ok(quote_currency)
1438    } else {
1439        Err(anyhow::anyhow!(
1440            "unrecognized settlement currency '{settle_coin}'"
1441        ))
1442    }
1443}
1444
1445/// Returns a currency from the internal map or creates a new crypto currency.
1446///
1447/// Uses [`Currency::get_or_create_crypto`] to handle unknown currency codes,
1448/// which automatically registers newly listed Bybit assets.
1449pub fn get_currency(code: &str) -> Currency {
1450    Currency::get_or_create_crypto(code)
1451}
1452
1453fn extract_strike_from_symbol(symbol: &str) -> anyhow::Result<Price> {
1454    let parts: Vec<&str> = symbol.split('-').collect();
1455    let strike = parts
1456        .get(2)
1457        .ok_or_else(|| anyhow::anyhow!("invalid option symbol '{symbol}'"))?;
1458    parse_price(strike, "option strike")
1459}
1460
1461/// Resolves a Nautilus [`OrderType`] from Bybit order classification fields.
1462///
1463/// Bybit represents conditional orders using a combination of `orderType` (Market/Limit),
1464/// `stopOrderType` (Stop, TakeProfit, StopLoss, etc.), `triggerDirection` (RisesTo/FallsTo),
1465/// and `side` (Buy/Sell). This function maps all combinations to the appropriate Nautilus
1466/// conditional order types.
1467///
1468/// When `triggerDirection` is `None`, the stop order type is informational only (a parent
1469/// order with TP/SL metadata attached), so the order is classified as plain Market/Limit.
1470#[must_use]
1471pub fn parse_bybit_order_type(
1472    order_type: BybitOrderType,
1473    stop_order_type: BybitStopOrderType,
1474    trigger_direction: BybitTriggerDirection,
1475    side: BybitOrderSide,
1476) -> OrderType {
1477    if matches!(
1478        stop_order_type,
1479        BybitStopOrderType::None | BybitStopOrderType::Unknown
1480    ) {
1481        return match order_type {
1482            BybitOrderType::Market => OrderType::Market,
1483            BybitOrderType::Limit | BybitOrderType::Unknown => OrderType::Limit,
1484        };
1485    }
1486
1487    // No trigger direction means TP/SL metadata on a parent order,
1488    // not a standalone conditional
1489    if trigger_direction == BybitTriggerDirection::None {
1490        return match order_type {
1491            BybitOrderType::Market => OrderType::Market,
1492            BybitOrderType::Limit | BybitOrderType::Unknown => OrderType::Limit,
1493        };
1494    }
1495
1496    // TrailingStop maps to StopMarket/StopLimit because Bybit does not
1497    // provide the trailing offset fields needed for the dedicated types.
1498    match (order_type, trigger_direction, side) {
1499        (BybitOrderType::Market, BybitTriggerDirection::RisesTo, BybitOrderSide::Buy) => {
1500            OrderType::StopMarket
1501        }
1502        (BybitOrderType::Market, BybitTriggerDirection::FallsTo, BybitOrderSide::Buy) => {
1503            OrderType::MarketIfTouched
1504        }
1505        (BybitOrderType::Market, BybitTriggerDirection::FallsTo, BybitOrderSide::Sell) => {
1506            OrderType::StopMarket
1507        }
1508        (BybitOrderType::Market, BybitTriggerDirection::RisesTo, BybitOrderSide::Sell) => {
1509            OrderType::MarketIfTouched
1510        }
1511        (BybitOrderType::Limit, BybitTriggerDirection::RisesTo, BybitOrderSide::Buy) => {
1512            OrderType::StopLimit
1513        }
1514        (BybitOrderType::Limit, BybitTriggerDirection::FallsTo, BybitOrderSide::Buy) => {
1515            OrderType::LimitIfTouched
1516        }
1517        (BybitOrderType::Limit, BybitTriggerDirection::FallsTo, BybitOrderSide::Sell) => {
1518            OrderType::StopLimit
1519        }
1520        (BybitOrderType::Limit, BybitTriggerDirection::RisesTo, BybitOrderSide::Sell) => {
1521            OrderType::LimitIfTouched
1522        }
1523        _ => match order_type {
1524            BybitOrderType::Market => OrderType::Market,
1525            BybitOrderType::Limit | BybitOrderType::Unknown => OrderType::Limit,
1526        },
1527    }
1528}
1529
1530/// Parses a Bybit order into a Nautilus OrderStatusReport.
1531///
1532/// Copies a venue `rejectReason` into `cancel_reason`, except `EC_NoError`. When the mapped
1533/// status is `Rejected` and `rejectReason` is empty or `EC_NoError`, the reason is
1534/// `venue omitted rejectReason`.
1535pub fn parse_order_status_report(
1536    order: &crate::http::models::BybitOrder,
1537    instrument: &InstrumentAny,
1538    account_id: AccountId,
1539    ts_init: UnixNanos,
1540) -> anyhow::Result<OrderStatusReport> {
1541    let instrument_id = instrument.id();
1542    let venue_order_id = VenueOrderId::new(order.order_id);
1543
1544    let order_side: Option<OrderSide> = order.side.into();
1545
1546    let order_type = parse_bybit_order_type(
1547        order.order_type,
1548        order.stop_order_type,
1549        order.trigger_direction,
1550        order.side,
1551    );
1552
1553    let time_in_force: TimeInForce = match order.time_in_force {
1554        BybitTimeInForce::Gtc => TimeInForce::Gtc,
1555        BybitTimeInForce::Ioc => TimeInForce::Ioc,
1556        BybitTimeInForce::Fok => TimeInForce::Fok,
1557        BybitTimeInForce::PostOnly | BybitTimeInForce::Rpi => TimeInForce::Gtc,
1558    };
1559
1560    let quantity =
1561        parse_quantity_with_precision(&order.qty, instrument.size_precision(), "order.qty")?;
1562
1563    let filled_qty = parse_quantity_with_precision(
1564        &order.cum_exec_qty,
1565        instrument.size_precision(),
1566        "order.cumExecQty",
1567    )?;
1568
1569    // Map Bybit order status to Nautilus order status
1570    // Special case: if Bybit reports "Rejected" but the order has fills, treat it as Canceled.
1571    // This handles the case where the exchange partially fills an order then rejects the
1572    // remaining quantity (e.g., due to margin, risk limits, or liquidity constraints).
1573    // The state machine does not allow PARTIALLY_FILLED -> REJECTED transitions.
1574    let order_status: OrderStatus = match order.order_status {
1575        BybitOrderStatus::Created | BybitOrderStatus::New | BybitOrderStatus::Untriggered => {
1576            OrderStatus::Accepted
1577        }
1578        BybitOrderStatus::Rejected => {
1579            if filled_qty.is_positive() {
1580                OrderStatus::Canceled
1581            } else {
1582                OrderStatus::Rejected
1583            }
1584        }
1585        BybitOrderStatus::PartiallyFilled => OrderStatus::PartiallyFilled,
1586        BybitOrderStatus::Filled => OrderStatus::Filled,
1587        // A post-only order that would take liquidity is reported as Cancelled with
1588        // rejectReason=EC_PostOnlyWillTakeLiquidity (not Rejected). Surface it as Rejected
1589        // for consistency with the tracked-order event path.
1590        BybitOrderStatus::Canceled
1591            if filled_qty.is_zero()
1592                && bybit_rejection_due_post_only(order.reject_reason.as_str()) =>
1593        {
1594            OrderStatus::Rejected
1595        }
1596        BybitOrderStatus::Canceled | BybitOrderStatus::PartiallyFilledCanceled => {
1597            OrderStatus::Canceled
1598        }
1599        BybitOrderStatus::Triggered => OrderStatus::Triggered,
1600        BybitOrderStatus::Deactivated => OrderStatus::Canceled,
1601    };
1602
1603    let ts_accepted = parse_millis_timestamp(&order.created_time, "order.createdTime")?;
1604    let ts_last = parse_millis_timestamp(&order.updated_time, "order.updatedTime")?;
1605
1606    let mut report = OrderStatusReport::new(
1607        account_id,
1608        instrument_id,
1609        None,
1610        venue_order_id,
1611        order_side,
1612        order_type,
1613        time_in_force,
1614        order_status,
1615        quantity,
1616        filled_qty,
1617        ts_accepted,
1618        ts_last,
1619        ts_init,
1620        Some(UUID4::new()),
1621    );
1622
1623    if !order.order_link_id.is_empty() {
1624        report = report.with_client_order_id(ClientOrderId::new(order.order_link_id));
1625    }
1626
1627    if !order.price.is_empty() && order.price != "0" {
1628        let price =
1629            parse_price_with_precision(&order.price, instrument.price_precision(), "order.price")?;
1630        report = report.with_price(price);
1631    }
1632
1633    if let Some(avg_price) = &order.avg_price
1634        && !avg_price.is_empty()
1635        && avg_price != "0"
1636    {
1637        let avg_px = avg_price
1638            .parse::<Decimal>()
1639            .with_context(|| format!("Failed to parse avg_price='{avg_price}' as Decimal"))?;
1640        report = report.with_avg_px(avg_px);
1641    }
1642
1643    if !order.trigger_price.is_empty() && order.trigger_price != "0" {
1644        let trigger_price = parse_price_with_precision(
1645            &order.trigger_price,
1646            instrument.price_precision(),
1647            "order.triggerPrice",
1648        )?;
1649        report = report.with_trigger_price(trigger_price);
1650
1651        // Set trigger_type for conditional orders
1652        let trigger_type: TriggerType = order.trigger_by.into();
1653        report = report.with_trigger_type(trigger_type);
1654    }
1655
1656    if let Some(venue_position_id) = make_hedge_venue_position_id(instrument_id, order.position_idx)
1657    {
1658        report = report.with_venue_position_id(venue_position_id);
1659    }
1660
1661    if order.reduce_only {
1662        report = report.with_reduce_only(true);
1663    }
1664
1665    if matches!(
1666        order.time_in_force,
1667        BybitTimeInForce::PostOnly | BybitTimeInForce::Rpi
1668    ) {
1669        report = report.with_post_only(true);
1670    }
1671
1672    let reject_reason = order.reject_reason.as_str();
1673    let report = report_with_reject_reason(report, reject_reason, order_status);
1674
1675    Ok(report)
1676}
1677
1678fn report_with_reject_reason(
1679    report: OrderStatusReport,
1680    reject_reason: &str,
1681    order_status: OrderStatus,
1682) -> OrderStatusReport {
1683    if !reject_reason.is_empty() && reject_reason != "EC_NoError" {
1684        report.with_cancel_reason(reject_reason.to_string())
1685    } else if order_status == OrderStatus::Rejected {
1686        // Reconciliation substitutes UNKNOWN when cancel_reason is absent
1687        report.with_cancel_reason("venue omitted rejectReason".to_string())
1688    } else {
1689        report
1690    }
1691}
1692
1693/// Returns the `marketUnit` parameter for spot market orders.
1694#[must_use]
1695pub fn spot_market_unit(
1696    product_type: BybitProductType,
1697    order_type: BybitOrderType,
1698    is_quote_quantity: bool,
1699) -> Option<BybitMarketUnit> {
1700    if product_type == BybitProductType::Spot && order_type == BybitOrderType::Market {
1701        if is_quote_quantity {
1702            Some(BybitMarketUnit::QuoteCoin)
1703        } else {
1704            Some(BybitMarketUnit::BaseCoin)
1705        }
1706    } else {
1707        None
1708    }
1709}
1710
1711/// Returns the `isLeverage` parameter (spot-only).
1712#[must_use]
1713pub fn spot_leverage(product_type: BybitProductType, is_leverage: bool) -> Option<i32> {
1714    if product_type == BybitProductType::Spot {
1715        Some(i32::from(is_leverage))
1716    } else {
1717        None
1718    }
1719}
1720
1721/// Returns the trigger direction for stop and MIT orders.
1722#[must_use]
1723pub fn trigger_direction(
1724    order_type: OrderType,
1725    order_side: OrderSide,
1726    is_stop_order: bool,
1727) -> Option<BybitTriggerDirection> {
1728    if !is_stop_order {
1729        return None;
1730    }
1731
1732    match (order_type, order_side) {
1733        (OrderType::StopMarket | OrderType::StopLimit, OrderSide::Buy) => {
1734            Some(BybitTriggerDirection::RisesTo)
1735        }
1736        (OrderType::StopMarket | OrderType::StopLimit, OrderSide::Sell) => {
1737            Some(BybitTriggerDirection::FallsTo)
1738        }
1739        (OrderType::MarketIfTouched | OrderType::LimitIfTouched, OrderSide::Buy) => {
1740            Some(BybitTriggerDirection::FallsTo)
1741        }
1742        (OrderType::MarketIfTouched | OrderType::LimitIfTouched, OrderSide::Sell) => {
1743            Some(BybitTriggerDirection::RisesTo)
1744        }
1745        _ => None,
1746    }
1747}
1748
1749/// Maps Nautilus time-in-force to Bybit's TIF.
1750///
1751/// GTD maps to GTC. Market orders omit TIF; post-only limit orders use `PostOnly`.
1752///
1753/// # Errors
1754///
1755/// Returns an error if the time in force is unsupported, including for market and post-only orders.
1756/// The error contains the unsupported value.
1757pub fn map_time_in_force(
1758    order_type: BybitOrderType,
1759    time_in_force: Option<TimeInForce>,
1760    post_only: Option<bool>,
1761) -> Result<Option<BybitTimeInForce>, TimeInForce> {
1762    let mapped = match time_in_force {
1763        Some(TimeInForce::Gtc | TimeInForce::Gtd) => Some(BybitTimeInForce::Gtc),
1764        Some(TimeInForce::Ioc) => Some(BybitTimeInForce::Ioc),
1765        Some(TimeInForce::Fok) => Some(BybitTimeInForce::Fok),
1766        Some(tif) => return Err(tif),
1767        None => None,
1768    };
1769
1770    if order_type == BybitOrderType::Market {
1771        return Ok(None);
1772    }
1773
1774    if post_only == Some(true) {
1775        return Ok(Some(BybitTimeInForce::PostOnly));
1776    }
1777
1778    Ok(mapped)
1779}
1780
1781/// Converts an optional `UnixNanos` timestamp to optional milliseconds.
1782pub fn nanos_to_millis(value: Option<UnixNanos>) -> Option<i64> {
1783    value.map(|nanos| nanos_to_millis_u64(nanos.as_u64()) as i64)
1784}
1785
1786/// Parsed and validated Bybit TP/SL parameters from a `SubmitOrder.params` map.
1787#[derive(Debug, Default)]
1788pub struct BybitTpSlParams {
1789    pub take_profit: Option<Price>,
1790    pub stop_loss: Option<Price>,
1791    pub tp_trigger_by: Option<BybitTriggerType>,
1792    pub sl_trigger_by: Option<BybitTriggerType>,
1793    pub tp_order_type: Option<BybitOrderType>,
1794    pub sl_order_type: Option<BybitOrderType>,
1795    pub tp_limit_price: Option<String>,
1796    pub sl_limit_price: Option<String>,
1797    pub tp_trigger_price: Option<String>,
1798    pub sl_trigger_price: Option<String>,
1799    pub tpsl_mode: Option<BybitTpSlMode>,
1800    pub close_on_trigger: Option<bool>,
1801    pub is_leverage: bool,
1802    pub order_iv: Option<String>,
1803    pub mmp: Option<bool>,
1804    pub smp_type: Option<BybitOrderSmpType>,
1805    pub position_idx: Option<BybitPositionIdx>,
1806    pub bbo_side_type: Option<BybitBboSideType>,
1807    pub bbo_level: Option<String>,
1808}
1809
1810impl BybitTpSlParams {
1811    pub fn has_tp_sl(&self) -> bool {
1812        self.take_profit.is_some() || self.stop_loss.is_some()
1813    }
1814
1815    pub fn has_bbo(&self) -> bool {
1816        self.bbo_side_type.is_some()
1817    }
1818
1819    /// Projects the native TP/SL and option fields onto the bundle the HTTP `submit_order` entry
1820    /// expects. BBO, `position_idx`, `smp_type`, and leverage stay separate because they are
1821    /// already first-class arguments on the `submit_order` signature.
1822    #[must_use]
1823    pub fn to_native_tp_sl(&self) -> BybitNativeTpSlParams {
1824        BybitNativeTpSlParams {
1825            take_profit: self.take_profit.map(|p| p.to_string()),
1826            stop_loss: self.stop_loss.map(|p| p.to_string()),
1827            tp_trigger_by: self.tp_trigger_by,
1828            sl_trigger_by: self.sl_trigger_by,
1829            tp_order_type: self.tp_order_type,
1830            sl_order_type: self.sl_order_type,
1831            tp_limit_price: self.tp_limit_price.clone(),
1832            sl_limit_price: self.sl_limit_price.clone(),
1833            tpsl_mode: self.tpsl_mode,
1834            close_on_trigger: self.close_on_trigger,
1835            order_iv: self.order_iv.clone(),
1836            mmp: self.mmp,
1837        }
1838    }
1839}
1840
1841/// Extracts a string value from params, accepting both string and numeric JSON values.
1842pub fn get_price_str(params: &Params, key: &str) -> Option<String> {
1843    let value = params.get(key)?;
1844    if let Some(s) = value.as_str() {
1845        Some(s.to_string())
1846    } else {
1847        let raw = value.as_number()?.to_string();
1848
1849        if raw.contains('e')
1850            && let Ok(number) = decimal::parse(&raw)
1851        {
1852            return Some(number.to_string());
1853        }
1854
1855        Some(raw)
1856    }
1857}
1858
1859/// Parses a Bybit margin action from a `query_account` parameter, accepting the
1860/// `BybitMarginAction` enum's snake_case and Python variant spellings.
1861#[must_use]
1862pub fn parse_margin_action(s: &str) -> Option<BybitMarginAction> {
1863    match s.to_ascii_lowercase().as_str() {
1864        "borrow" => Some(BybitMarginAction::Borrow),
1865        "repay" => Some(BybitMarginAction::Repay),
1866        "get_borrow_amount" => Some(BybitMarginAction::GetBorrowAmount),
1867        _ => None,
1868    }
1869}
1870
1871/// Parses a Bybit self-match prevention type from an order parameter or configuration value.
1872///
1873/// # Errors
1874///
1875/// Returns an error if the value falls outside the four types Bybit accepts on an order.
1876pub fn parse_smp_type(s: &str) -> anyhow::Result<BybitOrderSmpType> {
1877    match s.to_ascii_lowercase().as_str() {
1878        "none" => Ok(BybitOrderSmpType::None),
1879        "cancelmaker" => Ok(BybitOrderSmpType::CancelMaker),
1880        "canceltaker" => Ok(BybitOrderSmpType::CancelTaker),
1881        "cancelboth" => Ok(BybitOrderSmpType::CancelBoth),
1882        _ => anyhow::bail!(
1883            "invalid Bybit smp_type: '{s}', expected None, CancelMaker, CancelTaker, or CancelBoth"
1884        ),
1885    }
1886}
1887
1888/// Deserializes an optional self-match prevention type for a client configuration.
1889///
1890/// Routes the configured text through [`parse_smp_type`] so a serialized config reports an unknown
1891/// value instead of carrying it silently.
1892///
1893/// # Errors
1894///
1895/// Returns an error if the value falls outside the four types Bybit accepts on an order.
1896pub fn deserialize_optional_smp_type<'de, D: serde::Deserializer<'de>>(
1897    d: D,
1898) -> Result<Option<BybitOrderSmpType>, D::Error> {
1899    let Some(value) = Option::<String>::deserialize(d)? else {
1900        return Ok(None);
1901    };
1902
1903    parse_smp_type(&value).map(Some).map_err(D::Error::custom)
1904}
1905
1906pub fn parse_bbo_side_type(s: &str) -> anyhow::Result<BybitBboSideType> {
1907    match s.to_ascii_lowercase().as_str() {
1908        "queue" => Ok(BybitBboSideType::Queue),
1909        "counterparty" => Ok(BybitBboSideType::Counterparty),
1910        _ => anyhow::bail!("invalid Bybit bbo_side_type: '{s}', expected Queue or Counterparty"),
1911    }
1912}
1913
1914pub fn parse_bbo_level(s: String) -> anyhow::Result<String> {
1915    match s.as_str() {
1916        "1" | "2" | "3" | "4" | "5" => Ok(s),
1917        _ => anyhow::bail!("invalid 'bbo_level': '{s}', expected 1, 2, 3, 4, or 5"),
1918    }
1919}
1920
1921/// Parses Bybit TP/SL parameters from an optional params map.
1922pub fn parse_bybit_tp_sl_params(params: Option<&Params>) -> anyhow::Result<BybitTpSlParams> {
1923    let Some(params) = params else {
1924        return Ok(BybitTpSlParams::default());
1925    };
1926
1927    let mut result = BybitTpSlParams {
1928        is_leverage: params.get_bool("is_leverage").unwrap_or(false),
1929        ..Default::default()
1930    };
1931
1932    if let Some(s) = get_price_str(params, "take_profit") {
1933        let p =
1934            Price::from_str(&s).map_err(|e| anyhow::anyhow!("invalid 'take_profit' price: {e}"))?;
1935
1936        if p.as_decimal() < Decimal::ZERO {
1937            anyhow::bail!("invalid 'take_profit' price: '{s}', expected a non-negative value");
1938        }
1939        result.take_profit = Some(p);
1940    }
1941
1942    if let Some(s) = get_price_str(params, "stop_loss") {
1943        let p =
1944            Price::from_str(&s).map_err(|e| anyhow::anyhow!("invalid 'stop_loss' price: {e}"))?;
1945
1946        if p.as_decimal() < Decimal::ZERO {
1947            anyhow::bail!("invalid 'stop_loss' price: '{s}', expected a non-negative value");
1948        }
1949        result.stop_loss = Some(p);
1950    }
1951
1952    for (key, setter) in [
1953        (
1954            "tp_limit_price",
1955            &mut result.tp_limit_price as &mut Option<String>,
1956        ),
1957        ("sl_limit_price", &mut result.sl_limit_price),
1958        ("tp_trigger_price", &mut result.tp_trigger_price),
1959        ("sl_trigger_price", &mut result.sl_trigger_price),
1960    ] {
1961        if let Some(s) = get_price_str(params, key) {
1962            let v =
1963                decimal::parse(&s).with_context(|| format!("invalid price for '{key}': '{s}'"))?;
1964
1965            if s.contains('_') || v < Decimal::ZERO {
1966                anyhow::bail!(
1967                    "invalid price for '{key}': '{s}', expected a finite non-negative number"
1968                );
1969            }
1970            *setter = Some(s);
1971        }
1972    }
1973
1974    if let Some(s) = params.get_str("tp_trigger_by") {
1975        result.tp_trigger_by = Some(parse_trigger_type(s)?);
1976    }
1977
1978    if let Some(s) = params.get_str("sl_trigger_by") {
1979        result.sl_trigger_by = Some(parse_trigger_type(s)?);
1980    }
1981
1982    if let Some(s) = params.get_str("tp_order_type") {
1983        result.tp_order_type = Some(parse_tp_sl_order_type(s)?);
1984    }
1985
1986    if let Some(s) = params.get_str("sl_order_type") {
1987        result.sl_order_type = Some(parse_tp_sl_order_type(s)?);
1988    }
1989
1990    if let Some(s) = params.get_str("tpsl_mode") {
1991        result.tpsl_mode = Some(parse_tpsl_mode(s)?);
1992    }
1993
1994    let has_tp_fields = result.tp_trigger_by.is_some()
1995        || result.tp_order_type.is_some()
1996        || result.tp_limit_price.is_some()
1997        || result.tp_trigger_price.is_some();
1998
1999    let has_sl_fields = result.sl_trigger_by.is_some()
2000        || result.sl_order_type.is_some()
2001        || result.sl_limit_price.is_some()
2002        || result.sl_trigger_price.is_some();
2003
2004    if result.take_profit.is_none() && has_tp_fields {
2005        anyhow::bail!("TP override fields require 'take_profit' to be set");
2006    }
2007
2008    if result.stop_loss.is_none() && has_sl_fields {
2009        anyhow::bail!("SL override fields require 'stop_loss' to be set");
2010    }
2011
2012    if result.tp_order_type == Some(BybitOrderType::Limit) && result.tp_limit_price.is_none() {
2013        anyhow::bail!("'tp_order_type' is 'Limit' but 'tp_limit_price' was not provided");
2014    }
2015
2016    if result.sl_order_type == Some(BybitOrderType::Limit) && result.sl_limit_price.is_none() {
2017        anyhow::bail!("'sl_order_type' is 'Limit' but 'sl_limit_price' was not provided");
2018    }
2019
2020    if result.tp_limit_price.is_some() && result.tp_order_type != Some(BybitOrderType::Limit) {
2021        anyhow::bail!("'tp_limit_price' requires 'tp_order_type' to be 'Limit'");
2022    }
2023
2024    if result.sl_limit_price.is_some() && result.sl_order_type != Some(BybitOrderType::Limit) {
2025        anyhow::bail!("'sl_limit_price' requires 'sl_order_type' to be 'Limit'");
2026    }
2027
2028    result.close_on_trigger = params.get_bool("close_on_trigger");
2029
2030    if let Some(value) = params.get("order_iv") {
2031        match get_price_str(params, "order_iv") {
2032            Some(s) => result.order_iv = Some(s),
2033            None => {
2034                anyhow::bail!("invalid type for 'order_iv': {value}, expected string or number")
2035            }
2036        }
2037    }
2038
2039    if let Some(value) = params.get("mmp") {
2040        match value.as_bool() {
2041            Some(b) => result.mmp = Some(b),
2042            None => anyhow::bail!("invalid type for 'mmp': {value}, expected bool"),
2043        }
2044    }
2045
2046    if let Some(value) = params.get("smp_type") {
2047        let smp_type = value.as_str().ok_or_else(|| {
2048            anyhow::anyhow!("invalid type for 'smp_type': {value}, expected string")
2049        })?;
2050        result.smp_type = Some(parse_smp_type(smp_type)?);
2051    }
2052
2053    if let Some(value) = params.get("position_idx") {
2054        let idx = value.as_i64().ok_or_else(|| {
2055            anyhow::anyhow!("invalid type for 'position_idx': {value}, expected integer")
2056        })?;
2057        result.position_idx = Some(match idx {
2058            0 => BybitPositionIdx::OneWay,
2059            1 => BybitPositionIdx::BuyHedge,
2060            2 => BybitPositionIdx::SellHedge,
2061            _ => anyhow::bail!("invalid 'position_idx': {idx}, expected 0, 1, or 2"),
2062        });
2063    }
2064
2065    let has_bbo_side_type = params.get("bbo_side_type").is_some();
2066    let has_bbo_level = params.get("bbo_level").is_some();
2067
2068    if has_bbo_side_type != has_bbo_level {
2069        anyhow::bail!("'bbo_side_type' and 'bbo_level' must be provided together");
2070    }
2071
2072    if let Some(value) = params.get("bbo_side_type") {
2073        let side_type = value.as_str().ok_or_else(|| {
2074            anyhow::anyhow!("invalid type for 'bbo_side_type': {value}, expected string")
2075        })?;
2076        result.bbo_side_type = Some(parse_bbo_side_type(side_type)?);
2077    }
2078
2079    if let Some(value) = params.get("bbo_level") {
2080        let level = if let Some(s) = value.as_str() {
2081            s.to_string()
2082        } else if let Some(i) = value.as_i64() {
2083            i.to_string()
2084        } else if let Some(u) = value.as_u64() {
2085            u.to_string()
2086        } else {
2087            anyhow::bail!("invalid type for 'bbo_level': {value}, expected string or integer");
2088        };
2089        result.bbo_level = Some(parse_bbo_level(level)?);
2090    }
2091
2092    Ok(result)
2093}
2094
2095pub(crate) fn parse_trigger_type(s: &str) -> anyhow::Result<BybitTriggerType> {
2096    match s {
2097        "LastPrice" => Ok(BybitTriggerType::LastPrice),
2098        "MarkPrice" => Ok(BybitTriggerType::MarkPrice),
2099        "IndexPrice" => Ok(BybitTriggerType::IndexPrice),
2100        _ => anyhow::bail!(
2101            "invalid Bybit trigger type: '{s}', expected LastPrice, MarkPrice, or IndexPrice"
2102        ),
2103    }
2104}
2105
2106pub(crate) fn parse_tp_sl_order_type(s: &str) -> anyhow::Result<BybitOrderType> {
2107    match s {
2108        "Market" => Ok(BybitOrderType::Market),
2109        "Limit" => Ok(BybitOrderType::Limit),
2110        _ => anyhow::bail!("invalid Bybit TP/SL order type: '{s}', expected Market or Limit"),
2111    }
2112}
2113
2114// A plain `serde_json` deserialize would accept unknown strings: `BybitTpSlMode` carries a
2115// `#[serde(other)] Unknown` variant, so garbage would silently map to `Unknown`.
2116pub(crate) fn parse_tpsl_mode(s: &str) -> anyhow::Result<BybitTpSlMode> {
2117    match s {
2118        "Full" => Ok(BybitTpSlMode::Full),
2119        "Partial" => Ok(BybitTpSlMode::Partial),
2120        _ => anyhow::bail!("invalid Bybit TP/SL mode: '{s}', expected Full or Partial"),
2121    }
2122}
2123
2124#[cfg(test)]
2125mod tests {
2126    use nautilus_model::{
2127        data::BarSpecification,
2128        enums::{AggregationSource, BarAggregation, PositionSide, PriceType},
2129        orders::OrderAny,
2130    };
2131    use rstest::rstest;
2132    use rust_decimal_macros::dec;
2133    use serde_json::json;
2134
2135    use super::*;
2136    use crate::{
2137        common::{
2138            enums::{
2139                BybitExecType, BybitOrderSide, BybitOrderType, BybitStopOrderType,
2140                BybitTriggerDirection,
2141            },
2142            testing::load_test_json,
2143        },
2144        http::models::{
2145            BybitInstrumentInverseResponse, BybitInstrumentLinearResponse,
2146            BybitInstrumentOptionResponse, BybitInstrumentSpotResponse, BybitKlinesResponse,
2147            BybitOpenOrdersResponse, BybitPositionListResponse, BybitTradeHistoryResponse,
2148            BybitTradesResponse, BybitWalletBalanceResponse,
2149        },
2150    };
2151
2152    const TS: UnixNanos = UnixNanos::new(1_700_000_000_000_000_000);
2153
2154    #[rstest]
2155    #[case("100000000.00000001", Currency::BTC(), dec!(100000000.00000001))]
2156    #[case("0.006", Currency::USD(), dec!(0.01))]
2157    #[case("0.000000006", Currency::USDT(), dec!(0.00000001))]
2158    fn test_parse_optional_notional_preserves_decimal(
2159        #[case] raw: &str,
2160        #[case] currency: Currency,
2161        #[case] expected: Decimal,
2162    ) {
2163        let notional = parse_optional_notional(Some(raw), currency, "minNotionalValue")
2164            .unwrap()
2165            .unwrap();
2166
2167        assert_eq!(notional, Money::from_decimal(expected, currency).unwrap());
2168    }
2169
2170    #[rstest]
2171    #[case(None)]
2172    #[case(Some(""))]
2173    #[case(Some("  "))]
2174    fn test_parse_optional_notional_absent(#[case] raw: Option<&str>) {
2175        let result = parse_optional_notional(raw, Currency::USDT(), "minNotionalValue").unwrap();
2176
2177        assert_eq!(result, None);
2178    }
2179
2180    #[rstest]
2181    #[case("NaN")]
2182    #[case("inf")]
2183    #[case("-inf")]
2184    #[case("invalid")]
2185    #[case("1.00000000000000000000000000001")]
2186    #[case("0")]
2187    #[case("-1")]
2188    #[case("79228162514264337593543950335")]
2189    fn test_parse_optional_notional_rejects_invalid(#[case] raw: &str) {
2190        let result = parse_optional_notional(Some(raw), Currency::USDT(), "minNotionalValue");
2191
2192        assert!(result.is_err());
2193    }
2194
2195    #[rstest]
2196    #[case("0.004", Currency::USD())]
2197    #[case("0.005", Currency::USD())]
2198    #[case("0.000000004", Currency::USDT())]
2199    #[case("0.000000005", Currency::USDT())]
2200    fn test_parse_optional_notional_rejects_rounded_zero(
2201        #[case] raw: &str,
2202        #[case] currency: Currency,
2203    ) {
2204        let result = parse_optional_notional(Some(raw), currency, "minNotionalValue");
2205
2206        assert_eq!(
2207            result.unwrap_err().to_string(),
2208            format!("minNotionalValue must be positive, was {raw}")
2209        );
2210    }
2211
2212    #[rstest]
2213    fn test_parse_account_state_preserves_decimal_margins() {
2214        let json = load_test_json("http_get_wallet_balance.json");
2215        let mut response: BybitWalletBalanceResponse = serde_json::from_str(&json).unwrap();
2216        let wallet = &mut response.result.list[0];
2217        let coin = &mut wallet.coin[0];
2218        coin.total_position_im = Some("100000000.00000001".to_string());
2219        coin.total_order_im = Some("0.00000002".to_string());
2220        coin.total_position_mm = Some("100000000.00000001".to_string());
2221        let account_id = AccountId::from("BYBIT-001");
2222
2223        let account = parse_account_state(wallet, account_id, TS).unwrap();
2224
2225        let expected = MarginBalance::new(
2226            Money::from_decimal(dec!(100000000.00000003), Currency::BTC()).unwrap(),
2227            Money::from_decimal(dec!(100000000.00000001), Currency::BTC()).unwrap(),
2228            None,
2229        );
2230
2231        assert_eq!(account.margins, vec![expected]);
2232    }
2233
2234    #[rstest]
2235    #[case(None)]
2236    #[case(Some(""))]
2237    #[case(Some("0"))]
2238    fn test_parse_account_state_absent_margins(#[case] raw: Option<&str>) {
2239        let json = load_test_json("http_get_wallet_balance.json");
2240        let mut response: BybitWalletBalanceResponse = serde_json::from_str(&json).unwrap();
2241        let wallet = &mut response.result.list[0];
2242        let coin = &mut wallet.coin[0];
2243        coin.total_position_im = raw.map(str::to_string);
2244        coin.total_order_im = raw.map(str::to_string);
2245        coin.total_position_mm = raw.map(str::to_string);
2246
2247        let account = parse_account_state(wallet, AccountId::from("BYBIT-001"), TS).unwrap();
2248
2249        assert_eq!(account.margins, Vec::<MarginBalance>::new());
2250    }
2251
2252    #[rstest]
2253    fn test_parse_account_state_rejects_margin_sum_overflow() {
2254        let json = load_test_json("http_get_wallet_balance.json");
2255        let mut response: BybitWalletBalanceResponse = serde_json::from_str(&json).unwrap();
2256        let wallet = &mut response.result.list[0];
2257        let coin = &mut wallet.coin[0];
2258        coin.total_position_im = Some(Decimal::MAX.to_string());
2259        coin.total_order_im = Some(Decimal::MAX.to_string());
2260
2261        let result = parse_account_state(wallet, AccountId::from("BYBIT-001"), TS);
2262
2263        assert_eq!(result.unwrap_err().to_string(), "initial margin overflowed");
2264    }
2265
2266    #[rstest]
2267    fn test_parse_account_state_rejects_invalid_margin(
2268        #[values("totalPositionIM", "totalOrderIM", "totalPositionMM")] field: &str,
2269        #[values(
2270            "NaN",
2271            "inf",
2272            "invalid",
2273            "-1",
2274            "79228162514264337593543950335",
2275            "-0.00000000000000000000000000001",
2276            "2.00000000000000000000000000001"
2277        )]
2278        raw: &str,
2279    ) {
2280        let json = load_test_json("http_get_wallet_balance.json");
2281        let mut response: BybitWalletBalanceResponse = serde_json::from_str(&json).unwrap();
2282        let wallet = &mut response.result.list[0];
2283        let coin = &mut wallet.coin[0];
2284        coin.total_position_im = Some("2".to_string());
2285        coin.total_order_im = Some("3".to_string());
2286        coin.total_position_mm = Some("4".to_string());
2287        match field {
2288            "totalPositionIM" => coin.total_position_im = Some(raw.to_string()),
2289            "totalOrderIM" => coin.total_order_im = Some(raw.to_string()),
2290            "totalPositionMM" => coin.total_position_mm = Some(raw.to_string()),
2291            _ => unreachable!(),
2292        }
2293
2294        let result = parse_account_state(wallet, AccountId::from("BYBIT-001"), TS);
2295
2296        assert!(result.is_err());
2297    }
2298
2299    #[rstest]
2300    #[case(json!(u64::MAX), "18446744073709551615")]
2301    #[case(json!(i64::MIN), "-9223372036854775808")]
2302    #[case(json!(1.25), "1.25")]
2303    #[case(json!(55000.0), "55000.0")]
2304    #[case(json!(0.0000012), "0.0000012")]
2305    #[case(json!(1e16), "10000000000000000")]
2306    #[case(json!("123.4500"), "123.4500")]
2307    fn test_get_price_str_preserves_value(
2308        #[case] value: serde_json::Value,
2309        #[case] expected: &str,
2310    ) {
2311        let params = params_from(&[("take_profit", value)]);
2312
2313        assert_eq!(
2314            get_price_str(&params, "take_profit").as_deref(),
2315            Some(expected)
2316        );
2317    }
2318
2319    #[rstest]
2320    #[case(json!(null))]
2321    #[case(json!(true))]
2322    #[case(json!([]))]
2323    #[case(json!({}))]
2324    fn test_get_price_str_rejects_non_numeric(#[case] value: serde_json::Value) {
2325        let params = params_from(&[("take_profit", value)]);
2326
2327        assert_eq!(get_price_str(&params, "take_profit"), None);
2328    }
2329
2330    #[rstest]
2331    #[case::snake("borrow", BybitMarginAction::Borrow)]
2332    #[case::python_variant("BORROW", BybitMarginAction::Borrow)]
2333    #[case::repay_snake("repay", BybitMarginAction::Repay)]
2334    #[case::repay_variant("REPAY", BybitMarginAction::Repay)]
2335    #[case::query_snake("get_borrow_amount", BybitMarginAction::GetBorrowAmount)]
2336    #[case::query_variant("GET_BORROW_AMOUNT", BybitMarginAction::GetBorrowAmount)]
2337    fn test_parse_margin_action_accepts_param_spellings(
2338        #[case] action: &str,
2339        #[case] expected: BybitMarginAction,
2340    ) {
2341        assert_eq!(parse_margin_action(action), Some(expected));
2342    }
2343
2344    #[rstest]
2345    #[case("lend")]
2346    #[case("")]
2347    #[case("borrow_all")]
2348    fn test_parse_margin_action_rejects_unknown_actions(#[case] action: &str) {
2349        assert_eq!(parse_margin_action(action), None);
2350    }
2351
2352    fn linear_instrument() -> InstrumentAny {
2353        let json = load_test_json("http_get_instruments_linear.json");
2354        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
2355        let instrument = &response.result.list[0];
2356        parse_linear_instrument(instrument, TS, TS).unwrap()
2357    }
2358
2359    #[rstest]
2360    fn test_map_time_in_force_rejects_unsupported(
2361        #[values(BybitOrderType::Market, BybitOrderType::Limit)] order_type: BybitOrderType,
2362        #[values(None, Some(false), Some(true))] post_only: Option<bool>,
2363        #[values(TimeInForce::Day, TimeInForce::AtTheOpen, TimeInForce::AtTheClose)]
2364        tif: TimeInForce,
2365    ) {
2366        assert_eq!(
2367            map_time_in_force(order_type, Some(tif), post_only),
2368            Err(tif)
2369        );
2370    }
2371
2372    #[rstest]
2373    #[case(Some(TimeInForce::Gtc), Some(BybitTimeInForce::Gtc))]
2374    #[case(Some(TimeInForce::Gtd), Some(BybitTimeInForce::Gtc))]
2375    #[case(Some(TimeInForce::Ioc), Some(BybitTimeInForce::Ioc))]
2376    #[case(Some(TimeInForce::Fok), Some(BybitTimeInForce::Fok))]
2377    #[case(None, None)]
2378    fn test_map_time_in_force_preserves_supported(
2379        #[case] tif: Option<TimeInForce>,
2380        #[case] expected: Option<BybitTimeInForce>,
2381        #[values(BybitOrderType::Market, BybitOrderType::Limit)] order_type: BybitOrderType,
2382        #[values(None, Some(false), Some(true))] post_only: Option<bool>,
2383    ) {
2384        let expected = if order_type == BybitOrderType::Market {
2385            None
2386        } else if post_only == Some(true) {
2387            Some(BybitTimeInForce::PostOnly)
2388        } else {
2389            expected
2390        };
2391
2392        assert_eq!(map_time_in_force(order_type, tif, post_only), Ok(expected));
2393    }
2394
2395    #[rstest]
2396    fn test_parse_price_with_precision_preserves_decimal_value() {
2397        let price = parse_price_with_precision("9000000.000000001", 9, "test.price").unwrap();
2398
2399        assert_eq!(price, Price::from("9000000.000000001"));
2400        assert_eq!(price.precision, 9);
2401    }
2402
2403    #[rstest]
2404    #[case("25.000", 2, "25.00")]
2405    #[case("9000000.000000001", 9, "9000000.000000001")]
2406    fn test_parse_quantity_with_precision_preserves_decimal_value(
2407        #[case] value: &str,
2408        #[case] precision: u8,
2409        #[case] expected: &str,
2410    ) {
2411        let quantity = parse_quantity_with_precision(value, precision, "test.quantity").unwrap();
2412
2413        assert_eq!(quantity, Quantity::from(expected));
2414        assert_eq!(quantity.precision, precision);
2415    }
2416
2417    #[rstest]
2418    #[case::in_range("100.0".to_string(), Some("100.0".to_string()))]
2419    #[case::at_max(QUANTITY_MAX.to_string(), Some(QUANTITY_MAX.to_string()))]
2420    #[case::above_max(format!("{QUANTITY_MAX}.5"), None)]
2421    fn test_parse_max_quantity(#[case] value: String, #[case] expected: Option<String>) {
2422        let quantity = parse_max_quantity(&value, "test.quantity").unwrap();
2423
2424        assert_eq!(quantity, expected.as_deref().map(Quantity::from));
2425    }
2426
2427    #[rstest]
2428    #[case::post_only_cross("EC_PostOnlyWillTakeLiquidity", true)]
2429    #[case::post_only_cross_with_prefix("Order rejected: EC_PostOnlyWillTakeLiquidity", true)]
2430    #[case::other_reason("EC_OrigClOrdIDDoesNotExist", false)]
2431    #[case::generic("Order rejected by venue", false)]
2432    #[case::empty("", false)]
2433    fn test_bybit_rejection_due_post_only(#[case] reason: &str, #[case] expected: bool) {
2434        assert_eq!(bybit_rejection_due_post_only(reason), expected);
2435    }
2436
2437    #[rstest]
2438    fn parse_spot_instrument_builds_currency_pair() {
2439        let json = load_test_json("http_get_instruments_spot.json");
2440        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
2441        let instrument = &response.result.list[0];
2442
2443        let parsed = parse_spot_instrument(instrument, TS, TS).unwrap();
2444        match parsed {
2445            InstrumentAny::CurrencyPair(pair) => {
2446                assert_eq!(pair.id.to_string(), "BTCUSDT-SPOT.BYBIT");
2447                assert_eq!(pair.price_increment, Price::from_str("0.1").unwrap());
2448                assert_eq!(pair.size_increment, Quantity::from_str("0.0001").unwrap());
2449                assert_eq!(pair.base_currency.code, "BTC");
2450                assert_eq!(pair.quote_currency.code, "USDT");
2451                assert_eq!(
2452                    pair.min_notional,
2453                    Some(Money::from_decimal(Decimal::new(10, 0), Currency::USDT()).unwrap()),
2454                );
2455                assert_eq!(
2456                    pair.info.as_ref().unwrap().get_bool("margin_trading"),
2457                    Some(true)
2458                );
2459            }
2460            _ => panic!("expected CurrencyPair"),
2461        }
2462    }
2463
2464    #[rstest]
2465    fn parse_spot_instrument_forwards_symbol_info() {
2466        let json = load_test_json("http_get_instruments_spot_xstocks.json");
2467        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
2468        let instrument = &response.result.list[0];
2469
2470        let parsed = parse_spot_instrument(instrument, TS, TS).unwrap();
2471        let InstrumentAny::TokenizedAsset(asset) = parsed else {
2472            panic!("expected TokenizedAsset, was {parsed:?}");
2473        };
2474
2475        assert_eq!(asset.id.to_string(), "AAPLUSDT-SPOT.BYBIT");
2476        assert_eq!(asset.asset_class, AssetClass::Equity);
2477        assert_eq!(asset.base_currency.code, "AAPL");
2478        assert_eq!(asset.quote_currency, Currency::USDT());
2479        assert_eq!(asset.multiplier, Quantity::from(1));
2480
2481        let info = asset.info.as_ref().unwrap();
2482        assert_eq!(info.get_bool("margin_trading"), Some(false));
2483        assert_eq!(info.get_str("symbol_type"), Some("xstocks"));
2484        assert_eq!(info.get_str("xstock_multiplier"), Some("0.1"));
2485        assert_eq!(info.len(), 3);
2486    }
2487
2488    #[rstest]
2489    #[case::absent(None, None)]
2490    #[case::adventure(Some(BybitSymbolType::Adventure), None)]
2491    #[case::xstocks(Some(BybitSymbolType::Xstocks), Some(AssetClass::Equity))]
2492    #[case::mstocks(Some(BybitSymbolType::Mstocks), Some(AssetClass::Equity))]
2493    #[case::unknown(Some(BybitSymbolType::Other), Some(AssetClass::Alternative))]
2494    fn parse_spot_instrument_selects_tokenized_asset_for_non_crypto(
2495        #[case] symbol_type: Option<BybitSymbolType>,
2496        #[case] expected_asset_class: Option<AssetClass>,
2497    ) {
2498        let json = load_test_json("http_get_instruments_spot.json");
2499        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
2500        let mut instrument = response.result.list[0].clone();
2501        instrument.symbol_type = symbol_type;
2502
2503        let parsed = parse_spot_instrument(&instrument, TS, TS).unwrap();
2504        match (parsed, expected_asset_class) {
2505            (InstrumentAny::TokenizedAsset(asset), Some(expected)) => {
2506                assert_eq!(asset.asset_class, expected);
2507            }
2508            (InstrumentAny::CurrencyPair(_), None) => {}
2509            (other, _) => panic!("unexpected instrument variant: {other:?}"),
2510        }
2511    }
2512
2513    #[rstest]
2514    #[case::unknown(BybitSymbolType::Other, "1", None, 1)]
2515    #[case::non_xstock(BybitSymbolType::Adventure, "1", Some("adventure"), 2)]
2516    #[case::empty_xstock_multiplier(BybitSymbolType::Xstocks, "", Some("xstocks"), 2)]
2517    fn parse_spot_instrument_omits_inapplicable_symbol_info(
2518        #[case] symbol_type: BybitSymbolType,
2519        #[case] xstock_multiplier: &str,
2520        #[case] expected_symbol_type: Option<&str>,
2521        #[case] expected_len: usize,
2522    ) {
2523        let json = load_test_json("http_get_instruments_spot.json");
2524        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
2525        let mut instrument = response.result.list[0].clone();
2526        instrument.symbol_type = Some(symbol_type);
2527        instrument.xstock_multiplier = Some(xstock_multiplier.to_string());
2528
2529        let parsed = parse_spot_instrument(&instrument, TS, TS).unwrap();
2530        let info = parsed.info().unwrap();
2531
2532        assert_eq!(info.get_bool("margin_trading"), Some(true));
2533        assert_eq!(info.get_str("symbol_type"), expected_symbol_type);
2534        assert_eq!(info.get("xstock_multiplier"), None);
2535        assert_eq!(info.len(), expected_len);
2536    }
2537
2538    #[rstest]
2539    #[case(BybitMarginTrading::Both, true)]
2540    #[case(BybitMarginTrading::UtaOnly, true)]
2541    #[case(BybitMarginTrading::None, false)]
2542    #[case(BybitMarginTrading::Other, false)]
2543    fn parse_spot_instrument_maps_margin_trading(
2544        #[case] margin_trading: BybitMarginTrading,
2545        #[case] expected: bool,
2546    ) {
2547        let json = load_test_json("http_get_instruments_spot.json");
2548        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
2549        let mut instrument = response.result.list[0].clone();
2550        instrument.margin_trading = margin_trading;
2551
2552        let parsed = parse_spot_instrument(&instrument, TS, TS).unwrap();
2553        match parsed {
2554            InstrumentAny::CurrencyPair(pair) => {
2555                assert_eq!(
2556                    pair.info.as_ref().unwrap().get_bool("margin_trading"),
2557                    Some(expected)
2558                );
2559            }
2560            _ => panic!("expected CurrencyPair"),
2561        }
2562    }
2563
2564    #[rstest]
2565    fn parse_linear_perpetual_instrument_builds_crypto_perpetual() {
2566        let json = load_test_json("http_get_instruments_linear.json");
2567        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
2568        let instrument = &response.result.list[0];
2569
2570        let parsed = parse_linear_instrument(instrument, TS, TS).unwrap();
2571        match parsed {
2572            InstrumentAny::CryptoPerpetual(perp) => {
2573                assert_eq!(perp.id.to_string(), "BTCUSDT-LINEAR.BYBIT");
2574                assert!(!perp.is_inverse);
2575                assert_eq!(perp.price_increment, Price::from_str("0.5").unwrap());
2576                assert_eq!(perp.size_increment, Quantity::from_str("0.001").unwrap());
2577                assert_eq!(perp.min_notional, Some(Money::new(5.0, Currency::USDT())),);
2578                assert!(perp.info.is_none());
2579            }
2580            other => panic!("unexpected instrument variant: {other:?}"),
2581        }
2582    }
2583
2584    #[rstest]
2585    #[case::perpetual(BybitContractType::LinearPerpetual)]
2586    #[case::future(BybitContractType::LinearFutures)]
2587    fn parse_linear_instrument_forwards_symbol_info(#[case] contract_type: BybitContractType) {
2588        let json = load_test_json("http_get_instruments_linear_symbol_type.json");
2589        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
2590        let mut instrument = response.result.list[0].clone();
2591        instrument.contract_type = contract_type;
2592
2593        let parsed = parse_linear_instrument(&instrument, TS, TS).unwrap();
2594        let info = match (contract_type, parsed) {
2595            (BybitContractType::LinearPerpetual, InstrumentAny::PerpetualContract(perp)) => {
2596                perp.info.unwrap()
2597            }
2598            (BybitContractType::LinearFutures, InstrumentAny::CryptoFuture(future)) => {
2599                future.info.unwrap()
2600            }
2601            (_, other) => panic!("unexpected instrument variant: {other:?}"),
2602        };
2603
2604        assert_eq!(info.get_str("symbol_type"), Some("stock"));
2605        assert_eq!(info.get_str("full_name"), Some("Advanced Micro Devices"));
2606        assert_eq!(info.get_str("market_region"), Some("US"));
2607        assert_eq!(info.len(), 3);
2608    }
2609
2610    #[rstest]
2611    #[case::stock(BybitSymbolType::Stock, "AMD", Some("AMD"), AssetClass::Equity)]
2612    #[case::etf(BybitSymbolType::Etf, "ARKK", Some("ARKK"), AssetClass::Equity)]
2613    #[case::commodity(BybitSymbolType::Commodity, "XAU", None, AssetClass::Commodity)]
2614    #[case::forex(BybitSymbolType::Forex, "EURUSD", None, AssetClass::FX)]
2615    #[case::unknown(BybitSymbolType::Other, "NEWTHING", None, AssetClass::Alternative)]
2616    fn parse_linear_tradfi_perpetual_builds_perpetual_contract(
2617        #[case] symbol_type: BybitSymbolType,
2618        #[case] base_coin: &str,
2619        #[case] underlying_ticker: Option<&str>,
2620        #[case] expected_asset_class: AssetClass,
2621    ) {
2622        let json = load_test_json("http_get_instruments_linear_symbol_type.json");
2623        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
2624        let mut instrument = response.result.list[0].clone();
2625        instrument.symbol_type = Some(symbol_type);
2626        instrument.base_coin = Ustr::from(base_coin);
2627        instrument.underlying_ticker = underlying_ticker.map(str::to_string);
2628
2629        let parsed = parse_linear_instrument(&instrument, TS, TS).unwrap();
2630        let InstrumentAny::PerpetualContract(perp) = parsed else {
2631            panic!("expected PerpetualContract, was {parsed:?}");
2632        };
2633
2634        assert_eq!(perp.id.to_string(), "AMDSTOCKUSDT-LINEAR.BYBIT");
2635        assert_eq!(perp.underlying.as_str(), base_coin);
2636        assert_eq!(perp.asset_class, expected_asset_class);
2637        assert_eq!(perp.base_currency, None);
2638        assert_eq!(perp.quote_currency, Currency::USDT());
2639        assert_eq!(perp.settlement_currency, Currency::USDT());
2640        assert!(!perp.is_inverse);
2641        assert_eq!(perp.price_increment, Price::from("0.01"));
2642        assert_eq!(perp.size_increment, Quantity::from("0.001"));
2643        assert_eq!(perp.min_notional, Some(Money::new(1.0, Currency::USDT())));
2644    }
2645
2646    #[rstest]
2647    fn parse_linear_tradfi_perpetual_uses_underlying_ticker_over_base_coin() {
2648        let json = load_test_json("http_get_instruments_linear_symbol_type.json");
2649        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
2650        let instrument = &response.result.list[0];
2651
2652        let parsed = parse_linear_instrument(instrument, TS, TS).unwrap();
2653        let InstrumentAny::PerpetualContract(perp) = parsed else {
2654            panic!("expected PerpetualContract, was {parsed:?}");
2655        };
2656
2657        assert_eq!(instrument.base_coin.as_str(), "AMDSTOCK");
2658        assert_eq!(perp.underlying.as_str(), "AMD");
2659    }
2660
2661    #[rstest]
2662    #[case::innovation(Some(BybitSymbolType::Innovation))]
2663    #[case::absent(None)]
2664    fn parse_linear_crypto_perpetual_keeps_crypto_perpetual(
2665        #[case] symbol_type: Option<BybitSymbolType>,
2666    ) {
2667        let json = load_test_json("http_get_instruments_linear.json");
2668        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
2669        let mut instrument = response.result.list[0].clone();
2670        instrument.symbol_type = symbol_type;
2671
2672        let parsed = parse_linear_instrument(&instrument, TS, TS).unwrap();
2673
2674        assert!(
2675            matches!(parsed, InstrumentAny::CryptoPerpetual(_)),
2676            "expected CryptoPerpetual, was {parsed:?}"
2677        );
2678    }
2679
2680    #[rstest]
2681    fn parse_inverse_perpetual_instrument_builds_inverse_perpetual() {
2682        let json = load_test_json("http_get_instruments_inverse.json");
2683        let response: BybitInstrumentInverseResponse = serde_json::from_str(&json).unwrap();
2684        let instrument = &response.result.list[0];
2685
2686        let parsed = parse_inverse_instrument(instrument, TS, TS).unwrap();
2687        match parsed {
2688            InstrumentAny::CryptoPerpetual(perp) => {
2689                assert_eq!(perp.id.to_string(), "BTCUSD-INVERSE.BYBIT");
2690                assert!(perp.is_inverse);
2691                assert_eq!(perp.price_increment, Price::from_str("0.5").unwrap());
2692                assert_eq!(perp.size_increment, Quantity::from_str("1").unwrap());
2693                assert!(perp.min_notional.is_none());
2694                assert!(perp.info.is_none());
2695            }
2696            other => panic!("unexpected instrument variant: {other:?}"),
2697        }
2698    }
2699
2700    #[rstest]
2701    #[case::perpetual(BybitContractType::InversePerpetual)]
2702    #[case::future(BybitContractType::InverseFutures)]
2703    fn parse_inverse_instrument_forwards_symbol_info(#[case] contract_type: BybitContractType) {
2704        let json = load_test_json("http_get_instruments_inverse_symbol_type.json");
2705        let response: BybitInstrumentInverseResponse = serde_json::from_str(&json).unwrap();
2706        let mut instrument = response.result.list[0].clone();
2707        instrument.contract_type = contract_type;
2708
2709        let parsed = parse_inverse_instrument(&instrument, TS, TS).unwrap();
2710        let info = match (contract_type, parsed) {
2711            (BybitContractType::InversePerpetual, InstrumentAny::CryptoPerpetual(perp)) => {
2712                perp.info.unwrap()
2713            }
2714            (BybitContractType::InverseFutures, InstrumentAny::CryptoFuture(future)) => {
2715                future.info.unwrap()
2716            }
2717            (_, other) => panic!("unexpected instrument variant: {other:?}"),
2718        };
2719
2720        assert_eq!(info.get_str("symbol_type"), Some("commodity"));
2721        assert_eq!(info.len(), 1);
2722    }
2723
2724    #[rstest]
2725    fn parse_option_instrument_builds_crypto_option() {
2726        let json = load_test_json("http_get_instruments_option.json");
2727        let response: BybitInstrumentOptionResponse = serde_json::from_str(&json).unwrap();
2728        let instrument = &response.result.list[0];
2729
2730        let parsed = parse_option_instrument(instrument, TS, TS).unwrap();
2731        match parsed {
2732            InstrumentAny::CryptoOption(option) => {
2733                assert_eq!(option.id.to_string(), "ETH-26JUN26-16000-P-OPTION.BYBIT");
2734                assert_eq!(option.underlying.code, "ETH");
2735                assert_eq!(option.quote_currency.code, "USDC");
2736                assert_eq!(option.settlement_currency.code, "USDC");
2737                assert!(!option.is_inverse);
2738                assert_eq!(option.option_kind, OptionKind::Put);
2739                assert_eq!(option.exercise_style, Some(ExerciseStyle::European));
2740                assert_eq!(option.settlement_type, Some(SettlementType::Cash));
2741                assert_eq!(option.price_precision, 1);
2742                assert_eq!(option.price_increment, Price::from_str("0.1").unwrap());
2743                assert_eq!(option.size_precision, 0);
2744                assert_eq!(option.size_increment, Quantity::from_str("1").unwrap());
2745                assert_eq!(option.lot_size, Quantity::from_str("1").unwrap());
2746            }
2747            other => panic!("unexpected instrument variant: {other:?}"),
2748        }
2749    }
2750
2751    #[rstest]
2752    fn test_extract_base_coin_from_option_symbol() {
2753        assert_eq!(extract_base_coin("BTC-27MAR26-70000-P"), "BTC");
2754        assert_eq!(extract_base_coin("ETH-26JUN26-16000-C"), "ETH");
2755        assert_eq!(extract_base_coin("SOL-30MAR26-200-P-USDT"), "SOL");
2756        assert_eq!(extract_base_coin("BTC"), "BTC");
2757    }
2758
2759    #[rstest]
2760    fn test_extract_base_coin_from_nautilus_option_symbol() {
2761        // After extract_raw_symbol strips the "-OPTION" suffix
2762        let raw = extract_raw_symbol("BTC-27MAR26-70000-P-USDT-OPTION");
2763        assert_eq!(extract_base_coin(raw), "BTC");
2764    }
2765
2766    #[rstest]
2767    fn parse_http_trade_into_trade_tick() {
2768        let instrument = linear_instrument();
2769        let json = load_test_json("http_get_trades_recent.json");
2770        let response: BybitTradesResponse = serde_json::from_str(&json).unwrap();
2771        let trade = &response.result.list[0];
2772
2773        let tick = parse_trade_tick(trade, &instrument, Some(TS)).unwrap();
2774
2775        assert_eq!(tick.instrument_id, instrument.id());
2776        assert_eq!(tick.price, instrument.make_price(27450.50));
2777        assert_eq!(tick.size, instrument.make_qty(0.005, None));
2778        assert_eq!(tick.aggressor_side, AggressorSide::Buy);
2779        assert_eq!(
2780            tick.trade_id.to_string(),
2781            "a905d5c3-1ed0-4f37-83e4-9c73a2fe2f01"
2782        );
2783        assert_eq!(tick.ts_event, UnixNanos::new(1_709_891_679_000_000_000));
2784    }
2785
2786    #[rstest]
2787    fn parse_kline_into_bar() {
2788        let instrument = linear_instrument();
2789        let json = load_test_json("http_get_klines_linear.json");
2790        let response: BybitKlinesResponse = serde_json::from_str(&json).unwrap();
2791        let kline = &response.result.list[0];
2792
2793        let bar_type = BarType::new(
2794            instrument.id(),
2795            BarSpecification::new(1, BarAggregation::Minute, PriceType::Last),
2796            AggregationSource::External,
2797        );
2798
2799        let bar = parse_kline_bar(kline, &instrument, bar_type, false, Some(TS)).unwrap();
2800
2801        assert_eq!(bar.bar_type.to_string(), bar_type.to_string());
2802        assert_eq!(bar.open, instrument.make_price(27450.0));
2803        assert_eq!(bar.high, instrument.make_price(27460.0));
2804        assert_eq!(bar.low, instrument.make_price(27440.0));
2805        assert_eq!(bar.close, instrument.make_price(27455.0));
2806        assert_eq!(bar.volume, instrument.make_qty(123.45, None));
2807        assert_eq!(bar.ts_event, UnixNanos::new(1_709_891_679_000_000_000));
2808    }
2809
2810    #[rstest]
2811    fn parse_http_position_short_into_position_status_report() {
2812        use crate::http::models::BybitPositionListResponse;
2813
2814        let json = load_test_json("http_get_positions.json");
2815        let response: BybitPositionListResponse = serde_json::from_str(&json).unwrap();
2816
2817        // Get the short position (ETHUSDT, side="Sell", size="5.0")
2818        let short_position = &response.result.list[1];
2819        assert_eq!(short_position.symbol, "ETHUSDT");
2820        assert_eq!(short_position.side, BybitPositionSide::Sell);
2821
2822        // Create ETHUSDT instrument for parsing
2823        let eth_json = load_test_json("http_get_instruments_linear.json");
2824        let eth_response: BybitInstrumentLinearResponse = serde_json::from_str(&eth_json).unwrap();
2825        let eth_def = &eth_response.result.list[1]; // ETHUSDT is second in the list
2826        let eth_instrument = parse_linear_instrument(eth_def, TS, TS).unwrap();
2827
2828        let account_id = AccountId::new("BYBIT-001");
2829        let report =
2830            parse_position_status_report(short_position, account_id, &eth_instrument, TS).unwrap();
2831
2832        // Verify short position is correctly parsed
2833        assert_eq!(report.account_id, account_id);
2834        assert_eq!(report.instrument_id.symbol.as_str(), "ETHUSDT-LINEAR");
2835        assert_eq!(report.position_side, PositionSide::Short);
2836        assert_eq!(report.quantity, eth_instrument.make_qty(5.0, None));
2837        assert_eq!(
2838            report.avg_px_open,
2839            Some(Decimal::try_from(3000.00).unwrap())
2840        );
2841        assert_eq!(report.ts_last, UnixNanos::new(1_697_673_700_112_000_000));
2842    }
2843
2844    #[rstest]
2845    fn parse_http_position_preserves_decimal_quantity() {
2846        use crate::http::models::BybitPositionListResponse;
2847
2848        let json = load_test_json("http_get_positions.json");
2849        let response: BybitPositionListResponse = serde_json::from_str(&json).unwrap();
2850        let mut position = response.result.list[0].clone();
2851        position.size = "9000000.000000001".to_string();
2852
2853        let json = load_test_json("http_get_instruments_linear.json");
2854        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
2855        let mut definition = response.result.list[0].clone();
2856        definition.lot_size_filter.qty_step = "0.000000001".to_string();
2857        let instrument = parse_linear_instrument(&definition, TS, TS).unwrap();
2858
2859        let report =
2860            parse_position_status_report(&position, AccountId::new("BYBIT-001"), &instrument, TS)
2861                .unwrap();
2862
2863        assert_eq!(report.quantity, Quantity::from("9000000.000000001"));
2864        assert_eq!(report.quantity.precision, 9);
2865    }
2866
2867    #[rstest]
2868    fn parse_http_order_partially_filled_rejected_maps_to_canceled() {
2869        use crate::http::models::BybitOrderHistoryResponse;
2870
2871        let instrument = linear_instrument();
2872        let json = load_test_json("http_get_order_partially_filled_rejected.json");
2873        let response: BybitOrderHistoryResponse = serde_json::from_str(&json).unwrap();
2874        let order = &response.result.list[0];
2875        let account_id = AccountId::new("BYBIT-001");
2876
2877        let report = parse_order_status_report(order, &instrument, account_id, TS).unwrap();
2878
2879        // Verify that Bybit "Rejected" status with fills is mapped to Canceled, not Rejected
2880        assert_eq!(report.order_status, OrderStatus::Canceled);
2881        assert_eq!(report.filled_qty, instrument.make_qty(0.005, None));
2882        assert_eq!(
2883            report.client_order_id.as_ref().unwrap().to_string(),
2884            "O-20251001-164609-APEX-000-49"
2885        );
2886        assert_eq!(report.cancel_reason.as_deref(), Some("INSUFFICIENT_MARGIN"));
2887    }
2888
2889    // The post-only row is a redacted Bybit demo history capture, and the other rows are
2890    // synthetic variants of that envelope, including the reported reduce-only rejection text
2891    // and a rejected order whose rejectReason is the EC_NoError sentinel
2892    #[rstest]
2893    fn replay_rejected_order_history_keeps_venue_reason() {
2894        use nautilus_execution::reconciliation::generate_reconciliation_order_events;
2895        use nautilus_model::events::OrderEventAny;
2896
2897        use crate::http::models::BybitOrderHistoryResponse;
2898
2899        let instrument = linear_instrument();
2900        let json = load_test_json("http_get_orders_history_rejected.json");
2901        let response: BybitOrderHistoryResponse = serde_json::from_str(&json).unwrap();
2902        let orders = &response.result.list;
2903
2904        let post_only = history_report(orders, &instrument, "post-only-reject");
2905        assert_eq!(post_only.order_status, OrderStatus::Rejected);
2906        assert!(post_only.post_only);
2907        assert_replayed_rejection(
2908            &post_only,
2909            &instrument,
2910            "EC_PostOnlyWillTakeLiquidity",
2911            true,
2912        );
2913
2914        let reduce_only = history_report(orders, &instrument, "reduce-only-reject");
2915        assert_eq!(reduce_only.order_status, OrderStatus::Rejected);
2916        assert_replayed_rejection(
2917            &reduce_only,
2918            &instrument,
2919            "current position is zero, cannot fix reduce-only order qty",
2920            false,
2921        );
2922
2923        let omitted = history_report(orders, &instrument, "omitted-reject");
2924        assert_eq!(omitted.order_status, OrderStatus::Rejected);
2925        assert_replayed_rejection(&omitted, &instrument, "venue omitted rejectReason", false);
2926
2927        let rejected_no_error = history_report(orders, &instrument, "rejected-no-error");
2928        assert_eq!(rejected_no_error.order_status, OrderStatus::Rejected);
2929        assert_replayed_rejection(
2930            &rejected_no_error,
2931            &instrument,
2932            "venue omitted rejectReason",
2933            false,
2934        );
2935
2936        let filled = history_report(orders, &instrument, "filled-no-error");
2937        assert_eq!(filled.order_status, OrderStatus::Filled);
2938        assert_eq!(filled.cancel_reason, None);
2939
2940        let user_cancel = history_report(orders, &instrument, "user-cancel");
2941        assert_eq!(user_cancel.order_status, OrderStatus::Canceled);
2942        assert_eq!(user_cancel.cancel_reason, None);
2943        let order = submitted_limit(&user_cancel, &instrument);
2944        let events = generate_reconciliation_order_events(
2945            &order,
2946            &user_cancel,
2947            Some(&instrument),
2948            UnixNanos::from(2_000),
2949        );
2950
2951        let canceled = events.iter().find_map(|event| match event {
2952            OrderEventAny::Canceled(canceled) => Some(*canceled),
2953            _ => None,
2954        });
2955
2956        let canceled = canceled.expect("reconciliation did not emit OrderCanceled");
2957        assert_eq!(canceled.reason, None);
2958        assert!(
2959            !events
2960                .iter()
2961                .any(|event| matches!(event, OrderEventAny::Rejected(_)))
2962        );
2963    }
2964
2965    fn history_report(
2966        orders: &[crate::http::models::BybitOrder],
2967        instrument: &InstrumentAny,
2968        link_id: &str,
2969    ) -> OrderStatusReport {
2970        let order = orders
2971            .iter()
2972            .find(|order| order.order_link_id.as_str() == link_id)
2973            .unwrap_or_else(|| panic!("missing history row {link_id}"));
2974        parse_order_status_report(order, instrument, AccountId::new("BYBIT-001"), TS).unwrap()
2975    }
2976
2977    fn submitted_limit(report: &OrderStatusReport, instrument: &InstrumentAny) -> OrderAny {
2978        use nautilus_model::orders::builder::OrderTestBuilder;
2979
2980        let instrument_id = instrument.id();
2981        let client_order_id = report.client_order_id.expect("history row has orderLinkId");
2982        let side = report.order_side.expect("history row has a side");
2983        let price = report.price.expect("history row has a price");
2984        OrderTestBuilder::new(OrderType::Limit)
2985            .instrument_id(instrument_id)
2986            .client_order_id(client_order_id)
2987            .side(side)
2988            .quantity(report.quantity)
2989            .price(price)
2990            .submit(true)
2991            .build()
2992    }
2993
2994    fn assert_replayed_rejection(
2995        report: &OrderStatusReport,
2996        instrument: &InstrumentAny,
2997        reason: &str,
2998        due_post_only: bool,
2999    ) {
3000        use nautilus_execution::reconciliation::{
3001            generate_external_order_status_events, generate_reconciliation_order_events,
3002        };
3003        use nautilus_model::events::OrderEventAny;
3004
3005        let order = submitted_limit(report, instrument);
3006        let ts_now = UnixNanos::from(2_000);
3007        let cached = generate_reconciliation_order_events(&order, report, Some(instrument), ts_now);
3008        let external = generate_external_order_status_events(
3009            &order,
3010            report,
3011            &report.account_id,
3012            instrument,
3013            ts_now,
3014        );
3015
3016        for events in [&cached, &external] {
3017            let rejected = events.iter().find_map(|event| match event {
3018                OrderEventAny::Rejected(rejected) => Some(*rejected),
3019                _ => None,
3020            });
3021
3022            let rejected = rejected.expect("reconciliation did not emit OrderRejected");
3023            assert_eq!(rejected.reason.as_str(), reason);
3024            assert_eq!(rejected.due_post_only, due_post_only);
3025            assert!(rejected.reconciliation);
3026        }
3027    }
3028
3029    #[rstest]
3030    #[case(BarAggregation::Minute, 1, BybitKlineInterval::Minute1)]
3031    #[case(BarAggregation::Minute, 3, BybitKlineInterval::Minute3)]
3032    #[case(BarAggregation::Minute, 5, BybitKlineInterval::Minute5)]
3033    #[case(BarAggregation::Minute, 15, BybitKlineInterval::Minute15)]
3034    #[case(BarAggregation::Minute, 30, BybitKlineInterval::Minute30)]
3035    fn test_bar_spec_to_bybit_interval_minutes(
3036        #[case] aggregation: BarAggregation,
3037        #[case] step: u64,
3038        #[case] expected: BybitKlineInterval,
3039    ) {
3040        let result = bar_spec_to_bybit_interval(aggregation, step).unwrap();
3041        assert_eq!(result, expected);
3042    }
3043
3044    #[rstest]
3045    #[case(BarAggregation::Hour, 1, BybitKlineInterval::Hour1)]
3046    #[case(BarAggregation::Hour, 2, BybitKlineInterval::Hour2)]
3047    #[case(BarAggregation::Hour, 4, BybitKlineInterval::Hour4)]
3048    #[case(BarAggregation::Hour, 6, BybitKlineInterval::Hour6)]
3049    #[case(BarAggregation::Hour, 12, BybitKlineInterval::Hour12)]
3050    fn test_bar_spec_to_bybit_interval_hours(
3051        #[case] aggregation: BarAggregation,
3052        #[case] step: u64,
3053        #[case] expected: BybitKlineInterval,
3054    ) {
3055        let result = bar_spec_to_bybit_interval(aggregation, step).unwrap();
3056        assert_eq!(result, expected);
3057    }
3058
3059    #[rstest]
3060    #[case(BarAggregation::Day, 1, BybitKlineInterval::Day1)]
3061    #[case(BarAggregation::Week, 1, BybitKlineInterval::Week1)]
3062    #[case(BarAggregation::Month, 1, BybitKlineInterval::Month1)]
3063    fn test_bar_spec_to_bybit_interval_day_week_month(
3064        #[case] aggregation: BarAggregation,
3065        #[case] step: u64,
3066        #[case] expected: BybitKlineInterval,
3067    ) {
3068        let result = bar_spec_to_bybit_interval(aggregation, step).unwrap();
3069        assert_eq!(result, expected);
3070    }
3071
3072    #[rstest]
3073    #[case(BarAggregation::Minute, 2)]
3074    #[case(BarAggregation::Minute, 10)]
3075    #[case(BarAggregation::Hour, 3)]
3076    #[case(BarAggregation::Hour, 24)]
3077    #[case(BarAggregation::Day, 2)]
3078    #[case(BarAggregation::Week, 2)]
3079    #[case(BarAggregation::Month, 2)]
3080    fn test_bar_spec_to_bybit_interval_unsupported_steps(
3081        #[case] aggregation: BarAggregation,
3082        #[case] step: u64,
3083    ) {
3084        let result = bar_spec_to_bybit_interval(aggregation, step);
3085        result.unwrap_err();
3086    }
3087
3088    #[rstest]
3089    fn test_bar_spec_to_bybit_interval_unsupported_aggregation() {
3090        let result = bar_spec_to_bybit_interval(BarAggregation::Second, 1);
3091        result.unwrap_err();
3092    }
3093
3094    #[rstest]
3095    #[case("1", 1, BarAggregation::Minute)]
3096    #[case("3", 3, BarAggregation::Minute)]
3097    #[case("5", 5, BarAggregation::Minute)]
3098    #[case("15", 15, BarAggregation::Minute)]
3099    #[case("30", 30, BarAggregation::Minute)]
3100    fn test_bybit_interval_to_bar_spec_minutes(
3101        #[case] interval: &str,
3102        #[case] expected_step: usize,
3103        #[case] expected_aggregation: BarAggregation,
3104    ) {
3105        let result = bybit_interval_to_bar_spec(interval).unwrap();
3106        assert_eq!(result, (expected_step, expected_aggregation));
3107    }
3108
3109    #[rstest]
3110    #[case("60", 1, BarAggregation::Hour)]
3111    #[case("120", 2, BarAggregation::Hour)]
3112    #[case("240", 4, BarAggregation::Hour)]
3113    #[case("360", 6, BarAggregation::Hour)]
3114    #[case("720", 12, BarAggregation::Hour)]
3115    fn test_bybit_interval_to_bar_spec_hours(
3116        #[case] interval: &str,
3117        #[case] expected_step: usize,
3118        #[case] expected_aggregation: BarAggregation,
3119    ) {
3120        let result = bybit_interval_to_bar_spec(interval).unwrap();
3121        assert_eq!(result, (expected_step, expected_aggregation));
3122    }
3123
3124    #[rstest]
3125    #[case("D", 1, BarAggregation::Day)]
3126    #[case("W", 1, BarAggregation::Week)]
3127    #[case("M", 1, BarAggregation::Month)]
3128    fn test_bybit_interval_to_bar_spec_day_week_month(
3129        #[case] interval: &str,
3130        #[case] expected_step: usize,
3131        #[case] expected_aggregation: BarAggregation,
3132    ) {
3133        let result = bybit_interval_to_bar_spec(interval).unwrap();
3134        assert_eq!(result, (expected_step, expected_aggregation));
3135    }
3136
3137    #[rstest]
3138    #[case("2")]
3139    #[case("10")]
3140    #[case("100")]
3141    #[case("invalid")]
3142    #[case("")]
3143    fn test_bybit_interval_to_bar_spec_unsupported(#[case] interval: &str) {
3144        let result = bybit_interval_to_bar_spec(interval);
3145        assert!(result.is_none());
3146    }
3147
3148    fn params_from(pairs: &[(&str, serde_json::Value)]) -> Params {
3149        Params::new(
3150            pairs
3151                .iter()
3152                .map(|(k, v)| (k.to_string(), v.clone()))
3153                .collect(),
3154        )
3155    }
3156
3157    #[rstest]
3158    fn test_parse_tp_sl_params_none_returns_defaults() {
3159        let result = parse_bybit_tp_sl_params(None).unwrap();
3160        assert!(!result.is_leverage);
3161        assert!(!result.has_tp_sl());
3162        assert!(!result.has_bbo());
3163        assert!(result.order_iv.is_none());
3164        assert!(result.mmp.is_none());
3165    }
3166
3167    #[rstest]
3168    fn test_parse_tp_sl_params_empty_returns_defaults() {
3169        let p = Params::empty();
3170        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3171        assert!(!result.is_leverage);
3172        assert!(!result.has_tp_sl());
3173        assert!(!result.has_bbo());
3174        assert!(result.order_iv.is_none());
3175        assert!(result.mmp.is_none());
3176    }
3177
3178    #[rstest]
3179    fn test_parse_tp_sl_params_valid_full() {
3180        let p = params_from(&[
3181            ("take_profit", json!("55000.00")),
3182            ("stop_loss", json!("47000.00")),
3183            ("tp_trigger_by", json!("MarkPrice")),
3184            ("sl_trigger_by", json!("IndexPrice")),
3185            ("tp_order_type", json!("Limit")),
3186            ("tp_limit_price", json!("54990.00")),
3187            ("sl_order_type", json!("Market")),
3188            ("close_on_trigger", json!(true)),
3189            ("is_leverage", json!(true)),
3190        ]);
3191        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3192
3193        assert!(result.has_tp_sl());
3194        assert!(result.take_profit.is_some());
3195        assert!(result.stop_loss.is_some());
3196        assert_eq!(result.tp_trigger_by, Some(BybitTriggerType::MarkPrice));
3197        assert_eq!(result.sl_trigger_by, Some(BybitTriggerType::IndexPrice));
3198        assert_eq!(result.tp_order_type, Some(BybitOrderType::Limit));
3199        assert_eq!(result.sl_order_type, Some(BybitOrderType::Market));
3200        assert_eq!(result.tp_limit_price.as_deref(), Some("54990.00"));
3201        assert_eq!(result.close_on_trigger, Some(true));
3202        assert!(result.is_leverage);
3203    }
3204
3205    #[rstest]
3206    fn test_parse_tp_sl_params_preserves_scientific_prices() {
3207        let p = params_from(&[
3208            ("take_profit", json!("55000")),
3209            ("stop_loss", json!("47000")),
3210            ("tp_order_type", json!("Limit")),
3211            ("sl_order_type", json!("Limit")),
3212            ("tp_limit_price", json!("5.499e4")),
3213            ("sl_limit_price", json!("4.699e4")),
3214            ("tp_trigger_price", json!("5.5e4")),
3215            ("sl_trigger_price", json!("4.7e4")),
3216        ]);
3217        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3218
3219        assert_eq!(result.tp_limit_price.as_deref(), Some("5.499e4"));
3220        assert_eq!(result.sl_limit_price.as_deref(), Some("4.699e4"));
3221        assert_eq!(result.tp_trigger_price.as_deref(), Some("5.5e4"));
3222        assert_eq!(result.sl_trigger_price.as_deref(), Some("4.7e4"));
3223    }
3224
3225    #[rstest]
3226    fn test_parse_tp_sl_params_preserves_tpsl_mode() {
3227        let p = params_from(&[
3228            ("take_profit", json!("55000.00")),
3229            ("tpsl_mode", json!("Partial")),
3230        ]);
3231        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3232
3233        assert_eq!(result.tpsl_mode, Some(BybitTpSlMode::Partial));
3234    }
3235
3236    #[rstest]
3237    #[case("Unknown")]
3238    #[case("partial")]
3239    #[case("garbage")]
3240    fn test_parse_tp_sl_params_rejects_invalid_tpsl_mode(#[case] mode: &str) {
3241        let p = params_from(&[("tpsl_mode", json!(mode))]);
3242        let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3243
3244        assert!(err.to_string().contains("invalid Bybit TP/SL mode"));
3245    }
3246
3247    #[rstest]
3248    #[case("None", BybitOrderSmpType::None)]
3249    #[case("CancelMaker", BybitOrderSmpType::CancelMaker)]
3250    #[case("canceltaker", BybitOrderSmpType::CancelTaker)]
3251    #[case("CANCELBOTH", BybitOrderSmpType::CancelBoth)]
3252    fn test_parse_tp_sl_params_valid_smp_type(
3253        #[case] value: &str,
3254        #[case] expected: BybitOrderSmpType,
3255    ) {
3256        let p = params_from(&[("smp_type", json!(value))]);
3257        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3258
3259        assert_eq!(result.smp_type, Some(expected));
3260    }
3261
3262    #[rstest]
3263    fn test_parse_tp_sl_params_smp_type_absent_stays_none() {
3264        let p = params_from(&[("mmp", json!(true))]);
3265        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3266
3267        assert_eq!(result.smp_type, None);
3268    }
3269
3270    #[rstest]
3271    #[case(json!("Other"), "invalid Bybit smp_type: 'Other'")]
3272    #[case(json!("cancel_maker"), "invalid Bybit smp_type: 'cancel_maker'")]
3273    #[case(json!(""), "invalid Bybit smp_type: ''")]
3274    #[case(json!(1), "invalid type for 'smp_type'")]
3275    #[case(json!(true), "invalid type for 'smp_type'")]
3276    fn test_parse_tp_sl_params_rejects_invalid_smp_type(
3277        #[case] value: serde_json::Value,
3278        #[case] expected: &str,
3279    ) {
3280        let p = params_from(&[("smp_type", value)]);
3281        let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3282
3283        assert!(
3284            err.to_string().contains(expected),
3285            "expected '{expected}', was '{err}'"
3286        );
3287    }
3288
3289    #[rstest]
3290    fn test_parse_tp_sl_params_valid_bbo() {
3291        let p = params_from(&[("bbo_side_type", json!("queue")), ("bbo_level", json!(3))]);
3292        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3293
3294        assert!(result.has_bbo());
3295        assert_eq!(result.bbo_side_type, Some(BybitBboSideType::Queue));
3296        assert_eq!(result.bbo_level.as_deref(), Some("3"));
3297    }
3298
3299    #[rstest]
3300    fn test_parse_tp_sl_params_rejects_invalid_bbo() {
3301        let cases = vec![
3302            (
3303                params_from(&[("bbo_side_type", json!("Queue"))]),
3304                "must be provided together",
3305            ),
3306            (
3307                params_from(&[("bbo_level", json!("1"))]),
3308                "must be provided together",
3309            ),
3310            (
3311                params_from(&[
3312                    ("bbo_side_type", json!("invalid")),
3313                    ("bbo_level", json!("1")),
3314                ]),
3315                "invalid Bybit bbo_side_type",
3316            ),
3317            (
3318                params_from(&[("bbo_side_type", json!("Queue")), ("bbo_level", json!("6"))]),
3319                "invalid 'bbo_level'",
3320            ),
3321            (
3322                params_from(&[("bbo_side_type", json!(1)), ("bbo_level", json!("1"))]),
3323                "invalid type for 'bbo_side_type'",
3324            ),
3325            (
3326                params_from(&[
3327                    ("bbo_side_type", json!("Queue")),
3328                    ("bbo_level", json!(true)),
3329                ]),
3330                "invalid type for 'bbo_level'",
3331            ),
3332        ];
3333
3334        for (p, expected) in cases {
3335            let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3336            assert!(err.to_string().contains(expected));
3337        }
3338    }
3339
3340    #[rstest]
3341    #[case("abc")]
3342    #[case("nan")]
3343    #[case("inf")]
3344    #[case("-1.0")]
3345    fn test_parse_tp_sl_params_rejects_invalid_take_profit(#[case] price: &str) {
3346        let p = params_from(&[("take_profit", json!(price))]);
3347        parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3348    }
3349
3350    #[rstest]
3351    #[case("abc")]
3352    #[case("nan")]
3353    #[case("inf")]
3354    fn test_parse_tp_sl_params_rejects_invalid_stop_loss(#[case] price: &str) {
3355        let p = params_from(&[("stop_loss", json!(price))]);
3356        parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3357    }
3358
3359    #[rstest]
3360    #[case("nan")]
3361    #[case("inf")]
3362    #[case("-5.0")]
3363    #[case("-1e-400")]
3364    #[case("-0.00000000000000000000000000001")]
3365    #[case("-0.00000000000000000000000000001e1")]
3366    #[case("55_000")]
3367    #[case("not_a_number")]
3368    fn test_parse_tp_sl_params_rejects_invalid_limit_price(#[case] price: &str) {
3369        let p = params_from(&[
3370            ("take_profit", json!("55000.00")),
3371            ("tp_order_type", json!("Limit")),
3372            ("tp_limit_price", json!(price)),
3373        ]);
3374        parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3375    }
3376
3377    #[rstest]
3378    fn test_parse_tp_sl_params_rejects_invalid_trigger_type() {
3379        let p = params_from(&[
3380            ("take_profit", json!("55000.00")),
3381            ("tp_trigger_by", json!("InvalidType")),
3382        ]);
3383        parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3384    }
3385
3386    #[rstest]
3387    fn test_parse_tp_sl_params_rejects_invalid_order_type() {
3388        let p = params_from(&[
3389            ("stop_loss", json!("47000.00")),
3390            ("sl_order_type", json!("Stop")),
3391        ]);
3392        parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3393    }
3394
3395    #[rstest]
3396    fn test_parse_tp_sl_params_rejects_limit_without_limit_price() {
3397        let p = params_from(&[
3398            ("take_profit", json!("55000.00")),
3399            ("tp_order_type", json!("Limit")),
3400        ]);
3401        let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3402        assert!(err.to_string().contains("tp_limit_price"));
3403    }
3404
3405    #[rstest]
3406    fn test_parse_tp_sl_params_rejects_limit_price_without_limit_type() {
3407        let p = params_from(&[
3408            ("take_profit", json!("55000.00")),
3409            ("tp_limit_price", json!("54990.00")),
3410        ]);
3411        let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3412        assert!(err.to_string().contains("tp_order_type"));
3413    }
3414
3415    #[rstest]
3416    fn test_parse_tp_sl_params_rejects_orphaned_tp_fields() {
3417        let p = params_from(&[("tp_trigger_by", json!("MarkPrice"))]);
3418        let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3419        assert!(err.to_string().contains("TP override fields require"));
3420    }
3421
3422    #[rstest]
3423    fn test_parse_tp_sl_params_accepts_numeric_prices() {
3424        let p = params_from(&[("take_profit", json!(55000.0)), ("stop_loss", json!(47000))]);
3425        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3426        assert!(result.take_profit.is_some());
3427        assert!(result.stop_loss.is_some());
3428    }
3429
3430    #[rstest]
3431    fn test_parse_tp_sl_params_rejects_orphaned_sl_fields() {
3432        let p = params_from(&[("sl_trigger_by", json!("IndexPrice"))]);
3433        let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3434        assert!(err.to_string().contains("SL override fields require"));
3435    }
3436
3437    #[rstest]
3438    fn test_parse_tp_sl_params_rejects_bool_order_iv() {
3439        let p = params_from(&[("order_iv", json!(true))]);
3440        let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3441        assert!(err.to_string().contains("order_iv"));
3442    }
3443
3444    #[rstest]
3445    fn test_parse_tp_sl_params_rejects_string_mmp() {
3446        let p = params_from(&[("mmp", json!("true"))]);
3447        let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3448        assert!(err.to_string().contains("mmp"));
3449    }
3450
3451    #[rstest]
3452    fn test_parse_tp_sl_params_order_iv_string() {
3453        let p = params_from(&[("order_iv", json!("0.75"))]);
3454        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3455        assert_eq!(result.order_iv.as_deref(), Some("0.75"));
3456    }
3457
3458    #[rstest]
3459    fn test_parse_tp_sl_params_order_iv_numeric() {
3460        let p = params_from(&[("order_iv", json!(0.75))]);
3461        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3462        assert_eq!(result.order_iv.as_deref(), Some("0.75"));
3463    }
3464
3465    #[rstest]
3466    fn test_parse_tp_sl_params_mmp() {
3467        let p = params_from(&[("mmp", json!(true))]);
3468        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3469        assert_eq!(result.mmp, Some(true));
3470    }
3471
3472    #[rstest]
3473    #[case(0, BybitPositionIdx::OneWay)]
3474    #[case(1, BybitPositionIdx::BuyHedge)]
3475    #[case(2, BybitPositionIdx::SellHedge)]
3476    fn test_parse_tp_sl_params_position_idx_valid(
3477        #[case] idx: i64,
3478        #[case] expected: BybitPositionIdx,
3479    ) {
3480        let p = params_from(&[("position_idx", json!(idx))]);
3481        let result = parse_bybit_tp_sl_params(Some(&p)).unwrap();
3482        assert_eq!(result.position_idx, Some(expected));
3483    }
3484
3485    #[rstest]
3486    #[case(json!(3))]
3487    #[case(json!(-1))]
3488    #[case(json!("1"))]
3489    #[case(json!(true))]
3490    fn test_parse_tp_sl_params_position_idx_invalid(#[case] value: serde_json::Value) {
3491        let p = params_from(&[("position_idx", value)]);
3492        let err = parse_bybit_tp_sl_params(Some(&p)).unwrap_err();
3493        assert!(err.to_string().contains("position_idx"));
3494    }
3495
3496    #[rstest]
3497    #[case(
3498        BybitOrderType::Market,
3499        BybitStopOrderType::TakeProfit,
3500        BybitTriggerDirection::RisesTo,
3501        BybitOrderSide::Sell,
3502        OrderType::MarketIfTouched
3503    )]
3504    #[case(
3505        BybitOrderType::Market,
3506        BybitStopOrderType::StopLoss,
3507        BybitTriggerDirection::FallsTo,
3508        BybitOrderSide::Sell,
3509        OrderType::StopMarket
3510    )]
3511    #[case(
3512        BybitOrderType::Market,
3513        BybitStopOrderType::TakeProfit,
3514        BybitTriggerDirection::FallsTo,
3515        BybitOrderSide::Buy,
3516        OrderType::MarketIfTouched
3517    )]
3518    #[case(
3519        BybitOrderType::Market,
3520        BybitStopOrderType::StopLoss,
3521        BybitTriggerDirection::RisesTo,
3522        BybitOrderSide::Buy,
3523        OrderType::StopMarket
3524    )]
3525    #[case(
3526        BybitOrderType::Limit,
3527        BybitStopOrderType::TakeProfit,
3528        BybitTriggerDirection::RisesTo,
3529        BybitOrderSide::Sell,
3530        OrderType::LimitIfTouched
3531    )]
3532    #[case(
3533        BybitOrderType::Limit,
3534        BybitStopOrderType::StopLoss,
3535        BybitTriggerDirection::FallsTo,
3536        BybitOrderSide::Sell,
3537        OrderType::StopLimit
3538    )]
3539    #[case(
3540        BybitOrderType::Limit,
3541        BybitStopOrderType::PartialTakeProfit,
3542        BybitTriggerDirection::FallsTo,
3543        BybitOrderSide::Buy,
3544        OrderType::LimitIfTouched
3545    )]
3546    #[case(
3547        BybitOrderType::Limit,
3548        BybitStopOrderType::PartialStopLoss,
3549        BybitTriggerDirection::RisesTo,
3550        BybitOrderSide::Buy,
3551        OrderType::StopLimit
3552    )]
3553    #[case(
3554        BybitOrderType::Market,
3555        BybitStopOrderType::TpslOrder,
3556        BybitTriggerDirection::FallsTo,
3557        BybitOrderSide::Sell,
3558        OrderType::StopMarket
3559    )]
3560    #[case(
3561        BybitOrderType::Market,
3562        BybitStopOrderType::Stop,
3563        BybitTriggerDirection::RisesTo,
3564        BybitOrderSide::Buy,
3565        OrderType::StopMarket
3566    )]
3567    #[case(
3568        BybitOrderType::Market,
3569        BybitStopOrderType::Stop,
3570        BybitTriggerDirection::FallsTo,
3571        BybitOrderSide::Sell,
3572        OrderType::StopMarket
3573    )]
3574    #[case(
3575        BybitOrderType::Market,
3576        BybitStopOrderType::TrailingStop,
3577        BybitTriggerDirection::FallsTo,
3578        BybitOrderSide::Sell,
3579        OrderType::StopMarket
3580    )]
3581    #[case(
3582        BybitOrderType::Limit,
3583        BybitStopOrderType::TrailingStop,
3584        BybitTriggerDirection::RisesTo,
3585        BybitOrderSide::Buy,
3586        OrderType::StopLimit
3587    )]
3588    fn test_parse_bybit_order_type_conditional(
3589        #[case] order_type: BybitOrderType,
3590        #[case] stop_order_type: BybitStopOrderType,
3591        #[case] trigger_direction: BybitTriggerDirection,
3592        #[case] side: BybitOrderSide,
3593        #[case] expected: OrderType,
3594    ) {
3595        let result = parse_bybit_order_type(order_type, stop_order_type, trigger_direction, side);
3596        assert_eq!(result, expected);
3597    }
3598
3599    #[rstest]
3600    #[case(
3601        BybitOrderType::Market,
3602        BybitStopOrderType::None,
3603        BybitTriggerDirection::None,
3604        BybitOrderSide::Buy,
3605        OrderType::Market
3606    )]
3607    #[case(
3608        BybitOrderType::Limit,
3609        BybitStopOrderType::Unknown,
3610        BybitTriggerDirection::None,
3611        BybitOrderSide::Sell,
3612        OrderType::Limit
3613    )]
3614    #[case(
3615        BybitOrderType::Market,
3616        BybitStopOrderType::TakeProfit,
3617        BybitTriggerDirection::None,
3618        BybitOrderSide::Sell,
3619        OrderType::Market
3620    )]
3621    #[case(
3622        BybitOrderType::Limit,
3623        BybitStopOrderType::StopLoss,
3624        BybitTriggerDirection::None,
3625        BybitOrderSide::Buy,
3626        OrderType::Limit
3627    )]
3628    fn test_parse_bybit_order_type_plain(
3629        #[case] order_type: BybitOrderType,
3630        #[case] stop_order_type: BybitStopOrderType,
3631        #[case] trigger_direction: BybitTriggerDirection,
3632        #[case] side: BybitOrderSide,
3633        #[case] expected: OrderType,
3634    ) {
3635        let result = parse_bybit_order_type(order_type, stop_order_type, trigger_direction, side);
3636        assert_eq!(result, expected);
3637    }
3638
3639    #[rstest]
3640    fn test_parse_order_status_report_take_profit() {
3641        let instrument = linear_instrument();
3642        let json = load_test_json("http_get_orders_realtime_tp_sl.json");
3643        let response: BybitOpenOrdersResponse = serde_json::from_str(&json).unwrap();
3644        let order = &response.result.list[0];
3645        let account_id = AccountId::new("BYBIT-001");
3646
3647        let report = parse_order_status_report(order, &instrument, account_id, TS).unwrap();
3648
3649        assert_eq!(report.order_type, OrderType::MarketIfTouched);
3650        assert_eq!(report.order_side, OrderSide::Sell.into());
3651        assert_eq!(report.order_status, OrderStatus::Accepted);
3652        assert!(report.trigger_price.is_some());
3653        assert_eq!(
3654            report.trigger_price.unwrap(),
3655            Price::from_str("55000.0").unwrap()
3656        );
3657        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
3658        assert!(report.reduce_only);
3659    }
3660
3661    #[rstest]
3662    fn test_parse_order_status_report_stop_loss_limit() {
3663        let instrument = linear_instrument();
3664        let json = load_test_json("http_get_orders_realtime_tp_sl.json");
3665        let response: BybitOpenOrdersResponse = serde_json::from_str(&json).unwrap();
3666        let order = &response.result.list[1];
3667        let account_id = AccountId::new("BYBIT-001");
3668
3669        let report = parse_order_status_report(order, &instrument, account_id, TS).unwrap();
3670
3671        assert_eq!(report.order_type, OrderType::StopLimit);
3672        assert_eq!(report.order_side, OrderSide::Sell.into());
3673        assert_eq!(report.order_status, OrderStatus::Accepted);
3674        assert!(report.trigger_price.is_some());
3675        assert_eq!(
3676            report.trigger_price.unwrap(),
3677            Price::from_str("48000.0").unwrap()
3678        );
3679        assert!(report.price.is_some());
3680        assert_eq!(report.price.unwrap(), Price::from_str("47500.0").unwrap());
3681        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
3682        assert!(report.reduce_only);
3683    }
3684
3685    #[rstest]
3686    #[case::oneway(0, "BTCUSDT-LINEAR.BYBIT-ONEWAY")]
3687    #[case::long(1, "BTCUSDT-LINEAR.BYBIT-LONG")]
3688    #[case::short(2, "BTCUSDT-LINEAR.BYBIT-SHORT")]
3689    #[case::unknown(99, "BTCUSDT-LINEAR.BYBIT-UNKNOWN")]
3690    fn test_make_venue_position_id(#[case] position_idx: i32, #[case] expected: &str) {
3691        let instrument_id = InstrumentId::from("BTCUSDT-LINEAR.BYBIT");
3692        let result = make_venue_position_id(instrument_id, position_idx);
3693        assert_eq!(result, PositionId::from(expected));
3694    }
3695
3696    #[rstest]
3697    #[case::oneway(0, None)]
3698    #[case::long(1, Some("BTCUSDT-LINEAR.BYBIT-LONG"))]
3699    #[case::short(2, Some("BTCUSDT-LINEAR.BYBIT-SHORT"))]
3700    #[case::unknown(99, None)]
3701    fn test_make_hedge_venue_position_id(
3702        #[case] position_idx: i32,
3703        #[case] expected: Option<&str>,
3704    ) {
3705        let instrument_id = InstrumentId::from("BTCUSDT-LINEAR.BYBIT");
3706        let result = make_hedge_venue_position_id(instrument_id, position_idx);
3707        assert_eq!(result, expected.map(PositionId::from));
3708    }
3709
3710    #[rstest]
3711    #[case::buy_open(BybitOrderSide::Buy, false, BybitPositionIdx::BuyHedge)]
3712    #[case::sell_open(BybitOrderSide::Sell, false, BybitPositionIdx::SellHedge)]
3713    #[case::sell_close_long(BybitOrderSide::Sell, true, BybitPositionIdx::BuyHedge)]
3714    #[case::buy_close_short(BybitOrderSide::Buy, true, BybitPositionIdx::SellHedge)]
3715    fn test_resolve_position_idx_hedge_mode(
3716        #[case] side: BybitOrderSide,
3717        #[case] is_reduce_only: bool,
3718        #[case] expected: BybitPositionIdx,
3719    ) {
3720        let idx = resolve_position_idx(
3721            Some(BybitPositionMode::BothSides),
3722            side,
3723            is_reduce_only,
3724            None,
3725        );
3726        assert_eq!(idx, Some(expected));
3727    }
3728
3729    #[rstest]
3730    fn test_resolve_position_idx_one_way_mode() {
3731        let idx = resolve_position_idx(
3732            Some(BybitPositionMode::MergedSingle),
3733            BybitOrderSide::Buy,
3734            false,
3735            None,
3736        );
3737        assert_eq!(idx, Some(BybitPositionIdx::OneWay));
3738    }
3739
3740    #[rstest]
3741    fn test_resolve_position_idx_manual_override_wins() {
3742        let idx = resolve_position_idx(
3743            Some(BybitPositionMode::BothSides),
3744            BybitOrderSide::Buy,
3745            false,
3746            Some(BybitPositionIdx::SellHedge),
3747        );
3748        assert_eq!(idx, Some(BybitPositionIdx::SellHedge));
3749    }
3750
3751    #[rstest]
3752    fn test_resolve_position_idx_returns_none_when_unconfigured() {
3753        let idx = resolve_position_idx(None, BybitOrderSide::Buy, false, None);
3754        assert!(idx.is_none());
3755    }
3756
3757    #[rstest]
3758    fn test_parse_fill_report_venue_position_id_is_none() {
3759        let instrument = linear_instrument();
3760        let json = load_test_json("http_get_executions.json");
3761        let response: BybitTradeHistoryResponse = serde_json::from_str(&json).unwrap();
3762        let execution = &response.result.list[0];
3763        let account_id = AccountId::new("BYBIT-001");
3764
3765        let report = parse_fill_report(execution, account_id, &instrument, TS).unwrap();
3766
3767        assert_eq!(report.venue_position_id, None);
3768    }
3769
3770    #[rstest]
3771    #[case::corporate_action("CorporateAction", BybitExecType::CorporateAction, true)]
3772    #[case::forward_split_settle("ForwardSplitSettle", BybitExecType::ForwardSplitSettle, true)]
3773    #[case::reverse_split_settle("ReverseSplitSettle", BybitExecType::ReverseSplitSettle, true)]
3774    #[case::dividend("Dividend", BybitExecType::Dividend, true)]
3775    #[case::unknown_literal("UNKNOWN", BybitExecType::Unknown, false)]
3776    #[case::unrecognized("StockMerger", BybitExecType::Unknown, false)]
3777    fn test_parse_http_exec_type_fill_report(
3778        #[case] exec_type: &str,
3779        #[case] expected: BybitExecType,
3780        #[case] exchange_generated: bool,
3781    ) {
3782        let instrument = linear_instrument();
3783        let json = load_test_json("http_get_executions.json");
3784        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
3785        value["result"]["list"][0]["execType"] = json!(exec_type);
3786        let response: BybitTradeHistoryResponse = serde_json::from_value(value).unwrap();
3787        let execution = &response.result.list[0];
3788        let account_id = AccountId::new("BYBIT-001");
3789
3790        assert_eq!(execution.exec_type, expected);
3791        assert_eq!(
3792            execution.exec_type.is_exchange_generated(),
3793            exchange_generated
3794        );
3795
3796        let report = parse_fill_report(execution, account_id, &instrument, TS).unwrap();
3797
3798        assert_eq!(
3799            report.venue_order_id,
3800            VenueOrderId::from("8c065341-7b52-4ca9-ac2c-37e31ac55c94")
3801        );
3802    }
3803
3804    #[rstest]
3805    fn test_parse_order_status_report_venue_position_id_for_hedge() {
3806        let instrument = linear_instrument();
3807        let json = load_test_json("http_get_orders_realtime_tp_sl.json");
3808        let response: BybitOpenOrdersResponse = serde_json::from_str(&json).unwrap();
3809        let mut order = response.result.list[0].clone();
3810        order.position_idx = 2;
3811        let account_id = AccountId::new("BYBIT-001");
3812
3813        let report = parse_order_status_report(&order, &instrument, account_id, TS).unwrap();
3814
3815        assert_eq!(
3816            report.venue_position_id,
3817            Some(PositionId::from("BTCUSDT-LINEAR.BYBIT-SHORT"))
3818        );
3819    }
3820
3821    #[rstest]
3822    fn test_parse_position_status_report_venue_position_id_for_hedge() {
3823        let json = load_test_json("http_get_positions.json");
3824        let response: BybitPositionListResponse = serde_json::from_str(&json).unwrap();
3825        let mut position = response.result.list[0].clone();
3826        position.position_idx = BybitPositionIdx::BuyHedge;
3827        let instrument = linear_instrument();
3828        let account_id = AccountId::new("BYBIT-001");
3829
3830        let report = parse_position_status_report(&position, account_id, &instrument, TS).unwrap();
3831
3832        assert_eq!(
3833            report.venue_position_id,
3834            Some(PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG"))
3835        );
3836    }
3837
3838    #[rstest]
3839    fn test_parse_order_status_report_venue_position_id_is_none() {
3840        let instrument = linear_instrument();
3841        let json = load_test_json("http_get_orders_realtime_tp_sl.json");
3842        let response: BybitOpenOrdersResponse = serde_json::from_str(&json).unwrap();
3843        let order = &response.result.list[0]; // TP order, positionIdx=0
3844        let account_id = AccountId::new("BYBIT-001");
3845
3846        let report = parse_order_status_report(order, &instrument, account_id, TS).unwrap();
3847
3848        assert_eq!(report.venue_position_id, None);
3849    }
3850}