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, RoundingStrategy};
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. Commission is derived
964/// from the supplied account fee rates and is not venue-authoritative. A charged Linear
965/// fee rounds up at the settlement currency precision, as the venue fee does. Liquidity
966/// side is derived from `isMaker`.
967///
968/// `client_order_id` takes precedence over the payload's `orderLinkId`. The execution client
969/// supplies the identity it correlates by venue order ID for maker fills.
970///
971/// `venue_position_id` should be supplied for tracked hedge-mode orders so the
972/// emitted report carries the long/short position identity that the standard
973/// channel preserves via `OrderFilled`.
974///
975/// # Errors
976///
977/// Returns an error if:
978/// - Price or quantity fields cannot be parsed or timestamps are invalid.
979/// - The commission cannot be derived: `fee_rates` is `None`, the calculation fails, or
980///   the execution is an Option fill, whose payload lacks the inputs required by Bybit's
981///   Option fee formula.
982pub fn parse_ws_fill_report_fast(
983    execution: &BybitWsAccountExecutionFast,
984    account_id: AccountId,
985    instrument: &InstrumentAny,
986    fee_rates: Option<MakerTakerFeeRates>,
987    client_order_id: Option<ClientOrderId>,
988    venue_position_id: Option<PositionId>,
989    ts_init: UnixNanos,
990) -> anyhow::Result<FillReport> {
991    let instrument_id = instrument.id();
992    let venue_order_id = VenueOrderId::new(execution.order_id);
993    let trade_id = TradeId::new_checked(execution.exec_id.as_str())
994        .context("invalid execId in Bybit WebSocket fast-execution payload")?;
995
996    let order_side = OrderSide::try_from(execution.side)?;
997    let last_qty = parse_quantity_with_precision(
998        &execution.exec_qty,
999        instrument.size_precision(),
1000        "execution.execQty",
1001    )?;
1002    let last_px = parse_price_with_precision(
1003        &execution.exec_price,
1004        instrument.price_precision(),
1005        "execution.execPrice",
1006    )?;
1007
1008    let liquidity_side = if execution.is_maker {
1009        LiquiditySide::Maker
1010    } else {
1011        LiquiditySide::Taker
1012    };
1013
1014    let commission = derive_fast_commission(
1015        execution,
1016        instrument,
1017        order_side,
1018        fee_rates,
1019        last_qty,
1020        last_px,
1021        liquidity_side,
1022    )
1023    .context("cannot derive fast-execution commission")?;
1024    let ts_event = parse_millis_timestamp(&execution.exec_time, "execution.execTime")?;
1025    let client_order_id = client_order_id.or_else(|| {
1026        if execution.order_link_id.is_empty() {
1027            None
1028        } else {
1029            Some(ClientOrderId::new(execution.order_link_id))
1030        }
1031    });
1032
1033    Ok(FillReport::new(
1034        account_id,
1035        instrument_id,
1036        venue_order_id,
1037        trade_id,
1038        order_side,
1039        last_qty,
1040        last_px,
1041        commission,
1042        liquidity_side,
1043        client_order_id,
1044        venue_position_id,
1045        ts_event,
1046        ts_init,
1047        None,
1048    ))
1049}
1050
1051fn derive_fast_commission(
1052    execution: &BybitWsAccountExecutionFast,
1053    instrument: &InstrumentAny,
1054    order_side: OrderSide,
1055    fee_rates: Option<MakerTakerFeeRates>,
1056    last_qty: Quantity,
1057    last_px: Price,
1058    liquidity_side: LiquiditySide,
1059) -> anyhow::Result<Money> {
1060    anyhow::ensure!(
1061        execution.category != BybitProductType::Option,
1062        "fast-execution payload lacks the inputs for the Option fee formula"
1063    );
1064
1065    let rates =
1066        fee_rates.with_context(|| format!("no cached fee rates for {}", instrument.id()))?;
1067
1068    let fee_rate = if liquidity_side == LiquiditySide::Maker {
1069        rates.maker
1070    } else {
1071        rates.taker
1072    };
1073
1074    let currency = fast_commission_currency(execution, instrument, order_side, fee_rate);
1075
1076    calculate_fast_commission(execution, instrument, fee_rate, last_qty, last_px, currency)
1077}
1078
1079fn calculate_fast_commission(
1080    execution: &BybitWsAccountExecutionFast,
1081    instrument: &InstrumentAny,
1082    fee_rate: Decimal,
1083    last_qty: Quantity,
1084    last_px: Price,
1085    currency: Currency,
1086) -> anyhow::Result<Money> {
1087    if execution.category == BybitProductType::Spot {
1088        let base_currency = instrument
1089            .base_currency()
1090            .expect("Bybit spot instruments have a base currency");
1091
1092        if currency == base_currency {
1093            let amount = last_qty
1094                .as_decimal()
1095                .checked_mul(fee_rate)
1096                .ok_or_else(|| anyhow::anyhow!("fast commission calculation overflow"))?;
1097            return Money::from_decimal(amount, currency).map_err(Into::into);
1098        }
1099
1100        return calculate_maker_taker_commission(instrument, last_qty, last_px, fee_rate, None);
1101    }
1102
1103    let settlement_currency = instrument.settlement_currency();
1104
1105    // Bybit rounds a charged Linear fee up at the settlement precision
1106    if execution.category == BybitProductType::Linear && fee_rate > Decimal::ZERO {
1107        let notional = instrument.try_calculate_notional_value(last_qty, last_px, None)?;
1108        let amount = notional
1109            .as_decimal()
1110            .abs()
1111            .checked_mul(fee_rate)
1112            .ok_or_else(|| anyhow::anyhow!("fast commission calculation overflow"))?
1113            .round_dp_with_strategy(
1114                u32::from(settlement_currency.precision),
1115                RoundingStrategy::AwayFromZero,
1116            );
1117        return Money::from_decimal(amount, settlement_currency).map_err(Into::into);
1118    }
1119
1120    let commission =
1121        calculate_maker_taker_commission(instrument, last_qty, last_px, fee_rate, None)?;
1122    Money::from_decimal(commission.as_decimal(), settlement_currency).map_err(Into::into)
1123}
1124
1125fn fast_commission_currency(
1126    execution: &BybitWsAccountExecutionFast,
1127    instrument: &InstrumentAny,
1128    order_side: OrderSide,
1129    fee_rate: Decimal,
1130) -> Currency {
1131    if execution.category != BybitProductType::Spot {
1132        return instrument.settlement_currency();
1133    }
1134
1135    let is_rebate = execution.is_maker && fee_rate < Decimal::ZERO;
1136    let use_base = matches!(
1137        (order_side, is_rebate),
1138        (OrderSide::Buy, false) | (OrderSide::Sell, true)
1139    );
1140
1141    if use_base {
1142        instrument
1143            .base_currency()
1144            .expect("Bybit spot instruments have a base currency")
1145    } else {
1146        instrument.quote_currency()
1147    }
1148}
1149
1150/// Parses a WebSocket account position payload into a [`PositionStatusReport`].
1151///
1152/// # Errors
1153///
1154/// Returns an error if position size or prices cannot be parsed.
1155pub fn parse_ws_position_status_report(
1156    position: &BybitWsAccountPosition,
1157    account_id: AccountId,
1158    instrument: &InstrumentAny,
1159    ts_init: UnixNanos,
1160) -> anyhow::Result<PositionStatusReport> {
1161    let instrument_id = instrument.id();
1162
1163    // Parse absolute size as unsigned Quantity
1164    let quantity = parse_quantity_with_precision(
1165        &position.size,
1166        instrument.size_precision(),
1167        "position.size",
1168    )?;
1169
1170    let position_side = match position.side {
1171        BybitPositionSide::Buy => PositionSide::Long,
1172        BybitPositionSide::Sell => PositionSide::Short,
1173        BybitPositionSide::Flat => PositionSide::Flat,
1174    };
1175
1176    // Bybit ranks open positions 1-5 by ADL priority (5 = next to be deleveraged);
1177    // 0 means the account has no open position or is flat. Warn when approaching the
1178    // top tier so operators can react before the venue force-closes.
1179    if position.adl_rank_indicator >= 4 {
1180        log::warn!(
1181            "Elevated ADL risk: {} position size={} adl_rank={}",
1182            instrument_id,
1183            position.size,
1184            position.adl_rank_indicator,
1185        );
1186    }
1187
1188    let ts_last = parse_millis_timestamp(&position.updated_time, "position.updatedTime")?;
1189
1190    let venue_position_id = make_hedge_venue_position_id(instrument_id, position.position_idx);
1191
1192    Ok(PositionStatusReport::new(
1193        account_id,
1194        instrument_id,
1195        position_side,
1196        quantity,
1197        ts_last,
1198        ts_init,
1199        None, // report_id
1200        venue_position_id,
1201        position.entry_price, // avg_px_open
1202    ))
1203}
1204
1205/// Parses a WebSocket account wallet payload into an [`AccountState`].
1206///
1207/// # Errors
1208///
1209/// Returns an error if balance fields cannot be parsed.
1210pub fn parse_ws_account_state(
1211    wallet: &BybitWsAccountWallet,
1212    account_id: AccountId,
1213    ts_event: UnixNanos,
1214    ts_init: UnixNanos,
1215) -> anyhow::Result<AccountState> {
1216    let mut balances = Vec::new();
1217    let mut margins = Vec::new();
1218
1219    for coin_data in &wallet.coin {
1220        let currency = get_currency(coin_data.coin.as_str());
1221        let total_dec = coin_data.wallet_balance - coin_data.spot_borrow;
1222        let locked_dec = coin_data.total_order_im + coin_data.total_position_im;
1223
1224        balances.push(AccountBalance::from_total_and_locked(
1225            total_dec, locked_dec, currency,
1226        )?);
1227
1228        // Sum position IM (reserved by open positions) and order IM (reserved by
1229        // pending orders) so the reported initial margin reflects either source.
1230        let initial_margin_dec = coin_data.total_position_im + coin_data.total_order_im;
1231        let maintenance_margin_dec = match &coin_data.total_position_mm {
1232            Some(mm) if !mm.is_empty() => mm.parse::<Decimal>()?,
1233            _ => Decimal::ZERO,
1234        };
1235
1236        if !initial_margin_dec.is_zero() || !maintenance_margin_dec.is_zero() {
1237            margins.push(MarginBalance::new(
1238                Money::from_decimal(initial_margin_dec, currency)?,
1239                Money::from_decimal(maintenance_margin_dec, currency)?,
1240                None,
1241            ));
1242        }
1243    }
1244
1245    Ok(AccountState::new(
1246        account_id,
1247        AccountType::Margin, // Bybit unified account
1248        balances,
1249        margins,
1250        true, // is_reported
1251        UUID4::new(),
1252        ts_event,
1253        ts_init,
1254        None, // base_currency
1255    ))
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260    use std::str::FromStr;
1261
1262    use nautilus_model::{
1263        data::BarSpecification,
1264        enums::{
1265            AggregationSource, BarAggregation, OrderType, PositionSide, PriceType, TriggerType,
1266        },
1267        identifiers::PositionId,
1268        types::{Price, Quantity},
1269    };
1270    use rstest::rstest;
1271    use rust_decimal_macros::dec;
1272
1273    use super::*;
1274    use crate::{
1275        common::{
1276            enums::{BybitExecType, BybitOrderSide, BybitProductType},
1277            parse::{
1278                parse_inverse_instrument, parse_linear_instrument, parse_option_instrument,
1279                parse_spot_instrument,
1280            },
1281            testing::load_test_json,
1282        },
1283        http::models::{
1284            BybitInstrumentInverseResponse, BybitInstrumentLinearResponse,
1285            BybitInstrumentOptionResponse, BybitInstrumentSpotResponse,
1286        },
1287        websocket::messages::{
1288            BybitWsAccountExecutionMsg, BybitWsLiquidationMsg, BybitWsOrderbookDepthMsg,
1289            BybitWsTickerLinearMsg, BybitWsTickerOptionMsg, BybitWsTradeMsg,
1290        },
1291    };
1292
1293    const TS: UnixNanos = UnixNanos::new(1_700_000_000_000_000_000);
1294
1295    use ustr::Ustr;
1296
1297    fn linear_instrument() -> InstrumentAny {
1298        let json = load_test_json("http_get_instruments_linear.json");
1299        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
1300        let instrument = &response.result.list[0];
1301        parse_linear_instrument(instrument, TS, TS).unwrap()
1302    }
1303
1304    fn spot_instrument() -> InstrumentAny {
1305        let json = load_test_json("http_get_instruments_spot.json");
1306        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
1307        let instrument = &response.result.list[0];
1308        parse_spot_instrument(instrument, TS, TS).unwrap()
1309    }
1310
1311    fn inverse_instrument() -> InstrumentAny {
1312        let json = load_test_json("http_get_instruments_inverse.json");
1313        let response: BybitInstrumentInverseResponse = serde_json::from_str(&json).unwrap();
1314        let instrument = &response.result.list[0];
1315        parse_inverse_instrument(instrument, TS, TS).unwrap()
1316    }
1317
1318    fn option_instrument() -> InstrumentAny {
1319        let json = load_test_json("http_get_instruments_option.json");
1320        let response: BybitInstrumentOptionResponse = serde_json::from_str(&json).unwrap();
1321        let instrument = &response.result.list[0];
1322        parse_option_instrument(instrument, TS, TS).unwrap()
1323    }
1324
1325    fn option_instrument_with_distinct_settlement() -> InstrumentAny {
1326        let json = load_test_json("http_get_instruments_option_symbol_id.json");
1327        let response: BybitInstrumentOptionResponse = serde_json::from_str(&json).unwrap();
1328        let instrument = &response.result.list[0];
1329        parse_option_instrument(instrument, TS, TS).unwrap()
1330    }
1331
1332    #[rstest]
1333    fn parse_ws_trade_into_trade_tick() {
1334        let instrument = linear_instrument();
1335        let json = load_test_json("ws_public_trade.json");
1336        let msg: BybitWsTradeMsg = serde_json::from_str(&json).unwrap();
1337        let trade = &msg.data[0];
1338
1339        let tick = parse_ws_trade_tick(trade, &instrument, TS).unwrap();
1340
1341        assert_eq!(tick.instrument_id, instrument.id());
1342        assert_eq!(tick.price, instrument.make_price(27451.00));
1343        assert_eq!(tick.size, instrument.make_qty(0.010, None));
1344        assert_eq!(tick.aggressor_side, AggressorSide::Buy);
1345        assert_eq!(
1346            tick.trade_id.to_string(),
1347            "9dc75fca-4bdd-4773-9f78-6f5d7ab2a110"
1348        );
1349        assert_eq!(tick.ts_event, UnixNanos::new(1_709_891_679_000_000_000));
1350    }
1351
1352    #[rstest]
1353    fn parse_bybit_ws_frame_routes_all_liquidation_topic() {
1354        let value: serde_json::Value =
1355            serde_json::from_str(&load_test_json("ws_all_liquidation.json")).unwrap();
1356
1357        let frame = parse_bybit_ws_frame(value);
1358
1359        match frame {
1360            BybitWsFrame::Liquidation(msg) => {
1361                assert_eq!(msg.topic, Ustr::from("allLiquidation.BTCUSDT"));
1362                assert_eq!(msg.msg_type, Ustr::from("snapshot"));
1363                assert_eq!(msg.ts, 1_739_502_303_204);
1364                assert_eq!(msg.data.len(), 2);
1365                assert_eq!(msg.data[0].t, 1_739_502_302_929);
1366                assert_eq!(msg.data[0].s, Ustr::from("BTCUSDT"));
1367                assert_eq!(msg.data[0].side, BybitOrderSide::Buy);
1368                assert_eq!(msg.data[0].v, "0.015");
1369                assert_eq!(msg.data[0].p, "96250.5");
1370                assert_eq!(msg.data[1].t, 1_739_502_303_011);
1371                assert_eq!(msg.data[1].s, Ustr::from("BTCUSDT"));
1372                assert_eq!(msg.data[1].side, BybitOrderSide::Sell);
1373                assert_eq!(msg.data[1].v, "1.250");
1374                assert_eq!(msg.data[1].p, "97410.0");
1375            }
1376            other => panic!("Expected Liquidation, found {other:?}"),
1377        }
1378    }
1379
1380    #[rstest]
1381    #[case::buy_is_long(0, PositionSide::Long, "96250.5", "0.015", 1_739_502_302_929_000_000)]
1382    #[case::sell_is_short(1, PositionSide::Short, "97410.0", "1.250", 1_739_502_303_011_000_000)]
1383    fn parse_ws_liquidation_into_bybit_liquidation(
1384        #[case] index: usize,
1385        #[case] expected_side: PositionSide,
1386        #[case] expected_price: &str,
1387        #[case] expected_quantity: &str,
1388        #[case] expected_ts_event: u64,
1389    ) {
1390        let instrument = linear_instrument();
1391        let json = load_test_json("ws_all_liquidation.json");
1392        let msg: BybitWsLiquidationMsg = serde_json::from_str(&json).unwrap();
1393
1394        let liquidation = parse_ws_liquidation(&msg.data[index], &instrument, TS).unwrap();
1395
1396        assert_eq!(
1397            liquidation.instrument_id,
1398            InstrumentId::from("BTCUSDT-LINEAR.BYBIT")
1399        );
1400        assert_eq!(liquidation.position_side, expected_side);
1401        assert_eq!(liquidation.bankruptcy_price, Price::from(expected_price));
1402        assert_eq!(liquidation.quantity, Quantity::from(expected_quantity));
1403        assert_eq!(liquidation.ts_event, UnixNanos::new(expected_ts_event));
1404        assert_eq!(liquidation.ts_init, TS);
1405    }
1406
1407    #[rstest]
1408    fn parse_ws_liquidation_rejects_unknown_side() {
1409        let instrument = linear_instrument();
1410        let mut value: serde_json::Value =
1411            serde_json::from_str(&load_test_json("ws_all_liquidation.json")).unwrap();
1412        value["data"][0]["S"] = serde_json::json!("");
1413        let msg: BybitWsLiquidationMsg = serde_json::from_value(value).unwrap();
1414
1415        let err = parse_ws_liquidation(&msg.data[0], &instrument, TS).unwrap_err();
1416
1417        assert_eq!(msg.data[0].side, BybitOrderSide::Unknown);
1418        assert_eq!(
1419            err.to_string(),
1420            "Invalid liquidation side: expected Buy or Sell, was Unknown"
1421        );
1422    }
1423
1424    #[rstest]
1425    fn parse_orderbook_snapshot_into_deltas() {
1426        let instrument = linear_instrument();
1427        let json = load_test_json("ws_orderbook_snapshot.json");
1428        let msg: BybitWsOrderbookDepthMsg = serde_json::from_str(&json).unwrap();
1429
1430        let deltas = parse_orderbook_deltas(&msg, &instrument, TS).unwrap();
1431
1432        assert_eq!(deltas.instrument_id, instrument.id());
1433        assert_eq!(deltas.deltas.len(), 5);
1434        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
1435        assert!(
1436            deltas
1437                .deltas
1438                .iter()
1439                .all(|delta| RecordFlag::F_SNAPSHOT.matches(delta.flags))
1440        );
1441        assert_eq!(
1442            deltas.deltas[1].order.price,
1443            instrument.make_price(27450.00)
1444        );
1445        assert_eq!(
1446            deltas.deltas[1].order.size,
1447            instrument.make_qty(0.500, None)
1448        );
1449        let last = deltas.deltas.last().unwrap();
1450        assert_eq!(last.order.side, OrderSide::Sell.into());
1451        assert_eq!(last.order.price, instrument.make_price(27451.50));
1452        assert_eq!(
1453            last.flags & RecordFlag::F_LAST as u8,
1454            RecordFlag::F_LAST as u8
1455        );
1456    }
1457
1458    #[rstest]
1459    fn parse_orderbook_empty_snapshot_is_clear() {
1460        let instrument = linear_instrument();
1461        let mut msg: BybitWsOrderbookDepthMsg =
1462            serde_json::from_str(&load_test_json("ws_orderbook_snapshot.json")).unwrap();
1463        msg.data.b.clear();
1464        msg.data.a.clear();
1465
1466        let deltas = parse_orderbook_deltas(&msg, &instrument, TS).unwrap();
1467
1468        assert_eq!(deltas.deltas.len(), 1);
1469        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
1470        assert!(RecordFlag::F_SNAPSHOT.matches(deltas.deltas[0].flags));
1471        assert!(RecordFlag::F_LAST.matches(deltas.deltas[0].flags));
1472    }
1473
1474    #[rstest]
1475    fn parse_orderbook_delta_marks_actions() {
1476        let instrument = linear_instrument();
1477        let json = load_test_json("ws_orderbook_delta.json");
1478        let msg: BybitWsOrderbookDepthMsg = serde_json::from_str(&json).unwrap();
1479
1480        let deltas = parse_orderbook_deltas(&msg, &instrument, TS).unwrap();
1481
1482        assert_eq!(deltas.deltas.len(), 2);
1483        let bid = &deltas.deltas[0];
1484        assert_eq!(bid.action, BookAction::Update);
1485        assert_eq!(bid.order.side, OrderSide::Buy.into());
1486        assert_eq!(bid.order.size, instrument.make_qty(0.400, None));
1487
1488        let ask = &deltas.deltas[1];
1489        assert!(
1490            deltas
1491                .deltas
1492                .iter()
1493                .all(|delta| !RecordFlag::F_SNAPSHOT.matches(delta.flags))
1494        );
1495        assert_eq!(ask.action, BookAction::Delete);
1496        assert_eq!(ask.order.side, OrderSide::Sell.into());
1497        assert_eq!(ask.order.size, instrument.make_qty(0.0, None));
1498        assert_eq!(
1499            ask.flags & RecordFlag::F_LAST as u8,
1500            RecordFlag::F_LAST as u8
1501        );
1502    }
1503
1504    #[rstest]
1505    fn parse_orderbook_quote_produces_top_of_book() {
1506        let instrument = linear_instrument();
1507        let json = load_test_json("ws_orderbook_snapshot.json");
1508        let msg: BybitWsOrderbookDepthMsg = serde_json::from_str(&json).unwrap();
1509
1510        let quote = parse_orderbook_quote(&msg, &instrument, TS).unwrap();
1511
1512        assert_eq!(quote.instrument_id, instrument.id());
1513        assert_eq!(quote.bid_price, instrument.make_price(27450.00));
1514        assert_eq!(quote.bid_size, instrument.make_qty(0.500, None));
1515        assert_eq!(quote.ask_price, instrument.make_price(27451.00));
1516        assert_eq!(quote.ask_size, instrument.make_qty(0.750, None));
1517    }
1518
1519    #[rstest]
1520    #[case::delta(
1521        "orderbook.1.BTCUSDT",
1522        "delta",
1523        false,
1524        false,
1525        "Expected depth-1 orderbook snapshot"
1526    )]
1527    #[case::depth_50(
1528        "orderbook.50.BTCUSDT",
1529        "snapshot",
1530        false,
1531        false,
1532        "Expected depth-1 orderbook snapshot"
1533    )]
1534    #[case::missing_bid(
1535        "orderbook.1.BTCUSDT",
1536        "snapshot",
1537        true,
1538        false,
1539        "orderbook snapshot missing bid"
1540    )]
1541    #[case::missing_ask(
1542        "orderbook.1.BTCUSDT",
1543        "snapshot",
1544        false,
1545        true,
1546        "orderbook snapshot missing ask"
1547    )]
1548    fn parse_orderbook_quote_rejects_non_top_of_book(
1549        #[case] topic: &str,
1550        #[case] msg_type: &str,
1551        #[case] missing_bid: bool,
1552        #[case] missing_ask: bool,
1553        #[case] expected_error: &str,
1554    ) {
1555        let instrument = linear_instrument();
1556        let mut msg: BybitWsOrderbookDepthMsg =
1557            serde_json::from_str(&load_test_json("ws_orderbook_snapshot.json")).unwrap();
1558        msg.topic = topic.into();
1559        msg.msg_type = msg_type.into();
1560        if missing_bid {
1561            msg.data.b.clear();
1562        }
1563
1564        if missing_ask {
1565            msg.data.a.clear();
1566        }
1567
1568        assert_eq!(
1569            parse_orderbook_quote(&msg, &instrument, TS)
1570                .unwrap_err()
1571                .to_string(),
1572            expected_error
1573        );
1574    }
1575
1576    #[rstest]
1577    fn parse_option_ticker_quote_to_quote_tick() {
1578        let instrument = option_instrument();
1579        let json = load_test_json("ws_ticker_option.json");
1580        let msg: BybitWsTickerOptionMsg = serde_json::from_str(&json).unwrap();
1581
1582        let quote = parse_ticker_option_quote(&msg, &instrument, TS).unwrap();
1583
1584        assert_eq!(quote.instrument_id, instrument.id());
1585        assert_eq!(quote.bid_price, instrument.make_price(0.0));
1586        assert_eq!(quote.ask_price, instrument.make_price(10.0));
1587        assert_eq!(quote.bid_size, instrument.make_qty(0.0, None));
1588        assert_eq!(quote.ask_size, instrument.make_qty(5.1, None));
1589        assert_eq!(quote.ts_event, UnixNanos::new(1_672_917_511_074_000_000));
1590        assert_eq!(quote.ts_init, TS);
1591    }
1592
1593    #[rstest]
1594    #[case::timestamp_on_open(false, 1_672_324_800_000_000_000)]
1595    #[case::timestamp_on_close(true, 1_672_325_100_000_000_000)]
1596    fn parse_ws_kline_into_bar(#[case] timestamp_on_close: bool, #[case] expected_ts_event: u64) {
1597        use std::num::NonZero;
1598
1599        let instrument = linear_instrument();
1600        let json = load_test_json("ws_kline.json");
1601        let msg: crate::websocket::messages::BybitWsKlineMsg = serde_json::from_str(&json).unwrap();
1602        let kline = &msg.data[0];
1603
1604        let bar_spec = BarSpecification {
1605            step: NonZero::new(5).unwrap(),
1606            aggregation: BarAggregation::Minute,
1607            price_type: PriceType::Last,
1608        };
1609        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::External);
1610
1611        let bar = parse_ws_kline_bar(kline, &instrument, bar_type, timestamp_on_close, TS).unwrap();
1612
1613        assert_eq!(bar.bar_type, bar_type);
1614        assert_eq!(bar.open, instrument.make_price(16649.5));
1615        assert_eq!(bar.high, instrument.make_price(16677.0));
1616        assert_eq!(bar.low, instrument.make_price(16608.0));
1617        assert_eq!(bar.close, instrument.make_price(16677.0));
1618        assert_eq!(bar.volume, instrument.make_qty(2.081, None));
1619        assert_eq!(bar.ts_event, UnixNanos::new(expected_ts_event));
1620        assert_eq!(bar.ts_init, TS);
1621    }
1622
1623    #[rstest]
1624    #[case::timestamp_on_open(false)]
1625    #[case::timestamp_on_close(true)]
1626    fn parse_ws_kline_zero_ts_init_falls_back_to_close(#[case] timestamp_on_close: bool) {
1627        use std::num::NonZero;
1628
1629        let instrument = linear_instrument();
1630        let json = load_test_json("ws_kline.json");
1631        let msg: crate::websocket::messages::BybitWsKlineMsg = serde_json::from_str(&json).unwrap();
1632        let kline = &msg.data[0];
1633
1634        let bar_spec = BarSpecification {
1635            step: NonZero::new(5).unwrap(),
1636            aggregation: BarAggregation::Minute,
1637            price_type: PriceType::Last,
1638        };
1639        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::External);
1640
1641        let bar = parse_ws_kline_bar(
1642            kline,
1643            &instrument,
1644            bar_type,
1645            timestamp_on_close,
1646            UnixNanos::default(),
1647        )
1648        .unwrap();
1649
1650        assert_eq!(bar.ts_init, UnixNanos::new(1_672_325_100_000_000_000));
1651    }
1652
1653    #[rstest]
1654    fn parse_ws_order_into_order_status_report() {
1655        let instrument = linear_instrument();
1656        let json = load_test_json("ws_account_order_filled.json");
1657        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
1658            serde_json::from_str(&json).unwrap();
1659        let order = &msg.data[0];
1660        let account_id = AccountId::new("BYBIT-001");
1661
1662        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
1663
1664        assert_eq!(report.account_id, account_id);
1665        assert_eq!(report.instrument_id, instrument.id());
1666        assert_eq!(report.order_side, OrderSide::Buy.into());
1667        assert_eq!(report.order_type, OrderType::Limit);
1668        assert_eq!(report.time_in_force, TimeInForce::Gtc);
1669        assert_eq!(report.order_status, OrderStatus::Filled);
1670        assert_eq!(report.quantity, instrument.make_qty(0.100, None));
1671        assert_eq!(report.filled_qty, instrument.make_qty(0.100, None));
1672        assert_eq!(report.price, Some(instrument.make_price(30000.50)));
1673        assert_eq!(report.avg_px, Some(dec!(30000.50)));
1674        assert_eq!(
1675            report.client_order_id.as_ref().unwrap().to_string(),
1676            "test-client-order-001"
1677        );
1678        assert_eq!(
1679            report.ts_accepted,
1680            UnixNanos::new(1_672_364_262_444_000_000)
1681        );
1682        assert_eq!(report.ts_last, UnixNanos::new(1_672_364_262_457_000_000));
1683    }
1684
1685    #[rstest]
1686    fn parse_ws_order_avg_price_keeps_every_digit_the_venue_sent() {
1687        // 28 significant digits is exactly what `Decimal` holds, and more than `f64` can:
1688        // routing the same string through `f64` first collapses it to 30000.500000000004.
1689        let raw = "30000.50000000000372529029846";
1690        let instrument = linear_instrument();
1691        let json = load_test_json("ws_account_order_filled.json");
1692        let mut msg: crate::websocket::messages::BybitWsAccountOrderMsg =
1693            serde_json::from_str(&json).unwrap();
1694        msg.data[0].avg_price = raw.to_string();
1695
1696        let report = parse_ws_order_status_report(
1697            &msg.data[0],
1698            &instrument,
1699            AccountId::new("BYBIT-001"),
1700            TS,
1701        )
1702        .unwrap();
1703
1704        let via_f64: Decimal = raw.parse::<f64>().unwrap().to_string().parse().unwrap();
1705        assert_eq!(report.avg_px, Some(Decimal::from_str(raw).unwrap()));
1706        assert_ne!(report.avg_px, Some(via_f64));
1707    }
1708
1709    #[rstest]
1710    fn parse_ws_order_partially_filled_rejected_maps_to_canceled() {
1711        let instrument = linear_instrument();
1712        let json = load_test_json("ws_account_order_partially_filled_rejected.json");
1713        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
1714            serde_json::from_str(&json).unwrap();
1715        let order = &msg.data[0];
1716        let account_id = AccountId::new("BYBIT-001");
1717
1718        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
1719
1720        // Verify that Bybit "Rejected" status with fills is mapped to Canceled, not Rejected
1721        assert_eq!(report.order_status, OrderStatus::Canceled);
1722        assert_eq!(report.filled_qty, instrument.make_qty(50.0, None));
1723        assert_eq!(
1724            report.client_order_id.as_ref().unwrap().to_string(),
1725            "O-20251001-164609-APEX-000-49"
1726        );
1727        assert_eq!(report.cancel_reason, Some("UNKNOWN".to_string()));
1728    }
1729
1730    #[rstest]
1731    fn parse_ws_order_post_only_cancel_maps_to_rejected() {
1732        let instrument = linear_instrument();
1733        let json = load_test_json("ws_account_order.json");
1734        let mut msg: crate::websocket::messages::BybitWsAccountOrderMsg =
1735            serde_json::from_str(&json).unwrap();
1736
1737        let order = msg.data.first_mut().unwrap();
1738        order.reject_reason = Ustr::from("EC_PostOnlyWillTakeLiquidity");
1739        order.cum_exec_qty = "0".to_string();
1740        let account_id = AccountId::new("BYBIT-001");
1741
1742        let report =
1743            parse_ws_order_status_report(&msg.data[0], &instrument, account_id, TS).unwrap();
1744
1745        assert_eq!(report.order_status, OrderStatus::Rejected);
1746        assert_eq!(
1747            report.cancel_reason,
1748            Some("EC_PostOnlyWillTakeLiquidity".to_string())
1749        );
1750    }
1751
1752    #[rstest]
1753    fn parse_ws_execution_into_fill_report() {
1754        let instrument = linear_instrument();
1755        let json = load_test_json("ws_account_execution.json");
1756        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1757            serde_json::from_str(&json).unwrap();
1758        let execution = &msg.data[0];
1759        let account_id = AccountId::new("BYBIT-001");
1760
1761        let report = parse_ws_fill_report(execution, account_id, &instrument, TS).unwrap();
1762
1763        assert_eq!(report.account_id, account_id);
1764        assert_eq!(report.instrument_id, instrument.id());
1765        assert_eq!(
1766            report.venue_order_id.to_string(),
1767            "9aac161b-8ed6-450d-9cab-c5cc67c21784"
1768        );
1769        assert_eq!(
1770            report.trade_id.to_string(),
1771            "0ab1bdf7-4219-438b-b30a-32ec863018f7"
1772        );
1773        assert_eq!(report.order_side, OrderSide::Sell);
1774        assert_eq!(report.last_qty, instrument.make_qty(0.5, None));
1775        assert_eq!(report.last_px, instrument.make_price(95900.1));
1776        assert_eq!(report.commission.as_f64(), 26.3725275);
1777        assert_eq!(report.commission.currency.code, "USDT");
1778        assert_eq!(report.liquidity_side, LiquiditySide::Taker);
1779        assert_eq!(
1780            report.client_order_id.as_ref().unwrap().to_string(),
1781            "test-order-link-001"
1782        );
1783        assert_eq!(report.ts_event, UnixNanos::new(1_746_270_400_353_000_000));
1784    }
1785
1786    #[rstest]
1787    fn parse_ws_adl_execution_into_fill_report() {
1788        let instrument = linear_instrument();
1789        let json = load_test_json("ws_account_execution_adl.json");
1790        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1791            serde_json::from_str(&json).unwrap();
1792        let execution = &msg.data[0];
1793        let account_id = AccountId::new("BYBIT-001");
1794
1795        assert_eq!(execution.exec_type, BybitExecType::AdlTrade);
1796        assert!(execution.exec_type.is_exchange_generated());
1797        assert!(execution.order_link_id.is_empty());
1798
1799        let report = parse_ws_fill_report(execution, account_id, &instrument, TS).unwrap();
1800
1801        // ADL fills carry an empty orderLinkId; client_order_id is None so the engine
1802        // creates the order as external from the accompanying order status report.
1803        assert_eq!(report.client_order_id, None);
1804        assert_eq!(
1805            report.venue_order_id.to_string(),
1806            "9aac161b-8ed6-450d-9cab-c5cc67c21785"
1807        );
1808        assert_eq!(report.order_side, OrderSide::Sell);
1809        assert_eq!(report.last_qty, instrument.make_qty(0.5, None));
1810        assert_eq!(report.last_px, instrument.make_price(95850.0));
1811        assert_eq!(report.commission.as_f64(), 0.0);
1812        assert_eq!(report.commission.currency.code, "USDT");
1813    }
1814
1815    #[rstest]
1816    #[case::forward_split_settle("ForwardSplitSettle", BybitExecType::ForwardSplitSettle)]
1817    #[case::reverse_split_settle("ReverseSplitSettle", BybitExecType::ReverseSplitSettle)]
1818    #[case::dividend("Dividend", BybitExecType::Dividend)]
1819    fn parse_ws_exchange_generated_execution_into_fill_report(
1820        #[case] exec_type: &str,
1821        #[case] expected: BybitExecType,
1822    ) {
1823        let instrument = linear_instrument();
1824        let json = load_test_json("ws_account_execution_adl.json");
1825        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
1826        value["data"][0]["execType"] = serde_json::json!(exec_type);
1827        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1828            serde_json::from_value(value).unwrap();
1829        let execution = &msg.data[0];
1830        let account_id = AccountId::new("BYBIT-001");
1831
1832        assert_eq!(execution.exec_type, expected);
1833        assert!(execution.exec_type.is_exchange_generated());
1834        assert!(execution.order_link_id.is_empty());
1835
1836        let report = parse_ws_fill_report(execution, account_id, &instrument, TS).unwrap();
1837
1838        assert_eq!(report.client_order_id, None);
1839        assert_eq!(
1840            report.venue_order_id.to_string(),
1841            "9aac161b-8ed6-450d-9cab-c5cc67c21785"
1842        );
1843    }
1844
1845    #[rstest]
1846    fn parse_ws_fill_report_venue_position_id_is_none() {
1847        let instrument = linear_instrument();
1848        let json = load_test_json("ws_account_execution.json");
1849        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1850            serde_json::from_str(&json).unwrap();
1851        let execution = &msg.data[0];
1852        let account_id = AccountId::new("BYBIT-001");
1853
1854        let report = parse_ws_fill_report(execution, account_id, &instrument, TS).unwrap();
1855
1856        assert_eq!(report.venue_position_id, None);
1857    }
1858
1859    #[rstest]
1860    fn parse_ws_fill_report_uses_payload_fee_currency() {
1861        let instrument = linear_instrument();
1862        let json = load_test_json("ws_account_execution.json");
1863        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1864            serde_json::from_str(&json).unwrap();
1865
1866        let mut execution = msg.data[0].clone();
1867        execution.fee_currency = Ustr::from("BTC");
1868        let account_id = AccountId::new("BYBIT-001");
1869
1870        let report = parse_ws_fill_report(&execution, account_id, &instrument, TS).unwrap();
1871
1872        assert_eq!(report.commission.currency.code, "BTC");
1873    }
1874
1875    fn fast_execution(is_maker: bool, order_link_id: &str) -> BybitWsAccountExecutionFast {
1876        BybitWsAccountExecutionFast {
1877            category: BybitProductType::Linear,
1878            symbol: Ustr::from("BTCUSDT"),
1879            exec_id: "abc-123".to_string(),
1880            exec_price: "50000.0".to_string(),
1881            exec_qty: "0.5".to_string(),
1882            order_id: Ustr::from("ord-1"),
1883            order_link_id: Ustr::from(order_link_id),
1884            side: BybitOrderSide::Buy,
1885            exec_time: "1716800399334".to_string(),
1886            is_maker,
1887            seq: 42,
1888        }
1889    }
1890
1891    #[rstest]
1892    // Maker fast fill: docs say orderLinkId is always empty -> client_order_id is None.
1893    #[case(true, "", LiquiditySide::Maker, None, dec!(2.5))]
1894    // Taker fast fill: orderLinkId is populated -> client_order_id is set.
1895    #[case(false, "link-1", LiquiditySide::Taker, Some("link-1"), dec!(15))]
1896    fn parse_ws_fill_report_fast_maps_is_maker_and_link_id(
1897        #[case] is_maker: bool,
1898        #[case] order_link_id: &str,
1899        #[case] expected_liquidity: LiquiditySide,
1900        #[case] expected_cid: Option<&str>,
1901        #[case] expected_commission: Decimal,
1902    ) {
1903        let instrument = linear_instrument();
1904        let exec = fast_execution(is_maker, order_link_id);
1905        let account_id = AccountId::new("BYBIT-001");
1906        let rates = MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006));
1907
1908        let report =
1909            parse_ws_fill_report_fast(&exec, account_id, &instrument, Some(rates), None, None, TS)
1910                .unwrap();
1911
1912        assert_eq!(report.account_id, account_id);
1913        assert_eq!(report.instrument_id, instrument.id());
1914        assert_eq!(report.venue_order_id.to_string(), "ord-1");
1915        assert_eq!(report.trade_id.to_string(), "abc-123");
1916        assert_eq!(report.order_side, OrderSide::Buy);
1917        assert_eq!(report.last_qty, instrument.make_qty(0.5, None));
1918        assert_eq!(report.last_px, instrument.make_price(50000.0));
1919        assert_eq!(report.commission.as_decimal(), expected_commission);
1920        assert_eq!(report.commission.currency.code, "USDT");
1921        assert_eq!(report.liquidity_side, expected_liquidity);
1922        assert_eq!(
1923            report.client_order_id.map(|c| c.to_string()),
1924            expected_cid.map(str::to_string),
1925        );
1926        assert_eq!(report.venue_position_id, None);
1927        assert_eq!(report.ts_event, UnixNanos::new(1_716_800_399_334_000_000));
1928    }
1929
1930    #[rstest]
1931    #[case::charge_midpoint(false, "50000.3", dec!(0.00055), dec!(0.02750017))]
1932    #[case::charge_below_midpoint(false, "50000.1", dec!(0.00051), dec!(0.02550006))]
1933    #[case::rebate_below_midpoint(true, "50000.1", dec!(-0.00051), dec!(-0.02550005))]
1934    fn parse_ws_fill_report_fast_rounds_linear_charge_up(
1935        #[case] is_maker: bool,
1936        #[case] exec_price: &str,
1937        #[case] fee_rate: Decimal,
1938        #[case] expected_commission: Decimal,
1939    ) {
1940        let instrument = linear_instrument();
1941        let mut exec = fast_execution(is_maker, "link-1");
1942        exec.exec_price = exec_price.to_string();
1943        exec.exec_qty = "0.001".to_string();
1944        let account_id = AccountId::new("BYBIT-001");
1945        let rates = MakerTakerFeeRates::new(fee_rate, fee_rate);
1946
1947        let report =
1948            parse_ws_fill_report_fast(&exec, account_id, &instrument, Some(rates), None, None, TS)
1949                .unwrap();
1950
1951        assert_eq!(report.commission.as_decimal(), expected_commission);
1952        assert_eq!(report.commission.currency.code, "USDT");
1953    }
1954
1955    #[rstest]
1956    fn parse_ws_fill_report_fast_matches_standard_linear_commission() {
1957        let instrument = linear_instrument();
1958        let json = load_test_json("ws_account_execution.json");
1959        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
1960            serde_json::from_str(&json).unwrap();
1961        let standard = &msg.data[0];
1962        let account_id = AccountId::new("BYBIT-001");
1963        let standard_report = parse_ws_fill_report(standard, account_id, &instrument, TS).unwrap();
1964        let mut fast = fast_execution(false, "link-1");
1965        fast.exec_price = standard.exec_price.clone();
1966        fast.exec_qty = standard.exec_qty.clone();
1967        fast.side = standard.side;
1968        fast.is_maker = standard.is_maker;
1969        let rates = MakerTakerFeeRates::new(dec!(0.0001), dec!(0.00055));
1970
1971        let report =
1972            parse_ws_fill_report_fast(&fast, account_id, &instrument, Some(rates), None, None, TS)
1973                .unwrap();
1974
1975        assert_eq!(report.commission, standard_report.commission);
1976        assert_eq!(report.commission.as_decimal(), dec!(26.3725275));
1977        assert_eq!(report.commission.currency.code, "USDT");
1978    }
1979
1980    #[rstest]
1981    #[case::maker_buy(BybitOrderSide::Buy, true, dec!(0.0001), "BTC", dec!(0.00005))]
1982    #[case::maker_sell(BybitOrderSide::Sell, true, dec!(0.0001), "USDT", dec!(2.5))]
1983    #[case::taker_buy(BybitOrderSide::Buy, false, dec!(0.0001), "BTC", dec!(0.0003))]
1984    #[case::taker_sell(BybitOrderSide::Sell, false, dec!(0.0001), "USDT", dec!(15))]
1985    #[case::maker_buy_rebate(BybitOrderSide::Buy, true, dec!(-0.0001), "USDT", dec!(-2.5))]
1986    #[case::maker_sell_rebate(BybitOrderSide::Sell, true, dec!(-0.0001), "BTC", dec!(-0.00005))]
1987    fn parse_ws_fill_report_fast_calculates_spot_commission(
1988        #[case] side: BybitOrderSide,
1989        #[case] is_maker: bool,
1990        #[case] maker_rate: Decimal,
1991        #[case] expected_currency: &str,
1992        #[case] expected_amount: Decimal,
1993    ) {
1994        let instrument = spot_instrument();
1995        let mut exec = fast_execution(is_maker, "link-1");
1996        exec.category = BybitProductType::Spot;
1997        exec.side = side;
1998        let rates = MakerTakerFeeRates::new(maker_rate, dec!(0.0006));
1999
2000        let report = parse_ws_fill_report_fast(
2001            &exec,
2002            AccountId::new("BYBIT-001"),
2003            &instrument,
2004            Some(rates),
2005            None,
2006            None,
2007            TS,
2008        )
2009        .unwrap();
2010
2011        assert_eq!(report.commission.as_decimal(), expected_amount);
2012        assert_eq!(report.commission.currency.code, expected_currency);
2013    }
2014
2015    #[rstest]
2016    fn parse_ws_fill_report_fast_calculates_inverse_commission() {
2017        let instrument = inverse_instrument();
2018        let mut exec = fast_execution(false, "link-1");
2019        exec.category = BybitProductType::Inverse;
2020        exec.symbol = Ustr::from("BTCUSD");
2021        exec.exec_qty = "1000".to_string();
2022        exec.exec_price = "50000".to_string();
2023        let rates = MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006));
2024
2025        let report = parse_ws_fill_report_fast(
2026            &exec,
2027            AccountId::new("BYBIT-001"),
2028            &instrument,
2029            Some(rates),
2030            None,
2031            None,
2032            TS,
2033        )
2034        .unwrap();
2035
2036        assert_eq!(report.commission.as_decimal(), dec!(0.000012));
2037        assert_eq!(report.commission.currency.code, "BTC");
2038    }
2039
2040    #[rstest]
2041    fn parse_ws_fill_report_fast_option_returns_error() {
2042        let instrument = option_instrument_with_distinct_settlement();
2043        let mut exec = fast_execution(false, "link-1");
2044        exec.category = BybitProductType::Option;
2045        exec.symbol = Ustr::from("BTC-30JUN25-100000-C");
2046        exec.exec_qty = "0.5".to_string();
2047        exec.exec_price = "1000".to_string();
2048        let rates = MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0002));
2049
2050        let error = parse_ws_fill_report_fast(
2051            &exec,
2052            AccountId::new("BYBIT-001"),
2053            &instrument,
2054            Some(rates),
2055            None,
2056            None,
2057            TS,
2058        )
2059        .unwrap_err();
2060
2061        assert_eq!(
2062            format!("{error:#}"),
2063            "cannot derive fast-execution commission: \
2064             fast-execution payload lacks the inputs for the Option fee formula"
2065        );
2066    }
2067
2068    #[rstest]
2069    fn parse_ws_fill_report_fast_missing_rates_returns_error() {
2070        let instrument = spot_instrument();
2071        let mut exec = fast_execution(false, "link-1");
2072        exec.category = BybitProductType::Spot;
2073
2074        let error = parse_ws_fill_report_fast(
2075            &exec,
2076            AccountId::new("BYBIT-001"),
2077            &instrument,
2078            None,
2079            None,
2080            None,
2081            TS,
2082        )
2083        .unwrap_err();
2084
2085        assert_eq!(
2086            format!("{error:#}"),
2087            format!(
2088                "cannot derive fast-execution commission: no cached fee rates for {}",
2089                instrument.id()
2090            )
2091        );
2092    }
2093
2094    #[rstest]
2095    fn parse_ws_fill_report_fast_derivation_overflow_returns_error() {
2096        let instrument = linear_instrument();
2097        let exec = fast_execution(false, "link-1");
2098        let rates = MakerTakerFeeRates::new(dec!(0.0001), Decimal::MAX);
2099
2100        let error = parse_ws_fill_report_fast(
2101            &exec,
2102            AccountId::new("BYBIT-001"),
2103            &instrument,
2104            Some(rates),
2105            None,
2106            None,
2107            TS,
2108        )
2109        .unwrap_err();
2110
2111        assert!(
2112            format!("{error:#}").starts_with("cannot derive fast-execution commission: "),
2113            "unexpected error: {error:#}"
2114        );
2115    }
2116
2117    #[rstest]
2118    fn parse_ws_fill_report_fast_preserves_venue_position_id() {
2119        let instrument = linear_instrument();
2120        let exec = fast_execution(false, "link-hedge");
2121        let account_id = AccountId::new("BYBIT-001");
2122        let venue_pid = PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG");
2123
2124        let report = parse_ws_fill_report_fast(
2125            &exec,
2126            account_id,
2127            &instrument,
2128            Some(MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006))),
2129            None,
2130            Some(venue_pid),
2131            TS,
2132        )
2133        .unwrap();
2134
2135        assert_eq!(report.venue_position_id, Some(venue_pid));
2136    }
2137
2138    #[rstest]
2139    fn parse_bybit_ws_frame_routes_execution_fast_topic() {
2140        // The fixture topic is `execution.fast` (matches the venue-doc sample),
2141        // which the prefix check at parse_bybit_ws_frame routes to the fast frame.
2142        let value: serde_json::Value =
2143            serde_json::from_str(&load_test_json("ws_account_execution_fast.json")).unwrap();
2144        let frame = parse_bybit_ws_frame(value);
2145        assert!(
2146            matches!(frame, BybitWsFrame::AccountExecutionFast(_)),
2147            "expected AccountExecutionFast, found {frame:?}",
2148        );
2149    }
2150
2151    #[rstest]
2152    fn parse_bybit_ws_frame_routes_standard_execution_topic() {
2153        // Sanity: with the fast prefix checked first, a plain `execution.<cat>` topic
2154        // must still route to the standard variant (not the fast one).
2155        let envelope = BybitWsAccountExecutionMsg {
2156            topic: Ustr::from("execution.linear"),
2157            id: "std-1".to_string(),
2158            creation_time: 1_716_800_399_338,
2159            data: vec![],
2160        };
2161        let value = serde_json::to_value(envelope).unwrap();
2162        let frame = parse_bybit_ws_frame(value);
2163        assert!(
2164            matches!(frame, BybitWsFrame::AccountExecution(_)),
2165            "expected AccountExecution, found {frame:?}",
2166        );
2167    }
2168
2169    #[rstest]
2170    fn parse_bybit_ws_frame_unrecognized_exec_type_still_routes_execution() {
2171        let json = load_test_json("ws_account_execution_adl.json");
2172        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
2173        value["data"][0]["execType"] = serde_json::json!("StockMerger");
2174
2175        let frame = parse_bybit_ws_frame(value);
2176
2177        match frame {
2178            BybitWsFrame::AccountExecution(msg) => {
2179                assert_eq!(msg.data[0].exec_type, BybitExecType::Unknown);
2180            }
2181            other => panic!("Expected AccountExecution, found {other:?}"),
2182        }
2183    }
2184
2185    #[rstest]
2186    fn parse_ws_order_status_report_venue_position_id_is_none_for_tp() {
2187        let instrument = linear_instrument();
2188        let json = load_test_json("ws_account_order_take_profit.json");
2189        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2190            serde_json::from_str(&json).unwrap();
2191        let order = &msg.data[0]; // positionIdx=0
2192        let account_id = AccountId::new("BYBIT-001");
2193
2194        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2195
2196        assert_eq!(report.venue_position_id, None);
2197    }
2198
2199    #[rstest]
2200    fn parse_ws_order_status_report_venue_position_id_for_hedge() {
2201        let instrument = linear_instrument();
2202        let json = load_test_json("ws_account_order_take_profit.json");
2203        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2204            serde_json::from_str(&json).unwrap();
2205        let mut order = msg.data[0].clone();
2206        order.position_idx = 1;
2207        let account_id = AccountId::new("BYBIT-001");
2208
2209        let report = parse_ws_order_status_report(&order, &instrument, account_id, TS).unwrap();
2210
2211        assert_eq!(
2212            report.venue_position_id,
2213            Some(PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG"))
2214        );
2215    }
2216
2217    #[rstest]
2218    fn parse_ws_position_into_position_status_report() {
2219        let instrument = linear_instrument();
2220        let json = load_test_json("ws_account_position.json");
2221        let msg: crate::websocket::messages::BybitWsAccountPositionMsg =
2222            serde_json::from_str(&json).unwrap();
2223        let position = &msg.data[0];
2224        let account_id = AccountId::new("BYBIT-001");
2225
2226        let report =
2227            parse_ws_position_status_report(position, account_id, &instrument, TS).unwrap();
2228
2229        assert_eq!(report.account_id, account_id);
2230        assert_eq!(report.instrument_id, instrument.id());
2231        assert_eq!(report.position_side, PositionSide::Short);
2232        assert_eq!(report.quantity, instrument.make_qty(0.01, None));
2233        assert_eq!(
2234            report.avg_px_open,
2235            Some(Decimal::try_from(3641.075).unwrap())
2236        );
2237        assert_eq!(report.ts_last, UnixNanos::new(1_762_199_125_472_000_000));
2238        assert_eq!(report.ts_init, TS);
2239    }
2240
2241    #[rstest]
2242    fn parse_ws_position_status_report_venue_position_id_for_hedge() {
2243        let instrument = linear_instrument();
2244        let json = load_test_json("ws_account_position.json");
2245        let msg: crate::websocket::messages::BybitWsAccountPositionMsg =
2246            serde_json::from_str(&json).unwrap();
2247        let mut position = msg.data[0].clone();
2248        position.position_idx = 2;
2249        let account_id = AccountId::new("BYBIT-001");
2250
2251        let report =
2252            parse_ws_position_status_report(&position, account_id, &instrument, TS).unwrap();
2253
2254        assert_eq!(
2255            report.venue_position_id,
2256            Some(PositionId::from("BTCUSDT-LINEAR.BYBIT-SHORT"))
2257        );
2258    }
2259
2260    #[rstest]
2261    fn parse_ws_position_short_into_position_status_report() {
2262        // Create ETHUSDT instrument
2263        let instruments_json = load_test_json("http_get_instruments_linear.json");
2264        let instruments_response: crate::http::models::BybitInstrumentLinearResponse =
2265            serde_json::from_str(&instruments_json).unwrap();
2266        let eth_def = &instruments_response.result.list[1]; // ETHUSDT is second in the list
2267        let instrument = crate::common::parse::parse_linear_instrument(eth_def, TS, TS).unwrap();
2268
2269        let json = load_test_json("ws_account_position_short.json");
2270        let msg: crate::websocket::messages::BybitWsAccountPositionMsg =
2271            serde_json::from_str(&json).unwrap();
2272        let position = &msg.data[0];
2273        let account_id = AccountId::new("BYBIT-001");
2274
2275        let report =
2276            parse_ws_position_status_report(position, account_id, &instrument, TS).unwrap();
2277
2278        assert_eq!(report.account_id, account_id);
2279        assert_eq!(report.instrument_id.symbol.as_str(), "ETHUSDT-LINEAR");
2280        assert_eq!(report.position_side, PositionSide::Short);
2281        assert_eq!(report.quantity, instrument.make_qty(0.01, None));
2282        assert_eq!(
2283            report.avg_px_open,
2284            Some(Decimal::try_from(3641.075).unwrap())
2285        );
2286        assert_eq!(report.ts_last, UnixNanos::new(1_762_199_125_472_000_000));
2287        assert_eq!(report.ts_init, TS);
2288    }
2289
2290    #[rstest]
2291    fn parse_ws_wallet_into_account_state() {
2292        let json = load_test_json("ws_account_wallet.json");
2293        let msg: crate::websocket::messages::BybitWsAccountWalletMsg =
2294            serde_json::from_str(&json).unwrap();
2295        let wallet = &msg.data[0];
2296        let account_id = AccountId::new("BYBIT-001");
2297        let ts_event = UnixNanos::new(1_700_034_722_104_000_000);
2298
2299        let state = parse_ws_account_state(wallet, account_id, ts_event, TS).unwrap();
2300
2301        assert_eq!(state.account_id, account_id);
2302        assert_eq!(state.account_type, AccountType::Margin);
2303        assert_eq!(state.balances.len(), 2);
2304        assert!(state.is_reported);
2305
2306        // Check BTC balance
2307        let btc_balance = &state.balances[0];
2308        assert_eq!(btc_balance.currency.code, "BTC");
2309        assert!((btc_balance.total.as_f64() - 0.00102964).abs() < 1e-8);
2310        assert!((btc_balance.free.as_f64() - 0.00092964).abs() < 1e-8);
2311        assert!((btc_balance.locked.as_f64() - 0.0001).abs() < 1e-8);
2312
2313        // Check USDT balance
2314        let usdt_balance = &state.balances[1];
2315        assert_eq!(usdt_balance.currency.code, "USDT");
2316        assert!((usdt_balance.total.as_f64() - 9647.75537647).abs() < 1e-6);
2317        assert!((usdt_balance.free.as_f64() - 9519.89806037).abs() < 1e-6);
2318        assert!((usdt_balance.locked.as_f64() - 127.8573161).abs() < 1e-6);
2319
2320        // BTC has order IM only (no position), USDT has position IM+MM (no orders).
2321        assert_eq!(state.margins.len(), 2);
2322        assert!(state.margins.iter().all(|m| m.instrument_id.is_none()));
2323
2324        let btc_margin = state
2325            .margins
2326            .iter()
2327            .find(|m| m.currency.code == "BTC")
2328            .expect("BTC margin missing");
2329        assert!((btc_margin.initial.as_f64() - 0.0001).abs() < 1e-8);
2330        assert!(btc_margin.maintenance.as_f64().abs() < 1e-9);
2331
2332        let usdt_margin = state
2333            .margins
2334            .iter()
2335            .find(|m| m.currency.code == "USDT")
2336            .expect("USDT margin missing");
2337        assert!((usdt_margin.initial.as_f64() - 127.8573161).abs() < 1e-6);
2338        assert!((usdt_margin.maintenance.as_f64() - 12.78573161).abs() < 1e-6);
2339
2340        assert_eq!(state.ts_event, ts_event);
2341        assert_eq!(state.ts_init, TS);
2342    }
2343
2344    #[rstest]
2345    fn parse_ws_wallet_with_small_order_calculates_free_correctly() {
2346        // Regression test for issue where availableToWithdraw=0 caused all funds to appear locked
2347        // When a small order is placed, Bybit may report availableToWithdraw=0 due to margin calculations,
2348        // but totalOrderIM correctly shows only the margin locked for the order
2349        let json = load_test_json("ws_account_wallet_small_order.json");
2350        let msg: crate::websocket::messages::BybitWsAccountWalletMsg =
2351            serde_json::from_str(&json).unwrap();
2352        let wallet = &msg.data[0];
2353        let account_id = AccountId::new("BYBIT-UNIFIED");
2354        let ts_event = UnixNanos::new(1_762_960_669_000_000_000);
2355
2356        let state = parse_ws_account_state(wallet, account_id, ts_event, TS).unwrap();
2357
2358        assert_eq!(state.account_id, account_id);
2359        assert_eq!(state.balances.len(), 1);
2360
2361        // Check USDT balance
2362        let usdt_balance = &state.balances[0];
2363        assert_eq!(usdt_balance.currency.code, "USDT");
2364
2365        // Wallet has 51,333.82 USDT total
2366        assert!((usdt_balance.total.as_f64() - 51333.82543837).abs() < 1e-6);
2367
2368        // Only 50.028 USDT should be locked (for the order), not all funds
2369        assert!((usdt_balance.locked.as_f64() - 50.028).abs() < 1e-6);
2370
2371        // Free should be total - locked = 51,333.82 - 50.028 = 51,283.79
2372        assert!((usdt_balance.free.as_f64() - 51283.79743837).abs() < 1e-6);
2373
2374        // The bug would have calculated: locked = total - availableToWithdraw = 51,333.82 - 0 = 51,333.82 (all locked!)
2375        // This test verifies that we now correctly use totalOrderIM instead of deriving from availableToWithdraw
2376
2377        // The small order reserves 50.028 USDT of initial margin via `totalOrderIM`,
2378        // so the account-wide USDT margin must be populated even with no open position.
2379        assert_eq!(state.margins.len(), 1);
2380        let usdt_margin = &state.margins[0];
2381        assert!(usdt_margin.instrument_id.is_none());
2382        assert_eq!(usdt_margin.currency.code, "USDT");
2383        assert!((usdt_margin.initial.as_f64() - 50.028).abs() < 1e-6);
2384        assert!(usdt_margin.maintenance.as_f64().abs() < 1e-9);
2385    }
2386
2387    #[rstest]
2388    fn parse_ticker_linear_into_funding_rate() {
2389        let instrument = linear_instrument();
2390        let json = load_test_json("ws_ticker_linear.json");
2391        let msg: BybitWsTickerLinearMsg = serde_json::from_str(&json).unwrap();
2392
2393        let ts_event = UnixNanos::new(1_673_272_861_686_000_000);
2394
2395        let funding =
2396            parse_ticker_linear_funding(&msg.data, instrument.id(), ts_event, TS).unwrap();
2397
2398        assert_eq!(funding.instrument_id, instrument.id());
2399        assert_eq!(funding.rate, dec!(-0.000212)); // -0.000212
2400        assert_eq!(funding.interval, Some(8 * 60));
2401        assert_eq!(
2402            funding.next_funding_ns,
2403            Some(UnixNanos::new(1_673_280_000_000_000_000))
2404        );
2405        assert_eq!(funding.ts_event, ts_event);
2406        assert_eq!(funding.ts_init, TS);
2407    }
2408
2409    #[rstest]
2410    fn parse_ticker_linear_into_mark_price() {
2411        let instrument = linear_instrument();
2412        let json = load_test_json("ws_ticker_linear.json");
2413        let msg: BybitWsTickerLinearMsg = serde_json::from_str(&json).unwrap();
2414
2415        let ts_event = UnixNanos::new(1_673_272_861_686_000_000);
2416
2417        let mark_price =
2418            parse_ticker_linear_mark_price(&msg.data, &instrument, ts_event, TS).unwrap();
2419
2420        assert_eq!(mark_price.instrument_id, instrument.id());
2421        assert_eq!(mark_price.value, instrument.make_price(17217.33));
2422        assert_eq!(mark_price.ts_event, ts_event);
2423        assert_eq!(mark_price.ts_init, TS);
2424    }
2425
2426    #[rstest]
2427    fn parse_ticker_linear_into_index_price() {
2428        let instrument = linear_instrument();
2429        let json = load_test_json("ws_ticker_linear.json");
2430        let msg: BybitWsTickerLinearMsg = serde_json::from_str(&json).unwrap();
2431
2432        let ts_event = UnixNanos::new(1_673_272_861_686_000_000);
2433
2434        let index_price =
2435            parse_ticker_linear_index_price(&msg.data, &instrument, ts_event, TS).unwrap();
2436
2437        assert_eq!(index_price.instrument_id, instrument.id());
2438        assert_eq!(index_price.value, instrument.make_price(17227.36));
2439        assert_eq!(index_price.ts_event, ts_event);
2440        assert_eq!(index_price.ts_init, TS);
2441    }
2442
2443    #[rstest]
2444    fn parse_ticker_option_into_mark_price() {
2445        let instrument = option_instrument();
2446        let json = load_test_json("ws_ticker_option.json");
2447        let msg: BybitWsTickerOptionMsg = serde_json::from_str(&json).unwrap();
2448
2449        let mark_price = parse_ticker_option_mark_price(&msg, &instrument, TS).unwrap();
2450
2451        assert_eq!(mark_price.instrument_id, instrument.id());
2452        assert_eq!(mark_price.value, instrument.make_price(7.86976724));
2453        assert_eq!(mark_price.ts_init, TS);
2454    }
2455
2456    #[rstest]
2457    fn parse_ticker_option_into_index_price() {
2458        let instrument = option_instrument();
2459        let json = load_test_json("ws_ticker_option.json");
2460        let msg: BybitWsTickerOptionMsg = serde_json::from_str(&json).unwrap();
2461
2462        let index_price = parse_ticker_option_index_price(&msg, &instrument, TS).unwrap();
2463
2464        assert_eq!(index_price.instrument_id, instrument.id());
2465        assert_eq!(index_price.value, instrument.make_price(16823.73));
2466        assert_eq!(index_price.ts_init, TS);
2467    }
2468
2469    #[rstest]
2470    fn parse_ticker_option_greeks_keeps_f64_domain_values() {
2471        let instrument = option_instrument();
2472        let json = load_test_json("ws_ticker_option.json");
2473        let mut msg: BybitWsTickerOptionMsg = serde_json::from_str(&json).unwrap();
2474        msg.data.bid_iv = "0.4812".to_string();
2475
2476        let greeks = parse_ticker_option_greeks(&msg, &instrument, TS).unwrap();
2477
2478        let expected = OptionGreeks {
2479            instrument_id: instrument.id(),
2480            convention: GreeksConvention::BlackScholes,
2481            greeks: OptionGreekValues {
2482                delta: 0.047831,
2483                gamma: 0.00021453,
2484                vega: 0.81351067,
2485                theta: -19.9115368,
2486                rho: 0.0,
2487            },
2488            mark_iv: Some(0.4896),
2489            bid_iv: Some(0.4812),
2490            ask_iv: Some(0.514),
2491            underlying_price: Some(16815.1),
2492            open_interest: Some(49.85),
2493            ts_event: UnixNanos::new(1_672_917_511_074_000_000),
2494            ts_init: TS,
2495        };
2496
2497        assert_eq!(greeks, expected);
2498    }
2499
2500    #[rstest]
2501    fn parse_ws_order_stop_market_sell_preserves_type() {
2502        let instrument = linear_instrument();
2503        let json = load_test_json("ws_account_order_stop_market.json");
2504        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2505            serde_json::from_str(&json).unwrap();
2506        let order = &msg.data[0];
2507        let account_id = AccountId::new("BYBIT-001");
2508
2509        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2510
2511        // Verify sell StopMarket: orderType=Market + stopOrderType=Stop + triggerDirection=2 (falls to)
2512        assert_eq!(report.order_type, OrderType::StopMarket);
2513        assert_eq!(report.order_side, OrderSide::Sell.into());
2514        assert_eq!(report.order_status, OrderStatus::Accepted); // Untriggered maps to Accepted
2515        assert_eq!(report.trigger_price, Some(instrument.make_price(45000.00)));
2516        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2517        assert_eq!(
2518            report.client_order_id.as_ref().unwrap().to_string(),
2519            "test-client-stop-market-001"
2520        );
2521    }
2522
2523    #[rstest]
2524    fn parse_ws_order_stop_market_buy_preserves_type() {
2525        let instrument = linear_instrument();
2526        let json = load_test_json("ws_account_order_buy_stop_market.json");
2527        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2528            serde_json::from_str(&json).unwrap();
2529        let order = &msg.data[0];
2530        let account_id = AccountId::new("BYBIT-001");
2531
2532        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2533
2534        // Verify buy StopMarket: orderType=Market + stopOrderType=Stop + triggerDirection=1 (rises to)
2535        assert_eq!(report.order_type, OrderType::StopMarket);
2536        assert_eq!(report.order_side, OrderSide::Buy.into());
2537        assert_eq!(report.order_status, OrderStatus::Accepted);
2538        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2539        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2540        assert_eq!(
2541            report.client_order_id.as_ref().unwrap().to_string(),
2542            "test-client-buy-stop-market-001"
2543        );
2544    }
2545
2546    #[rstest]
2547    fn parse_ws_order_market_if_touched_buy_preserves_type() {
2548        let instrument = linear_instrument();
2549        let json = load_test_json("ws_account_order_market_if_touched.json");
2550        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2551            serde_json::from_str(&json).unwrap();
2552        let order = &msg.data[0];
2553        let account_id = AccountId::new("BYBIT-001");
2554
2555        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2556
2557        // Verify buy MIT: orderType=Market + stopOrderType=Stop + triggerDirection=2 (falls to)
2558        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2559        assert_eq!(report.order_side, OrderSide::Buy.into());
2560        assert_eq!(report.order_status, OrderStatus::Accepted); // Untriggered maps to Accepted
2561        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2562        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2563        assert_eq!(
2564            report.client_order_id.as_ref().unwrap().to_string(),
2565            "test-client-mit-001"
2566        );
2567    }
2568
2569    #[rstest]
2570    fn parse_ws_order_market_if_touched_sell_preserves_type() {
2571        let instrument = linear_instrument();
2572        let json = load_test_json("ws_account_order_sell_market_if_touched.json");
2573        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2574            serde_json::from_str(&json).unwrap();
2575        let order = &msg.data[0];
2576        let account_id = AccountId::new("BYBIT-001");
2577
2578        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2579
2580        // Verify sell MIT: orderType=Market + stopOrderType=Stop + triggerDirection=1 (rises to)
2581        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2582        assert_eq!(report.order_side, OrderSide::Sell.into());
2583        assert_eq!(report.order_status, OrderStatus::Accepted);
2584        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2585        assert_eq!(
2586            report.client_order_id.as_ref().unwrap().to_string(),
2587            "test-client-sell-mit-001"
2588        );
2589    }
2590
2591    #[rstest]
2592    fn parse_ws_order_stop_limit_preserves_type() {
2593        let instrument = linear_instrument();
2594        let json = load_test_json("ws_account_order_stop_limit.json");
2595        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2596            serde_json::from_str(&json).unwrap();
2597        let order = &msg.data[0];
2598        let account_id = AccountId::new("BYBIT-001");
2599
2600        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2601
2602        // Verify StopLimit order type is correctly parsed
2603        // orderType=Limit + stopOrderType=Stop + triggerDirection=2 (falls to)
2604        assert_eq!(report.order_type, OrderType::StopLimit);
2605        assert_eq!(report.order_side, OrderSide::Sell.into());
2606        assert_eq!(report.order_status, OrderStatus::Accepted); // Untriggered maps to Accepted
2607        assert_eq!(report.price, Some(instrument.make_price(44500.00)));
2608        assert_eq!(report.trigger_price, Some(instrument.make_price(45000.00)));
2609        assert_eq!(
2610            report.client_order_id.as_ref().unwrap().to_string(),
2611            "test-client-stop-limit-001"
2612        );
2613    }
2614
2615    #[rstest]
2616    fn parse_ws_order_limit_if_touched_preserves_type() {
2617        let instrument = linear_instrument();
2618        let json = load_test_json("ws_account_order_limit_if_touched.json");
2619        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2620            serde_json::from_str(&json).unwrap();
2621        let order = &msg.data[0];
2622        let account_id = AccountId::new("BYBIT-001");
2623
2624        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2625
2626        // Verify LimitIfTouched order type is correctly parsed
2627        // orderType=Limit + stopOrderType=Stop + triggerDirection=1 (rises to)
2628        assert_eq!(report.order_type, OrderType::LimitIfTouched);
2629        assert_eq!(report.order_side, OrderSide::Buy.into());
2630        assert_eq!(report.order_status, OrderStatus::Accepted); // Untriggered maps to Accepted
2631        assert_eq!(report.price, Some(instrument.make_price(55500.00)));
2632        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2633        assert_eq!(
2634            report.client_order_id.as_ref().unwrap().to_string(),
2635            "test-client-lit-001"
2636        );
2637    }
2638
2639    #[rstest]
2640    fn parse_ws_wallet_clamps_free_to_zero_when_locked_exceeds_total() {
2641        // totalOrderIM (80) + totalPositionIM (40) = 120, which exceeds
2642        // walletBalance (100). Free balance should clamp to zero, not underflow.
2643        let json = load_test_json("ws_account_wallet_locked_exceeds_total.json");
2644        let msg: crate::websocket::messages::BybitWsAccountWalletMsg =
2645            serde_json::from_str(&json).unwrap();
2646        let wallet = &msg.data[0];
2647        let account_id = AccountId::new("BYBIT-UNIFIED");
2648        let ts_event = UnixNanos::new(1_762_960_669_000_000_000);
2649
2650        let state = parse_ws_account_state(wallet, account_id, ts_event, TS).unwrap();
2651
2652        let usdt_balance = &state.balances[0];
2653        assert_eq!(usdt_balance.currency.code, "USDT");
2654        assert!((usdt_balance.total.as_f64() - 100.0).abs() < 1e-6);
2655        // Locked is capped at total to prevent negative free balance
2656        assert!((usdt_balance.locked.as_f64() - 100.0).abs() < 1e-6);
2657        assert_eq!(usdt_balance.free.as_f64(), 0.0);
2658    }
2659
2660    #[rstest]
2661    fn parse_ws_order_take_profit_maps_to_market_if_touched() {
2662        let instrument = linear_instrument();
2663        let json = load_test_json("ws_account_order_take_profit.json");
2664        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2665            serde_json::from_str(&json).unwrap();
2666        let order = &msg.data[0];
2667        let account_id = AccountId::new("BYBIT-001");
2668
2669        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2670
2671        assert_eq!(report.order_type, OrderType::MarketIfTouched);
2672        assert_eq!(report.order_side, OrderSide::Sell.into());
2673        assert_eq!(report.trigger_price, Some(instrument.make_price(55000.00)));
2674        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2675        assert!(report.reduce_only);
2676    }
2677
2678    #[rstest]
2679    fn parse_ws_order_stop_loss_maps_to_stop_market() {
2680        let instrument = linear_instrument();
2681        let json = load_test_json("ws_account_order_stop_loss.json");
2682        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2683            serde_json::from_str(&json).unwrap();
2684        let order = &msg.data[0];
2685        let account_id = AccountId::new("BYBIT-001");
2686
2687        let report = parse_ws_order_status_report(order, &instrument, account_id, TS).unwrap();
2688
2689        assert_eq!(report.order_type, OrderType::StopMarket);
2690        assert_eq!(report.order_side, OrderSide::Sell.into());
2691        assert_eq!(report.trigger_price, Some(instrument.make_price(48000.00)));
2692        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2693        assert!(report.reduce_only);
2694    }
2695}