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