Skip to main content

nautilus_bybit/websocket/
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//! Parsers for Bybit WebSocket payloads.
17
18use std::convert::TryFrom;
19
20use anyhow::Context;
21use nautilus_core::{datetime::NANOSECONDS_IN_MILLISECOND, nanos::UnixNanos, uuid::UUID4};
22use nautilus_model::{
23    data::{
24        Bar, BarType, BookOrder, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate,
25        OrderBookDelta, OrderBookDeltas, QuoteTick, TradeTick, greeks::OptionGreekValues,
26        option_chain::OptionGreeks,
27    },
28    enums::{
29        AccountType, AggressorSide, BookAction, GreeksConvention, LiquiditySide, OrderSide,
30        OrderStatus, PositionSide, RecordFlag, TimeInForce, TriggerType,
31    },
32    events::account::state::AccountState,
33    fees::{MakerTakerFeeRates, calculate_maker_taker_commission},
34    identifiers::{AccountId, ClientOrderId, InstrumentId, PositionId, TradeId, VenueOrderId},
35    instruments::{Instrument, any::InstrumentAny},
36    reports::{FillReport, OrderStatusReport, PositionStatusReport},
37    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
38};
39use rust_decimal::Decimal;
40
41use super::{
42    enums::{BybitWsOperation, BybitWsPrivateChannel, BybitWsPublicChannel},
43    messages::{
44        BybitWsAccountExecution, BybitWsAccountExecutionFast, BybitWsAccountOrder,
45        BybitWsAccountPosition, BybitWsAccountWallet, BybitWsAuthResponse, BybitWsFrame,
46        BybitWsKline, BybitWsLiquidation, BybitWsOrderResponse, BybitWsOrderbookDepthMsg,
47        BybitWsResponse, BybitWsSubscriptionMsg, BybitWsTickerLinear, BybitWsTickerOptionMsg,
48        BybitWsTrade,
49    },
50};
51use crate::{
52    common::{
53        consts::BYBIT_QUOTE_DEPTH,
54        enums::{
55            BybitOrderSide, BybitOrderStatus, BybitPositionSide, BybitProductType, BybitTimeInForce,
56        },
57        parse::{
58            bybit_rejection_due_post_only, get_currency, make_hedge_venue_position_id,
59            parse_book_level, parse_bybit_order_type, parse_millis_timestamp,
60            parse_price_with_precision, parse_quantity_with_precision,
61        },
62    },
63    data_types::BybitLiquidation,
64};
65
66/// Classifies a parsed JSON value into a typed Bybit WebSocket frame.
67///
68/// Returns `Unknown(value)` if no specific type matches.
69pub fn parse_bybit_ws_frame(value: serde_json::Value) -> BybitWsFrame {
70    if let Some(op_val) = value.get("op") {
71        if let Ok(op) = serde_json::from_value::<BybitWsOperation>(op_val.clone())
72            && op == BybitWsOperation::Auth
73            && let Ok(auth) = serde_json::from_value::<BybitWsAuthResponse>(value.clone())
74        {
75            let is_success = auth.success.unwrap_or(false) || auth.ret_code.unwrap_or(-1) == 0;
76            if is_success {
77                return BybitWsFrame::Auth(auth);
78            }
79            let resp = BybitWsResponse {
80                op: Some(auth.op.clone()),
81                topic: None,
82                success: auth.success,
83                conn_id: auth.conn_id.clone(),
84                req_id: None,
85                ret_code: auth.ret_code,
86                ret_msg: auth.ret_msg,
87            };
88            return BybitWsFrame::ErrorResponse(resp);
89        }
90
91        if let Some(op_str) = op_val.as_str()
92            && op_str.starts_with("order.")
93        {
94            return serde_json::from_value::<BybitWsOrderResponse>(value.clone()).map_or_else(
95                |_| BybitWsFrame::Unknown(value),
96                BybitWsFrame::OrderResponse,
97            );
98        }
99    }
100
101    if let Some(success) = value.get("success").and_then(serde_json::Value::as_bool) {
102        if success {
103            return serde_json::from_value::<BybitWsSubscriptionMsg>(value.clone())
104                .map_or_else(|_| BybitWsFrame::Unknown(value), BybitWsFrame::Subscription);
105        }
106        return serde_json::from_value::<BybitWsResponse>(value.clone()).map_or_else(
107            |_| BybitWsFrame::Unknown(value),
108            BybitWsFrame::ErrorResponse,
109        );
110    }
111
112    if let Some(topic) = value.get("topic").and_then(serde_json::Value::as_str) {
113        if topic.starts_with(BybitWsPublicChannel::OrderBook.as_ref()) {
114            return serde_json::from_value(value.clone())
115                .map_or_else(|_| BybitWsFrame::Unknown(value), BybitWsFrame::Orderbook);
116        }
117
118        if topic.contains(BybitWsPublicChannel::PublicTrade.as_ref())
119            || topic.starts_with(BybitWsPublicChannel::Trade.as_ref())
120        {
121            return serde_json::from_value(value.clone())
122                .map_or_else(|_| BybitWsFrame::Unknown(value), BybitWsFrame::Trade);
123        }
124
125        if topic.starts_with(BybitWsPublicChannel::Kline.as_ref()) {
126            return serde_json::from_value(value.clone())
127                .map_or_else(|_| BybitWsFrame::Unknown(value), BybitWsFrame::Kline);
128        }
129
130        if topic.starts_with(BybitWsPublicChannel::Tickers.as_ref()) {
131            // Option symbols have 3+ hyphens: BTC-6JAN23-17500-C
132            let is_option = value
133                .get("data")
134                .and_then(|d| d.get("symbol"))
135                .and_then(|s| s.as_str())
136                .is_some_and(|symbol| symbol.contains('-') && symbol.matches('-').count() >= 3);
137
138            if is_option {
139                return serde_json::from_value(value.clone())
140                    .map_or_else(|_| BybitWsFrame::Unknown(value), BybitWsFrame::TickerOption);
141            }
142            return serde_json::from_value(value.clone())
143                .map_or_else(|_| BybitWsFrame::Unknown(value), BybitWsFrame::TickerLinear);
144        }
145
146        if topic.starts_with(BybitWsPublicChannel::AllLiquidation.as_ref()) {
147            return serde_json::from_value(value.clone())
148                .map_or_else(|_| BybitWsFrame::Unknown(value), BybitWsFrame::Liquidation);
149        }
150
151        if topic.starts_with(BybitWsPrivateChannel::Order.as_ref()) {
152            return serde_json::from_value(value.clone())
153                .map_or_else(|_| BybitWsFrame::Unknown(value), BybitWsFrame::AccountOrder);
154        }
155
156        if topic.starts_with(BybitWsPrivateChannel::ExecutionFast.as_ref()) {
157            return serde_json::from_value(value.clone()).map_or_else(
158                |_| BybitWsFrame::Unknown(value),
159                BybitWsFrame::AccountExecutionFast,
160            );
161        }
162
163        if topic.starts_with(BybitWsPrivateChannel::Execution.as_ref()) {
164            return serde_json::from_value(value.clone()).map_or_else(
165                |_| BybitWsFrame::Unknown(value),
166                BybitWsFrame::AccountExecution,
167            );
168        }
169
170        if topic.starts_with(BybitWsPrivateChannel::Wallet.as_ref()) {
171            return serde_json::from_value(value.clone()).map_or_else(
172                |_| BybitWsFrame::Unknown(value),
173                BybitWsFrame::AccountWallet,
174            );
175        }
176
177        if topic.starts_with(BybitWsPrivateChannel::Position.as_ref()) {
178            return serde_json::from_value(value.clone()).map_or_else(
179                |_| BybitWsFrame::Unknown(value),
180                BybitWsFrame::AccountPosition,
181            );
182        }
183    }
184
185    BybitWsFrame::Unknown(value)
186}
187
188/// Parses a Bybit WebSocket topic string into its components.
189///
190/// # Errors
191///
192/// Returns an error if the topic format is invalid.
193pub fn parse_topic(topic: &str) -> anyhow::Result<Vec<&str>> {
194    let parts: Vec<&str> = topic.split('.').collect();
195    if parts.is_empty() {
196        anyhow::bail!("Invalid topic format: empty topic");
197    }
198    Ok(parts)
199}
200
201/// Parses a Bybit kline topic into (interval, symbol).
202///
203/// Topic format: "kline.{interval}.{symbol}" (e.g., "kline.5.BTCUSDT")
204///
205/// # Errors
206///
207/// Returns an error if the topic format is invalid.
208pub fn parse_kline_topic(topic: &str) -> anyhow::Result<(&str, &str)> {
209    let kline = BybitWsPublicChannel::Kline.as_ref();
210    let parts = parse_topic(topic)?;
211    if parts.len() != 3 || parts[0] != kline {
212        anyhow::bail!(
213            "Invalid kline topic format: expected '{kline}.{{interval}}.{{symbol}}', was '{topic}'"
214        );
215    }
216    Ok((parts[1], parts[2]))
217}
218
219/// Parses a WebSocket trade frame into a [`TradeTick`].
220pub fn parse_ws_trade_tick(
221    trade: &BybitWsTrade,
222    instrument: &InstrumentAny,
223    ts_init: UnixNanos,
224) -> anyhow::Result<TradeTick> {
225    let price = parse_price_with_precision(&trade.p, instrument.price_precision(), "trade.p")?;
226    let size = parse_quantity_with_precision(&trade.v, instrument.size_precision(), "trade.v")?;
227    let aggressor: AggressorSide = trade.taker_side.into();
228    let trade_id = TradeId::new_checked(trade.i.as_str())
229        .context("invalid trade identifier in Bybit trade message")?;
230    let ts_event = parse_millis_i64(trade.t, "trade.T")?;
231
232    TradeTick::new_checked(
233        instrument.id(),
234        price,
235        size,
236        aggressor,
237        trade_id,
238        ts_event,
239        ts_init,
240    )
241    .context("failed to construct TradeTick from Bybit trade message")
242}
243
244/// Parses a WebSocket liquidation entry into a [`BybitLiquidation`].
245///
246/// Bybit reports the side of the liquidated position, so `Buy` maps to
247/// [`PositionSide::Long`] and `Sell` maps to [`PositionSide::Short`].
248///
249/// # Errors
250///
251/// Returns an error if the side is neither `Buy` nor `Sell`, or if the price, size, or
252/// timestamp cannot be parsed.
253pub fn parse_ws_liquidation(
254    liquidation: &BybitWsLiquidation,
255    instrument: &InstrumentAny,
256    ts_init: UnixNanos,
257) -> anyhow::Result<BybitLiquidation> {
258    let position_side = match liquidation.side {
259        BybitOrderSide::Buy => PositionSide::Long,
260        BybitOrderSide::Sell => PositionSide::Short,
261        side @ BybitOrderSide::Unknown => {
262            anyhow::bail!("Invalid liquidation side: expected Buy or Sell, was {side:?}")
263        }
264    };
265
266    let bankruptcy_price = parse_price_with_precision(
267        &liquidation.p,
268        instrument.price_precision(),
269        "liquidation.p",
270    )?;
271    let quantity = parse_quantity_with_precision(
272        &liquidation.v,
273        instrument.size_precision(),
274        "liquidation.v",
275    )?;
276    let ts_event = parse_millis_i64(liquidation.t, "liquidation.T")?;
277
278    Ok(BybitLiquidation::new(
279        instrument.id(),
280        position_side,
281        bankruptcy_price,
282        quantity,
283        ts_event,
284        ts_init,
285    ))
286}
287
288/// Parses an order book depth message into [`OrderBookDeltas`].
289pub fn parse_orderbook_deltas(
290    msg: &BybitWsOrderbookDepthMsg,
291    instrument: &InstrumentAny,
292    ts_init: UnixNanos,
293) -> anyhow::Result<OrderBookDeltas> {
294    let is_snapshot = msg.msg_type.eq_ignore_ascii_case("snapshot");
295    let ts_event = parse_millis_i64(msg.ts, "orderbook.ts")?;
296    let ts_init = if ts_init.is_zero() { ts_event } else { ts_init };
297
298    let depth = &msg.data;
299    let instrument_id = instrument.id();
300    let price_precision = instrument.price_precision();
301    let size_precision = instrument.size_precision();
302    let update_id = u64::try_from(depth.u)
303        .context("received negative update id in Bybit order book message")?;
304    let sequence = u64::try_from(depth.seq)
305        .context("received negative sequence in Bybit order book message")?;
306
307    let total_levels = depth.b.len() + depth.a.len();
308    let capacity = total_levels + usize::from(is_snapshot);
309
310    let snapshot_flag = if is_snapshot {
311        RecordFlag::F_SNAPSHOT as u8
312    } else {
313        0
314    };
315    let mut deltas = Vec::with_capacity(capacity);
316
317    if is_snapshot {
318        deltas.push(OrderBookDelta::clear(
319            instrument_id,
320            sequence,
321            ts_event,
322            ts_init,
323        ));
324    }
325    let mut processed = 0_usize;
326
327    let mut push_level = |values: &[String], side: OrderSide| -> anyhow::Result<()> {
328        let (price, size) = parse_book_level(values, price_precision, size_precision, "orderbook")?;
329        let action = if size.is_zero() {
330            BookAction::Delete
331        } else if is_snapshot {
332            BookAction::Add
333        } else {
334            BookAction::Update
335        };
336
337        processed += 1;
338        let mut flags = RecordFlag::F_MBP as u8 | snapshot_flag;
339
340        if processed == total_levels {
341            flags |= RecordFlag::F_LAST as u8;
342        }
343
344        let order = BookOrder::new(side, price, size, update_id);
345        let delta = OrderBookDelta::new_checked(
346            instrument_id,
347            action,
348            order,
349            flags,
350            sequence,
351            ts_event,
352            ts_init,
353        )
354        .context("failed to construct OrderBookDelta from Bybit book level")?;
355        deltas.push(delta);
356        Ok(())
357    };
358
359    for level in &depth.b {
360        push_level(level, OrderSide::Buy)?;
361    }
362
363    for level in &depth.a {
364        push_level(level, OrderSide::Sell)?;
365    }
366
367    if total_levels == 0
368        && let Some(last) = deltas.last_mut()
369    {
370        last.flags |= RecordFlag::F_LAST as u8;
371    }
372
373    OrderBookDeltas::new_checked(instrument_id, deltas)
374        .context("failed to assemble OrderBookDeltas from Bybit message")
375}
376
377/// Parses a depth-1 order book snapshot into a [`QuoteTick`].
378///
379/// # Errors
380///
381/// Returns an error if the depth or message type differs, a side is missing, or price or size data
382/// is invalid.
383pub fn parse_orderbook_quote(
384    msg: &BybitWsOrderbookDepthMsg,
385    instrument: &InstrumentAny,
386    ts_init: UnixNanos,
387) -> anyhow::Result<QuoteTick> {
388    let (depth, _) = parse_orderbook_topic(msg.topic.as_str())?;
389    anyhow::ensure!(
390        depth == BYBIT_QUOTE_DEPTH && msg.msg_type == "snapshot",
391        "Expected depth-1 orderbook snapshot"
392    );
393    let ts_event = parse_millis_i64(msg.ts, "orderbook.ts")?;
394    let ts_init = if ts_init.is_zero() { ts_event } else { ts_init };
395    let price_precision = instrument.price_precision();
396    let size_precision = instrument.size_precision();
397    let bid = msg
398        .data
399        .b
400        .first()
401        .context("orderbook snapshot missing bid")?;
402    let ask = msg
403        .data
404        .a
405        .first()
406        .context("orderbook snapshot missing ask")?;
407    let (bid_price, bid_size) = parse_book_level(bid, price_precision, size_precision, "bid")?;
408    let (ask_price, ask_size) = parse_book_level(ask, price_precision, size_precision, "ask")?;
409
410    QuoteTick::new_checked(
411        instrument.id(),
412        bid_price,
413        ask_price,
414        bid_size,
415        ask_size,
416        ts_event,
417        ts_init,
418    )
419    .context("failed to construct QuoteTick from Bybit order book message")
420}
421
422pub(crate) fn parse_orderbook_topic(topic: &str) -> anyhow::Result<(u32, &str)> {
423    let mut parts = topic.splitn(3, '.');
424    anyhow::ensure!(
425        parts.next() == Some("orderbook"),
426        "Invalid orderbook topic: {topic}"
427    );
428    let depth = parts.next().context("missing orderbook depth")?.parse()?;
429    let symbol = parts
430        .next()
431        .filter(|s| !s.is_empty())
432        .context("missing orderbook symbol")?;
433    Ok((depth, symbol))
434}
435
436/// Parses an option ticker payload into a [`QuoteTick`].
437pub fn parse_ticker_option_quote(
438    msg: &BybitWsTickerOptionMsg,
439    instrument: &InstrumentAny,
440    ts_init: UnixNanos,
441) -> anyhow::Result<QuoteTick> {
442    let ts_event = parse_millis_i64(msg.ts, "ticker.ts")?;
443    let ts_init = if ts_init.is_zero() { ts_event } else { ts_init };
444    let price_precision = instrument.price_precision();
445    let size_precision = instrument.size_precision();
446
447    let data = &msg.data;
448    let bid_price =
449        parse_price_with_precision(&data.bid_price, price_precision, "ticker.bidPrice")?;
450    let ask_price =
451        parse_price_with_precision(&data.ask_price, price_precision, "ticker.askPrice")?;
452    let bid_size = parse_quantity_with_precision(&data.bid_size, size_precision, "ticker.bidSize")?;
453    let ask_size = parse_quantity_with_precision(&data.ask_size, size_precision, "ticker.askSize")?;
454
455    QuoteTick::new_checked(
456        instrument.id(),
457        bid_price,
458        ask_price,
459        bid_size,
460        ask_size,
461        ts_event,
462        ts_init,
463    )
464    .context("failed to construct QuoteTick from Bybit option ticker message")
465}
466
467/// Parses a linear ticker payload into a [`FundingRateUpdate`].
468///
469/// # Errors
470///
471/// Returns an error if funding rate, funding interval or next funding time fields are missing or cannot be parsed.
472pub fn parse_ticker_linear_funding(
473    data: &BybitWsTickerLinear,
474    instrument_id: InstrumentId,
475    ts_event: UnixNanos,
476    ts_init: UnixNanos,
477) -> anyhow::Result<FundingRateUpdate> {
478    let funding_rate_str = data
479        .funding_rate
480        .as_ref()
481        .context("Bybit ticker missing funding_rate")?;
482
483    if funding_rate_str.is_empty() {
484        anyhow::bail!(
485            "empty funding_rate for {instrument_id} (dated futures do not have funding rates)"
486        );
487    }
488
489    let funding_rate = funding_rate_str
490        .as_str()
491        .parse::<Decimal>()
492        .with_context(|| {
493            format!("invalid funding_rate value '{funding_rate_str}' for {instrument_id}")
494        })?;
495
496    let funding_interval = if let Some(funding_interval_hour) = &data.funding_interval_hour {
497        let funding_interval_hour = funding_interval_hour
498            .as_str()
499            .parse::<u16>()
500            .context("invalid funding_interval_hour value")?;
501        Some(
502            funding_interval_hour
503                .checked_mul(60)
504                .ok_or_else(|| anyhow::anyhow!("funding_interval_hour out of bounds"))?,
505        )
506    } else {
507        None
508    };
509
510    let next_funding_ns = if let Some(next_funding_time) = &data.next_funding_time {
511        let next_funding_millis = next_funding_time
512            .as_str()
513            .parse::<i64>()
514            .context("invalid next_funding_time value")?;
515        Some(parse_millis_i64(next_funding_millis, "next_funding_time")?)
516    } else {
517        None
518    };
519
520    Ok(FundingRateUpdate::new(
521        instrument_id,
522        funding_rate,
523        funding_interval,
524        next_funding_ns,
525        ts_event,
526        ts_init,
527    ))
528}
529
530/// Parses a linear/inverse ticker payload into a [`MarkPriceUpdate`].
531///
532/// # Errors
533///
534/// Returns an error if the mark_price field is missing or cannot be parsed.
535pub fn parse_ticker_linear_mark_price(
536    data: &BybitWsTickerLinear,
537    instrument: &InstrumentAny,
538    ts_event: UnixNanos,
539    ts_init: UnixNanos,
540) -> anyhow::Result<MarkPriceUpdate> {
541    let mark_price_str = data
542        .mark_price
543        .as_ref()
544        .context("Bybit ticker missing mark_price")?;
545
546    let price =
547        parse_price_with_precision(mark_price_str, instrument.price_precision(), "mark_price")?;
548
549    Ok(MarkPriceUpdate::new(
550        instrument.id(),
551        price,
552        ts_event,
553        ts_init,
554    ))
555}
556
557/// Parses a linear/inverse ticker payload into an [`IndexPriceUpdate`].
558///
559/// # Errors
560///
561/// Returns an error if the index_price field is missing or cannot be parsed.
562pub fn parse_ticker_linear_index_price(
563    data: &BybitWsTickerLinear,
564    instrument: &InstrumentAny,
565    ts_event: UnixNanos,
566    ts_init: UnixNanos,
567) -> anyhow::Result<IndexPriceUpdate> {
568    let index_price_str = data
569        .index_price
570        .as_ref()
571        .context("Bybit ticker missing index_price")?;
572
573    let price =
574        parse_price_with_precision(index_price_str, instrument.price_precision(), "index_price")?;
575
576    Ok(IndexPriceUpdate::new(
577        instrument.id(),
578        price,
579        ts_event,
580        ts_init,
581    ))
582}
583
584/// Parses an option ticker payload into a [`MarkPriceUpdate`].
585///
586/// # Errors
587///
588/// Returns an error if the mark_price field cannot be parsed.
589pub fn parse_ticker_option_mark_price(
590    msg: &BybitWsTickerOptionMsg,
591    instrument: &InstrumentAny,
592    ts_init: UnixNanos,
593) -> anyhow::Result<MarkPriceUpdate> {
594    let ts_event = parse_millis_i64(msg.ts, "ticker.ts")?;
595
596    let price = parse_price_with_precision(
597        &msg.data.mark_price,
598        instrument.price_precision(),
599        "mark_price",
600    )?;
601
602    Ok(MarkPriceUpdate::new(
603        instrument.id(),
604        price,
605        ts_event,
606        ts_init,
607    ))
608}
609
610/// Parses an option ticker payload into an [`IndexPriceUpdate`].
611///
612/// # Errors
613///
614/// Returns an error if the index_price field cannot be parsed.
615pub fn parse_ticker_option_index_price(
616    msg: &BybitWsTickerOptionMsg,
617    instrument: &InstrumentAny,
618    ts_init: UnixNanos,
619) -> anyhow::Result<IndexPriceUpdate> {
620    let ts_event = parse_millis_i64(msg.ts, "ticker.ts")?;
621
622    let price = parse_price_with_precision(
623        &msg.data.index_price,
624        instrument.price_precision(),
625        "index_price",
626    )?;
627
628    Ok(IndexPriceUpdate::new(
629        instrument.id(),
630        price,
631        ts_event,
632        ts_init,
633    ))
634}
635
636/// Parses an option ticker payload into [`OptionGreeks`].
637///
638/// # Errors
639///
640/// Returns an error if any of the greek fields cannot be parsed as f64.
641pub fn parse_ticker_option_greeks(
642    msg: &BybitWsTickerOptionMsg,
643    instrument: &InstrumentAny,
644    ts_init: UnixNanos,
645) -> anyhow::Result<OptionGreeks> {
646    let ts_event = parse_millis_i64(msg.ts, "ticker.ts")?;
647
648    let delta: f64 = msg.data.delta.parse().context("invalid delta")?;
649    let gamma: f64 = msg.data.gamma.parse().context("invalid gamma")?;
650    let vega: f64 = msg.data.vega.parse().context("invalid vega")?;
651    let theta: f64 = msg.data.theta.parse().context("invalid theta")?;
652
653    let bid_iv: f64 = msg.data.bid_iv.parse().context("invalid bid_iv")?;
654    let ask_iv: f64 = msg.data.ask_iv.parse().context("invalid ask_iv")?;
655    let mark_iv: f64 = msg
656        .data
657        .mark_price_iv
658        .parse()
659        .context("invalid mark_price_iv")?;
660    let underlying_price: f64 = msg
661        .data
662        .underlying_price
663        .parse()
664        .context("invalid underlying_price")?;
665    let open_interest: f64 = msg
666        .data
667        .open_interest
668        .parse()
669        .context("invalid open_interest")?;
670
671    Ok(OptionGreeks {
672        instrument_id: instrument.id(),
673        convention: GreeksConvention::BlackScholes,
674        greeks: OptionGreekValues {
675            delta,
676            gamma,
677            vega,
678            theta,
679            rho: 0.0, // Bybit doesn't provide rho
680        },
681        mark_iv: Some(mark_iv),
682        bid_iv: Some(bid_iv),
683        ask_iv: Some(ask_iv),
684        underlying_price: Some(underlying_price),
685        open_interest: Some(open_interest),
686        ts_event,
687        ts_init,
688    })
689}
690
691pub(crate) fn parse_millis_i64(value: i64, field: &str) -> anyhow::Result<UnixNanos> {
692    if value < 0 {
693        Err(anyhow::anyhow!("{field} must be non-negative, was {value}"))
694    } else {
695        let nanos = (value as u64)
696            .checked_mul(NANOSECONDS_IN_MILLISECOND)
697            .ok_or_else(|| anyhow::anyhow!("millisecond timestamp overflowed"))?;
698        Ok(UnixNanos::from(nanos))
699    }
700}
701
702/// Parses a WebSocket kline payload into a [`Bar`].
703///
704/// # Errors
705///
706/// Returns an error if price or volume fields cannot be parsed or if the bar cannot be constructed.
707pub fn parse_ws_kline_bar(
708    kline: &BybitWsKline,
709    instrument: &InstrumentAny,
710    bar_type: BarType,
711    timestamp_on_close: bool,
712    ts_init: UnixNanos,
713) -> anyhow::Result<Bar> {
714    let price_precision = instrument.price_precision();
715    let size_precision = instrument.size_precision();
716
717    let open = parse_price_with_precision(&kline.open, price_precision, "kline.open")?;
718    let high = parse_price_with_precision(&kline.high, price_precision, "kline.high")?;
719    let low = parse_price_with_precision(&kline.low, price_precision, "kline.low")?;
720    let close = parse_price_with_precision(&kline.close, price_precision, "kline.close")?;
721    let volume = parse_quantity_with_precision(&kline.volume, size_precision, "kline.volume")?;
722
723    let ts_open = parse_millis_i64(kline.start, "kline.start")?;
724    let interval_ns = bar_type.spec().timedelta().as_nanos();
725    let interval_ns = u64::try_from(interval_ns)
726        .context("bar interval overflowed the u64 range for nanoseconds")?;
727    let ts_close = ts_open
728        .as_u64()
729        .checked_add(interval_ns)
730        .map(UnixNanos::from)
731        .context("bar timestamp overflowed when adjusting to close time")?;
732
733    let ts_event = if timestamp_on_close {
734        ts_close
735    } else {
736        ts_open
737    };
738    let ts_init = if ts_init.is_zero() { ts_close } else { ts_init };
739
740    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
741        .context("failed to construct Bar from Bybit WebSocket kline")
742}
743
744/// Parses a WebSocket account order payload into an [`OrderStatusReport`].
745///
746/// # Errors
747///
748/// Returns an error if price or quantity fields cannot be parsed or timestamps are invalid.
749pub fn parse_ws_order_status_report(
750    order: &BybitWsAccountOrder,
751    instrument: &InstrumentAny,
752    account_id: AccountId,
753    ts_init: UnixNanos,
754) -> anyhow::Result<OrderStatusReport> {
755    let instrument_id = instrument.id();
756    let venue_order_id = VenueOrderId::new(order.order_id);
757    let order_side: Option<OrderSide> = order.side.into();
758
759    let order_type = parse_bybit_order_type(
760        order.order_type,
761        order.stop_order_type,
762        order.trigger_direction,
763        order.side,
764    );
765
766    let time_in_force: TimeInForce = match order.time_in_force {
767        BybitTimeInForce::Gtc => TimeInForce::Gtc,
768        BybitTimeInForce::Ioc => TimeInForce::Ioc,
769        BybitTimeInForce::Fok => TimeInForce::Fok,
770        BybitTimeInForce::PostOnly | BybitTimeInForce::Rpi => TimeInForce::Gtc,
771    };
772
773    let quantity =
774        parse_quantity_with_precision(&order.qty, instrument.size_precision(), "order.qty")?;
775
776    let filled_qty = parse_quantity_with_precision(
777        &order.cum_exec_qty,
778        instrument.size_precision(),
779        "order.cumExecQty",
780    )?;
781
782    // Map Bybit order status to Nautilus order status
783    // Special case: if Bybit reports "Rejected" but the order has fills, treat it as Canceled.
784    // This handles the case where the exchange partially fills an order then rejects the
785    // remaining quantity (e.g., due to margin, risk limits, or liquidity constraints).
786    // The state machine does not allow PARTIALLY_FILLED -> REJECTED transitions.
787    let order_status: OrderStatus = match order.order_status {
788        BybitOrderStatus::Created | BybitOrderStatus::New | BybitOrderStatus::Untriggered => {
789            OrderStatus::Accepted
790        }
791        BybitOrderStatus::Rejected => {
792            if filled_qty.is_positive() {
793                OrderStatus::Canceled
794            } else {
795                OrderStatus::Rejected
796            }
797        }
798        BybitOrderStatus::PartiallyFilled => OrderStatus::PartiallyFilled,
799        BybitOrderStatus::Filled => OrderStatus::Filled,
800        // A post-only order that would take liquidity is reported as Cancelled with
801        // rejectReason=EC_PostOnlyWillTakeLiquidity (not Rejected). Surface it as Rejected
802        // for consistency with the tracked-order event path.
803        BybitOrderStatus::Canceled
804            if filled_qty.is_zero()
805                && bybit_rejection_due_post_only(order.reject_reason.as_str()) =>
806        {
807            OrderStatus::Rejected
808        }
809        BybitOrderStatus::Canceled | BybitOrderStatus::PartiallyFilledCanceled => {
810            OrderStatus::Canceled
811        }
812        BybitOrderStatus::Triggered => OrderStatus::Triggered,
813        BybitOrderStatus::Deactivated => OrderStatus::Canceled,
814    };
815
816    let ts_accepted = parse_millis_timestamp(&order.created_time, "order.createdTime")?;
817    let ts_last = parse_millis_timestamp(&order.updated_time, "order.updatedTime")?;
818
819    let mut report = OrderStatusReport::new(
820        account_id,
821        instrument_id,
822        None,
823        venue_order_id,
824        order_side,
825        order_type,
826        time_in_force,
827        order_status,
828        quantity,
829        filled_qty,
830        ts_accepted,
831        ts_last,
832        ts_init,
833        Some(UUID4::new()),
834    );
835
836    if !order.order_link_id.is_empty() {
837        report = report.with_client_order_id(ClientOrderId::new(order.order_link_id));
838    }
839
840    if !order.price.is_empty() && order.price != "0" {
841        let price =
842            parse_price_with_precision(&order.price, instrument.price_precision(), "order.price")?;
843        report = report.with_price(price);
844    }
845
846    if !order.avg_price.is_empty() && order.avg_price != "0" {
847        let avg_px = order.avg_price.parse::<Decimal>().with_context(|| {
848            format!("Failed to parse avg_price='{}' as Decimal", order.avg_price)
849        })?;
850        report = report.with_avg_px(avg_px);
851    }
852
853    if !order.trigger_price.is_empty() && order.trigger_price != "0" {
854        let trigger_price = parse_price_with_precision(
855            &order.trigger_price,
856            instrument.price_precision(),
857            "order.triggerPrice",
858        )?;
859        report = report.with_trigger_price(trigger_price);
860
861        // Set trigger_type for conditional orders
862        let trigger_type: TriggerType = order.trigger_by.into();
863        report = report.with_trigger_type(trigger_type);
864    }
865
866    if let Some(venue_position_id) = make_hedge_venue_position_id(instrument_id, order.position_idx)
867    {
868        report = report.with_venue_position_id(venue_position_id);
869    }
870
871    if order.reduce_only {
872        report = report.with_reduce_only(true);
873    }
874
875    if matches!(
876        order.time_in_force,
877        BybitTimeInForce::PostOnly | BybitTimeInForce::Rpi
878    ) {
879        report = report.with_post_only(true);
880    }
881
882    if !order.reject_reason.is_empty() {
883        report = report.with_cancel_reason(order.reject_reason.to_string());
884    }
885
886    Ok(report)
887}
888
889/// Parses a WebSocket account execution payload into a [`FillReport`].
890///
891/// # Errors
892///
893/// Returns an error if price or quantity fields cannot be parsed or timestamps are invalid.
894pub fn parse_ws_fill_report(
895    execution: &BybitWsAccountExecution,
896    account_id: AccountId,
897    instrument: &InstrumentAny,
898    ts_init: UnixNanos,
899) -> anyhow::Result<FillReport> {
900    let instrument_id = instrument.id();
901    let venue_order_id = VenueOrderId::new(execution.order_id);
902    let trade_id = TradeId::new_checked(execution.exec_id.as_str())
903        .context("invalid execId in Bybit WebSocket execution payload")?;
904
905    let order_side = OrderSide::try_from(execution.side)?;
906    let last_qty = parse_quantity_with_precision(
907        &execution.exec_qty,
908        instrument.size_precision(),
909        "execution.execQty",
910    )?;
911    let last_px = parse_price_with_precision(
912        &execution.exec_price,
913        instrument.price_precision(),
914        "execution.execPrice",
915    )?;
916
917    let liquidity_side = if execution.is_maker {
918        LiquiditySide::Maker
919    } else {
920        LiquiditySide::Taker
921    };
922
923    let fee_decimal: Decimal = execution
924        .exec_fee
925        .parse()
926        .with_context(|| format!("Failed to parse execFee='{}'", execution.exec_fee))?;
927
928    let commission_currency = get_currency(&execution.fee_currency);
929    let commission = Money::from_decimal(fee_decimal, commission_currency).with_context(|| {
930        format!(
931            "Failed to create commission from execFee='{}'",
932            execution.exec_fee
933        )
934    })?;
935    let ts_event = parse_millis_timestamp(&execution.exec_time, "execution.execTime")?;
936
937    let client_order_id = if execution.order_link_id.is_empty() {
938        None
939    } else {
940        Some(ClientOrderId::new(execution.order_link_id))
941    };
942
943    Ok(FillReport::new(
944        account_id,
945        instrument_id,
946        venue_order_id,
947        trade_id,
948        order_side,
949        last_qty,
950        last_px,
951        commission,
952        liquidity_side,
953        client_order_id,
954        None, // venue_position_id: execution data lacks position_idx
955        ts_event,
956        ts_init,
957        None, // report_id
958    ))
959}
960
961/// Parses a fast-stream WebSocket execution payload into a [`FillReport`].
962///
963/// The `execution.fast` channel omits fee and exec-type fields. When account fee
964/// rates are supplied, commission is derived on a best-effort basis and is not
965/// venue-authoritative. Missing rates or derivation failures produce zero commission.
966/// Option fast fills always use zero commission because the payload lacks the inputs
967/// required by Bybit's Option fee formula. Liquidity side is derived from `isMaker`.
968///
969/// `client_order_id` takes precedence over the payload's `orderLinkId`. The execution client
970/// supplies the identity it correlates by venue order ID for maker fills.
971///
972/// `venue_position_id` should be supplied for tracked hedge-mode orders so the
973/// emitted report carries the long/short position identity that the standard
974/// channel preserves via `OrderFilled`.
975///
976/// # Errors
977///
978/// Returns an error if price or quantity fields cannot be parsed or timestamps are invalid.
979pub fn parse_ws_fill_report_fast(
980    execution: &BybitWsAccountExecutionFast,
981    account_id: AccountId,
982    instrument: &InstrumentAny,
983    fee_rates: Option<MakerTakerFeeRates>,
984    client_order_id: Option<ClientOrderId>,
985    venue_position_id: Option<PositionId>,
986    ts_init: UnixNanos,
987) -> anyhow::Result<FillReport> {
988    let instrument_id = instrument.id();
989    let venue_order_id = VenueOrderId::new(execution.order_id);
990    let trade_id = TradeId::new_checked(execution.exec_id.as_str())
991        .context("invalid execId in Bybit WebSocket fast-execution payload")?;
992
993    let order_side = OrderSide::try_from(execution.side)?;
994    let last_qty = parse_quantity_with_precision(
995        &execution.exec_qty,
996        instrument.size_precision(),
997        "execution.execQty",
998    )?;
999    let last_px = parse_price_with_precision(
1000        &execution.exec_price,
1001        instrument.price_precision(),
1002        "execution.execPrice",
1003    )?;
1004
1005    let liquidity_side = if execution.is_maker {
1006        LiquiditySide::Maker
1007    } else {
1008        LiquiditySide::Taker
1009    };
1010
1011    let commission = derive_fast_commission(
1012        execution,
1013        instrument,
1014        order_side,
1015        fee_rates,
1016        last_qty,
1017        last_px,
1018        liquidity_side,
1019    );
1020    let ts_event = parse_millis_timestamp(&execution.exec_time, "execution.execTime")?;
1021    let client_order_id = client_order_id.or_else(|| {
1022        if execution.order_link_id.is_empty() {
1023            None
1024        } else {
1025            Some(ClientOrderId::new(execution.order_link_id))
1026        }
1027    });
1028
1029    Ok(FillReport::new(
1030        account_id,
1031        instrument_id,
1032        venue_order_id,
1033        trade_id,
1034        order_side,
1035        last_qty,
1036        last_px,
1037        commission,
1038        liquidity_side,
1039        client_order_id,
1040        venue_position_id,
1041        ts_event,
1042        ts_init,
1043        None,
1044    ))
1045}
1046
1047fn derive_fast_commission(
1048    execution: &BybitWsAccountExecutionFast,
1049    instrument: &InstrumentAny,
1050    order_side: OrderSide,
1051    fee_rates: Option<MakerTakerFeeRates>,
1052    last_qty: Quantity,
1053    last_px: Price,
1054    liquidity_side: LiquiditySide,
1055) -> Money {
1056    let fee_rate = fee_rates.map(|rates| {
1057        if liquidity_side == LiquiditySide::Maker {
1058            rates.maker
1059        } else {
1060            rates.taker
1061        }
1062    });
1063
1064    let currency = fast_commission_currency(execution, instrument, order_side, fee_rate);
1065    let zero_commission = || {
1066        Money::from_decimal(Decimal::ZERO, currency)
1067            .expect("zero commission is valid in any currency")
1068    };
1069
1070    if execution.category == BybitProductType::Option {
1071        return zero_commission();
1072    }
1073
1074    let Some(fee_rate) = fee_rate else {
1075        return zero_commission();
1076    };
1077
1078    match calculate_fast_commission(execution, instrument, fee_rate, last_qty, last_px, currency) {
1079        Ok(commission) => commission,
1080        Err(e) => {
1081            log::warn!(
1082                "Failed to derive fast execution commission for {} on {}, using zero: {e}",
1083                execution.exec_id,
1084                instrument.id()
1085            );
1086            zero_commission()
1087        }
1088    }
1089}
1090
1091fn calculate_fast_commission(
1092    execution: &BybitWsAccountExecutionFast,
1093    instrument: &InstrumentAny,
1094    fee_rate: Decimal,
1095    last_qty: Quantity,
1096    last_px: Price,
1097    currency: Currency,
1098) -> anyhow::Result<Money> {
1099    if execution.category == BybitProductType::Spot {
1100        let base_currency = instrument
1101            .base_currency()
1102            .expect("Bybit spot instruments have a base currency");
1103
1104        if currency == base_currency {
1105            let amount = last_qty
1106                .as_decimal()
1107                .checked_mul(fee_rate)
1108                .ok_or_else(|| anyhow::anyhow!("fast commission calculation overflow"))?;
1109            return Money::from_decimal(amount, currency).map_err(Into::into);
1110        }
1111
1112        return calculate_maker_taker_commission(instrument, last_qty, last_px, fee_rate, None);
1113    }
1114
1115    let commission =
1116        calculate_maker_taker_commission(instrument, last_qty, last_px, fee_rate, None)?;
1117    Money::from_decimal(commission.as_decimal(), instrument.settlement_currency())
1118        .map_err(Into::into)
1119}
1120
1121fn fast_commission_currency(
1122    execution: &BybitWsAccountExecutionFast,
1123    instrument: &InstrumentAny,
1124    order_side: OrderSide,
1125    fee_rate: Option<Decimal>,
1126) -> Currency {
1127    if execution.category != BybitProductType::Spot {
1128        return instrument.settlement_currency();
1129    }
1130
1131    let is_rebate = execution.is_maker && fee_rate.is_some_and(|rate| rate < Decimal::ZERO);
1132    let use_base = matches!(
1133        (order_side, is_rebate),
1134        (OrderSide::Buy, false) | (OrderSide::Sell, true)
1135    );
1136
1137    if use_base {
1138        instrument
1139            .base_currency()
1140            .expect("Bybit spot instruments have a base currency")
1141    } else {
1142        instrument.quote_currency()
1143    }
1144}
1145
1146/// Parses a WebSocket account position payload into a [`PositionStatusReport`].
1147///
1148/// # Errors
1149///
1150/// Returns an error if position size or prices cannot be parsed.
1151pub fn parse_ws_position_status_report(
1152    position: &BybitWsAccountPosition,
1153    account_id: AccountId,
1154    instrument: &InstrumentAny,
1155    ts_init: UnixNanos,
1156) -> anyhow::Result<PositionStatusReport> {
1157    let instrument_id = instrument.id();
1158
1159    // Parse absolute size as unsigned Quantity
1160    let quantity = parse_quantity_with_precision(
1161        &position.size,
1162        instrument.size_precision(),
1163        "position.size",
1164    )?;
1165
1166    let position_side = match position.side {
1167        BybitPositionSide::Buy => PositionSide::Long,
1168        BybitPositionSide::Sell => PositionSide::Short,
1169        BybitPositionSide::Flat => PositionSide::Flat,
1170    };
1171
1172    // Bybit ranks open positions 1-5 by ADL priority (5 = next to be deleveraged);
1173    // 0 means the account has no open position or is flat. Warn when approaching the
1174    // top tier so operators can react before the venue force-closes.
1175    if position.adl_rank_indicator >= 4 {
1176        log::warn!(
1177            "Elevated ADL risk: {} position size={} adl_rank={}",
1178            instrument_id,
1179            position.size,
1180            position.adl_rank_indicator,
1181        );
1182    }
1183
1184    let ts_last = parse_millis_timestamp(&position.updated_time, "position.updatedTime")?;
1185
1186    let venue_position_id = make_hedge_venue_position_id(instrument_id, position.position_idx);
1187
1188    Ok(PositionStatusReport::new(
1189        account_id,
1190        instrument_id,
1191        position_side,
1192        quantity,
1193        ts_last,
1194        ts_init,
1195        None, // report_id
1196        venue_position_id,
1197        position.entry_price, // avg_px_open
1198    ))
1199}
1200
1201/// Parses a WebSocket account wallet payload into an [`AccountState`].
1202///
1203/// # Errors
1204///
1205/// Returns an error if balance fields cannot be parsed.
1206pub fn parse_ws_account_state(
1207    wallet: &BybitWsAccountWallet,
1208    account_id: AccountId,
1209    ts_event: UnixNanos,
1210    ts_init: UnixNanos,
1211) -> anyhow::Result<AccountState> {
1212    let mut balances = Vec::new();
1213    let mut margins = Vec::new();
1214
1215    for coin_data in &wallet.coin {
1216        let currency = get_currency(coin_data.coin.as_str());
1217        let total_dec = coin_data.wallet_balance - coin_data.spot_borrow;
1218        let locked_dec = coin_data.total_order_im + coin_data.total_position_im;
1219
1220        balances.push(AccountBalance::from_total_and_locked(
1221            total_dec, locked_dec, currency,
1222        )?);
1223
1224        // Sum position IM (reserved by open positions) and order IM (reserved by
1225        // pending orders) so the reported initial margin reflects either source.
1226        let initial_margin_dec = coin_data.total_position_im + coin_data.total_order_im;
1227        let maintenance_margin_dec = match &coin_data.total_position_mm {
1228            Some(mm) if !mm.is_empty() => mm.parse::<Decimal>()?,
1229            _ => Decimal::ZERO,
1230        };
1231
1232        if !initial_margin_dec.is_zero() || !maintenance_margin_dec.is_zero() {
1233            margins.push(MarginBalance::new(
1234                Money::from_decimal(initial_margin_dec, currency)?,
1235                Money::from_decimal(maintenance_margin_dec, currency)?,
1236                None,
1237            ));
1238        }
1239    }
1240
1241    Ok(AccountState::new(
1242        account_id,
1243        AccountType::Margin, // Bybit unified account
1244        balances,
1245        margins,
1246        true, // is_reported
1247        UUID4::new(),
1248        ts_event,
1249        ts_init,
1250        None, // base_currency
1251    ))
1252}
1253
1254#[cfg(test)]
1255mod tests {
1256    use std::str::FromStr;
1257
1258    use nautilus_model::{
1259        data::BarSpecification,
1260        enums::{
1261            AggregationSource, BarAggregation, OrderType, PositionSide, PriceType, TriggerType,
1262        },
1263        identifiers::PositionId,
1264        types::{Price, Quantity},
1265    };
1266    use rstest::rstest;
1267    use rust_decimal_macros::dec;
1268
1269    use super::*;
1270    use crate::{
1271        common::{
1272            enums::{BybitExecType, BybitOrderSide, BybitProductType},
1273            parse::{
1274                parse_inverse_instrument, parse_linear_instrument, parse_option_instrument,
1275                parse_spot_instrument,
1276            },
1277            testing::load_test_json,
1278        },
1279        http::models::{
1280            BybitInstrumentInverseResponse, BybitInstrumentLinearResponse,
1281            BybitInstrumentOptionResponse, BybitInstrumentSpotResponse,
1282        },
1283        websocket::messages::{
1284            BybitWsAccountExecutionMsg, BybitWsLiquidationMsg, BybitWsOrderbookDepthMsg,
1285            BybitWsTickerLinearMsg, BybitWsTickerOptionMsg, BybitWsTradeMsg,
1286        },
1287    };
1288
1289    const TS: UnixNanos = UnixNanos::new(1_700_000_000_000_000_000);
1290
1291    use ustr::Ustr;
1292
1293    fn linear_instrument() -> InstrumentAny {
1294        let json = load_test_json("http_get_instruments_linear.json");
1295        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
1296        let instrument = &response.result.list[0];
1297        parse_linear_instrument(instrument, TS, TS).unwrap()
1298    }
1299
1300    fn spot_instrument() -> InstrumentAny {
1301        let json = load_test_json("http_get_instruments_spot.json");
1302        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
1303        let instrument = &response.result.list[0];
1304        parse_spot_instrument(instrument, TS, TS).unwrap()
1305    }
1306
1307    fn inverse_instrument() -> InstrumentAny {
1308        let json = load_test_json("http_get_instruments_inverse.json");
1309        let response: BybitInstrumentInverseResponse = serde_json::from_str(&json).unwrap();
1310        let instrument = &response.result.list[0];
1311        parse_inverse_instrument(instrument, TS, TS).unwrap()
1312    }
1313
1314    fn option_instrument() -> InstrumentAny {
1315        let json = load_test_json("http_get_instruments_option.json");
1316        let response: BybitInstrumentOptionResponse = serde_json::from_str(&json).unwrap();
1317        let instrument = &response.result.list[0];
1318        parse_option_instrument(instrument, TS, TS).unwrap()
1319    }
1320
1321    fn option_instrument_with_distinct_settlement() -> InstrumentAny {
1322        let json = load_test_json("http_get_instruments_option_symbol_id.json");
1323        let response: BybitInstrumentOptionResponse = serde_json::from_str(&json).unwrap();
1324        let instrument = &response.result.list[0];
1325        parse_option_instrument(instrument, TS, TS).unwrap()
1326    }
1327
1328    #[rstest]
1329    fn parse_ws_trade_into_trade_tick() {
1330        let instrument = linear_instrument();
1331        let json = load_test_json("ws_public_trade.json");
1332        let msg: BybitWsTradeMsg = serde_json::from_str(&json).unwrap();
1333        let trade = &msg.data[0];
1334
1335        let tick = parse_ws_trade_tick(trade, &instrument, TS).unwrap();
1336
1337        assert_eq!(tick.instrument_id, instrument.id());
1338        assert_eq!(tick.price, instrument.make_price(27451.00));
1339        assert_eq!(tick.size, instrument.make_qty(0.010, None));
1340        assert_eq!(tick.aggressor_side, AggressorSide::Buy);
1341        assert_eq!(
1342            tick.trade_id.to_string(),
1343            "9dc75fca-4bdd-4773-9f78-6f5d7ab2a110"
1344        );
1345        assert_eq!(tick.ts_event, UnixNanos::new(1_709_891_679_000_000_000));
1346    }
1347
1348    #[rstest]
1349    fn parse_bybit_ws_frame_routes_all_liquidation_topic() {
1350        let value: serde_json::Value =
1351            serde_json::from_str(&load_test_json("ws_all_liquidation.json")).unwrap();
1352
1353        let frame = parse_bybit_ws_frame(value);
1354
1355        match frame {
1356            BybitWsFrame::Liquidation(msg) => {
1357                assert_eq!(msg.topic, Ustr::from("allLiquidation.BTCUSDT"));
1358                assert_eq!(msg.msg_type, Ustr::from("snapshot"));
1359                assert_eq!(msg.ts, 1_739_502_303_204);
1360                assert_eq!(msg.data.len(), 2);
1361                assert_eq!(msg.data[0].t, 1_739_502_302_929);
1362                assert_eq!(msg.data[0].s, Ustr::from("BTCUSDT"));
1363                assert_eq!(msg.data[0].side, BybitOrderSide::Buy);
1364                assert_eq!(msg.data[0].v, "0.015");
1365                assert_eq!(msg.data[0].p, "96250.5");
1366                assert_eq!(msg.data[1].t, 1_739_502_303_011);
1367                assert_eq!(msg.data[1].s, Ustr::from("BTCUSDT"));
1368                assert_eq!(msg.data[1].side, BybitOrderSide::Sell);
1369                assert_eq!(msg.data[1].v, "1.250");
1370                assert_eq!(msg.data[1].p, "97410.0");
1371            }
1372            other => panic!("Expected Liquidation, found {other:?}"),
1373        }
1374    }
1375
1376    #[rstest]
1377    #[case::buy_is_long(0, PositionSide::Long, "96250.5", "0.015", 1_739_502_302_929_000_000)]
1378    #[case::sell_is_short(1, PositionSide::Short, "97410.0", "1.250", 1_739_502_303_011_000_000)]
1379    fn parse_ws_liquidation_into_bybit_liquidation(
1380        #[case] index: usize,
1381        #[case] expected_side: PositionSide,
1382        #[case] expected_price: &str,
1383        #[case] expected_quantity: &str,
1384        #[case] expected_ts_event: u64,
1385    ) {
1386        let instrument = linear_instrument();
1387        let json = load_test_json("ws_all_liquidation.json");
1388        let msg: BybitWsLiquidationMsg = serde_json::from_str(&json).unwrap();
1389
1390        let liquidation = parse_ws_liquidation(&msg.data[index], &instrument, TS).unwrap();
1391
1392        assert_eq!(
1393            liquidation.instrument_id,
1394            InstrumentId::from("BTCUSDT-LINEAR.BYBIT")
1395        );
1396        assert_eq!(liquidation.position_side, expected_side);
1397        assert_eq!(liquidation.bankruptcy_price, Price::from(expected_price));
1398        assert_eq!(liquidation.quantity, Quantity::from(expected_quantity));
1399        assert_eq!(liquidation.ts_event, UnixNanos::new(expected_ts_event));
1400        assert_eq!(liquidation.ts_init, TS);
1401    }
1402
1403    #[rstest]
1404    fn parse_ws_liquidation_rejects_unknown_side() {
1405        let instrument = linear_instrument();
1406        let mut value: serde_json::Value =
1407            serde_json::from_str(&load_test_json("ws_all_liquidation.json")).unwrap();
1408        value["data"][0]["S"] = serde_json::json!("");
1409        let msg: BybitWsLiquidationMsg = serde_json::from_value(value).unwrap();
1410
1411        let err = parse_ws_liquidation(&msg.data[0], &instrument, TS).unwrap_err();
1412
1413        assert_eq!(msg.data[0].side, BybitOrderSide::Unknown);
1414        assert_eq!(
1415            err.to_string(),
1416            "Invalid liquidation side: expected Buy or Sell, was Unknown"
1417        );
1418    }
1419
1420    #[rstest]
1421    fn parse_orderbook_snapshot_into_deltas() {
1422        let instrument = linear_instrument();
1423        let json = load_test_json("ws_orderbook_snapshot.json");
1424        let msg: BybitWsOrderbookDepthMsg = serde_json::from_str(&json).unwrap();
1425
1426        let deltas = parse_orderbook_deltas(&msg, &instrument, TS).unwrap();
1427
1428        assert_eq!(deltas.instrument_id, instrument.id());
1429        assert_eq!(deltas.deltas.len(), 5);
1430        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
1431        assert!(
1432            deltas
1433                .deltas
1434                .iter()
1435                .all(|delta| RecordFlag::F_SNAPSHOT.matches(delta.flags))
1436        );
1437        assert_eq!(
1438            deltas.deltas[1].order.price,
1439            instrument.make_price(27450.00)
1440        );
1441        assert_eq!(
1442            deltas.deltas[1].order.size,
1443            instrument.make_qty(0.500, None)
1444        );
1445        let last = deltas.deltas.last().unwrap();
1446        assert_eq!(last.order.side, OrderSide::Sell.into());
1447        assert_eq!(last.order.price, instrument.make_price(27451.50));
1448        assert_eq!(
1449            last.flags & RecordFlag::F_LAST as u8,
1450            RecordFlag::F_LAST as u8
1451        );
1452    }
1453
1454    #[rstest]
1455    fn parse_orderbook_empty_snapshot_is_clear() {
1456        let instrument = linear_instrument();
1457        let mut msg: BybitWsOrderbookDepthMsg =
1458            serde_json::from_str(&load_test_json("ws_orderbook_snapshot.json")).unwrap();
1459        msg.data.b.clear();
1460        msg.data.a.clear();
1461
1462        let deltas = parse_orderbook_deltas(&msg, &instrument, TS).unwrap();
1463
1464        assert_eq!(deltas.deltas.len(), 1);
1465        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
1466        assert!(RecordFlag::F_SNAPSHOT.matches(deltas.deltas[0].flags));
1467        assert!(RecordFlag::F_LAST.matches(deltas.deltas[0].flags));
1468    }
1469
1470    #[rstest]
1471    fn parse_orderbook_delta_marks_actions() {
1472        let instrument = linear_instrument();
1473        let json = load_test_json("ws_orderbook_delta.json");
1474        let msg: BybitWsOrderbookDepthMsg = serde_json::from_str(&json).unwrap();
1475
1476        let deltas = parse_orderbook_deltas(&msg, &instrument, TS).unwrap();
1477
1478        assert_eq!(deltas.deltas.len(), 2);
1479        let bid = &deltas.deltas[0];
1480        assert_eq!(bid.action, BookAction::Update);
1481        assert_eq!(bid.order.side, OrderSide::Buy.into());
1482        assert_eq!(bid.order.size, instrument.make_qty(0.400, None));
1483
1484        let ask = &deltas.deltas[1];
1485        assert!(
1486            deltas
1487                .deltas
1488                .iter()
1489                .all(|delta| !RecordFlag::F_SNAPSHOT.matches(delta.flags))
1490        );
1491        assert_eq!(ask.action, BookAction::Delete);
1492        assert_eq!(ask.order.side, OrderSide::Sell.into());
1493        assert_eq!(ask.order.size, instrument.make_qty(0.0, None));
1494        assert_eq!(
1495            ask.flags & RecordFlag::F_LAST as u8,
1496            RecordFlag::F_LAST as u8
1497        );
1498    }
1499
1500    #[rstest]
1501    fn parse_orderbook_quote_produces_top_of_book() {
1502        let instrument = linear_instrument();
1503        let json = load_test_json("ws_orderbook_snapshot.json");
1504        let msg: BybitWsOrderbookDepthMsg = serde_json::from_str(&json).unwrap();
1505
1506        let quote = parse_orderbook_quote(&msg, &instrument, TS).unwrap();
1507
1508        assert_eq!(quote.instrument_id, instrument.id());
1509        assert_eq!(quote.bid_price, instrument.make_price(27450.00));
1510        assert_eq!(quote.bid_size, instrument.make_qty(0.500, None));
1511        assert_eq!(quote.ask_price, instrument.make_price(27451.00));
1512        assert_eq!(quote.ask_size, instrument.make_qty(0.750, None));
1513    }
1514
1515    #[rstest]
1516    #[case::delta(
1517        "orderbook.1.BTCUSDT",
1518        "delta",
1519        false,
1520        false,
1521        "Expected depth-1 orderbook snapshot"
1522    )]
1523    #[case::depth_50(
1524        "orderbook.50.BTCUSDT",
1525        "snapshot",
1526        false,
1527        false,
1528        "Expected depth-1 orderbook snapshot"
1529    )]
1530    #[case::missing_bid(
1531        "orderbook.1.BTCUSDT",
1532        "snapshot",
1533        true,
1534        false,
1535        "orderbook snapshot missing bid"
1536    )]
1537    #[case::missing_ask(
1538        "orderbook.1.BTCUSDT",
1539        "snapshot",
1540        false,
1541        true,
1542        "orderbook snapshot missing ask"
1543    )]
1544    fn parse_orderbook_quote_rejects_non_top_of_book(
1545        #[case] topic: &str,
1546        #[case] msg_type: &str,
1547        #[case] missing_bid: bool,
1548        #[case] missing_ask: bool,
1549        #[case] expected_error: &str,
1550    ) {
1551        let instrument = linear_instrument();
1552        let mut msg: BybitWsOrderbookDepthMsg =
1553            serde_json::from_str(&load_test_json("ws_orderbook_snapshot.json")).unwrap();
1554        msg.topic = topic.into();
1555        msg.msg_type = msg_type.into();
1556        if missing_bid {
1557            msg.data.b.clear();
1558        }
1559
1560        if missing_ask {
1561            msg.data.a.clear();
1562        }
1563
1564        assert_eq!(
1565            parse_orderbook_quote(&msg, &instrument, TS)
1566                .unwrap_err()
1567                .to_string(),
1568            expected_error
1569        );
1570    }
1571
1572    #[rstest]
1573    fn parse_option_ticker_quote_to_quote_tick() {
1574        let instrument = option_instrument();
1575        let json = load_test_json("ws_ticker_option.json");
1576        let msg: BybitWsTickerOptionMsg = serde_json::from_str(&json).unwrap();
1577
1578        let quote = parse_ticker_option_quote(&msg, &instrument, TS).unwrap();
1579
1580        assert_eq!(quote.instrument_id, instrument.id());
1581        assert_eq!(quote.bid_price, instrument.make_price(0.0));
1582        assert_eq!(quote.ask_price, instrument.make_price(10.0));
1583        assert_eq!(quote.bid_size, instrument.make_qty(0.0, None));
1584        assert_eq!(quote.ask_size, instrument.make_qty(5.1, None));
1585        assert_eq!(quote.ts_event, UnixNanos::new(1_672_917_511_074_000_000));
1586        assert_eq!(quote.ts_init, TS);
1587    }
1588
1589    #[rstest]
1590    #[case::timestamp_on_open(false, 1_672_324_800_000_000_000)]
1591    #[case::timestamp_on_close(true, 1_672_325_100_000_000_000)]
1592    fn parse_ws_kline_into_bar(#[case] timestamp_on_close: bool, #[case] expected_ts_event: u64) {
1593        use std::num::NonZero;
1594
1595        let instrument = linear_instrument();
1596        let json = load_test_json("ws_kline.json");
1597        let msg: crate::websocket::messages::BybitWsKlineMsg = serde_json::from_str(&json).unwrap();
1598        let kline = &msg.data[0];
1599
1600        let bar_spec = BarSpecification {
1601            step: NonZero::new(5).unwrap(),
1602            aggregation: BarAggregation::Minute,
1603            price_type: PriceType::Last,
1604        };
1605        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::External);
1606
1607        let bar = parse_ws_kline_bar(kline, &instrument, bar_type, timestamp_on_close, TS).unwrap();
1608
1609        assert_eq!(bar.bar_type, bar_type);
1610        assert_eq!(bar.open, instrument.make_price(16649.5));
1611        assert_eq!(bar.high, instrument.make_price(16677.0));
1612        assert_eq!(bar.low, instrument.make_price(16608.0));
1613        assert_eq!(bar.close, instrument.make_price(16677.0));
1614        assert_eq!(bar.volume, instrument.make_qty(2.081, None));
1615        assert_eq!(bar.ts_event, UnixNanos::new(expected_ts_event));
1616        assert_eq!(bar.ts_init, TS);
1617    }
1618
1619    #[rstest]
1620    #[case::timestamp_on_open(false)]
1621    #[case::timestamp_on_close(true)]
1622    fn parse_ws_kline_zero_ts_init_falls_back_to_close(#[case] timestamp_on_close: bool) {
1623        use std::num::NonZero;
1624
1625        let instrument = linear_instrument();
1626        let json = load_test_json("ws_kline.json");
1627        let msg: crate::websocket::messages::BybitWsKlineMsg = serde_json::from_str(&json).unwrap();
1628        let kline = &msg.data[0];
1629
1630        let bar_spec = BarSpecification {
1631            step: NonZero::new(5).unwrap(),
1632            aggregation: BarAggregation::Minute,
1633            price_type: PriceType::Last,
1634        };
1635        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::External);
1636
1637        let bar = parse_ws_kline_bar(
1638            kline,
1639            &instrument,
1640            bar_type,
1641            timestamp_on_close,
1642            UnixNanos::default(),
1643        )
1644        .unwrap();
1645
1646        assert_eq!(bar.ts_init, UnixNanos::new(1_672_325_100_000_000_000));
1647    }
1648
1649    #[rstest]
1650    fn parse_ws_order_into_order_status_report() {
1651        let instrument = linear_instrument();
1652        let json = load_test_json("ws_account_order_filled.json");
1653        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
1654            serde_json::from_str(&json).unwrap();
1655        let order = &msg.data[0];
1656        let account_id = AccountId::new("BYBIT-001");
1657
1658        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
1659
1660        assert_eq!(report.account_id, account_id);
1661        assert_eq!(report.instrument_id, instrument.id());
1662        assert_eq!(report.order_side, OrderSide::Buy.into());
1663        assert_eq!(report.order_type, OrderType::Limit);
1664        assert_eq!(report.time_in_force, TimeInForce::Gtc);
1665        assert_eq!(report.order_status, OrderStatus::Filled);
1666        assert_eq!(report.quantity, instrument.make_qty(0.100, None));
1667        assert_eq!(report.filled_qty, instrument.make_qty(0.100, None));
1668        assert_eq!(report.price, Some(instrument.make_price(30000.50)));
1669        assert_eq!(report.avg_px, Some(dec!(30000.50)));
1670        assert_eq!(
1671            report.client_order_id.as_ref().unwrap().to_string(),
1672            "test-client-order-001"
1673        );
1674        assert_eq!(
1675            report.ts_accepted,
1676            UnixNanos::new(1_672_364_262_444_000_000)
1677        );
1678        assert_eq!(report.ts_last, UnixNanos::new(1_672_364_262_457_000_000));
1679    }
1680
1681    #[rstest]
1682    fn parse_ws_order_avg_price_keeps_every_digit_the_venue_sent() {
1683        // 28 significant digits is exactly what `Decimal` holds, and more than `f64` can:
1684        // routing the same string through `f64` first collapses it to 30000.500000000004.
1685        let raw = "30000.50000000000372529029846";
1686        let instrument = linear_instrument();
1687        let json = load_test_json("ws_account_order_filled.json");
1688        let mut msg: crate::websocket::messages::BybitWsAccountOrderMsg =
1689            serde_json::from_str(&json).unwrap();
1690        msg.data[0].avg_price = raw.to_string();
1691
1692        let report = parse_ws_order_status_report(
1693            &msg.data[0],
1694            &instrument,
1695            AccountId::new("BYBIT-001"),
1696            TS,
1697        )
1698        .unwrap();
1699
1700        let via_f64: Decimal = raw.parse::<f64>().unwrap().to_string().parse().unwrap();
1701        assert_eq!(report.avg_px, Some(Decimal::from_str(raw).unwrap()));
1702        assert_ne!(report.avg_px, Some(via_f64));
1703    }
1704
1705    #[rstest]
1706    fn parse_ws_order_partially_filled_rejected_maps_to_canceled() {
1707        let instrument = linear_instrument();
1708        let json = load_test_json("ws_account_order_partially_filled_rejected.json");
1709        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
1710            serde_json::from_str(&json).unwrap();
1711        let order = &msg.data[0];
1712        let account_id = AccountId::new("BYBIT-001");
1713
1714        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
1715
1716        // Verify that Bybit "Rejected" status with fills is mapped to Canceled, not Rejected
1717        assert_eq!(report.order_status, OrderStatus::Canceled);
1718        assert_eq!(report.filled_qty, instrument.make_qty(50.0, None));
1719        assert_eq!(
1720            report.client_order_id.as_ref().unwrap().to_string(),
1721            "O-20251001-164609-APEX-000-49"
1722        );
1723        assert_eq!(report.cancel_reason, Some("UNKNOWN".to_string()));
1724    }
1725
1726    #[rstest]
1727    fn parse_ws_order_post_only_cancel_maps_to_rejected() {
1728        let instrument = linear_instrument();
1729        let json = load_test_json("ws_account_order.json");
1730        let mut msg: crate::websocket::messages::BybitWsAccountOrderMsg =
1731            serde_json::from_str(&json).unwrap();
1732
1733        let order = msg.data.first_mut().unwrap();
1734        order.reject_reason = Ustr::from("EC_PostOnlyWillTakeLiquidity");
1735        order.cum_exec_qty = "0".to_string();
1736        let account_id = AccountId::new("BYBIT-001");
1737
1738        let report =
1739            parse_ws_order_status_report(&msg.data[0], &instrument, account_id, TS).unwrap();
1740
1741        assert_eq!(report.order_status, OrderStatus::Rejected);
1742        assert_eq!(
1743            report.cancel_reason,
1744            Some("EC_PostOnlyWillTakeLiquidity".to_string())
1745        );
1746    }
1747
1748    #[rstest]
1749    fn parse_ws_execution_into_fill_report() {
1750        let instrument = linear_instrument();
1751        let json = load_test_json("ws_account_execution.json");
1752        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1753            serde_json::from_str(&json).unwrap();
1754        let execution = &msg.data[0];
1755        let account_id = AccountId::new("BYBIT-001");
1756
1757        let report = parse_ws_fill_report(execution, account_id, &instrument, TS).unwrap();
1758
1759        assert_eq!(report.account_id, account_id);
1760        assert_eq!(report.instrument_id, instrument.id());
1761        assert_eq!(
1762            report.venue_order_id.to_string(),
1763            "9aac161b-8ed6-450d-9cab-c5cc67c21784"
1764        );
1765        assert_eq!(
1766            report.trade_id.to_string(),
1767            "0ab1bdf7-4219-438b-b30a-32ec863018f7"
1768        );
1769        assert_eq!(report.order_side, OrderSide::Sell);
1770        assert_eq!(report.last_qty, instrument.make_qty(0.5, None));
1771        assert_eq!(report.last_px, instrument.make_price(95900.1));
1772        assert_eq!(report.commission.as_f64(), 26.3725275);
1773        assert_eq!(report.commission.currency.code, "USDT");
1774        assert_eq!(report.liquidity_side, LiquiditySide::Taker);
1775        assert_eq!(
1776            report.client_order_id.as_ref().unwrap().to_string(),
1777            "test-order-link-001"
1778        );
1779        assert_eq!(report.ts_event, UnixNanos::new(1_746_270_400_353_000_000));
1780    }
1781
1782    #[rstest]
1783    fn parse_ws_adl_execution_into_fill_report() {
1784        let instrument = linear_instrument();
1785        let json = load_test_json("ws_account_execution_adl.json");
1786        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1787            serde_json::from_str(&json).unwrap();
1788        let execution = &msg.data[0];
1789        let account_id = AccountId::new("BYBIT-001");
1790
1791        assert_eq!(execution.exec_type, BybitExecType::AdlTrade);
1792        assert!(execution.exec_type.is_exchange_generated());
1793        assert!(execution.order_link_id.is_empty());
1794
1795        let report = parse_ws_fill_report(execution, account_id, &instrument, TS).unwrap();
1796
1797        // ADL fills carry an empty orderLinkId; client_order_id is None so the engine
1798        // creates the order as external from the accompanying order status report.
1799        assert_eq!(report.client_order_id, None);
1800        assert_eq!(
1801            report.venue_order_id.to_string(),
1802            "9aac161b-8ed6-450d-9cab-c5cc67c21785"
1803        );
1804        assert_eq!(report.order_side, OrderSide::Sell);
1805        assert_eq!(report.last_qty, instrument.make_qty(0.5, None));
1806        assert_eq!(report.last_px, instrument.make_price(95850.0));
1807        assert_eq!(report.commission.as_f64(), 0.0);
1808        assert_eq!(report.commission.currency.code, "USDT");
1809    }
1810
1811    #[rstest]
1812    #[case::forward_split_settle("ForwardSplitSettle", BybitExecType::ForwardSplitSettle)]
1813    #[case::reverse_split_settle("ReverseSplitSettle", BybitExecType::ReverseSplitSettle)]
1814    #[case::dividend("Dividend", BybitExecType::Dividend)]
1815    fn parse_ws_exchange_generated_execution_into_fill_report(
1816        #[case] exec_type: &str,
1817        #[case] expected: BybitExecType,
1818    ) {
1819        let instrument = linear_instrument();
1820        let json = load_test_json("ws_account_execution_adl.json");
1821        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
1822        value["data"][0]["execType"] = serde_json::json!(exec_type);
1823        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1824            serde_json::from_value(value).unwrap();
1825        let execution = &msg.data[0];
1826        let account_id = AccountId::new("BYBIT-001");
1827
1828        assert_eq!(execution.exec_type, expected);
1829        assert!(execution.exec_type.is_exchange_generated());
1830        assert!(execution.order_link_id.is_empty());
1831
1832        let report = parse_ws_fill_report(execution, account_id, &instrument, TS).unwrap();
1833
1834        assert_eq!(report.client_order_id, None);
1835        assert_eq!(
1836            report.venue_order_id.to_string(),
1837            "9aac161b-8ed6-450d-9cab-c5cc67c21785"
1838        );
1839    }
1840
1841    #[rstest]
1842    fn parse_ws_fill_report_venue_position_id_is_none() {
1843        let instrument = linear_instrument();
1844        let json = load_test_json("ws_account_execution.json");
1845        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1846            serde_json::from_str(&json).unwrap();
1847        let execution = &msg.data[0];
1848        let account_id = AccountId::new("BYBIT-001");
1849
1850        let report = parse_ws_fill_report(execution, account_id, &instrument, TS).unwrap();
1851
1852        assert_eq!(report.venue_position_id, None);
1853    }
1854
1855    #[rstest]
1856    fn parse_ws_fill_report_uses_payload_fee_currency() {
1857        let instrument = linear_instrument();
1858        let json = load_test_json("ws_account_execution.json");
1859        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1860            serde_json::from_str(&json).unwrap();
1861
1862        let mut execution = msg.data[0].clone();
1863        execution.fee_currency = Ustr::from("BTC");
1864        let account_id = AccountId::new("BYBIT-001");
1865
1866        let report = parse_ws_fill_report(&execution, account_id, &instrument, TS).unwrap();
1867
1868        assert_eq!(report.commission.currency.code, "BTC");
1869    }
1870
1871    fn fast_execution(is_maker: bool, order_link_id: &str) -> BybitWsAccountExecutionFast {
1872        BybitWsAccountExecutionFast {
1873            category: BybitProductType::Linear,
1874            symbol: Ustr::from("BTCUSDT"),
1875            exec_id: "abc-123".to_string(),
1876            exec_price: "50000.0".to_string(),
1877            exec_qty: "0.5".to_string(),
1878            order_id: Ustr::from("ord-1"),
1879            order_link_id: Ustr::from(order_link_id),
1880            side: BybitOrderSide::Buy,
1881            exec_time: "1716800399334".to_string(),
1882            is_maker,
1883            seq: 42,
1884        }
1885    }
1886
1887    #[rstest]
1888    // Maker fast fill: docs say orderLinkId is always empty -> client_order_id is None.
1889    #[case(true, "", LiquiditySide::Maker, None)]
1890    // Taker fast fill: orderLinkId is populated -> client_order_id is set.
1891    #[case(false, "link-1", LiquiditySide::Taker, Some("link-1"))]
1892    fn parse_ws_fill_report_fast_maps_is_maker_and_link_id(
1893        #[case] is_maker: bool,
1894        #[case] order_link_id: &str,
1895        #[case] expected_liquidity: LiquiditySide,
1896        #[case] expected_cid: Option<&str>,
1897    ) {
1898        let instrument = linear_instrument();
1899        let exec = fast_execution(is_maker, order_link_id);
1900        let account_id = AccountId::new("BYBIT-001");
1901
1902        let report =
1903            parse_ws_fill_report_fast(&exec, account_id, &instrument, None, None, None, TS)
1904                .unwrap();
1905
1906        assert_eq!(report.account_id, account_id);
1907        assert_eq!(report.instrument_id, instrument.id());
1908        assert_eq!(report.venue_order_id.to_string(), "ord-1");
1909        assert_eq!(report.trade_id.to_string(), "abc-123");
1910        assert_eq!(report.order_side, OrderSide::Buy);
1911        assert_eq!(report.last_qty, instrument.make_qty(0.5, None));
1912        assert_eq!(report.last_px, instrument.make_price(50000.0));
1913        assert_eq!(report.commission.as_decimal(), Decimal::ZERO);
1914        assert_eq!(report.liquidity_side, expected_liquidity);
1915        assert_eq!(
1916            report.client_order_id.map(|c| c.to_string()),
1917            expected_cid.map(str::to_string),
1918        );
1919        assert_eq!(report.venue_position_id, None);
1920        assert_eq!(report.ts_event, UnixNanos::new(1_716_800_399_334_000_000));
1921    }
1922
1923    #[rstest]
1924    fn parse_ws_fill_report_fast_matches_standard_linear_commission() {
1925        let instrument = linear_instrument();
1926        let json = load_test_json("ws_account_execution.json");
1927        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1928            serde_json::from_str(&json).unwrap();
1929        let standard = &msg.data[0];
1930        let account_id = AccountId::new("BYBIT-001");
1931        let standard_report = parse_ws_fill_report(standard, account_id, &instrument, TS).unwrap();
1932        let mut fast = fast_execution(false, "link-1");
1933        fast.exec_price = standard.exec_price.clone();
1934        fast.exec_qty = standard.exec_qty.clone();
1935        fast.side = standard.side;
1936        fast.is_maker = standard.is_maker;
1937        let rates = MakerTakerFeeRates::new(dec!(0.0001), dec!(0.00055));
1938
1939        let report =
1940            parse_ws_fill_report_fast(&fast, account_id, &instrument, Some(rates), None, None, TS)
1941                .unwrap();
1942
1943        assert_eq!(report.commission, standard_report.commission);
1944        assert_eq!(report.commission.as_decimal(), dec!(26.3725275));
1945        assert_eq!(report.commission.currency.code, "USDT");
1946    }
1947
1948    #[rstest]
1949    #[case::maker_buy(BybitOrderSide::Buy, true, dec!(0.0001), "BTC", dec!(0.00005))]
1950    #[case::maker_sell(BybitOrderSide::Sell, true, dec!(0.0001), "USDT", dec!(2.5))]
1951    #[case::taker_buy(BybitOrderSide::Buy, false, dec!(0.0001), "BTC", dec!(0.0003))]
1952    #[case::taker_sell(BybitOrderSide::Sell, false, dec!(0.0001), "USDT", dec!(15))]
1953    #[case::maker_buy_rebate(BybitOrderSide::Buy, true, dec!(-0.0001), "USDT", dec!(-2.5))]
1954    #[case::maker_sell_rebate(BybitOrderSide::Sell, true, dec!(-0.0001), "BTC", dec!(-0.00005))]
1955    fn parse_ws_fill_report_fast_calculates_spot_commission(
1956        #[case] side: BybitOrderSide,
1957        #[case] is_maker: bool,
1958        #[case] maker_rate: Decimal,
1959        #[case] expected_currency: &str,
1960        #[case] expected_amount: Decimal,
1961    ) {
1962        let instrument = spot_instrument();
1963        let mut exec = fast_execution(is_maker, "link-1");
1964        exec.category = BybitProductType::Spot;
1965        exec.side = side;
1966        let rates = MakerTakerFeeRates::new(maker_rate, dec!(0.0006));
1967
1968        let report = parse_ws_fill_report_fast(
1969            &exec,
1970            AccountId::new("BYBIT-001"),
1971            &instrument,
1972            Some(rates),
1973            None,
1974            None,
1975            TS,
1976        )
1977        .unwrap();
1978
1979        assert_eq!(report.commission.as_decimal(), expected_amount);
1980        assert_eq!(report.commission.currency.code, expected_currency);
1981    }
1982
1983    #[rstest]
1984    fn parse_ws_fill_report_fast_calculates_inverse_commission() {
1985        let instrument = inverse_instrument();
1986        let mut exec = fast_execution(false, "link-1");
1987        exec.category = BybitProductType::Inverse;
1988        exec.symbol = Ustr::from("BTCUSD");
1989        exec.exec_qty = "1000".to_string();
1990        exec.exec_price = "50000".to_string();
1991        let rates = MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006));
1992
1993        let report = parse_ws_fill_report_fast(
1994            &exec,
1995            AccountId::new("BYBIT-001"),
1996            &instrument,
1997            Some(rates),
1998            None,
1999            None,
2000            TS,
2001        )
2002        .unwrap();
2003
2004        assert_eq!(report.commission.as_decimal(), dec!(0.000012));
2005        assert_eq!(report.commission.currency.code, "BTC");
2006    }
2007
2008    #[rstest]
2009    fn parse_ws_fill_report_fast_option_missing_data_uses_zero_settlement_commission() {
2010        let instrument = option_instrument_with_distinct_settlement();
2011        let mut exec = fast_execution(false, "link-1");
2012        exec.category = BybitProductType::Option;
2013        exec.symbol = Ustr::from("BTC-30JUN25-100000-C");
2014        exec.exec_qty = "0.5".to_string();
2015        exec.exec_price = "1000".to_string();
2016        let rates = MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0002));
2017
2018        let report = parse_ws_fill_report_fast(
2019            &exec,
2020            AccountId::new("BYBIT-001"),
2021            &instrument,
2022            Some(rates),
2023            None,
2024            None,
2025            TS,
2026        )
2027        .unwrap();
2028
2029        assert_eq!(report.commission.as_decimal(), Decimal::ZERO);
2030        assert_eq!(report.commission.currency.code, "USDC");
2031    }
2032
2033    #[rstest]
2034    fn parse_ws_fill_report_fast_missing_spot_rate_uses_side_currency() {
2035        let instrument = spot_instrument();
2036        let mut exec = fast_execution(false, "link-1");
2037        exec.category = BybitProductType::Spot;
2038
2039        let report = parse_ws_fill_report_fast(
2040            &exec,
2041            AccountId::new("BYBIT-001"),
2042            &instrument,
2043            None,
2044            None,
2045            None,
2046            TS,
2047        )
2048        .unwrap();
2049
2050        assert_eq!(report.commission.as_decimal(), Decimal::ZERO);
2051        assert_eq!(report.commission.currency.code, "BTC");
2052    }
2053
2054    #[rstest]
2055    fn parse_ws_fill_report_fast_derivation_overflow_preserves_fill() {
2056        let instrument = linear_instrument();
2057        let exec = fast_execution(false, "link-1");
2058        let rates = MakerTakerFeeRates::new(dec!(0.0001), Decimal::MAX);
2059
2060        let report = parse_ws_fill_report_fast(
2061            &exec,
2062            AccountId::new("BYBIT-001"),
2063            &instrument,
2064            Some(rates),
2065            None,
2066            None,
2067            TS,
2068        )
2069        .unwrap();
2070
2071        assert_eq!(report.trade_id.to_string(), "abc-123");
2072        assert_eq!(report.commission.as_decimal(), Decimal::ZERO);
2073        assert_eq!(report.commission.currency.code, "USDT");
2074    }
2075
2076    #[rstest]
2077    fn parse_ws_fill_report_fast_preserves_venue_position_id() {
2078        let instrument = linear_instrument();
2079        let exec = fast_execution(false, "link-hedge");
2080        let account_id = AccountId::new("BYBIT-001");
2081        let venue_pid = PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG");
2082
2083        let report = parse_ws_fill_report_fast(
2084            &exec,
2085            account_id,
2086            &instrument,
2087            None,
2088            None,
2089            Some(venue_pid),
2090            TS,
2091        )
2092        .unwrap();
2093
2094        assert_eq!(report.venue_position_id, Some(venue_pid));
2095    }
2096
2097    #[rstest]
2098    fn parse_bybit_ws_frame_routes_execution_fast_topic() {
2099        // The fixture topic is `execution.fast` (matches the venue-doc sample),
2100        // which the prefix check at parse_bybit_ws_frame routes to the fast frame.
2101        let value: serde_json::Value =
2102            serde_json::from_str(&load_test_json("ws_account_execution_fast.json")).unwrap();
2103        let frame = parse_bybit_ws_frame(value);
2104        assert!(
2105            matches!(frame, BybitWsFrame::AccountExecutionFast(_)),
2106            "expected AccountExecutionFast, found {frame:?}",
2107        );
2108    }
2109
2110    #[rstest]
2111    fn parse_bybit_ws_frame_routes_standard_execution_topic() {
2112        // Sanity: with the fast prefix checked first, a plain `execution.<cat>` topic
2113        // must still route to the standard variant (not the fast one).
2114        let envelope = BybitWsAccountExecutionMsg {
2115            topic: Ustr::from("execution.linear"),
2116            id: "std-1".to_string(),
2117            creation_time: 1_716_800_399_338,
2118            data: vec![],
2119        };
2120        let value = serde_json::to_value(envelope).unwrap();
2121        let frame = parse_bybit_ws_frame(value);
2122        assert!(
2123            matches!(frame, BybitWsFrame::AccountExecution(_)),
2124            "expected AccountExecution, found {frame:?}",
2125        );
2126    }
2127
2128    #[rstest]
2129    fn parse_bybit_ws_frame_unrecognized_exec_type_still_routes_execution() {
2130        let json = load_test_json("ws_account_execution_adl.json");
2131        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
2132        value["data"][0]["execType"] = serde_json::json!("StockMerger");
2133
2134        let frame = parse_bybit_ws_frame(value);
2135
2136        match frame {
2137            BybitWsFrame::AccountExecution(msg) => {
2138                assert_eq!(msg.data[0].exec_type, BybitExecType::Unknown);
2139            }
2140            other => panic!("Expected AccountExecution, found {other:?}"),
2141        }
2142    }
2143
2144    #[rstest]
2145    fn parse_ws_order_status_report_venue_position_id_is_none_for_tp() {
2146        let instrument = linear_instrument();
2147        let json = load_test_json("ws_account_order_take_profit.json");
2148        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2149            serde_json::from_str(&json).unwrap();
2150        let order = &msg.data[0]; // positionIdx=0
2151        let account_id = AccountId::new("BYBIT-001");
2152
2153        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2154
2155        assert_eq!(report.venue_position_id, None);
2156    }
2157
2158    #[rstest]
2159    fn parse_ws_order_status_report_venue_position_id_for_hedge() {
2160        let instrument = linear_instrument();
2161        let json = load_test_json("ws_account_order_take_profit.json");
2162        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2163            serde_json::from_str(&json).unwrap();
2164        let mut order = msg.data[0].clone();
2165        order.position_idx = 1;
2166        let account_id = AccountId::new("BYBIT-001");
2167
2168        let report = parse_ws_order_status_report(&order, &instrument, account_id, TS).unwrap();
2169
2170        assert_eq!(
2171            report.venue_position_id,
2172            Some(PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG"))
2173        );
2174    }
2175
2176    #[rstest]
2177    fn parse_ws_position_into_position_status_report() {
2178        let instrument = linear_instrument();
2179        let json = load_test_json("ws_account_position.json");
2180        let msg: crate::websocket::messages::BybitWsAccountPositionMsg =
2181            serde_json::from_str(&json).unwrap();
2182        let position = &msg.data[0];
2183        let account_id = AccountId::new("BYBIT-001");
2184
2185        let report =
2186            parse_ws_position_status_report(position, account_id, &instrument, TS).unwrap();
2187
2188        assert_eq!(report.account_id, account_id);
2189        assert_eq!(report.instrument_id, instrument.id());
2190        assert_eq!(report.position_side, PositionSide::Short);
2191        assert_eq!(report.quantity, instrument.make_qty(0.01, None));
2192        assert_eq!(
2193            report.avg_px_open,
2194            Some(Decimal::try_from(3641.075).unwrap())
2195        );
2196        assert_eq!(report.ts_last, UnixNanos::new(1_762_199_125_472_000_000));
2197        assert_eq!(report.ts_init, TS);
2198    }
2199
2200    #[rstest]
2201    fn parse_ws_position_status_report_venue_position_id_for_hedge() {
2202        let instrument = linear_instrument();
2203        let json = load_test_json("ws_account_position.json");
2204        let msg: crate::websocket::messages::BybitWsAccountPositionMsg =
2205            serde_json::from_str(&json).unwrap();
2206        let mut position = msg.data[0].clone();
2207        position.position_idx = 2;
2208        let account_id = AccountId::new("BYBIT-001");
2209
2210        let report =
2211            parse_ws_position_status_report(&position, account_id, &instrument, TS).unwrap();
2212
2213        assert_eq!(
2214            report.venue_position_id,
2215            Some(PositionId::from("BTCUSDT-LINEAR.BYBIT-SHORT"))
2216        );
2217    }
2218
2219    #[rstest]
2220    fn parse_ws_position_short_into_position_status_report() {
2221        // Create ETHUSDT instrument
2222        let instruments_json = load_test_json("http_get_instruments_linear.json");
2223        let instruments_response: crate::http::models::BybitInstrumentLinearResponse =
2224            serde_json::from_str(&instruments_json).unwrap();
2225        let eth_def = &instruments_response.result.list[1]; // ETHUSDT is second in the list
2226        let instrument = crate::common::parse::parse_linear_instrument(eth_def, TS, TS).unwrap();
2227
2228        let json = load_test_json("ws_account_position_short.json");
2229        let msg: crate::websocket::messages::BybitWsAccountPositionMsg =
2230            serde_json::from_str(&json).unwrap();
2231        let position = &msg.data[0];
2232        let account_id = AccountId::new("BYBIT-001");
2233
2234        let report =
2235            parse_ws_position_status_report(position, account_id, &instrument, TS).unwrap();
2236
2237        assert_eq!(report.account_id, account_id);
2238        assert_eq!(report.instrument_id.symbol.as_str(), "ETHUSDT-LINEAR");
2239        assert_eq!(report.position_side, PositionSide::Short);
2240        assert_eq!(report.quantity, instrument.make_qty(0.01, None));
2241        assert_eq!(
2242            report.avg_px_open,
2243            Some(Decimal::try_from(3641.075).unwrap())
2244        );
2245        assert_eq!(report.ts_last, UnixNanos::new(1_762_199_125_472_000_000));
2246        assert_eq!(report.ts_init, TS);
2247    }
2248
2249    #[rstest]
2250    fn parse_ws_wallet_into_account_state() {
2251        let json = load_test_json("ws_account_wallet.json");
2252        let msg: crate::websocket::messages::BybitWsAccountWalletMsg =
2253            serde_json::from_str(&json).unwrap();
2254        let wallet = &msg.data[0];
2255        let account_id = AccountId::new("BYBIT-001");
2256        let ts_event = UnixNanos::new(1_700_034_722_104_000_000);
2257
2258        let state = parse_ws_account_state(wallet, account_id, ts_event, TS).unwrap();
2259
2260        assert_eq!(state.account_id, account_id);
2261        assert_eq!(state.account_type, AccountType::Margin);
2262        assert_eq!(state.balances.len(), 2);
2263        assert!(state.is_reported);
2264
2265        // Check BTC balance
2266        let btc_balance = &state.balances[0];
2267        assert_eq!(btc_balance.currency.code, "BTC");
2268        assert!((btc_balance.total.as_f64() - 0.00102964).abs() < 1e-8);
2269        assert!((btc_balance.free.as_f64() - 0.00092964).abs() < 1e-8);
2270        assert!((btc_balance.locked.as_f64() - 0.0001).abs() < 1e-8);
2271
2272        // Check USDT balance
2273        let usdt_balance = &state.balances[1];
2274        assert_eq!(usdt_balance.currency.code, "USDT");
2275        assert!((usdt_balance.total.as_f64() - 9647.75537647).abs() < 1e-6);
2276        assert!((usdt_balance.free.as_f64() - 9519.89806037).abs() < 1e-6);
2277        assert!((usdt_balance.locked.as_f64() - 127.8573161).abs() < 1e-6);
2278
2279        // BTC has order IM only (no position), USDT has position IM+MM (no orders).
2280        assert_eq!(state.margins.len(), 2);
2281        assert!(state.margins.iter().all(|m| m.instrument_id.is_none()));
2282
2283        let btc_margin = state
2284            .margins
2285            .iter()
2286            .find(|m| m.currency.code == "BTC")
2287            .expect("BTC margin missing");
2288        assert!((btc_margin.initial.as_f64() - 0.0001).abs() < 1e-8);
2289        assert!(btc_margin.maintenance.as_f64().abs() < 1e-9);
2290
2291        let usdt_margin = state
2292            .margins
2293            .iter()
2294            .find(|m| m.currency.code == "USDT")
2295            .expect("USDT margin missing");
2296        assert!((usdt_margin.initial.as_f64() - 127.8573161).abs() < 1e-6);
2297        assert!((usdt_margin.maintenance.as_f64() - 12.78573161).abs() < 1e-6);
2298
2299        assert_eq!(state.ts_event, ts_event);
2300        assert_eq!(state.ts_init, TS);
2301    }
2302
2303    #[rstest]
2304    fn parse_ws_wallet_with_small_order_calculates_free_correctly() {
2305        // Regression test for issue where availableToWithdraw=0 caused all funds to appear locked
2306        // When a small order is placed, Bybit may report availableToWithdraw=0 due to margin calculations,
2307        // but totalOrderIM correctly shows only the margin locked for the order
2308        let json = load_test_json("ws_account_wallet_small_order.json");
2309        let msg: crate::websocket::messages::BybitWsAccountWalletMsg =
2310            serde_json::from_str(&json).unwrap();
2311        let wallet = &msg.data[0];
2312        let account_id = AccountId::new("BYBIT-UNIFIED");
2313        let ts_event = UnixNanos::new(1_762_960_669_000_000_000);
2314
2315        let state = parse_ws_account_state(wallet, account_id, ts_event, TS).unwrap();
2316
2317        assert_eq!(state.account_id, account_id);
2318        assert_eq!(state.balances.len(), 1);
2319
2320        // Check USDT balance
2321        let usdt_balance = &state.balances[0];
2322        assert_eq!(usdt_balance.currency.code, "USDT");
2323
2324        // Wallet has 51,333.82 USDT total
2325        assert!((usdt_balance.total.as_f64() - 51333.82543837).abs() < 1e-6);
2326
2327        // Only 50.028 USDT should be locked (for the order), not all funds
2328        assert!((usdt_balance.locked.as_f64() - 50.028).abs() < 1e-6);
2329
2330        // Free should be total - locked = 51,333.82 - 50.028 = 51,283.79
2331        assert!((usdt_balance.free.as_f64() - 51283.79743837).abs() < 1e-6);
2332
2333        // The bug would have calculated: locked = total - availableToWithdraw = 51,333.82 - 0 = 51,333.82 (all locked!)
2334        // This test verifies that we now correctly use totalOrderIM instead of deriving from availableToWithdraw
2335
2336        // The small order reserves 50.028 USDT of initial margin via `totalOrderIM`,
2337        // so the account-wide USDT margin must be populated even with no open position.
2338        assert_eq!(state.margins.len(), 1);
2339        let usdt_margin = &state.margins[0];
2340        assert!(usdt_margin.instrument_id.is_none());
2341        assert_eq!(usdt_margin.currency.code, "USDT");
2342        assert!((usdt_margin.initial.as_f64() - 50.028).abs() < 1e-6);
2343        assert!(usdt_margin.maintenance.as_f64().abs() < 1e-9);
2344    }
2345
2346    #[rstest]
2347    fn parse_ticker_linear_into_funding_rate() {
2348        let instrument = linear_instrument();
2349        let json = load_test_json("ws_ticker_linear.json");
2350        let msg: BybitWsTickerLinearMsg = serde_json::from_str(&json).unwrap();
2351
2352        let ts_event = UnixNanos::new(1_673_272_861_686_000_000);
2353
2354        let funding =
2355            parse_ticker_linear_funding(&msg.data, instrument.id(), ts_event, TS).unwrap();
2356
2357        assert_eq!(funding.instrument_id, instrument.id());
2358        assert_eq!(funding.rate, dec!(-0.000212)); // -0.000212
2359        assert_eq!(funding.interval, Some(8 * 60));
2360        assert_eq!(
2361            funding.next_funding_ns,
2362            Some(UnixNanos::new(1_673_280_000_000_000_000))
2363        );
2364        assert_eq!(funding.ts_event, ts_event);
2365        assert_eq!(funding.ts_init, TS);
2366    }
2367
2368    #[rstest]
2369    fn parse_ticker_linear_into_mark_price() {
2370        let instrument = linear_instrument();
2371        let json = load_test_json("ws_ticker_linear.json");
2372        let msg: BybitWsTickerLinearMsg = serde_json::from_str(&json).unwrap();
2373
2374        let ts_event = UnixNanos::new(1_673_272_861_686_000_000);
2375
2376        let mark_price =
2377            parse_ticker_linear_mark_price(&msg.data, &instrument, ts_event, TS).unwrap();
2378
2379        assert_eq!(mark_price.instrument_id, instrument.id());
2380        assert_eq!(mark_price.value, instrument.make_price(17217.33));
2381        assert_eq!(mark_price.ts_event, ts_event);
2382        assert_eq!(mark_price.ts_init, TS);
2383    }
2384
2385    #[rstest]
2386    fn parse_ticker_linear_into_index_price() {
2387        let instrument = linear_instrument();
2388        let json = load_test_json("ws_ticker_linear.json");
2389        let msg: BybitWsTickerLinearMsg = serde_json::from_str(&json).unwrap();
2390
2391        let ts_event = UnixNanos::new(1_673_272_861_686_000_000);
2392
2393        let index_price =
2394            parse_ticker_linear_index_price(&msg.data, &instrument, ts_event, TS).unwrap();
2395
2396        assert_eq!(index_price.instrument_id, instrument.id());
2397        assert_eq!(index_price.value, instrument.make_price(17227.36));
2398        assert_eq!(index_price.ts_event, ts_event);
2399        assert_eq!(index_price.ts_init, TS);
2400    }
2401
2402    #[rstest]
2403    fn parse_ticker_option_into_mark_price() {
2404        let instrument = option_instrument();
2405        let json = load_test_json("ws_ticker_option.json");
2406        let msg: BybitWsTickerOptionMsg = serde_json::from_str(&json).unwrap();
2407
2408        let mark_price = parse_ticker_option_mark_price(&msg, &instrument, TS).unwrap();
2409
2410        assert_eq!(mark_price.instrument_id, instrument.id());
2411        assert_eq!(mark_price.value, instrument.make_price(7.86976724));
2412        assert_eq!(mark_price.ts_init, TS);
2413    }
2414
2415    #[rstest]
2416    fn parse_ticker_option_into_index_price() {
2417        let instrument = option_instrument();
2418        let json = load_test_json("ws_ticker_option.json");
2419        let msg: BybitWsTickerOptionMsg = serde_json::from_str(&json).unwrap();
2420
2421        let index_price = parse_ticker_option_index_price(&msg, &instrument, TS).unwrap();
2422
2423        assert_eq!(index_price.instrument_id, instrument.id());
2424        assert_eq!(index_price.value, instrument.make_price(16823.73));
2425        assert_eq!(index_price.ts_init, TS);
2426    }
2427
2428    #[rstest]
2429    fn parse_ws_order_stop_market_sell_preserves_type() {
2430        let instrument = linear_instrument();
2431        let json = load_test_json("ws_account_order_stop_market.json");
2432        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2433            serde_json::from_str(&json).unwrap();
2434        let order = &msg.data[0];
2435        let account_id = AccountId::new("BYBIT-001");
2436
2437        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2438
2439        // Verify sell StopMarket: orderType=Market + stopOrderType=Stop + triggerDirection=2 (falls to)
2440        assert_eq!(report.order_type, OrderType::StopMarket);
2441        assert_eq!(report.order_side, OrderSide::Sell.into());
2442        assert_eq!(report.order_status, OrderStatus::Accepted); // Untriggered maps to Accepted
2443        assert_eq!(report.trigger_price, Some(instrument.make_price(45000.00)));
2444        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2445        assert_eq!(
2446            report.client_order_id.as_ref().unwrap().to_string(),
2447            "test-client-stop-market-001"
2448        );
2449    }
2450
2451    #[rstest]
2452    fn parse_ws_order_stop_market_buy_preserves_type() {
2453        let instrument = linear_instrument();
2454        let json = load_test_json("ws_account_order_buy_stop_market.json");
2455        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2456            serde_json::from_str(&json).unwrap();
2457        let order = &msg.data[0];
2458        let account_id = AccountId::new("BYBIT-001");
2459
2460        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2461
2462        // Verify buy StopMarket: orderType=Market + stopOrderType=Stop + triggerDirection=1 (rises to)
2463        assert_eq!(report.order_type, OrderType::StopMarket);
2464        assert_eq!(report.order_side, OrderSide::Buy.into());
2465        assert_eq!(report.order_status, OrderStatus::Accepted);
2466        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2467        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2468        assert_eq!(
2469            report.client_order_id.as_ref().unwrap().to_string(),
2470            "test-client-buy-stop-market-001"
2471        );
2472    }
2473
2474    #[rstest]
2475    fn parse_ws_order_market_if_touched_buy_preserves_type() {
2476        let instrument = linear_instrument();
2477        let json = load_test_json("ws_account_order_market_if_touched.json");
2478        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2479            serde_json::from_str(&json).unwrap();
2480        let order = &msg.data[0];
2481        let account_id = AccountId::new("BYBIT-001");
2482
2483        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2484
2485        // Verify buy MIT: orderType=Market + stopOrderType=Stop + triggerDirection=2 (falls to)
2486        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2487        assert_eq!(report.order_side, OrderSide::Buy.into());
2488        assert_eq!(report.order_status, OrderStatus::Accepted); // Untriggered maps to Accepted
2489        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2490        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2491        assert_eq!(
2492            report.client_order_id.as_ref().unwrap().to_string(),
2493            "test-client-mit-001"
2494        );
2495    }
2496
2497    #[rstest]
2498    fn parse_ws_order_market_if_touched_sell_preserves_type() {
2499        let instrument = linear_instrument();
2500        let json = load_test_json("ws_account_order_sell_market_if_touched.json");
2501        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2502            serde_json::from_str(&json).unwrap();
2503        let order = &msg.data[0];
2504        let account_id = AccountId::new("BYBIT-001");
2505
2506        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2507
2508        // Verify sell MIT: orderType=Market + stopOrderType=Stop + triggerDirection=1 (rises to)
2509        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2510        assert_eq!(report.order_side, OrderSide::Sell.into());
2511        assert_eq!(report.order_status, OrderStatus::Accepted);
2512        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2513        assert_eq!(
2514            report.client_order_id.as_ref().unwrap().to_string(),
2515            "test-client-sell-mit-001"
2516        );
2517    }
2518
2519    #[rstest]
2520    fn parse_ws_order_stop_limit_preserves_type() {
2521        let instrument = linear_instrument();
2522        let json = load_test_json("ws_account_order_stop_limit.json");
2523        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2524            serde_json::from_str(&json).unwrap();
2525        let order = &msg.data[0];
2526        let account_id = AccountId::new("BYBIT-001");
2527
2528        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2529
2530        // Verify StopLimit order type is correctly parsed
2531        // orderType=Limit + stopOrderType=Stop + triggerDirection=2 (falls to)
2532        assert_eq!(report.order_type, OrderType::StopLimit);
2533        assert_eq!(report.order_side, OrderSide::Sell.into());
2534        assert_eq!(report.order_status, OrderStatus::Accepted); // Untriggered maps to Accepted
2535        assert_eq!(report.price, Some(instrument.make_price(44500.00)));
2536        assert_eq!(report.trigger_price, Some(instrument.make_price(45000.00)));
2537        assert_eq!(
2538            report.client_order_id.as_ref().unwrap().to_string(),
2539            "test-client-stop-limit-001"
2540        );
2541    }
2542
2543    #[rstest]
2544    fn parse_ws_order_limit_if_touched_preserves_type() {
2545        let instrument = linear_instrument();
2546        let json = load_test_json("ws_account_order_limit_if_touched.json");
2547        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2548            serde_json::from_str(&json).unwrap();
2549        let order = &msg.data[0];
2550        let account_id = AccountId::new("BYBIT-001");
2551
2552        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2553
2554        // Verify LimitIfTouched order type is correctly parsed
2555        // orderType=Limit + stopOrderType=Stop + triggerDirection=1 (rises to)
2556        assert_eq!(report.order_type, OrderType::LimitIfTouched);
2557        assert_eq!(report.order_side, OrderSide::Buy.into());
2558        assert_eq!(report.order_status, OrderStatus::Accepted); // Untriggered maps to Accepted
2559        assert_eq!(report.price, Some(instrument.make_price(55500.00)));
2560        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2561        assert_eq!(
2562            report.client_order_id.as_ref().unwrap().to_string(),
2563            "test-client-lit-001"
2564        );
2565    }
2566
2567    #[rstest]
2568    fn parse_ws_wallet_clamps_free_to_zero_when_locked_exceeds_total() {
2569        // totalOrderIM (80) + totalPositionIM (40) = 120, which exceeds
2570        // walletBalance (100). Free balance should clamp to zero, not underflow.
2571        let json = load_test_json("ws_account_wallet_locked_exceeds_total.json");
2572        let msg: crate::websocket::messages::BybitWsAccountWalletMsg =
2573            serde_json::from_str(&json).unwrap();
2574        let wallet = &msg.data[0];
2575        let account_id = AccountId::new("BYBIT-UNIFIED");
2576        let ts_event = UnixNanos::new(1_762_960_669_000_000_000);
2577
2578        let state = parse_ws_account_state(wallet, account_id, ts_event, TS).unwrap();
2579
2580        let usdt_balance = &state.balances[0];
2581        assert_eq!(usdt_balance.currency.code, "USDT");
2582        assert!((usdt_balance.total.as_f64() - 100.0).abs() < 1e-6);
2583        // Locked is capped at total to prevent negative free balance
2584        assert!((usdt_balance.locked.as_f64() - 100.0).abs() < 1e-6);
2585        assert_eq!(usdt_balance.free.as_f64(), 0.0);
2586    }
2587
2588    #[rstest]
2589    fn parse_ws_order_take_profit_maps_to_market_if_touched() {
2590        let instrument = linear_instrument();
2591        let json = load_test_json("ws_account_order_take_profit.json");
2592        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2593            serde_json::from_str(&json).unwrap();
2594        let order = &msg.data[0];
2595        let account_id = AccountId::new("BYBIT-001");
2596
2597        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2598
2599        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2600        assert_eq!(report.order_side, OrderSide::Sell.into());
2601        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2602        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2603        assert!(report.reduce_only);
2604    }
2605
2606    #[rstest]
2607    fn parse_ws_order_stop_loss_maps_to_stop_market() {
2608        let instrument = linear_instrument();
2609        let json = load_test_json("ws_account_order_stop_loss.json");
2610        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2611            serde_json::from_str(&json).unwrap();
2612        let order = &msg.data[0];
2613        let account_id = AccountId::new("BYBIT-001");
2614
2615        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2616
2617        assert_eq!(report.order_type, OrderType::StopMarket);
2618        assert_eq!(report.order_side, OrderSide::Sell.into());
2619        assert_eq!(report.trigger_price, Some(instrument.make_price(48000.00)));
2620        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2621        assert!(report.reduce_only);
2622    }
2623}