Skip to main content

nautilus_bybit/websocket/
dispatch.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//! WebSocket message dispatch for the Bybit execution client.
17//!
18//! Routes incoming [`BybitWsMessage`] variants to the appropriate parsing and
19//! event emission paths. Tracked orders (submitted through this client) produce
20//! proper order events; untracked orders fall back to execution reports for
21//! downstream reconciliation.
22
23use std::{
24    collections::VecDeque,
25    hash::Hash,
26    sync::{
27        Arc, Mutex,
28        atomic::{AtomicBool, Ordering},
29    },
30};
31
32use ahash::AHashMap;
33use anyhow::Context;
34use arc_swap::ArcSwapOption;
35use dashmap::{DashMap, DashSet, mapref::entry::Entry};
36use nautilus_core::{UUID4, UnixNanos, time::AtomicTime};
37use nautilus_live::ExecutionEventEmitter;
38use nautilus_model::{
39    enums::{LiquiditySide, OrderSide, OrderType},
40    events::{
41        OrderAccepted, OrderCanceled, OrderEventAny, OrderFilled, OrderTriggered, OrderUpdated,
42    },
43    fees::MakerTakerFeeRates,
44    identifiers::{
45        AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TradeId, VenueOrderId,
46    },
47    instruments::{Instrument, InstrumentAny},
48    orders::TRIGGERABLE_ORDER_TYPES,
49    types::{Money, Price, Quantity},
50};
51use rust_decimal::Decimal;
52use ustr::Ustr;
53
54use super::{
55    messages::{
56        BybitWsAccountExecution, BybitWsAccountExecutionFast, BybitWsAccountOrder, BybitWsMessage,
57    },
58    parse::{
59        parse_millis_i64, parse_ws_account_state, parse_ws_fill_report_fast,
60        parse_ws_position_status_report,
61    },
62};
63use crate::{
64    common::{
65        enums::{BybitExecType, BybitOrderSide, BybitOrderStatus, BybitProductType},
66        parse::{
67            bybit_rejection_due_post_only, extract_raw_symbol, get_currency, make_bybit_symbol,
68            parse_millis_timestamp, parse_price_with_precision, parse_quantity_with_precision,
69        },
70    },
71    http::{error::is_bybit_ambiguous_order_error_code, models::BybitFeeRate},
72    repay::RepayRequest,
73};
74
75const DEDUP_CAPACITY: usize = 10_000;
76
77const BYBIT_OP_ORDER_CREATE: &str = "order.create";
78const BYBIT_OP_ORDER_AMEND: &str = "order.amend";
79const BYBIT_OP_ORDER_CANCEL: &str = "order.cancel";
80const BYBIT_OP_ORDER_CREATE_BATCH: &str = "order.create-batch";
81const BYBIT_OP_ORDER_AMEND_BATCH: &str = "order.amend-batch";
82const BYBIT_OP_ORDER_CANCEL_BATCH: &str = "order.cancel-batch";
83
84/// Order identity context stored at submission time, used by the WS dispatch
85/// task to produce proper order events without Cache access.
86#[derive(Debug, Clone)]
87pub struct OrderIdentity {
88    pub instrument_id: InstrumentId,
89    pub strategy_id: StrategyId,
90    pub order_side: OrderSide,
91    pub order_type: OrderType,
92    pub venue_position_id: Option<PositionId>,
93}
94
95/// Tracks which type of WS request is pending for a given req_id.
96#[derive(Debug, Clone, Copy)]
97pub enum PendingOperation {
98    Place,
99    Cancel,
100    Amend,
101}
102
103/// Shared state for cross-stream event deduplication between the private
104/// and trade WebSocket dispatch loops.
105pub type PendingRequestData = (
106    Vec<ClientOrderId>,
107    Vec<Option<VenueOrderId>>,
108    PendingOperation,
109    Vec<Option<UUID4>>,
110);
111
112/// Snapshot of an order's price, quantity, and trigger price at last dispatch.
113/// Used to detect modifications when Bybit sends back an order with the same
114/// status but changed fields.
115#[derive(Debug, Clone)]
116pub struct OrderStateSnapshot {
117    pub quantity: Quantity,
118    pub price: Option<Price>,
119    pub trigger_price: Option<Price>,
120}
121
122#[derive(Clone, Copy, Debug)]
123struct SpotRepayFill {
124    quantity: Quantity,
125    base_fee: Decimal,
126}
127
128#[derive(Debug)]
129struct RecentIds<T: Eq + Hash> {
130    ids: DashSet<T>,
131    order: Mutex<VecDeque<T>>,
132}
133
134impl<T: Eq + Hash> Default for RecentIds<T> {
135    fn default() -> Self {
136        Self {
137            ids: DashSet::default(),
138            order: Mutex::new(VecDeque::new()),
139        }
140    }
141}
142
143impl<T: Copy + Eq + Hash> RecentIds<T> {
144    fn insert(&self, id: T) -> bool {
145        let mut order = self.order.lock().unwrap_or_else(|e| e.into_inner());
146
147        if self.ids.contains(&id) {
148            return false;
149        }
150
151        if order.len() == DEDUP_CAPACITY
152            && let Some(oldest) = order.pop_front()
153        {
154            self.ids.remove(&oldest);
155        }
156
157        order.push_back(id);
158        self.ids.insert(id)
159    }
160
161    fn contains(&self, id: &T) -> bool {
162        self.ids.contains(id)
163    }
164
165    fn remove(&self, id: T) {
166        let mut order = self.order.lock().unwrap_or_else(|e| e.into_inner());
167        self.ids.remove(&id);
168        order.retain(|existing| *existing != id);
169    }
170}
171
172#[derive(Debug)]
173pub struct WsDispatchState {
174    pub fast_execution: bool,
175    pub order_identities: DashMap<ClientOrderId, OrderIdentity>,
176    pub order_venue_ids: DashMap<ClientOrderId, VenueOrderId>,
177    pub venue_order_ids: DashMap<VenueOrderId, ClientOrderId>,
178    pub fee_rates: DashMap<InstrumentId, MakerTakerFeeRates>,
179    pub pending_requests: DashMap<String, PendingRequestData>,
180    pub order_snapshots: DashMap<ClientOrderId, OrderStateSnapshot>,
181    pub emitted_accepted: DashSet<ClientOrderId>,
182    pub triggered_orders: DashSet<ClientOrderId>,
183    pub filled_orders: DashSet<ClientOrderId>,
184    fast_execution_ids: RecentIds<TradeId>,
185    fast_filled_quantities: DashMap<ClientOrderId, Quantity>,
186    pub terminal_order_quantities: DashMap<ClientOrderId, Quantity>,
187    untracked_order_ids: RecentIds<VenueOrderId>,
188    pending_fast_executions: DashMap<VenueOrderId, Vec<BybitWsAccountExecutionFast>>,
189    spot_repay_fills: DashMap<ClientOrderId, SpotRepayFill>,
190    repay_tx: ArcSwapOption<tokio::sync::mpsc::UnboundedSender<RepayRequest>>,
191    clearing: AtomicBool,
192}
193
194impl Default for WsDispatchState {
195    fn default() -> Self {
196        Self {
197            fast_execution: false,
198            order_identities: DashMap::new(),
199            order_venue_ids: DashMap::new(),
200            venue_order_ids: DashMap::new(),
201            fee_rates: DashMap::new(),
202            pending_requests: DashMap::new(),
203            order_snapshots: DashMap::new(),
204            emitted_accepted: DashSet::default(),
205            triggered_orders: DashSet::default(),
206            filled_orders: DashSet::default(),
207            fast_execution_ids: RecentIds::default(),
208            fast_filled_quantities: DashMap::new(),
209            terminal_order_quantities: DashMap::new(),
210            untracked_order_ids: RecentIds::default(),
211            pending_fast_executions: DashMap::new(),
212            spot_repay_fills: DashMap::new(),
213            repay_tx: ArcSwapOption::empty(),
214            clearing: AtomicBool::new(false),
215        }
216    }
217}
218
219impl WsDispatchState {
220    pub(crate) fn new(fast_execution: bool) -> Self {
221        Self {
222            fast_execution,
223            ..Default::default()
224        }
225    }
226
227    fn evict_if_full<T: Eq + Hash>(&self, set: &DashSet<T>) {
228        if set.len() >= DEDUP_CAPACITY
229            && self
230                .clearing
231                .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed)
232                .is_ok()
233        {
234            set.clear();
235            self.clearing.store(false, Ordering::Release);
236        }
237    }
238
239    fn insert_accepted(&self, cid: ClientOrderId) {
240        self.evict_if_full(&self.emitted_accepted);
241        self.emitted_accepted.insert(cid);
242    }
243
244    fn insert_filled(&self, cid: ClientOrderId) {
245        self.evict_if_full(&self.filled_orders);
246        self.filled_orders.insert(cid);
247    }
248
249    fn insert_fast_execution(&self, trade_id: TradeId) -> bool {
250        self.fast_execution_ids.insert(trade_id)
251    }
252
253    fn remove_fast_execution(&self, trade_id: TradeId) {
254        self.fast_execution_ids.remove(trade_id);
255    }
256
257    fn insert_triggered(&self, cid: ClientOrderId) {
258        self.evict_if_full(&self.triggered_orders);
259        self.triggered_orders.insert(cid);
260    }
261
262    pub(crate) fn set_repay_sender(&self, tx: tokio::sync::mpsc::UnboundedSender<RepayRequest>) {
263        self.repay_tx.store(Some(Arc::new(tx)));
264    }
265
266    pub(crate) fn clear_repay_sender(&self) {
267        self.repay_tx.store(None);
268    }
269
270    fn enqueue_repay(&self, req: RepayRequest) {
271        if let Some(tx) = self.repay_tx.load_full()
272            && let Err(e) = tx.send(req)
273        {
274            log::warn!("Failed to enqueue spot borrow repayment: {e}");
275        }
276    }
277}
278
279/// Dispatches a WebSocket message with cross-stream deduplication.
280///
281/// For orders with a tracked identity (submitted through this client), produces
282/// proper order events (OrderAccepted, OrderCanceled, OrderFilled, etc.).
283/// For untracked orders (external or pre-existing), falls back to execution
284/// reports for downstream reconciliation.
285pub fn dispatch_ws_message(
286    message: &BybitWsMessage,
287    account_id: AccountId,
288    instruments: &AHashMap<Ustr, InstrumentAny>,
289    clock: &AtomicTime,
290    state: &WsDispatchState,
291    emitter: &ExecutionEventEmitter,
292) {
293    match message {
294        BybitWsMessage::AccountOrder(msg) => {
295            let ts_init = clock.get_time_ns();
296
297            for order in &msg.data {
298                let symbol = make_bybit_symbol(order.symbol, order.category);
299                let Some(instrument) = instruments.get(&symbol) else {
300                    log::warn!("No instrument for order update: {symbol}");
301                    continue;
302                };
303
304                dispatch_order_update(order, instrument, account_id, ts_init, state, emitter);
305            }
306        }
307        BybitWsMessage::AccountExecution(msg) => {
308            let ts_init = clock.get_time_ns();
309
310            for exec in &msg.data {
311                let symbol = make_bybit_symbol(exec.symbol, exec.category);
312                let Some(instrument) = instruments.get(&symbol) else {
313                    log::warn!("No instrument for execution update: {symbol}");
314                    continue;
315                };
316                dispatch_execution_fill(exec, instrument, emitter, state, account_id, ts_init);
317            }
318        }
319        BybitWsMessage::AccountExecutionFast(msg) => {
320            let ts_init = clock.get_time_ns();
321
322            for exec in &msg.data {
323                let symbol = make_bybit_symbol(exec.symbol, exec.category);
324                let Some(instrument) = instruments.get(&symbol) else {
325                    log::warn!("No instrument for fast-execution update: {symbol}");
326                    continue;
327                };
328
329                dispatch_execution_fill_fast(
330                    exec, instrument, account_id, ts_init, true, state, emitter,
331                );
332            }
333        }
334        BybitWsMessage::AccountWallet(msg) => {
335            let ts_init = clock.get_time_ns();
336            let ts_event = parse_millis_i64(msg.creation_time, "wallet.creation_time")
337                .unwrap_or_else(|e| {
338                    log::warn!("Failed to parse wallet creation_time, using ts_init: {e}");
339                    ts_init
340                });
341
342            for wallet in &msg.data {
343                match parse_ws_account_state(wallet, account_id, ts_event, ts_init) {
344                    Ok(state) => emitter.send_account_state(state),
345                    Err(e) => log::error!("Failed to parse account state: {e}"),
346                }
347            }
348        }
349        BybitWsMessage::AccountPosition(msg) => {
350            let ts_init = clock.get_time_ns();
351
352            for position in &msg.data {
353                let symbol = make_bybit_symbol(position.symbol, position.category);
354                let Some(instrument) = instruments.get(&symbol) else {
355                    log::warn!("No instrument for position update: {symbol}");
356                    continue;
357                };
358
359                match parse_ws_position_status_report(position, account_id, instrument, ts_init) {
360                    Ok(report) => emitter.send_position_report(report),
361                    Err(e) => log::error!("Failed to parse position status report: {e}"),
362                }
363            }
364        }
365        BybitWsMessage::OrderNotSent { request_id, reason } => {
366            dispatch_order_not_sent(request_id, reason, emitter, state, clock.get_time_ns());
367        }
368        BybitWsMessage::OrderResponse(resp) => {
369            let ts_init = clock.get_time_ns();
370            dispatch_order_response(resp, emitter, state, ts_init);
371        }
372        BybitWsMessage::Error(e) => {
373            log::warn!("WebSocket error: code={} message={}", e.code, e.message);
374        }
375        BybitWsMessage::Reconnected => {
376            log::info!("WebSocket reconnected");
377            flush_pending_fast_executions(
378                instruments,
379                account_id,
380                clock.get_time_ns(),
381                state,
382                emitter,
383            );
384        }
385        BybitWsMessage::Auth(_)
386        | BybitWsMessage::Orderbook(_)
387        | BybitWsMessage::Trade(_)
388        | BybitWsMessage::Liquidation(_)
389        | BybitWsMessage::Kline(_)
390        | BybitWsMessage::TickerLinear(_)
391        | BybitWsMessage::TickerOption(_) => {}
392    }
393}
394
395pub(crate) fn cache_execution_fee_rates(
396    state: &WsDispatchState,
397    instruments: &AHashMap<Ustr, InstrumentAny>,
398    product_type: BybitProductType,
399    fee_rates: Vec<BybitFeeRate>,
400) -> usize {
401    let mut parsed_rates = AHashMap::new();
402
403    for fee_rate in fee_rates {
404        let key = if product_type == BybitProductType::Option {
405            fee_rate.base_coin
406        } else {
407            Some(fee_rate.symbol)
408        };
409
410        let Some(key) = key.filter(|key| !key.is_empty()) else {
411            log::warn!(
412                "Skipping execution fee rate with no symbol or base coin for {product_type:?}"
413            );
414            continue;
415        };
416
417        match parse_execution_fee_rate(&fee_rate) {
418            Ok(rates) => {
419                parsed_rates.insert(key, rates);
420            }
421            Err(e) => log::warn!("Skipping invalid execution fee rate for {key}: {e}"),
422        }
423    }
424
425    let mut cached = 0;
426
427    for instrument in instruments.values().filter(|instrument| {
428        BybitProductType::from_suffix(instrument.id().symbol.as_str()) == Some(product_type)
429    }) {
430        let key = if product_type == BybitProductType::Option {
431            instrument.base_currency().map(|currency| currency.code)
432        } else {
433            Some(Ustr::from(extract_raw_symbol(
434                instrument.id().symbol.as_str(),
435            )))
436        };
437
438        let Some(rates) = key.and_then(|key| parsed_rates.get(&key)) else {
439            continue;
440        };
441
442        state.fee_rates.insert(instrument.id(), *rates);
443        cached += 1;
444    }
445
446    cached
447}
448
449fn parse_execution_fee_rate(fee_rate: &BybitFeeRate) -> anyhow::Result<MakerTakerFeeRates> {
450    let maker = fee_rate
451        .maker_fee_rate
452        .parse::<Decimal>()
453        .with_context(|| format!("invalid makerFeeRate '{}'", fee_rate.maker_fee_rate))?;
454    let taker = fee_rate
455        .taker_fee_rate
456        .parse::<Decimal>()
457        .with_context(|| format!("invalid takerFeeRate '{}'", fee_rate.taker_fee_rate))?;
458    Ok(MakerTakerFeeRates::new(maker, taker))
459}
460
461/// Dispatches a single order status update.
462///
463/// Tracked orders produce lifecycle events (OrderAccepted, OrderTriggered,
464/// OrderCanceled, OrderRejected). Untracked orders fall back to
465/// `OrderStatusReport` for reconciliation.
466fn dispatch_order_update(
467    order: &BybitWsAccountOrder,
468    instrument: &InstrumentAny,
469    account_id: AccountId,
470    ts_init: UnixNanos,
471    state: &WsDispatchState,
472    emitter: &ExecutionEventEmitter,
473) {
474    let client_order_id = if order.order_link_id.is_empty() {
475        None
476    } else {
477        Some(ClientOrderId::new(order.order_link_id))
478    };
479
480    let identity = client_order_id
481        .as_ref()
482        .and_then(|cid| state.order_identities.get(cid).map(|r| r.clone()));
483    let venue_order_id = VenueOrderId::new(order.order_id);
484    if let (Some(client_order_id), Some(identity)) = (client_order_id, identity) {
485        record_venue_order_id(client_order_id, venue_order_id, state);
486        drain_pending_fast_executions(
487            venue_order_id,
488            instrument,
489            account_id,
490            ts_init,
491            state,
492            emitter,
493        );
494
495        match order.order_status {
496            BybitOrderStatus::Created | BybitOrderStatus::New | BybitOrderStatus::Untriggered => {
497                dispatch_order_created(
498                    order,
499                    instrument,
500                    client_order_id,
501                    &identity,
502                    account_id,
503                    ts_init,
504                    state,
505                    emitter,
506                );
507            }
508            BybitOrderStatus::Triggered => {
509                if state.filled_orders.contains(&client_order_id) {
510                    log::debug!("Skipping stale Triggered for {client_order_id} (already filled)");
511                    return;
512                }
513
514                if !TRIGGERABLE_ORDER_TYPES.contains(&identity.order_type) {
515                    log::debug!(
516                        "Skipping OrderTriggered for {} order {client_order_id}: market-style stops have no TRIGGERED state",
517                        identity.order_type,
518                    );
519                    return;
520                }
521
522                ensure_accepted_emitted(
523                    client_order_id,
524                    account_id,
525                    venue_order_id,
526                    &identity,
527                    ts_init,
528                    state,
529                    emitter,
530                );
531                state.insert_triggered(client_order_id);
532                let triggered = OrderTriggered::new(
533                    emitter.trader_id(),
534                    identity.strategy_id,
535                    identity.instrument_id,
536                    client_order_id,
537                    UUID4::new(),
538                    ts_init,
539                    ts_init,
540                    false,
541                    Some(venue_order_id),
542                    Some(account_id),
543                );
544                emitter.send_order_event(OrderEventAny::Triggered(triggered));
545            }
546            BybitOrderStatus::Rejected => {
547                dispatch_order_rejected(
548                    order,
549                    instrument,
550                    client_order_id,
551                    &identity,
552                    account_id,
553                    ts_init,
554                    state,
555                    emitter,
556                );
557            }
558            BybitOrderStatus::PartiallyFilled => {
559                // Fills arrive on the execution channel; no event needed here.
560                // Ensure accepted was emitted so the fill has a valid prior state.
561                ensure_accepted_emitted(
562                    client_order_id,
563                    account_id,
564                    venue_order_id,
565                    &identity,
566                    ts_init,
567                    state,
568                    emitter,
569                );
570
571                // A successful amend on a partially filled order keeps the
572                // PartiallyFilled status. Detect price/qty/trigger changes and
573                // emit OrderUpdated so PendingUpdate resolves.
574                emit_order_updated_if_changed(
575                    order,
576                    instrument,
577                    client_order_id,
578                    &identity,
579                    account_id,
580                    ts_init,
581                    false,
582                    state,
583                    emitter,
584                );
585            }
586            BybitOrderStatus::Filled => {
587                dispatch_order_filled(
588                    order,
589                    instrument,
590                    client_order_id,
591                    &identity,
592                    account_id,
593                    ts_init,
594                    state,
595                    emitter,
596                );
597            }
598            BybitOrderStatus::Canceled
599            | BybitOrderStatus::PartiallyFilledCanceled
600            | BybitOrderStatus::Deactivated => {
601                dispatch_order_canceled(
602                    order,
603                    instrument,
604                    client_order_id,
605                    &identity,
606                    account_id,
607                    ts_init,
608                    state,
609                    emitter,
610                );
611            }
612        }
613    } else {
614        state.untracked_order_ids.insert(venue_order_id);
615        drain_pending_fast_executions(
616            venue_order_id,
617            instrument,
618            account_id,
619            ts_init,
620            state,
621            emitter,
622        );
623
624        // Untracked order: fall back to report for reconciliation
625        match super::parse::parse_ws_order_status_report(order, instrument, account_id, ts_init) {
626            Ok(report) => emitter.send_order_status_report(report),
627            Err(e) => log::error!("Failed to parse order status report: {e}"),
628        }
629    }
630}
631
632#[expect(
633    clippy::too_many_arguments,
634    reason = "status handling shares the dispatcher's order context"
635)]
636fn dispatch_order_created(
637    order: &BybitWsAccountOrder,
638    instrument: &InstrumentAny,
639    client_order_id: ClientOrderId,
640    identity: &OrderIdentity,
641    account_id: AccountId,
642    ts_init: UnixNanos,
643    state: &WsDispatchState,
644    emitter: &ExecutionEventEmitter,
645) {
646    let snapshot = parse_order_snapshot(order, instrument);
647
648    if state.emitted_accepted.contains(&client_order_id)
649        || state.filled_orders.contains(&client_order_id)
650        || state.triggered_orders.contains(&client_order_id)
651    {
652        if emit_order_updated_if_changed(
653            order,
654            instrument,
655            client_order_id,
656            identity,
657            account_id,
658            ts_init,
659            false,
660            state,
661            emitter,
662        ) {
663            return;
664        }
665
666        log::debug!("Skipping duplicate Accepted for {client_order_id}");
667        return;
668    }
669
670    state.insert_accepted(client_order_id);
671
672    // BBO orders resolve their limit price venue-side: emit
673    // OrderUpdated after OrderAccepted when the seed diverges.
674    let venue_differs_from_submitted = snapshot
675        .as_ref()
676        .is_some_and(|s| is_snapshot_updated(s, &client_order_id, state));
677    if let Some(snapshot) = snapshot.as_ref() {
678        state
679            .order_snapshots
680            .insert(client_order_id, snapshot.clone());
681    }
682
683    let venue_order_id = VenueOrderId::new(order.order_id);
684
685    let accepted = OrderAccepted::new(
686        emitter.trader_id(),
687        identity.strategy_id,
688        identity.instrument_id,
689        client_order_id,
690        venue_order_id,
691        account_id,
692        UUID4::new(),
693        ts_init,
694        ts_init,
695        false,
696    );
697    emitter.send_order_event(OrderEventAny::Accepted(accepted));
698
699    if venue_differs_from_submitted {
700        emit_order_updated_if_changed(
701            order,
702            instrument,
703            client_order_id,
704            identity,
705            account_id,
706            ts_init,
707            true,
708            state,
709            emitter,
710        );
711    }
712}
713
714#[expect(
715    clippy::too_many_arguments,
716    reason = "status handling shares the dispatcher's order context"
717)]
718fn dispatch_order_rejected(
719    order: &BybitWsAccountOrder,
720    instrument: &InstrumentAny,
721    client_order_id: ClientOrderId,
722    identity: &OrderIdentity,
723    account_id: AccountId,
724    ts_init: UnixNanos,
725    state: &WsDispatchState,
726    emitter: &ExecutionEventEmitter,
727) {
728    let filled_qty = parse_quantity_with_precision(
729        &order.cum_exec_qty,
730        instrument.size_precision(),
731        "order.cumExecQty",
732    )
733    .unwrap_or_default();
734    let venue_order_id = VenueOrderId::new(order.order_id);
735
736    if filled_qty.is_positive() {
737        // Partially filled then rejected - treat as canceled
738        ensure_accepted_emitted(
739            client_order_id,
740            account_id,
741            venue_order_id,
742            identity,
743            ts_init,
744            state,
745            emitter,
746        );
747
748        let canceled = OrderCanceled::new(
749            emitter.trader_id(),
750            identity.strategy_id,
751            identity.instrument_id,
752            client_order_id,
753            UUID4::new(),
754            ts_init,
755            ts_init,
756            false,
757            Some(venue_order_id),
758            Some(account_id),
759            None,
760        );
761        cleanup_terminal_when_ready(client_order_id, filled_qty, state);
762        emitter.send_order_event(OrderEventAny::Canceled(canceled));
763    } else {
764        let reason = if order.reject_reason.is_empty() {
765            Ustr::from("Order rejected by venue")
766        } else {
767            order.reject_reason
768        };
769
770        cleanup_terminal_when_ready(client_order_id, filled_qty, state);
771
772        emitter.emit_order_rejected_event(
773            identity.strategy_id,
774            identity.instrument_id,
775            client_order_id,
776            reason.as_str(),
777            ts_init,
778            bybit_rejection_due_post_only(reason.as_str()),
779        );
780    }
781}
782
783#[expect(
784    clippy::too_many_arguments,
785    reason = "status handling shares the dispatcher's order context"
786)]
787fn dispatch_order_filled(
788    order: &BybitWsAccountOrder,
789    instrument: &InstrumentAny,
790    client_order_id: ClientOrderId,
791    identity: &OrderIdentity,
792    account_id: AccountId,
793    ts_init: UnixNanos,
794    state: &WsDispatchState,
795    emitter: &ExecutionEventEmitter,
796) {
797    // Fills arrive on the execution channel; no event needed here.
798    // Ensure accepted was emitted so the fill has a valid prior state.
799    let venue_order_id = VenueOrderId::new(order.order_id);
800    ensure_accepted_emitted(
801        client_order_id,
802        account_id,
803        venue_order_id,
804        identity,
805        ts_init,
806        state,
807        emitter,
808    );
809
810    // Reconcile seed against venue values before the fill (BBO
811    // orders may land directly on Filled).
812    emit_order_updated_if_changed(
813        order,
814        instrument,
815        client_order_id,
816        identity,
817        account_id,
818        ts_init,
819        false,
820        state,
821        emitter,
822    );
823
824    if let Ok(terminal_qty) = parse_quantity_with_precision(
825        &order.cum_exec_qty,
826        instrument.size_precision(),
827        "order.cumExecQty",
828    ) {
829        state
830            .terminal_order_quantities
831            .insert(client_order_id, terminal_qty);
832        if state.fast_execution && fast_fill_is_terminal(client_order_id, state) {
833            cleanup_terminal(client_order_id, state);
834        }
835    }
836}
837
838#[expect(
839    clippy::too_many_arguments,
840    reason = "status handling shares the dispatcher's order context"
841)]
842fn dispatch_order_canceled(
843    order: &BybitWsAccountOrder,
844    instrument: &InstrumentAny,
845    client_order_id: ClientOrderId,
846    identity: &OrderIdentity,
847    account_id: AccountId,
848    ts_init: UnixNanos,
849    state: &WsDispatchState,
850    emitter: &ExecutionEventEmitter,
851) {
852    let filled_qty = parse_quantity_with_precision(
853        &order.cum_exec_qty,
854        instrument.size_precision(),
855        "order.cumExecQty",
856    )
857    .unwrap_or_default();
858
859    // Bybit reports a post-only order that would take liquidity as
860    // Cancelled with rejectReason=EC_PostOnlyWillTakeLiquidity,
861    // not Rejected. Surface it as OrderRejected carrying due_post_only.
862    if filled_qty.is_zero() && bybit_rejection_due_post_only(order.reject_reason.as_str()) {
863        cleanup_terminal_when_ready(client_order_id, filled_qty, state);
864        emitter.emit_order_rejected_event(
865            identity.strategy_id,
866            identity.instrument_id,
867            client_order_id,
868            order.reject_reason.as_str(),
869            ts_init,
870            true,
871        );
872    } else {
873        let venue_order_id = VenueOrderId::new(order.order_id);
874        ensure_accepted_emitted(
875            client_order_id,
876            account_id,
877            venue_order_id,
878            identity,
879            ts_init,
880            state,
881            emitter,
882        );
883
884        let canceled = OrderCanceled::new(
885            emitter.trader_id(),
886            identity.strategy_id,
887            identity.instrument_id,
888            client_order_id,
889            UUID4::new(),
890            ts_init,
891            ts_init,
892            false,
893            Some(venue_order_id),
894            Some(account_id),
895            None,
896        );
897        cleanup_terminal_when_ready(client_order_id, filled_qty, state);
898        emitter.send_order_event(OrderEventAny::Canceled(canceled));
899    }
900}
901
902pub(crate) fn has_pending_fast_execution(
903    venue_order_id: VenueOrderId,
904    state: &WsDispatchState,
905) -> bool {
906    state.pending_fast_executions.contains_key(&venue_order_id)
907}
908
909pub(crate) fn drain_pending_fast_executions(
910    venue_order_id: VenueOrderId,
911    instrument: &InstrumentAny,
912    account_id: AccountId,
913    ts_init: UnixNanos,
914    state: &WsDispatchState,
915    emitter: &ExecutionEventEmitter,
916) {
917    let Some((_, executions)) = state.pending_fast_executions.remove(&venue_order_id) else {
918        return;
919    };
920
921    for exec in executions {
922        dispatch_execution_fill_fast(
923            &exec, instrument, account_id, ts_init, false, state, emitter,
924        );
925    }
926}
927
928pub(crate) fn flush_pending_fast_executions(
929    instruments: &AHashMap<Ustr, InstrumentAny>,
930    account_id: AccountId,
931    ts_init: UnixNanos,
932    state: &WsDispatchState,
933    emitter: &ExecutionEventEmitter,
934) {
935    let venue_order_ids = state
936        .pending_fast_executions
937        .iter()
938        .map(|entry| *entry.key())
939        .collect::<Vec<_>>();
940
941    for venue_order_id in venue_order_ids {
942        let Some(execution) = state
943            .pending_fast_executions
944            .get(&venue_order_id)
945            .and_then(|executions| executions.first().cloned())
946        else {
947            continue;
948        };
949
950        let symbol = make_bybit_symbol(execution.symbol, execution.category);
951
952        let Some(instrument) = instruments.get(&symbol) else {
953            log::warn!("Cannot flush fast execution without instrument: {symbol}");
954            continue;
955        };
956
957        drain_pending_fast_executions(
958            venue_order_id,
959            instrument,
960            account_id,
961            ts_init,
962            state,
963            emitter,
964        );
965    }
966}
967
968/// Dispatches a single execution (fill) message.
969///
970/// Tracked orders are parsed directly to [`OrderFilled`]. Untracked orders
971/// fall back to [`FillReport`] for reconciliation.
972fn dispatch_execution_fill(
973    exec: &BybitWsAccountExecution,
974    instrument: &InstrumentAny,
975    emitter: &ExecutionEventEmitter,
976    state: &WsDispatchState,
977    account_id: AccountId,
978    ts_init: UnixNanos,
979) {
980    if exec.exec_type == BybitExecType::Funding {
981        log::debug!(
982            "Skipping funding execution: symbol={}, order_id={}, exec_id={}",
983            exec.symbol,
984            exec.order_id,
985            exec.exec_id,
986        );
987        return;
988    }
989
990    if exec.exec_type.is_exchange_generated() {
991        log::warn!(
992            "Exchange-generated execution: exec_type={:?}, symbol={}, order_id={}, order_link_id={}, side={:?}, qty={}, price={}",
993            exec.exec_type,
994            exec.symbol,
995            exec.order_id,
996            exec.order_link_id,
997            exec.side,
998            exec.exec_qty,
999            exec.exec_price,
1000        );
1001    }
1002
1003    let client_order_id = if exec.order_link_id.is_empty() {
1004        None
1005    } else {
1006        Some(ClientOrderId::new(exec.order_link_id))
1007    };
1008
1009    let identity = client_order_id
1010        .as_ref()
1011        .and_then(|cid| state.order_identities.get(cid).map(|r| r.clone()));
1012
1013    if let (Some(client_order_id), Some(identity)) = (client_order_id, identity) {
1014        match parse_order_filled(exec, instrument, &identity, emitter, account_id, ts_init) {
1015            Ok(filled) => {
1016                let venue_order_id = filled.venue_order_id;
1017                ensure_accepted_emitted(
1018                    client_order_id,
1019                    account_id,
1020                    venue_order_id,
1021                    &identity,
1022                    ts_init,
1023                    state,
1024                    emitter,
1025                );
1026
1027                let is_spot_buy =
1028                    exec.category == BybitProductType::Spot && exec.side == BybitOrderSide::Buy;
1029
1030                if is_spot_buy {
1031                    record_spot_repay_fill(client_order_id, &filled, instrument, state);
1032                }
1033
1034                state.insert_filled(client_order_id);
1035                state.triggered_orders.remove(&client_order_id);
1036                emitter.send_order_event(OrderEventAny::Filled(filled));
1037
1038                if exec.leaves_qty == "0" {
1039                    if is_spot_buy {
1040                        enqueue_spot_repay(client_order_id, instrument, state);
1041                    }
1042
1043                    cleanup_terminal(client_order_id, state);
1044                }
1045            }
1046            Err(e) => log::error!("Failed to parse OrderFilled for {client_order_id}: {e}"),
1047        }
1048    } else {
1049        // Untracked: fall back to FillReport for reconciliation
1050        match super::parse::parse_ws_fill_report(exec, account_id, instrument, ts_init) {
1051            Ok(report) => emitter.send_fill_report(report),
1052            Err(e) => log::error!("Failed to parse fill report: {e}"),
1053        }
1054    }
1055}
1056
1057/// Dispatches a single fast-execution (fill) message.
1058///
1059/// The fast channel lacks fee and exec-type fields, so all fills route to
1060/// [`FillReport`]. Commission is derived from cached account fee rates when available,
1061/// with a zero fallback. Liquidity side is derived from the payload's `isMaker` flag.
1062/// Subscribe to the standard `execution` channel for venue-authoritative fees.
1063fn dispatch_execution_fill_fast(
1064    exec: &BybitWsAccountExecutionFast,
1065    instrument: &InstrumentAny,
1066    account_id: AccountId,
1067    ts_init: UnixNanos,
1068    defer_untracked: bool,
1069    state: &WsDispatchState,
1070    emitter: &ExecutionEventEmitter,
1071) {
1072    let Ok(trade_id) = TradeId::new_checked(exec.exec_id.as_str()) else {
1073        log::error!(
1074            "Invalid execId in Bybit WebSocket fast-execution payload: {}",
1075            exec.exec_id
1076        );
1077        return;
1078    };
1079
1080    if defer_untracked && !state.insert_fast_execution(trade_id) {
1081        log::debug!("Skipping duplicate fast execution: {trade_id}");
1082        return;
1083    }
1084
1085    let venue_order_id = VenueOrderId::new(exec.order_id);
1086    let client_order_id = if exec.order_link_id.is_empty() {
1087        let venue_mapping = state.venue_order_ids.entry(venue_order_id);
1088
1089        let client_order_id = match &venue_mapping {
1090            Entry::Occupied(entry) => Some(*entry.get()),
1091            Entry::Vacant(_) => None,
1092        };
1093
1094        // Hold the mapping guard through any pending enqueue so REST correlation cannot interleave
1095        if client_order_id.is_none()
1096            && defer_untracked
1097            && !state.untracked_order_ids.contains(&venue_order_id)
1098        {
1099            state
1100                .pending_fast_executions
1101                .entry(venue_order_id)
1102                .or_default()
1103                .push(exec.clone());
1104            return;
1105        }
1106
1107        client_order_id
1108    } else {
1109        Some(ClientOrderId::new(exec.order_link_id))
1110    };
1111
1112    let identity = client_order_id
1113        .as_ref()
1114        .and_then(|cid| state.order_identities.get(cid).map(|r| r.clone()));
1115
1116    let venue_position_id =
1117        if let (Some(client_order_id), Some(identity)) = (client_order_id, identity.as_ref()) {
1118            ensure_accepted_emitted(
1119                client_order_id,
1120                account_id,
1121                venue_order_id,
1122                identity,
1123                ts_init,
1124                state,
1125                emitter,
1126            );
1127            identity.venue_position_id
1128        } else {
1129            None
1130        };
1131
1132    let fee_rates = state.fee_rates.get(&instrument.id()).map(|rates| *rates);
1133
1134    match parse_ws_fill_report_fast(
1135        exec,
1136        account_id,
1137        instrument,
1138        fee_rates,
1139        client_order_id,
1140        venue_position_id,
1141        ts_init,
1142    ) {
1143        Ok(report) => {
1144            let last_qty = report.last_qty;
1145            emitter.send_fill_report(report);
1146
1147            if let Some(client_order_id) = client_order_id
1148                && identity.is_some()
1149            {
1150                state.insert_filled(client_order_id);
1151                record_fast_fill(client_order_id, last_qty, state);
1152            }
1153        }
1154        Err(e) => {
1155            state.remove_fast_execution(trade_id);
1156            log::error!("Failed to parse fast fill report: {e}");
1157        }
1158    }
1159}
1160
1161/// Parses a Bybit execution message directly into an [`OrderFilled`] event.
1162fn parse_order_filled(
1163    exec: &BybitWsAccountExecution,
1164    instrument: &InstrumentAny,
1165    identity: &OrderIdentity,
1166    emitter: &ExecutionEventEmitter,
1167    account_id: AccountId,
1168    ts_init: UnixNanos,
1169) -> anyhow::Result<OrderFilled> {
1170    let client_order_id = ClientOrderId::new(exec.order_link_id);
1171    let venue_order_id = VenueOrderId::new(exec.order_id);
1172    let trade_id =
1173        TradeId::new_checked(exec.exec_id.as_str()).context("invalid execId in Bybit execution")?;
1174
1175    let last_qty = parse_quantity_with_precision(
1176        &exec.exec_qty,
1177        instrument.size_precision(),
1178        "execution.execQty",
1179    )?;
1180    let last_px = parse_price_with_precision(
1181        &exec.exec_price,
1182        instrument.price_precision(),
1183        "execution.execPrice",
1184    )?;
1185
1186    let liquidity_side = if exec.is_maker {
1187        LiquiditySide::Maker
1188    } else {
1189        LiquiditySide::Taker
1190    };
1191
1192    let fee_decimal: Decimal = exec
1193        .exec_fee
1194        .parse()
1195        .with_context(|| format!("failed to parse execFee='{}'", exec.exec_fee))?;
1196    let price_currency = instrument.quote_currency();
1197    let commission_currency = get_currency(&exec.fee_currency);
1198
1199    let commission = Money::from_decimal(fee_decimal, commission_currency).with_context(|| {
1200        format!(
1201            "failed to create commission from execFee='{}'",
1202            exec.exec_fee
1203        )
1204    })?;
1205
1206    let ts_event = parse_millis_timestamp(&exec.exec_time, "execution.execTime")?;
1207
1208    Ok(OrderFilled::new(
1209        emitter.trader_id(),
1210        identity.strategy_id,
1211        identity.instrument_id,
1212        client_order_id,
1213        venue_order_id,
1214        account_id,
1215        trade_id,
1216        identity.order_side,
1217        identity.order_type,
1218        last_qty,
1219        last_px,
1220        price_currency,
1221        liquidity_side,
1222        UUID4::new(),
1223        ts_event,
1224        ts_init,
1225        false,
1226        identity.venue_position_id,
1227        Some(commission),
1228        None,
1229    ))
1230}
1231
1232/// Handles a Bybit WS order command response.
1233fn dispatch_order_response(
1234    resp: &super::messages::BybitWsOrderResponse,
1235    emitter: &ExecutionEventEmitter,
1236    state: &WsDispatchState,
1237    ts_init: UnixNanos,
1238) {
1239    if resp.ret_code == 0 {
1240        // Check for per-order failures in batch retExtInfo even on success
1241        let pending = resp
1242            .req_id
1243            .as_ref()
1244            .and_then(|rid| state.pending_requests.remove(rid))
1245            .map(|(_, v)| v);
1246
1247        if let Some((cids, voids, pending_op, command_ids)) = pending {
1248            let batch_errors = resp.extract_batch_errors();
1249            let data_array = resp.data.as_array();
1250
1251            for (idx, error) in batch_errors.iter().enumerate() {
1252                if error.code == 0 {
1253                    continue;
1254                }
1255
1256                if is_bybit_ambiguous_order_error_code(error.code) {
1257                    log::warn!(
1258                        "Ambiguous batch order item failure at index {idx}: code={}, msg={}; awaiting reconciliation",
1259                        error.code,
1260                        error.msg,
1261                    );
1262                    continue;
1263                }
1264
1265                // Extract orderLinkId from the corresponding data entry
1266                let cid = data_array
1267                    .and_then(|arr| arr.get(idx))
1268                    .and_then(extract_order_link_id_from_data)
1269                    .or_else(|| cids.get(idx).copied());
1270
1271                let Some(cid) = cid else {
1272                    log::warn!(
1273                        "Batch error at index {idx} without correlation: code={}, msg={}",
1274                        error.code,
1275                        error.msg,
1276                    );
1277                    continue;
1278                };
1279
1280                let Some(identity) = state.order_identities.get(&cid).map(|r| r.clone()) else {
1281                    log::warn!(
1282                        "Batch error for untracked order: client_order_id={cid}, msg={}",
1283                        error.msg,
1284                    );
1285                    continue;
1286                };
1287
1288                let stored_void = voids.get(idx).and_then(|v| *v);
1289
1290                emit_rejection_for_op(
1291                    &pending_op,
1292                    cid,
1293                    &identity,
1294                    stored_void,
1295                    &error.msg,
1296                    emitter,
1297                    state,
1298                    ts_init,
1299                    command_ids.get(idx).copied().flatten(),
1300                );
1301            }
1302        }
1303
1304        return;
1305    }
1306
1307    // Remove the pending request entry (if any) to get client_order_ids and op
1308    let pending = resp
1309        .req_id
1310        .as_ref()
1311        .and_then(|rid| state.pending_requests.remove(rid))
1312        .map(|(_, v)| v);
1313
1314    let is_batch_response = is_batch_order_op(resp.op.as_str())
1315        || pending
1316            .as_ref()
1317            .is_some_and(|(cids, _, _, _)| cids.len() > 1);
1318
1319    if is_batch_response {
1320        if is_bybit_ambiguous_order_error_code(resp.ret_code) {
1321            let order_count = pending.as_ref().map_or(0, |(cids, _, _, _)| cids.len());
1322            log::warn!(
1323                "Ambiguous batch order response failure for {order_count} orders: op={}, ret_code={}, ret_msg={}; awaiting reconciliation",
1324                resp.op,
1325                resp.ret_code,
1326                resp.ret_msg,
1327            );
1328            return;
1329        }
1330
1331        let Some((client_order_ids, venue_order_ids, pending_op, command_ids)) = pending else {
1332            log::warn!(
1333                "Batch order response error without correlation: op={}, ret_code={}, ret_msg={}, req_id={:?}",
1334                resp.op,
1335                resp.ret_code,
1336                resp.ret_msg,
1337                resp.req_id,
1338            );
1339            return;
1340        };
1341
1342        for (index, client_order_id) in client_order_ids.into_iter().enumerate() {
1343            let Some(identity) = state
1344                .order_identities
1345                .get(&client_order_id)
1346                .map(|identity| identity.clone())
1347            else {
1348                log::warn!(
1349                    "Batch order response error for untracked order: op={}, client_order_id={client_order_id}, ret_msg={}",
1350                    resp.op,
1351                    resp.ret_msg,
1352                );
1353                continue;
1354            };
1355
1356            emit_rejection_for_op(
1357                &pending_op,
1358                client_order_id,
1359                &identity,
1360                venue_order_ids.get(index).copied().flatten(),
1361                &resp.ret_msg,
1362                emitter,
1363                state,
1364                ts_init,
1365                command_ids.get(index).copied().flatten(),
1366            );
1367        }
1368
1369        return;
1370    }
1371
1372    if is_bybit_ambiguous_order_error_code(resp.ret_code) {
1373        log::warn!(
1374            "Ambiguous order response failure: op={}, ret_code={}, ret_msg={}; awaiting reconciliation",
1375            resp.op,
1376            resp.ret_code,
1377            resp.ret_msg,
1378        );
1379        return;
1380    }
1381
1382    let effective_op = pending
1383        .as_ref()
1384        .map(|(_, _, op, _)| *op)
1385        .or_else(|| pending_op_from_str(resp.op.as_str()))
1386        .unwrap_or_else(|| {
1387            log::warn!("Unknown order operation '{}', defaulting to Place", resp.op);
1388            PendingOperation::Place
1389        });
1390
1391    // Single-order rejection path
1392    let client_order_id = extract_order_link_id_from_data(&resp.data).or_else(|| {
1393        pending
1394            .as_ref()
1395            .and_then(|(cids, _, _, _)| cids.first().copied())
1396    });
1397
1398    let stored_venue_order_id = pending
1399        .as_ref()
1400        .and_then(|(_, voids, _, _)| voids.first().and_then(|v| *v));
1401
1402    let Some(client_order_id) = client_order_id else {
1403        log::warn!(
1404            "Order response error without correlation: op={}, ret_code={}, ret_msg={}, req_id={:?}",
1405            resp.op,
1406            resp.ret_code,
1407            resp.ret_msg,
1408            resp.req_id,
1409        );
1410        return;
1411    };
1412
1413    let Some(identity) = state
1414        .order_identities
1415        .get(&client_order_id)
1416        .map(|r| r.clone())
1417    else {
1418        log::warn!(
1419            "Order response error for untracked order: op={}, client_order_id={client_order_id}, ret_msg={}",
1420            resp.op,
1421            resp.ret_msg,
1422        );
1423        return;
1424    };
1425
1426    let venue_order_id = extract_venue_order_id_from_data(&resp.data).or(stored_venue_order_id);
1427
1428    emit_rejection_for_op(
1429        &effective_op,
1430        client_order_id,
1431        &identity,
1432        venue_order_id,
1433        &resp.ret_msg,
1434        emitter,
1435        state,
1436        ts_init,
1437        pending.as_ref().and_then(|(cids, _, _, command_ids)| {
1438            cids.iter()
1439                .position(|id| *id == client_order_id)
1440                .and_then(|index| command_ids.get(index).copied().flatten())
1441        }),
1442    );
1443}
1444
1445fn dispatch_order_not_sent(
1446    request_id: &str,
1447    reason: &str,
1448    emitter: &ExecutionEventEmitter,
1449    state: &WsDispatchState,
1450    ts_init: UnixNanos,
1451) {
1452    let Some((_, (client_order_ids, venue_order_ids, operation, command_ids))) =
1453        state.pending_requests.remove(request_id)
1454    else {
1455        log::warn!("Unsent order command has no request correlation: {request_id}");
1456        return;
1457    };
1458
1459    for (index, client_order_id) in client_order_ids.into_iter().enumerate() {
1460        let Some(identity) = state
1461            .order_identities
1462            .get(&client_order_id)
1463            .map(|entry| entry.clone())
1464        else {
1465            continue;
1466        };
1467
1468        let venue_order_id = venue_order_ids.get(index).copied().flatten();
1469        let causation_id = command_ids.get(index).copied().flatten();
1470
1471        match operation {
1472            PendingOperation::Place => emit_rejection_for_op(
1473                &operation,
1474                client_order_id,
1475                &identity,
1476                venue_order_id,
1477                reason,
1478                emitter,
1479                state,
1480                ts_init,
1481                causation_id,
1482            ),
1483            PendingOperation::Amend => emitter.emit_order_modify_denied_event(
1484                identity.strategy_id,
1485                identity.instrument_id,
1486                client_order_id,
1487                venue_order_id,
1488                reason,
1489                ts_init,
1490                causation_id,
1491            ),
1492            PendingOperation::Cancel => emitter.emit_order_cancel_denied_event(
1493                identity.strategy_id,
1494                identity.instrument_id,
1495                client_order_id,
1496                venue_order_id,
1497                reason,
1498                ts_init,
1499                causation_id,
1500            ),
1501        }
1502    }
1503}
1504
1505/// Emits the appropriate rejection event based on the pending operation type.
1506#[expect(clippy::too_many_arguments)]
1507fn emit_rejection_for_op(
1508    pending_op: &PendingOperation,
1509    client_order_id: ClientOrderId,
1510    identity: &OrderIdentity,
1511    venue_order_id: Option<VenueOrderId>,
1512    reason: &str,
1513    emitter: &ExecutionEventEmitter,
1514    state: &WsDispatchState,
1515    ts_init: UnixNanos,
1516    causation_id: Option<UUID4>,
1517) {
1518    match pending_op {
1519        PendingOperation::Place => {
1520            state.order_identities.remove(&client_order_id);
1521            state.order_snapshots.remove(&client_order_id);
1522            emitter.emit_order_rejected_event(
1523                identity.strategy_id,
1524                identity.instrument_id,
1525                client_order_id,
1526                reason,
1527                ts_init,
1528                false,
1529            );
1530        }
1531        PendingOperation::Cancel => {
1532            emitter.emit_order_cancel_rejected_event(
1533                identity.strategy_id,
1534                identity.instrument_id,
1535                client_order_id,
1536                venue_order_id,
1537                reason,
1538                ts_init,
1539                causation_id,
1540            );
1541        }
1542        PendingOperation::Amend => {
1543            emitter.emit_order_modify_rejected_event(
1544                identity.strategy_id,
1545                identity.instrument_id,
1546                client_order_id,
1547                venue_order_id,
1548                reason,
1549                ts_init,
1550                causation_id,
1551            );
1552        }
1553    }
1554}
1555
1556/// Maps an operation string to a `PendingOperation`.
1557fn pending_op_from_str(op: &str) -> Option<PendingOperation> {
1558    match op {
1559        BYBIT_OP_ORDER_CREATE => Some(PendingOperation::Place),
1560        BYBIT_OP_ORDER_CANCEL => Some(PendingOperation::Cancel),
1561        BYBIT_OP_ORDER_AMEND => Some(PendingOperation::Amend),
1562        _ => None,
1563    }
1564}
1565
1566fn is_batch_order_op(op: &str) -> bool {
1567    matches!(
1568        op,
1569        BYBIT_OP_ORDER_CREATE_BATCH | BYBIT_OP_ORDER_AMEND_BATCH | BYBIT_OP_ORDER_CANCEL_BATCH
1570    )
1571}
1572
1573/// Parses an order snapshot from a WS order message for modification detection.
1574fn parse_order_snapshot(
1575    order: &BybitWsAccountOrder,
1576    instrument: &InstrumentAny,
1577) -> Option<OrderStateSnapshot> {
1578    let quantity =
1579        parse_quantity_with_precision(&order.qty, instrument.size_precision(), "order.qty").ok()?;
1580    let price = if !order.price.is_empty() && order.price != "0" {
1581        parse_price_with_precision(&order.price, instrument.price_precision(), "order.price").ok()
1582    } else {
1583        None
1584    };
1585
1586    let trigger_price = if !order.trigger_price.is_empty() && order.trigger_price != "0" {
1587        parse_price_with_precision(
1588            &order.trigger_price,
1589            instrument.price_precision(),
1590            "order.triggerPrice",
1591        )
1592        .ok()
1593    } else {
1594        None
1595    };
1596
1597    Some(OrderStateSnapshot {
1598        quantity,
1599        price,
1600        trigger_price,
1601    })
1602}
1603
1604/// Returns whether the incoming snapshot differs from the stored snapshot.
1605fn is_snapshot_updated(
1606    snapshot: &OrderStateSnapshot,
1607    client_order_id: &ClientOrderId,
1608    state: &WsDispatchState,
1609) -> bool {
1610    let Some(previous) = state.order_snapshots.get(client_order_id) else {
1611        return false;
1612    };
1613
1614    if let (Some(prev_price), Some(new_price)) = (previous.price, snapshot.price)
1615        && prev_price != new_price
1616    {
1617        return true;
1618    }
1619
1620    if let (Some(prev_trigger), Some(new_trigger)) =
1621        (previous.trigger_price, snapshot.trigger_price)
1622        && prev_trigger != new_trigger
1623    {
1624        return true;
1625    }
1626
1627    previous.quantity != snapshot.quantity
1628}
1629
1630#[expect(
1631    clippy::too_many_arguments,
1632    reason = "updates share the dispatcher's order context"
1633)]
1634fn emit_order_updated_if_changed(
1635    order: &BybitWsAccountOrder,
1636    instrument: &InstrumentAny,
1637    client_order_id: ClientOrderId,
1638    identity: &OrderIdentity,
1639    account_id: AccountId,
1640    ts_init: UnixNanos,
1641    force: bool,
1642    state: &WsDispatchState,
1643    emitter: &ExecutionEventEmitter,
1644) -> bool {
1645    let Some(snapshot) = parse_order_snapshot(order, instrument) else {
1646        return false;
1647    };
1648
1649    if !force && !is_snapshot_updated(&snapshot, &client_order_id, state) {
1650        return false;
1651    }
1652
1653    let venue_order_id = VenueOrderId::new(order.order_id);
1654
1655    let updated = OrderUpdated::new(
1656        emitter.trader_id(),
1657        identity.strategy_id,
1658        identity.instrument_id,
1659        client_order_id,
1660        snapshot.quantity,
1661        UUID4::new(),
1662        ts_init,
1663        ts_init,
1664        false,
1665        Some(venue_order_id),
1666        Some(account_id),
1667        snapshot.price,
1668        snapshot.trigger_price,
1669        None,
1670        false,
1671    );
1672    state.order_snapshots.insert(client_order_id, snapshot);
1673    emitter.send_order_event(OrderEventAny::Updated(updated));
1674    true
1675}
1676
1677pub(crate) fn record_venue_order_id(
1678    client_order_id: ClientOrderId,
1679    venue_order_id: VenueOrderId,
1680    state: &WsDispatchState,
1681) {
1682    state
1683        .order_venue_ids
1684        .insert(client_order_id, venue_order_id);
1685    state
1686        .venue_order_ids
1687        .insert(venue_order_id, client_order_id);
1688}
1689
1690/// Synthesizes and emits `OrderAccepted` if one has not yet been emitted for
1691/// this order. Handles fast-filling orders that skip the `New` state on Bybit.
1692fn ensure_accepted_emitted(
1693    client_order_id: ClientOrderId,
1694    account_id: AccountId,
1695    venue_order_id: VenueOrderId,
1696    identity: &OrderIdentity,
1697    ts_init: UnixNanos,
1698    state: &WsDispatchState,
1699    emitter: &ExecutionEventEmitter,
1700) {
1701    record_venue_order_id(client_order_id, venue_order_id, state);
1702    if state.emitted_accepted.contains(&client_order_id) {
1703        return;
1704    }
1705
1706    state.insert_accepted(client_order_id);
1707
1708    let accepted = OrderAccepted::new(
1709        emitter.trader_id(),
1710        identity.strategy_id,
1711        identity.instrument_id,
1712        client_order_id,
1713        venue_order_id,
1714        account_id,
1715        UUID4::new(),
1716        ts_init,
1717        ts_init,
1718        false,
1719    );
1720    emitter.send_order_event(OrderEventAny::Accepted(accepted));
1721}
1722
1723pub(crate) fn cleanup_terminal_when_ready(
1724    client_order_id: ClientOrderId,
1725    terminal_qty: Quantity,
1726    state: &WsDispatchState,
1727) {
1728    state
1729        .terminal_order_quantities
1730        .insert(client_order_id, terminal_qty);
1731    if state.fast_execution && !fast_fill_is_terminal(client_order_id, state) {
1732        return;
1733    }
1734
1735    cleanup_terminal(client_order_id, state);
1736}
1737
1738fn record_fast_fill(client_order_id: ClientOrderId, last_qty: Quantity, state: &WsDispatchState) {
1739    let mut overflow = false;
1740    state
1741        .fast_filled_quantities
1742        .entry(client_order_id)
1743        .and_modify(|total| {
1744            if let Some(new_total) = total.checked_add(last_qty) {
1745                *total = new_total;
1746            } else {
1747                overflow = true;
1748            }
1749        })
1750        .or_insert(last_qty);
1751
1752    if overflow {
1753        log::warn!("Fast fill quantity overflow for {client_order_id}, retaining order state");
1754        return;
1755    }
1756
1757    if fast_fill_is_terminal(client_order_id, state) {
1758        cleanup_terminal(client_order_id, state);
1759    }
1760}
1761
1762fn fast_fill_is_terminal(client_order_id: ClientOrderId, state: &WsDispatchState) -> bool {
1763    let Some(terminal_qty) = state.terminal_order_quantities.get(&client_order_id) else {
1764        return false;
1765    };
1766
1767    if terminal_qty.is_zero() {
1768        return true;
1769    }
1770
1771    state
1772        .fast_filled_quantities
1773        .get(&client_order_id)
1774        .is_some_and(|filled_qty| *filled_qty >= *terminal_qty)
1775}
1776
1777/// Removes a terminal order from all tracking sets.
1778pub(crate) fn cleanup_terminal(client_order_id: ClientOrderId, state: &WsDispatchState) {
1779    if let Some((_, venue_order_id)) = state.order_venue_ids.remove(&client_order_id) {
1780        state.venue_order_ids.remove(&venue_order_id);
1781    }
1782
1783    state.order_identities.remove(&client_order_id);
1784    state.order_snapshots.remove(&client_order_id);
1785    state.emitted_accepted.remove(&client_order_id);
1786    state.triggered_orders.remove(&client_order_id);
1787    state.filled_orders.remove(&client_order_id);
1788    state.fast_filled_quantities.remove(&client_order_id);
1789    state.terminal_order_quantities.remove(&client_order_id);
1790    state.spot_repay_fills.remove(&client_order_id);
1791}
1792
1793/// Tries to extract `orderLinkId` from the response data Value.
1794fn extract_order_link_id_from_data(data: &serde_json::Value) -> Option<ClientOrderId> {
1795    data.get("orderLinkId")
1796        .and_then(|v| v.as_str())
1797        .filter(|s| !s.is_empty())
1798        .map(ClientOrderId::new)
1799}
1800
1801/// Tries to extract `orderId` from the response data Value.
1802fn extract_venue_order_id_from_data(data: &serde_json::Value) -> Option<VenueOrderId> {
1803    data.get("orderId")
1804        .and_then(|v| v.as_str())
1805        .filter(|s| !s.is_empty())
1806        .map(VenueOrderId::new)
1807}
1808
1809fn record_spot_repay_fill(
1810    client_order_id: ClientOrderId,
1811    filled: &OrderFilled,
1812    instrument: &InstrumentAny,
1813    state: &WsDispatchState,
1814) {
1815    let Some(base_currency) = instrument.base_currency() else {
1816        return;
1817    };
1818
1819    let base_fee = filled
1820        .commission
1821        .filter(|fee| fee.currency.code == base_currency.code)
1822        .map_or(Decimal::ZERO, |fee| fee.as_decimal().max(Decimal::ZERO));
1823
1824    let fill = SpotRepayFill {
1825        quantity: filled.last_qty,
1826        base_fee,
1827    };
1828
1829    state
1830        .spot_repay_fills
1831        .entry(client_order_id)
1832        .and_modify(|total| {
1833            total.quantity = total.quantity + fill.quantity;
1834            total.base_fee += fill.base_fee;
1835        })
1836        .or_insert(fill);
1837}
1838
1839/// Enqueues an auto-repay for a fully-filled SPOT BUY.
1840fn enqueue_spot_repay(
1841    client_order_id: ClientOrderId,
1842    instrument: &InstrumentAny,
1843    state: &WsDispatchState,
1844) {
1845    let Some(base_currency) = instrument.base_currency() else {
1846        return;
1847    };
1848
1849    let Some((_, fill)) = state.spot_repay_fills.remove(&client_order_id) else {
1850        return;
1851    };
1852
1853    state.enqueue_repay(RepayRequest {
1854        coin: base_currency.code,
1855        quantity: fill.quantity,
1856        base_fee: fill.base_fee,
1857        repayment_precision: fill.quantity.precision.max(base_currency.precision),
1858    });
1859}
1860
1861#[cfg(test)]
1862mod tests {
1863    use ahash::AHashMap;
1864    use nautilus_common::messages::{ExecutionEvent, execution::ExecutionReport};
1865    use nautilus_core::{
1866        UnixNanos,
1867        time::{AtomicTime, get_atomic_clock_realtime},
1868    };
1869    use nautilus_live::{emitter::ExecutionEventEmitter, testing::ExecutionHarness};
1870    use nautilus_model::{
1871        accounts::MarginAccount,
1872        enums::{AccountType, OrderSide, OrderStatus, OrderType},
1873        events::OrderEventAny,
1874        identifiers::{
1875            AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TraderId, VenueOrderId,
1876        },
1877        instruments::{Instrument, InstrumentAny},
1878        orders::{Order, builder::OrderTestBuilder, stubs::TestOrderEventStubs},
1879        reports::FillReport,
1880        types::Currency,
1881    };
1882    use rstest::rstest;
1883    use rust_decimal_macros::dec;
1884    use ustr::Ustr;
1885
1886    use super::*;
1887    use crate::{
1888        common::{
1889            enums::{BybitExecType, BybitOrderSide, BybitProductType},
1890            parse::{
1891                parse_inverse_instrument, parse_linear_instrument, parse_option_instrument,
1892                parse_spot_instrument,
1893            },
1894            testing::load_test_json,
1895        },
1896        http::models::{
1897            BybitInstrumentInverseResponse, BybitInstrumentLinearResponse,
1898            BybitInstrumentOptionResponse, BybitInstrumentSpotResponse,
1899        },
1900        websocket::messages::{
1901            BybitWsAccountExecutionFastMsg, BybitWsMessage, BybitWsOrderResponse,
1902        },
1903    };
1904
1905    fn linear_instrument() -> InstrumentAny {
1906        let json = load_test_json("http_get_instruments_linear.json");
1907        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
1908        let instrument = &response.result.list[0];
1909        let ts = UnixNanos::new(1_700_000_000_000_000_000);
1910        parse_linear_instrument(instrument, ts, ts).unwrap()
1911    }
1912
1913    fn spot_instrument() -> InstrumentAny {
1914        let json = load_test_json("http_get_instruments_spot.json");
1915        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
1916        let instrument = &response.result.list[0];
1917        let ts = UnixNanos::new(1_700_000_000_000_000_000);
1918        parse_spot_instrument(instrument, ts, ts).unwrap()
1919    }
1920
1921    fn inverse_instrument() -> InstrumentAny {
1922        let json = load_test_json("http_get_instruments_inverse.json");
1923        let response: BybitInstrumentInverseResponse = serde_json::from_str(&json).unwrap();
1924        let instrument = &response.result.list[0];
1925        let ts = UnixNanos::new(1_700_000_000_000_000_000);
1926        parse_inverse_instrument(instrument, ts, ts).unwrap()
1927    }
1928
1929    fn option_instrument_with_distinct_settlement() -> InstrumentAny {
1930        let json = load_test_json("http_get_instruments_option_symbol_id.json");
1931        let response: BybitInstrumentOptionResponse = serde_json::from_str(&json).unwrap();
1932        let instrument = &response.result.list[0];
1933        let ts = UnixNanos::new(1_700_000_000_000_000_000);
1934        parse_option_instrument(instrument, ts, ts).unwrap()
1935    }
1936
1937    fn build_instruments(instruments: &[InstrumentAny]) -> AHashMap<Ustr, InstrumentAny> {
1938        let mut map = AHashMap::new();
1939        for inst in instruments {
1940            map.insert(inst.id().symbol.inner(), inst.clone());
1941        }
1942
1943        map
1944    }
1945
1946    fn test_account_id() -> AccountId {
1947        AccountId::from("BYBIT-001")
1948    }
1949
1950    fn create_emitter() -> (
1951        ExecutionEventEmitter,
1952        tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
1953    ) {
1954        let clock = get_atomic_clock_realtime();
1955        let trader_id = TraderId::from("TESTER-001");
1956        let account_id = test_account_id();
1957        let mut emitter =
1958            ExecutionEventEmitter::new(clock, trader_id, account_id, AccountType::Margin, None);
1959        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
1960        emitter.set_sender(tx);
1961        (emitter, rx)
1962    }
1963
1964    fn default_identity() -> OrderIdentity {
1965        OrderIdentity {
1966            instrument_id: InstrumentId::from("BTCUSDT-LINEAR.BYBIT"),
1967            strategy_id: StrategyId::from("S-001"),
1968            order_side: OrderSide::Buy,
1969            order_type: OrderType::Limit,
1970            venue_position_id: None,
1971        }
1972    }
1973
1974    #[rstest]
1975    #[case::base_fee("BTC", "0.0000015", "0.0000025", "0.000004")]
1976    #[case::base_rebate("BTC", "-0.0000015", "-0.0000025", "0")]
1977    #[case::quote_fee("USDT", "0.075", "0.125", "0")]
1978    fn test_spot_repay_uses_accumulated_execution_quantity(
1979        #[case] fee_currency: &str,
1980        #[case] first_fee: &str,
1981        #[case] second_fee: &str,
1982        #[case] expected_base_fee: &str,
1983    ) {
1984        let instrument = spot_instrument();
1985        let instruments = build_instruments(std::slice::from_ref(&instrument));
1986        let (emitter, _rx) = create_emitter();
1987        let clock = get_atomic_clock_realtime();
1988        let state = WsDispatchState::default();
1989        let (repay_tx, mut repay_rx) = tokio::sync::mpsc::unbounded_channel();
1990        state.set_repay_sender(repay_tx);
1991
1992        let json = load_test_json("ws_account_execution.json");
1993        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
1994        value["data"][0]["category"] = serde_json::Value::String("spot".to_string());
1995        value["data"][0]["symbol"] = serde_json::Value::String("BTCUSDT".to_string());
1996        value["data"][0]["side"] = serde_json::Value::String("Buy".to_string());
1997        value["data"][0]["orderType"] = serde_json::Value::String("Market".to_string());
1998        value["data"][0]["orderQty"] = serde_json::Value::String("100".to_string());
1999        value["data"][0]["execQty"] = serde_json::Value::String("0.0015".to_string());
2000        value["data"][0]["leavesQty"] = serde_json::Value::String("0.0025".to_string());
2001        value["data"][0]["execFee"] = serde_json::Value::String(first_fee.to_string());
2002        value["data"][0]["feeCurrency"] = serde_json::Value::String(fee_currency.to_string());
2003
2004        let first: crate::websocket::messages::BybitWsAccountExecutionMsg =
2005            serde_json::from_value(value.clone()).unwrap();
2006        let client_order_id = ClientOrderId::new(first.data[0].order_link_id);
2007        state.order_identities.insert(
2008            client_order_id,
2009            OrderIdentity {
2010                instrument_id: InstrumentId::from("BTCUSDT-SPOT.BYBIT"),
2011                order_type: OrderType::Market,
2012                ..default_identity()
2013            },
2014        );
2015
2016        dispatch_ws_message(
2017            &BybitWsMessage::AccountExecution(first),
2018            test_account_id(),
2019            &instruments,
2020            clock,
2021            &state,
2022            &emitter,
2023        );
2024        assert!(repay_rx.try_recv().is_err());
2025
2026        value["data"][0]["execId"] = serde_json::Value::String("second-execution".to_string());
2027        value["data"][0]["execQty"] = serde_json::Value::String("0.0025".to_string());
2028        value["data"][0]["leavesQty"] = serde_json::Value::String("0".to_string());
2029        value["data"][0]["execFee"] = serde_json::Value::String(second_fee.to_string());
2030        let second: crate::websocket::messages::BybitWsAccountExecutionMsg =
2031            serde_json::from_value(value).unwrap();
2032
2033        dispatch_ws_message(
2034            &BybitWsMessage::AccountExecution(second),
2035            test_account_id(),
2036            &instruments,
2037            clock,
2038            &state,
2039            &emitter,
2040        );
2041
2042        let repay = repay_rx.try_recv().expect("expected a repay request");
2043        assert_eq!(repay.coin, "BTC");
2044        assert_eq!(repay.quantity, Quantity::from("0.0040"));
2045        assert_eq!(
2046            repay.base_fee,
2047            expected_base_fee.parse::<Decimal>().unwrap()
2048        );
2049        assert_eq!(repay.repayment_precision, 8);
2050        assert!(repay_rx.try_recv().is_err());
2051    }
2052
2053    #[rstest]
2054    fn test_dispatch_tracked_canceled_order_emits_accepted_then_canceled() {
2055        let instrument = linear_instrument();
2056        let instruments = build_instruments(std::slice::from_ref(&instrument));
2057        let (emitter, mut rx) = create_emitter();
2058        let clock = get_atomic_clock_realtime();
2059        let state = WsDispatchState::default();
2060
2061        // Fixture has orderStatus=Cancelled
2062        let json = load_test_json("ws_account_order.json");
2063        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2064            serde_json::from_str(&json).unwrap();
2065
2066        if let Some(order) = msg.data.first()
2067            && !order.order_link_id.is_empty()
2068        {
2069            let cid = ClientOrderId::new(order.order_link_id);
2070            state.order_identities.insert(cid, default_identity());
2071        }
2072
2073        let ws_msg = BybitWsMessage::AccountOrder(msg);
2074        dispatch_ws_message(
2075            &ws_msg,
2076            test_account_id(),
2077            &instruments,
2078            clock,
2079            &state,
2080            &emitter,
2081        );
2082
2083        // First: synthesized Accepted
2084        let event1 = rx.try_recv().unwrap();
2085        assert!(
2086            matches!(event1, ExecutionEvent::Order(OrderEventAny::Accepted(ref a)) if a.strategy_id == StrategyId::from("S-001")),
2087            "Expected Accepted, found {event1:?}"
2088        );
2089
2090        // Second: Canceled (from Cancelled status)
2091        let event2 = rx.try_recv().unwrap();
2092        assert!(
2093            matches!(event2, ExecutionEvent::Order(OrderEventAny::Canceled(_))),
2094            "Expected Canceled, found {event2:?}"
2095        );
2096    }
2097
2098    #[rstest]
2099    fn test_dispatch_tracked_post_only_cancel_emits_rejected() {
2100        const BYBIT_POST_ONLY_REJECT_REASON: &str = "EC_PostOnlyWillTakeLiquidity";
2101
2102        let instrument = linear_instrument();
2103        let instruments = build_instruments(std::slice::from_ref(&instrument));
2104        let (emitter, mut rx) = create_emitter();
2105        let clock = get_atomic_clock_realtime();
2106        let state = WsDispatchState::default();
2107
2108        // Bybit reports a post-only order that would take liquidity as
2109        // orderStatus=Cancelled with rejectReason=EC_PostOnlyWillTakeLiquidity.
2110        let json = load_test_json("ws_account_order.json");
2111        let mut msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2112            serde_json::from_str(&json).unwrap();
2113
2114        let order = msg.data.first_mut().expect("fixture has an order");
2115        order.reject_reason = Ustr::from(BYBIT_POST_ONLY_REJECT_REASON);
2116        order.cum_exec_qty = "0".to_string();
2117        let cid = ClientOrderId::new(order.order_link_id);
2118        state.order_identities.insert(cid, default_identity());
2119
2120        let ws_msg = BybitWsMessage::AccountOrder(msg);
2121        dispatch_ws_message(
2122            &ws_msg,
2123            test_account_id(),
2124            &instruments,
2125            clock,
2126            &state,
2127            &emitter,
2128        );
2129
2130        let event = rx.try_recv().unwrap();
2131
2132        let ExecutionEvent::Order(OrderEventAny::Rejected(rejected)) = event else {
2133            panic!("Expected Rejected, found {event:?}");
2134        };
2135
2136        assert!(rejected.due_post_only);
2137        assert_eq!(rejected.reason, BYBIT_POST_ONLY_REJECT_REASON);
2138        assert_eq!(rejected.client_order_id, cid);
2139        assert!(rx.try_recv().is_err(), "expected only a single event");
2140    }
2141
2142    #[rstest]
2143    fn test_dispatch_untracked_order_emits_report() {
2144        let instrument = linear_instrument();
2145        let instruments = build_instruments(std::slice::from_ref(&instrument));
2146        let (emitter, mut rx) = create_emitter();
2147        let clock = get_atomic_clock_realtime();
2148        let state = WsDispatchState::default();
2149
2150        let json = load_test_json("ws_account_order.json");
2151        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2152            serde_json::from_str(&json).unwrap();
2153
2154        // No identity registered → untracked
2155        let ws_msg = BybitWsMessage::AccountOrder(msg);
2156        dispatch_ws_message(
2157            &ws_msg,
2158            test_account_id(),
2159            &instruments,
2160            clock,
2161            &state,
2162            &emitter,
2163        );
2164
2165        let event = rx.try_recv().unwrap();
2166        assert!(matches!(
2167            event,
2168            ExecutionEvent::Report(ExecutionReport::Order(_))
2169        ));
2170    }
2171
2172    #[rstest]
2173    fn test_dispatch_tracked_execution_emits_order_filled() {
2174        let instrument = linear_instrument();
2175        let instruments = build_instruments(std::slice::from_ref(&instrument));
2176        let (emitter, mut rx) = create_emitter();
2177        let clock = get_atomic_clock_realtime();
2178        let state = WsDispatchState::default();
2179
2180        let json = load_test_json("ws_account_execution.json");
2181        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2182            serde_json::from_str(&json).unwrap();
2183
2184        // Register identity for the execution's orderLinkId
2185        if let Some(exec) = msg.data.first()
2186            && !exec.order_link_id.is_empty()
2187        {
2188            let cid = ClientOrderId::new(exec.order_link_id);
2189            state.order_identities.insert(cid, default_identity());
2190        }
2191
2192        let ws_msg = BybitWsMessage::AccountExecution(msg);
2193        dispatch_ws_message(
2194            &ws_msg,
2195            test_account_id(),
2196            &instruments,
2197            clock,
2198            &state,
2199            &emitter,
2200        );
2201
2202        // First event should be synthesized Accepted
2203        let event1 = rx.try_recv().unwrap();
2204        assert!(
2205            matches!(event1, ExecutionEvent::Order(OrderEventAny::Accepted(_))),
2206            "Expected Accepted, found {event1:?}"
2207        );
2208
2209        // Second event should be OrderFilled
2210        let event2 = rx.try_recv().unwrap();
2211        match event2 {
2212            ExecutionEvent::Order(OrderEventAny::Filled(filled)) => {
2213                assert_eq!(filled.strategy_id, StrategyId::from("S-001"));
2214                assert_eq!(filled.order_side, OrderSide::Buy);
2215                assert_eq!(filled.order_type, OrderType::Limit);
2216            }
2217            other => panic!("Expected Filled event, found {other:?}"),
2218        }
2219    }
2220
2221    #[rstest]
2222    #[case::commission_overflow("execFee", "9999999999999999999999999999")]
2223    #[case::commission_parse("execFee", "invalid")]
2224    #[case::qty("execQty", "invalid")]
2225    #[case::price("execPrice", "invalid")]
2226    #[case::timestamp("execTime", "invalid")]
2227    #[case::trade_id("execId", "")]
2228    fn test_dispatch_invalid_execution_preserves_state(
2229        #[case] field: &str,
2230        #[case] value: &str,
2231        #[values(false, true)] spot: bool,
2232    ) {
2233        let instrument = if spot {
2234            spot_instrument()
2235        } else {
2236            linear_instrument()
2237        };
2238
2239        let instruments = build_instruments(std::slice::from_ref(&instrument));
2240        let (emitter, mut rx) = create_emitter();
2241        let state = WsDispatchState::default();
2242        let (repay_tx, mut repay_rx) = tokio::sync::mpsc::unbounded_channel();
2243        state.set_repay_sender(repay_tx);
2244        let mut payload: serde_json::Value =
2245            serde_json::from_str(&load_test_json("ws_account_execution.json")).unwrap();
2246        payload["data"][0][field] = serde_json::Value::String(value.to_string());
2247        payload["data"][0]["side"] = serde_json::Value::String("Buy".to_string());
2248        if spot {
2249            payload["data"][0]["category"] = serde_json::Value::String("spot".to_string());
2250        }
2251
2252        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2253            serde_json::from_value(payload).unwrap();
2254        let cid = ClientOrderId::new(msg.data[0].order_link_id);
2255
2256        let identity = OrderIdentity {
2257            instrument_id: instrument.id(),
2258            venue_position_id: Some(PositionId::from("P-001")),
2259            ..default_identity()
2260        };
2261
2262        state.order_identities.insert(cid, identity.clone());
2263        state.order_snapshots.insert(
2264            cid,
2265            OrderStateSnapshot {
2266                quantity: Quantity::from("0.500"),
2267                price: Some(Price::from("95900.1")),
2268                trigger_price: Some(Price::from("95800.2")),
2269            },
2270        );
2271
2272        state.insert_triggered(cid);
2273
2274        dispatch_ws_message(
2275            &BybitWsMessage::AccountExecution(msg),
2276            test_account_id(),
2277            &instruments,
2278            get_atomic_clock_realtime(),
2279            &state,
2280            &emitter,
2281        );
2282
2283        assert!(rx.try_recv().is_err());
2284        assert!(repay_rx.try_recv().is_err());
2285        assert!(state.emitted_accepted.is_empty());
2286        assert!(state.filled_orders.is_empty());
2287        assert!(state.spot_repay_fills.is_empty());
2288        assert!(state.pending_requests.is_empty());
2289        assert_eq!(state.triggered_orders.len(), 1);
2290        assert!(state.triggered_orders.contains(&cid));
2291        assert_eq!(state.order_identities.len(), 1);
2292        let retained = state.order_identities.get(&cid).unwrap();
2293        assert_eq!(retained.instrument_id, identity.instrument_id);
2294        assert_eq!(retained.strategy_id, identity.strategy_id);
2295        assert_eq!(retained.order_side, identity.order_side);
2296        assert_eq!(retained.order_type, identity.order_type);
2297        assert_eq!(retained.venue_position_id, identity.venue_position_id);
2298        assert_eq!(state.order_snapshots.len(), 1);
2299        let snapshot = state.order_snapshots.get(&cid).unwrap();
2300        assert_eq!(snapshot.quantity, Quantity::from("0.500"));
2301        assert_eq!(snapshot.price, Some(Price::from("95900.1")));
2302        assert_eq!(snapshot.trigger_price, Some(Price::from("95800.2")));
2303    }
2304
2305    #[rstest]
2306    #[case::partial("0.5", "1.000", OrderStatus::PartiallyFilled)]
2307    #[case::terminal("0", "0.500", OrderStatus::Filled)]
2308    fn test_dispatch_execution_commission_failure_recovery_and_replay(
2309        #[case] leaves_qty: &str,
2310        #[case] order_qty: &str,
2311        #[case] expected_status: OrderStatus,
2312    ) {
2313        let instrument = linear_instrument();
2314        let instruments = build_instruments(std::slice::from_ref(&instrument));
2315        let (emitter, mut rx) = create_emitter();
2316        let state = WsDispatchState::default();
2317        let clock = AtomicTime::new(false, UnixNanos::new(1_746_270_400_400_000_000));
2318        let mut msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2319            serde_json::from_str(&load_test_json("ws_account_execution.json")).unwrap();
2320        msg.data[0].leaves_qty = leaves_qty.to_string();
2321        msg.data[0].side = BybitOrderSide::Buy;
2322        msg.data[0].exec_fee = "9999999999999999999999999999".to_string();
2323        let cid = ClientOrderId::new(msg.data[0].order_link_id);
2324        let identity = default_identity();
2325        state.order_identities.insert(cid, identity.clone());
2326
2327        let harness = ExecutionHarness::new(
2328            emitter.trader_id(),
2329            *crate::common::consts::BYBIT_CLIENT_ID,
2330            test_account_id(),
2331            instrument.clone(),
2332        );
2333        let wallet: crate::websocket::messages::BybitWsAccountWalletMsg =
2334            serde_json::from_str(&load_test_json("ws_account_wallet.json")).unwrap();
2335        let account_state = parse_ws_account_state(
2336            &wallet.data[0],
2337            test_account_id(),
2338            UnixNanos::default(),
2339            UnixNanos::default(),
2340        )
2341        .unwrap();
2342        let account = MarginAccount::new(account_state, false);
2343        harness
2344            .cache()
2345            .borrow_mut()
2346            .add_account(account.into())
2347            .unwrap();
2348        let mut order = OrderTestBuilder::new(identity.order_type)
2349            .trader_id(emitter.trader_id())
2350            .strategy_id(identity.strategy_id)
2351            .instrument_id(instrument.id())
2352            .client_order_id(cid)
2353            .side(identity.order_side)
2354            .quantity(Quantity::from(order_qty))
2355            .price(Price::from("94942.5"))
2356            .build();
2357        let submitted = TestOrderEventStubs::submitted(&order, test_account_id());
2358        order.apply(submitted).unwrap();
2359        harness
2360            .cache()
2361            .borrow_mut()
2362            .add_order(order, None, None, false)
2363            .unwrap();
2364
2365        dispatch_ws_message(
2366            &BybitWsMessage::AccountExecution(msg.clone()),
2367            test_account_id(),
2368            &instruments,
2369            &clock,
2370            &state,
2371            &emitter,
2372        );
2373
2374        assert!(rx.try_recv().is_err());
2375        assert!(state.emitted_accepted.is_empty());
2376        assert!(state.filled_orders.is_empty());
2377        assert_eq!(state.order_identities.len(), 1);
2378
2379        msg.data[0].exec_fee = "0.01234567".to_string();
2380        let message = BybitWsMessage::AccountExecution(msg);
2381        dispatch_ws_message(
2382            &message,
2383            test_account_id(),
2384            &instruments,
2385            &clock,
2386            &state,
2387            &emitter,
2388        );
2389
2390        let ExecutionEvent::Order(OrderEventAny::Accepted(accepted)) = rx.try_recv().unwrap()
2391        else {
2392            panic!("expected Accepted before Filled");
2393        };
2394
2395        let expected_accepted = OrderAccepted::new(
2396            emitter.trader_id(),
2397            identity.strategy_id,
2398            instrument.id(),
2399            cid,
2400            VenueOrderId::from("9aac161b-8ed6-450d-9cab-c5cc67c21784"),
2401            test_account_id(),
2402            accepted.event_id,
2403            clock.get_time_ns(),
2404            clock.get_time_ns(),
2405            false,
2406        );
2407        assert_eq!(accepted, expected_accepted);
2408        harness
2409            .exec_engine()
2410            .borrow_mut()
2411            .process(&OrderEventAny::Accepted(accepted));
2412
2413        let ExecutionEvent::Order(OrderEventAny::Filled(filled)) = rx.try_recv().unwrap() else {
2414            panic!("expected Filled after Accepted");
2415        };
2416
2417        let commission = Money::from("0.01234567 USDT");
2418
2419        let expected_filled = OrderFilled::new(
2420            emitter.trader_id(),
2421            identity.strategy_id,
2422            instrument.id(),
2423            cid,
2424            VenueOrderId::from("9aac161b-8ed6-450d-9cab-c5cc67c21784"),
2425            test_account_id(),
2426            TradeId::from("0ab1bdf7-4219-438b-b30a-32ec863018f7"),
2427            OrderSide::Buy,
2428            OrderType::Limit,
2429            Quantity::from("0.500"),
2430            Price::from("95900.1"),
2431            Currency::USDT(),
2432            LiquiditySide::Taker,
2433            filled.event_id,
2434            UnixNanos::new(1_746_270_400_353_000_000),
2435            clock.get_time_ns(),
2436            false,
2437            None,
2438            Some(commission),
2439            None,
2440        );
2441        assert_eq!(filled, expected_filled);
2442        assert!(rx.try_recv().is_err());
2443        harness
2444            .exec_engine()
2445            .borrow_mut()
2446            .process(&OrderEventAny::Filled(filled.clone()));
2447        let applied = harness.cache().borrow().order(&cid).unwrap().clone();
2448        assert_eq!(applied.status(), expected_status);
2449        assert_eq!(applied.filled_qty(), Quantity::from("0.500"));
2450        assert_eq!(
2451            applied.commissions().get(&Currency::USDT()),
2452            Some(&commission)
2453        );
2454        assert_eq!(applied.trade_ids(), vec![&filled.trade_id]);
2455        let position_id = *harness.cache().borrow().position_id(&cid).unwrap();
2456        let position = harness
2457            .cache()
2458            .borrow()
2459            .position(&position_id)
2460            .unwrap()
2461            .clone();
2462        assert_eq!(position.quantity, Quantity::from("0.500"));
2463        assert_eq!(position.commissions(), vec![commission]);
2464        let mut expected_position_fill = filled.clone();
2465        expected_position_fill.position_id = Some(position_id);
2466        assert_eq!(position.events, vec![expected_position_fill]);
2467
2468        dispatch_ws_message(
2469            &message,
2470            test_account_id(),
2471            &instruments,
2472            &clock,
2473            &state,
2474            &emitter,
2475        );
2476        let replay = rx.try_recv().unwrap();
2477        match replay {
2478            ExecutionEvent::Order(OrderEventAny::Filled(replayed)) => {
2479                let expected_replay = OrderFilled {
2480                    event_id: replayed.event_id,
2481                    ..filled.clone()
2482                };
2483
2484                assert_eq!(replayed, expected_replay);
2485                assert_eq!(leaves_qty, "0.5");
2486                harness
2487                    .exec_engine()
2488                    .borrow_mut()
2489                    .process(&OrderEventAny::Filled(replayed));
2490            }
2491            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
2492                let expected_report = FillReport::new(
2493                    filled.account_id,
2494                    filled.instrument_id,
2495                    filled.venue_order_id,
2496                    filled.trade_id,
2497                    filled.order_side,
2498                    filled.last_qty,
2499                    filled.last_px,
2500                    commission,
2501                    filled.liquidity_side,
2502                    Some(cid),
2503                    None,
2504                    filled.ts_event,
2505                    filled.ts_init,
2506                    Some(report.report_id),
2507                );
2508                assert_eq!(*report, expected_report);
2509                assert_eq!(leaves_qty, "0");
2510                harness
2511                    .exec_engine()
2512                    .borrow_mut()
2513                    .reconcile_fill_report(&report);
2514            }
2515            other => panic!("unexpected replay: {other:?}"),
2516        }
2517
2518        harness
2519            .exec_engine()
2520            .borrow_mut()
2521            .process(&OrderEventAny::Filled(filled));
2522
2523        assert!(rx.try_recv().is_err());
2524        assert_eq!(
2525            serde_json::to_value(harness.cache().borrow().order(&cid).unwrap().clone()).unwrap(),
2526            serde_json::to_value(&applied).unwrap()
2527        );
2528        assert_eq!(
2529            serde_json::to_value(
2530                harness
2531                    .cache()
2532                    .borrow()
2533                    .position(&position_id)
2534                    .unwrap()
2535                    .clone()
2536            )
2537            .unwrap(),
2538            serde_json::to_value(&position).unwrap()
2539        );
2540    }
2541
2542    #[rstest]
2543    fn parse_order_filled_uses_payload_fee_currency() {
2544        let instrument = linear_instrument();
2545        let (emitter, _rx) = create_emitter();
2546
2547        let json = load_test_json("ws_account_execution.json");
2548        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2549            serde_json::from_str(&json).unwrap();
2550
2551        let mut exec = msg.data[0].clone();
2552        exec.fee_currency = Ustr::from("BTC");
2553
2554        let filled = parse_order_filled(
2555            &exec,
2556            &instrument,
2557            &default_identity(),
2558            &emitter,
2559            test_account_id(),
2560            UnixNanos::default(),
2561        )
2562        .unwrap();
2563
2564        let commission = filled.commission.expect("commission present");
2565        assert_eq!(commission.currency.code, "BTC");
2566    }
2567
2568    #[rstest]
2569    #[case::spot_base_fee(BybitProductType::Spot, "BTC", "0.000001", "USDT")]
2570    #[case::spot_quote_fee(BybitProductType::Spot, "USDT", "0.1", "USDT")]
2571    #[case::linear_fee(BybitProductType::Linear, "USDT", "0.1", "USDT")]
2572    #[case::inverse_fee(BybitProductType::Inverse, "BTC", "0.000001", "USD")]
2573    #[case::spot_zero_fee(BybitProductType::Spot, "BTC", "0", "USDT")]
2574    #[case::inverse_rebate(BybitProductType::Inverse, "BTC", "-0.000001", "USD")]
2575    fn parse_order_filled_separates_price_and_commission_currencies(
2576        #[case] category: BybitProductType,
2577        #[case] fee_currency: &str,
2578        #[case] fee: &str,
2579        #[case] expected_price_currency: &str,
2580    ) {
2581        let instrument = match category {
2582            BybitProductType::Spot => spot_instrument(),
2583            BybitProductType::Linear => linear_instrument(),
2584            BybitProductType::Inverse => inverse_instrument(),
2585            _ => unreachable!("unsupported test product"),
2586        };
2587
2588        let (emitter, _rx) = create_emitter();
2589        let json = load_test_json("ws_account_execution.json");
2590        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2591            serde_json::from_str(&json).unwrap();
2592        let mut exec = msg.data[0].clone();
2593        exec.category = category;
2594        exec.symbol = instrument.raw_symbol().inner();
2595        exec.exec_qty = "1".to_string();
2596        exec.exec_fee = fee.to_string();
2597        exec.fee_currency = Ustr::from(fee_currency);
2598
2599        let identity = OrderIdentity {
2600            instrument_id: instrument.id(),
2601            order_side: OrderSide::Sell,
2602            order_type: OrderType::Market,
2603            ..default_identity()
2604        };
2605
2606        let filled = parse_order_filled(
2607            &exec,
2608            &instrument,
2609            &identity,
2610            &emitter,
2611            test_account_id(),
2612            UnixNanos::default(),
2613        )
2614        .unwrap();
2615
2616        let commission = filled.commission.expect("commission present");
2617        assert_eq!(commission.currency.code, fee_currency);
2618        assert_eq!(commission.as_decimal(), fee.parse::<Decimal>().unwrap());
2619        assert_eq!(filled.currency.code, expected_price_currency);
2620    }
2621
2622    #[rstest]
2623    fn test_dispatch_tracked_execution_preserves_venue_position_id() {
2624        let instrument = linear_instrument();
2625        let instruments = build_instruments(std::slice::from_ref(&instrument));
2626        let (emitter, mut rx) = create_emitter();
2627        let clock = get_atomic_clock_realtime();
2628        let state = WsDispatchState::default();
2629
2630        let json = load_test_json("ws_account_execution.json");
2631        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2632            serde_json::from_str(&json).unwrap();
2633        let venue_position_id = PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG");
2634
2635        if let Some(exec) = msg.data.first()
2636            && !exec.order_link_id.is_empty()
2637        {
2638            let cid = ClientOrderId::new(exec.order_link_id);
2639            state.order_identities.insert(
2640                cid,
2641                OrderIdentity {
2642                    venue_position_id: Some(venue_position_id),
2643                    ..default_identity()
2644                },
2645            );
2646        }
2647
2648        let ws_msg = BybitWsMessage::AccountExecution(msg);
2649        dispatch_ws_message(
2650            &ws_msg,
2651            test_account_id(),
2652            &instruments,
2653            clock,
2654            &state,
2655            &emitter,
2656        );
2657
2658        let _accepted = rx.try_recv().unwrap();
2659        let event = rx.try_recv().unwrap();
2660        match event {
2661            ExecutionEvent::Order(OrderEventAny::Filled(filled)) => {
2662                assert_eq!(filled.position_id, Some(venue_position_id));
2663            }
2664            other => panic!("Expected Filled event, found {other:?}"),
2665        }
2666    }
2667
2668    fn fee_rate(symbol: &str, base_coin: Option<&str>, maker: &str, taker: &str) -> BybitFeeRate {
2669        BybitFeeRate {
2670            symbol: Ustr::from(symbol),
2671            taker_fee_rate: taker.to_string(),
2672            maker_fee_rate: maker.to_string(),
2673            base_coin: base_coin.map(Ustr::from),
2674        }
2675    }
2676
2677    #[rstest]
2678    fn test_cache_execution_fee_rates_scopes_products_and_fans_out_options() {
2679        let linear = linear_instrument();
2680        let spot = spot_instrument();
2681        let option_1 = option_instrument_with_distinct_settlement();
2682        let mut option_2 = option_instrument_with_distinct_settlement();
2683
2684        let InstrumentAny::CryptoOption(ref mut option) = option_2 else {
2685            panic!("expected crypto option");
2686        };
2687
2688        option.id = InstrumentId::from("BTC-30JUN25-110000-C-OPTION.BYBIT");
2689        let instruments = build_instruments(&[
2690            linear.clone(),
2691            spot.clone(),
2692            option_1.clone(),
2693            option_2.clone(),
2694        ]);
2695        let state = WsDispatchState::default();
2696
2697        let linear_cached = cache_execution_fee_rates(
2698            &state,
2699            &instruments,
2700            BybitProductType::Linear,
2701            vec![fee_rate("BTCUSDT", None, "0.0001", "0.0006")],
2702        );
2703        assert_eq!(linear_cached, 1);
2704        assert_eq!(
2705            *state.fee_rates.get(&linear.id()).unwrap(),
2706            MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006),)
2707        );
2708        assert!(!state.fee_rates.contains_key(&spot.id()));
2709
2710        let spot_cached = cache_execution_fee_rates(
2711            &state,
2712            &instruments,
2713            BybitProductType::Spot,
2714            vec![fee_rate("BTCUSDT", None, "0.001", "0.002")],
2715        );
2716        assert_eq!(spot_cached, 1);
2717        assert_eq!(
2718            *state.fee_rates.get(&spot.id()).unwrap(),
2719            MakerTakerFeeRates::new(dec!(0.001), dec!(0.002),)
2720        );
2721        assert_eq!(
2722            *state.fee_rates.get(&linear.id()).unwrap(),
2723            MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006),)
2724        );
2725
2726        let option_cached = cache_execution_fee_rates(
2727            &state,
2728            &instruments,
2729            BybitProductType::Option,
2730            vec![fee_rate("", Some("BTC"), "0.0002", "0.0003")],
2731        );
2732        assert_eq!(option_cached, 2);
2733        assert!(state.fee_rates.contains_key(&option_1.id()));
2734        assert!(state.fee_rates.contains_key(&option_2.id()));
2735    }
2736
2737    #[rstest]
2738    fn test_cache_execution_fee_rates_skips_malformed_rates() {
2739        let instrument = linear_instrument();
2740        let instruments = build_instruments(std::slice::from_ref(&instrument));
2741        let state = WsDispatchState::default();
2742
2743        let cached = cache_execution_fee_rates(
2744            &state,
2745            &instruments,
2746            BybitProductType::Linear,
2747            vec![fee_rate("BTCUSDT", None, "invalid", "0.0006")],
2748        );
2749
2750        assert_eq!(cached, 0);
2751        assert!(state.fee_rates.is_empty());
2752    }
2753
2754    fn fast_execution_msg(is_maker: bool, order_link_id: &str) -> BybitWsAccountExecutionFastMsg {
2755        BybitWsAccountExecutionFastMsg {
2756            topic: Ustr::from("execution.fast"),
2757            id: String::new(),
2758            creation_time: 1_716_800_399_338,
2759            data: vec![BybitWsAccountExecutionFast {
2760                category: BybitProductType::Linear,
2761                symbol: Ustr::from("BTCUSDT"),
2762                exec_id: "fast-1".to_string(),
2763                exec_price: "50000.0".to_string(),
2764                exec_qty: "0.5".to_string(),
2765                order_id: Ustr::from("ord-1"),
2766                order_link_id: Ustr::from(order_link_id),
2767                side: BybitOrderSide::Buy,
2768                exec_time: "1716800399334".to_string(),
2769                is_maker,
2770                seq: 42,
2771            }],
2772        }
2773    }
2774
2775    #[rstest]
2776    fn test_dispatch_tracked_fast_execution_preserves_venue_position_id() {
2777        let instrument = linear_instrument();
2778        let instruments = build_instruments(std::slice::from_ref(&instrument));
2779        let (emitter, mut rx) = create_emitter();
2780        let clock = get_atomic_clock_realtime();
2781        let state = WsDispatchState::default();
2782        let venue_position_id = PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG");
2783
2784        // Taker fast fill (orderLinkId populated) so the identity lookup hits.
2785        let msg = fast_execution_msg(false, "link-1");
2786        let cid = ClientOrderId::new(msg.data[0].order_link_id);
2787        state.order_identities.insert(
2788            cid,
2789            OrderIdentity {
2790                venue_position_id: Some(venue_position_id),
2791                ..default_identity()
2792            },
2793        );
2794
2795        let ws_msg = BybitWsMessage::AccountExecutionFast(msg);
2796        dispatch_ws_message(
2797            &ws_msg,
2798            test_account_id(),
2799            &instruments,
2800            clock,
2801            &state,
2802            &emitter,
2803        );
2804
2805        // First event: synthesized OrderAccepted from the identity hit.
2806        let event1 = rx.try_recv().unwrap();
2807        assert!(
2808            matches!(event1, ExecutionEvent::Order(OrderEventAny::Accepted(_))),
2809            "Expected Accepted, found {event1:?}",
2810        );
2811
2812        // Second event: FillReport carrying the hedge venue_position_id.
2813        let event2 = rx.try_recv().unwrap();
2814        match event2 {
2815            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
2816                assert_eq!(report.venue_position_id, Some(venue_position_id));
2817                assert_eq!(report.client_order_id, Some(cid));
2818            }
2819            other => panic!("Expected FillReport, found {other:?}"),
2820        }
2821    }
2822
2823    fn order_msg(
2824        order_link_id: &str,
2825        status: &str,
2826        cum_exec_qty: &str,
2827    ) -> crate::websocket::messages::BybitWsAccountOrderMsg {
2828        let json = load_test_json("ws_account_order.json");
2829        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
2830        value["data"][0]["orderId"] = serde_json::Value::String("ord-1".to_string());
2831        value["data"][0]["orderLinkId"] = serde_json::Value::String(order_link_id.to_string());
2832        value["data"][0]["orderStatus"] = serde_json::Value::String(status.to_string());
2833        value["data"][0]["price"] = serde_json::Value::String("50000.0".to_string());
2834        value["data"][0]["qty"] = serde_json::Value::String("0.5".to_string());
2835        value["data"][0]["cumExecQty"] = serde_json::Value::String(cum_exec_qty.to_string());
2836        serde_json::from_value(value).unwrap()
2837    }
2838
2839    fn assert_fast_state_cleared(state: &WsDispatchState, client_order_id: ClientOrderId) {
2840        assert!(!state.order_identities.contains_key(&client_order_id));
2841        assert!(!state.order_venue_ids.contains_key(&client_order_id));
2842        assert!(
2843            !state
2844                .venue_order_ids
2845                .contains_key(&VenueOrderId::from("ord-1"))
2846        );
2847        assert!(!state.filled_orders.contains(&client_order_id));
2848        assert!(!state.fast_filled_quantities.contains_key(&client_order_id));
2849        assert!(
2850            !state
2851                .terminal_order_quantities
2852                .contains_key(&client_order_id)
2853        );
2854        assert!(state.pending_fast_executions.is_empty());
2855    }
2856
2857    #[rstest]
2858    #[case::fast_first(true)]
2859    #[case::order_first(false)]
2860    fn test_dispatch_untracked_fast_execution_emits_fill_report_without_position(
2861        #[case] fast_first: bool,
2862    ) {
2863        let instrument = linear_instrument();
2864        let instruments = build_instruments(std::slice::from_ref(&instrument));
2865        let (emitter, mut rx) = create_emitter();
2866        let clock = get_atomic_clock_realtime();
2867        let state = WsDispatchState::default();
2868
2869        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
2870        let order_msg = BybitWsMessage::AccountOrder(order_msg("", "Filled", "0.5"));
2871
2872        if fast_first {
2873            dispatch_ws_message(
2874                &fast_msg,
2875                test_account_id(),
2876                &instruments,
2877                clock,
2878                &state,
2879                &emitter,
2880            );
2881            assert!(rx.try_recv().is_err());
2882            assert_eq!(state.pending_fast_executions.len(), 1);
2883        }
2884
2885        dispatch_ws_message(
2886            &order_msg,
2887            test_account_id(),
2888            &instruments,
2889            clock,
2890            &state,
2891            &emitter,
2892        );
2893
2894        if !fast_first {
2895            dispatch_ws_message(
2896                &fast_msg,
2897                test_account_id(),
2898                &instruments,
2899                clock,
2900                &state,
2901                &emitter,
2902            );
2903        }
2904
2905        let first = rx.try_recv().unwrap();
2906        let second = rx.try_recv().unwrap();
2907
2908        let report = if fast_first {
2909            assert!(matches!(
2910                second,
2911                ExecutionEvent::Report(ExecutionReport::Order(_))
2912            ));
2913
2914            match first {
2915                ExecutionEvent::Report(ExecutionReport::Fill(report)) => report,
2916                other => panic!("Expected FillReport first, found {other:?}"),
2917            }
2918        } else {
2919            assert!(matches!(
2920                first,
2921                ExecutionEvent::Report(ExecutionReport::Order(_))
2922            ));
2923
2924            match second {
2925                ExecutionEvent::Report(ExecutionReport::Fill(report)) => report,
2926                other => panic!("Expected FillReport second, found {other:?}"),
2927            }
2928        };
2929
2930        assert_eq!(report.client_order_id, None);
2931        assert_eq!(report.venue_position_id, None);
2932        assert_eq!(report.liquidity_side, LiquiditySide::Maker);
2933        assert_eq!(report.commission.as_decimal(), Decimal::ZERO);
2934        assert!(state.pending_fast_executions.is_empty());
2935    }
2936
2937    #[rstest]
2938    fn test_dispatch_reconnected_flushes_pending_fast_execution() {
2939        let instrument = linear_instrument();
2940        let instruments = build_instruments(std::slice::from_ref(&instrument));
2941        let (emitter, mut rx) = create_emitter();
2942        let clock = get_atomic_clock_realtime();
2943        let state = WsDispatchState::new(true);
2944        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
2945        dispatch_ws_message(
2946            &fast_msg,
2947            test_account_id(),
2948            &instruments,
2949            clock,
2950            &state,
2951            &emitter,
2952        );
2953        assert!(rx.try_recv().is_err());
2954        assert_eq!(state.pending_fast_executions.len(), 1);
2955
2956        dispatch_ws_message(
2957            &BybitWsMessage::Reconnected,
2958            test_account_id(),
2959            &instruments,
2960            clock,
2961            &state,
2962            &emitter,
2963        );
2964
2965        match rx.try_recv().unwrap() {
2966            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
2967                assert_eq!(report.client_order_id, None);
2968                assert_eq!(report.last_qty, Quantity::from("0.5"));
2969            }
2970            other => panic!("Expected FillReport, found {other:?}"),
2971        }
2972
2973        assert!(state.pending_fast_executions.is_empty());
2974    }
2975
2976    #[rstest]
2977    #[case::rejected("Rejected")]
2978    #[case::partially_filled_canceled("PartiallyFilledCanceled")]
2979    fn test_dispatch_partially_filled_terminal_defers_cleanup_until_fast_fill(
2980        #[case] status: &str,
2981    ) {
2982        let instrument = linear_instrument();
2983        let instruments = build_instruments(std::slice::from_ref(&instrument));
2984        let (emitter, _rx) = create_emitter();
2985        let clock = get_atomic_clock_realtime();
2986
2987        let state = WsDispatchState {
2988            fast_execution: true,
2989            ..Default::default()
2990        };
2991
2992        let client_order_id = ClientOrderId::from("link-1");
2993        state
2994            .order_identities
2995            .insert(client_order_id, default_identity());
2996        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", status, "0.5"));
2997        dispatch_ws_message(
2998            &order_msg,
2999            test_account_id(),
3000            &instruments,
3001            clock,
3002            &state,
3003            &emitter,
3004        );
3005
3006        assert!(state.order_identities.contains_key(&client_order_id));
3007        assert_eq!(
3008            *state
3009                .terminal_order_quantities
3010                .get(&client_order_id)
3011                .unwrap(),
3012            Quantity::from("0.5")
3013        );
3014
3015        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
3016        dispatch_ws_message(
3017            &fast_msg,
3018            test_account_id(),
3019            &instruments,
3020            clock,
3021            &state,
3022            &emitter,
3023        );
3024
3025        assert_fast_state_cleared(&state, client_order_id);
3026    }
3027
3028    #[rstest]
3029    fn test_dispatch_tracked_terminal_emits_deferred_fill_before_cancel() {
3030        let instrument = linear_instrument();
3031        let instruments = build_instruments(std::slice::from_ref(&instrument));
3032        let (emitter, mut rx) = create_emitter();
3033        let clock = get_atomic_clock_realtime();
3034        let state = WsDispatchState::new(true);
3035        let client_order_id = ClientOrderId::from("link-1");
3036        state
3037            .order_identities
3038            .insert(client_order_id, default_identity());
3039        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
3040        dispatch_ws_message(
3041            &fast_msg,
3042            test_account_id(),
3043            &instruments,
3044            clock,
3045            &state,
3046            &emitter,
3047        );
3048        assert!(rx.try_recv().is_err());
3049
3050        let order_msg =
3051            BybitWsMessage::AccountOrder(order_msg("link-1", "PartiallyFilledCanceled", "0.5"));
3052        dispatch_ws_message(
3053            &order_msg,
3054            test_account_id(),
3055            &instruments,
3056            clock,
3057            &state,
3058            &emitter,
3059        );
3060
3061        assert!(matches!(
3062            rx.try_recv().unwrap(),
3063            ExecutionEvent::Order(OrderEventAny::Accepted(_))
3064        ));
3065        assert!(matches!(
3066            rx.try_recv().unwrap(),
3067            ExecutionEvent::Report(ExecutionReport::Fill(_))
3068        ));
3069        assert!(matches!(
3070            rx.try_recv().unwrap(),
3071            ExecutionEvent::Order(OrderEventAny::Canceled(_))
3072        ));
3073        assert_fast_state_cleared(&state, client_order_id);
3074    }
3075
3076    #[rstest]
3077    fn test_dispatch_zero_terminal_cleans_immediately() {
3078        let instrument = linear_instrument();
3079        let instruments = build_instruments(std::slice::from_ref(&instrument));
3080        let (emitter, _rx) = create_emitter();
3081        let clock = get_atomic_clock_realtime();
3082
3083        let state = WsDispatchState {
3084            fast_execution: true,
3085            ..Default::default()
3086        };
3087
3088        let client_order_id = ClientOrderId::from("link-1");
3089        state
3090            .order_identities
3091            .insert(client_order_id, default_identity());
3092        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", "Cancelled", "0"));
3093
3094        dispatch_ws_message(
3095            &order_msg,
3096            test_account_id(),
3097            &instruments,
3098            clock,
3099            &state,
3100            &emitter,
3101        );
3102
3103        assert_fast_state_cleared(&state, client_order_id);
3104    }
3105
3106    #[rstest]
3107    fn test_dispatch_standard_rejected_cleans_venue_correlation() {
3108        let instrument = linear_instrument();
3109        let instruments = build_instruments(std::slice::from_ref(&instrument));
3110        let (emitter, _rx) = create_emitter();
3111        let clock = get_atomic_clock_realtime();
3112        let state = WsDispatchState::default();
3113        let client_order_id = ClientOrderId::from("link-1");
3114        state
3115            .order_identities
3116            .insert(client_order_id, default_identity());
3117        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", "Rejected", "0"));
3118
3119        dispatch_ws_message(
3120            &order_msg,
3121            test_account_id(),
3122            &instruments,
3123            clock,
3124            &state,
3125            &emitter,
3126        );
3127
3128        assert_fast_state_cleared(&state, client_order_id);
3129    }
3130
3131    #[rstest]
3132    fn test_dispatch_fast_execution_parse_failure_allows_valid_replay() {
3133        let instrument = linear_instrument();
3134        let instruments = build_instruments(std::slice::from_ref(&instrument));
3135        let (emitter, mut rx) = create_emitter();
3136        let clock = get_atomic_clock_realtime();
3137        let state = WsDispatchState::default();
3138        let mut invalid = fast_execution_msg(false, "link-1");
3139        invalid.data[0].exec_qty = "invalid".to_string();
3140        let invalid = BybitWsMessage::AccountExecutionFast(invalid);
3141
3142        dispatch_ws_message(
3143            &invalid,
3144            test_account_id(),
3145            &instruments,
3146            clock,
3147            &state,
3148            &emitter,
3149        );
3150        assert!(rx.try_recv().is_err());
3151
3152        let valid = BybitWsMessage::AccountExecutionFast(fast_execution_msg(false, "link-1"));
3153        dispatch_ws_message(
3154            &valid,
3155            test_account_id(),
3156            &instruments,
3157            clock,
3158            &state,
3159            &emitter,
3160        );
3161
3162        match rx.try_recv().unwrap() {
3163            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
3164                assert_eq!(report.trade_id.to_string(), "fast-1");
3165                assert_eq!(report.last_qty, Quantity::from("0.5"));
3166            }
3167            other => panic!("Expected FillReport, found {other:?}"),
3168        }
3169
3170        assert!(rx.try_recv().is_err());
3171    }
3172
3173    #[rstest]
3174    fn test_recent_ids_evicts_oldest_without_clearing_history() {
3175        let state = WsDispatchState::default();
3176        let first = TradeId::from("first");
3177        assert!(state.insert_fast_execution(first));
3178
3179        for index in 0..DEDUP_CAPACITY {
3180            assert!(state.insert_fast_execution(TradeId::from(format!("id-{index}"))));
3181        }
3182
3183        assert!(!state.fast_execution_ids.contains(&first));
3184        assert_eq!(state.fast_execution_ids.ids.len(), DEDUP_CAPACITY);
3185        assert!(state.insert_fast_execution(first));
3186        assert_eq!(state.fast_execution_ids.ids.len(), DEDUP_CAPACITY);
3187        assert!(!state.insert_fast_execution(first));
3188    }
3189
3190    #[rstest]
3191    fn test_fast_execution_correlation_and_enqueue_are_atomic() {
3192        for _ in 0..32 {
3193            let instrument = linear_instrument();
3194            let instruments = build_instruments(std::slice::from_ref(&instrument));
3195            let (emitter, mut rx) = create_emitter();
3196            let clock = get_atomic_clock_realtime();
3197            let state = Arc::new(WsDispatchState::new(true));
3198            let client_order_id = ClientOrderId::from("link-1");
3199            state
3200                .order_identities
3201                .insert(client_order_id, default_identity());
3202            let venue_order_id = VenueOrderId::from("ord-1");
3203            let barrier = Arc::new(std::sync::Barrier::new(2));
3204
3205            std::thread::scope(|scope| {
3206                let state_ws = Arc::clone(&state);
3207                let barrier_ws = Arc::clone(&barrier);
3208                let emitter_ws = emitter.clone();
3209                let instruments_ws = &instruments;
3210
3211                scope.spawn(move || {
3212                    barrier_ws.wait();
3213                    let msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
3214                    dispatch_ws_message(
3215                        &msg,
3216                        test_account_id(),
3217                        instruments_ws,
3218                        clock,
3219                        &state_ws,
3220                        &emitter_ws,
3221                    );
3222                });
3223
3224                let state_rest = Arc::clone(&state);
3225                let barrier_rest = Arc::clone(&barrier);
3226                let emitter_rest = emitter.clone();
3227
3228                scope.spawn(move || {
3229                    barrier_rest.wait();
3230                    record_venue_order_id(client_order_id, venue_order_id, &state_rest);
3231                    drain_pending_fast_executions(
3232                        venue_order_id,
3233                        &instrument,
3234                        test_account_id(),
3235                        clock.get_time_ns(),
3236                        &state_rest,
3237                        &emitter_rest,
3238                    );
3239                });
3240            });
3241
3242            assert!(state.pending_fast_executions.is_empty());
3243            let mut fill_count = 0;
3244
3245            while let Ok(event) = rx.try_recv() {
3246                if matches!(event, ExecutionEvent::Report(ExecutionReport::Fill(_))) {
3247                    fill_count += 1;
3248                }
3249            }
3250
3251            assert_eq!(fill_count, 1);
3252        }
3253    }
3254
3255    #[rstest]
3256    #[case::fast_first(true)]
3257    #[case::order_first(false)]
3258    fn test_dispatch_maker_fast_execution_correlates_and_cleans_terminal_state(
3259        #[case] fast_first: bool,
3260    ) {
3261        let instrument = linear_instrument();
3262        let instruments = build_instruments(std::slice::from_ref(&instrument));
3263        let (emitter, mut rx) = create_emitter();
3264        let clock = get_atomic_clock_realtime();
3265        let state = WsDispatchState::new(true);
3266        let client_order_id = ClientOrderId::from("link-1");
3267        let venue_position_id = PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG");
3268        state.order_identities.insert(
3269            client_order_id,
3270            OrderIdentity {
3271                venue_position_id: Some(venue_position_id),
3272                ..default_identity()
3273            },
3274        );
3275
3276        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
3277        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", "Filled", "0.5"));
3278
3279        if fast_first {
3280            dispatch_ws_message(
3281                &fast_msg,
3282                test_account_id(),
3283                &instruments,
3284                clock,
3285                &state,
3286                &emitter,
3287            );
3288            assert!(rx.try_recv().is_err());
3289        }
3290
3291        dispatch_ws_message(
3292            &order_msg,
3293            test_account_id(),
3294            &instruments,
3295            clock,
3296            &state,
3297            &emitter,
3298        );
3299
3300        if !fast_first {
3301            dispatch_ws_message(
3302                &fast_msg,
3303                test_account_id(),
3304                &instruments,
3305                clock,
3306                &state,
3307                &emitter,
3308            );
3309        }
3310
3311        assert!(matches!(
3312            rx.try_recv().unwrap(),
3313            ExecutionEvent::Order(OrderEventAny::Accepted(_))
3314        ));
3315
3316        match rx.try_recv().unwrap() {
3317            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
3318                assert_eq!(report.client_order_id, Some(client_order_id));
3319                assert_eq!(report.venue_position_id, Some(venue_position_id));
3320            }
3321            other => panic!("Expected FillReport, found {other:?}"),
3322        }
3323
3324        assert_fast_state_cleared(&state, client_order_id);
3325    }
3326
3327    #[rstest]
3328    fn test_dispatch_fast_execution_waits_for_terminal_quantity_and_dedups() {
3329        let instrument = linear_instrument();
3330        let instruments = build_instruments(std::slice::from_ref(&instrument));
3331        let (emitter, _rx) = create_emitter();
3332        let clock = get_atomic_clock_realtime();
3333        let state = WsDispatchState::default();
3334        let client_order_id = ClientOrderId::from("link-1");
3335        state
3336            .order_identities
3337            .insert(client_order_id, default_identity());
3338        let mut first = fast_execution_msg(false, "link-1");
3339        first.data[0].exec_qty = "0.25".to_string();
3340        let first = BybitWsMessage::AccountExecutionFast(first);
3341
3342        dispatch_ws_message(
3343            &first,
3344            test_account_id(),
3345            &instruments,
3346            clock,
3347            &state,
3348            &emitter,
3349        );
3350        dispatch_ws_message(
3351            &first,
3352            test_account_id(),
3353            &instruments,
3354            clock,
3355            &state,
3356            &emitter,
3357        );
3358        assert_eq!(
3359            *state.fast_filled_quantities.get(&client_order_id).unwrap(),
3360            Quantity::from("0.25")
3361        );
3362
3363        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", "Filled", "0.5"));
3364        dispatch_ws_message(
3365            &order_msg,
3366            test_account_id(),
3367            &instruments,
3368            clock,
3369            &state,
3370            &emitter,
3371        );
3372        assert!(state.order_identities.contains_key(&client_order_id));
3373
3374        let mut second = fast_execution_msg(false, "link-1");
3375        second.data[0].exec_id = "fast-2".to_string();
3376        second.data[0].exec_qty = "0.25".to_string();
3377        let second = BybitWsMessage::AccountExecutionFast(second);
3378        dispatch_ws_message(
3379            &second,
3380            test_account_id(),
3381            &instruments,
3382            clock,
3383            &state,
3384            &emitter,
3385        );
3386
3387        assert_fast_state_cleared(&state, client_order_id);
3388        assert_eq!(state.fast_execution_ids.ids.len(), 2);
3389    }
3390
3391    #[rstest]
3392    fn test_dispatch_untracked_execution_emits_fill_report() {
3393        let instrument = linear_instrument();
3394        let instruments = build_instruments(std::slice::from_ref(&instrument));
3395        let (emitter, mut rx) = create_emitter();
3396        let clock = get_atomic_clock_realtime();
3397        let state = WsDispatchState::default();
3398
3399        let json = load_test_json("ws_account_execution.json");
3400        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
3401            serde_json::from_str(&json).unwrap();
3402
3403        // No identity registered → untracked
3404        let ws_msg = BybitWsMessage::AccountExecution(msg);
3405        dispatch_ws_message(
3406            &ws_msg,
3407            test_account_id(),
3408            &instruments,
3409            clock,
3410            &state,
3411            &emitter,
3412        );
3413
3414        let event = rx.try_recv().unwrap();
3415        assert!(matches!(
3416            event,
3417            ExecutionEvent::Report(ExecutionReport::Fill(_))
3418        ));
3419    }
3420
3421    #[rstest]
3422    #[case::untracked("")]
3423    #[case::tracked("test-order-link-001")]
3424    fn test_dispatch_funding_execution_emits_no_event(#[case] order_link_id: &str) {
3425        let instrument = linear_instrument();
3426        let instruments = build_instruments(std::slice::from_ref(&instrument));
3427        let (emitter, mut rx) = create_emitter();
3428        let clock = get_atomic_clock_realtime();
3429        let state = WsDispatchState::default();
3430
3431        let json = load_test_json("ws_account_execution_funding.json");
3432        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
3433        value["data"][0]["orderLinkId"] = serde_json::Value::String(order_link_id.to_string());
3434        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
3435            serde_json::from_value(value).unwrap();
3436        let execution = &msg.data[0];
3437
3438        assert_eq!(execution.exec_type, BybitExecType::Funding);
3439
3440        if !execution.order_link_id.is_empty() {
3441            state.order_identities.insert(
3442                ClientOrderId::new(execution.order_link_id),
3443                default_identity(),
3444            );
3445        }
3446
3447        dispatch_ws_message(
3448            &BybitWsMessage::AccountExecution(msg),
3449            test_account_id(),
3450            &instruments,
3451            clock,
3452            &state,
3453            &emitter,
3454        );
3455
3456        assert!(matches!(
3457            rx.try_recv(),
3458            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
3459        ));
3460    }
3461
3462    #[rstest]
3463    #[case::corporate_action("CorporateAction")]
3464    #[case::forward_split_settle("ForwardSplitSettle")]
3465    #[case::reverse_split_settle("ReverseSplitSettle")]
3466    #[case::dividend("Dividend")]
3467    #[case::unrecognized("StockMerger")]
3468    fn test_dispatch_venue_initiated_execution_emits_only_fill_report(#[case] exec_type: &str) {
3469        let instrument = linear_instrument();
3470        let instruments = build_instruments(std::slice::from_ref(&instrument));
3471        let (emitter, mut rx) = create_emitter();
3472        let clock = get_atomic_clock_realtime();
3473        let state = WsDispatchState::default();
3474
3475        let json = load_test_json("ws_account_execution_adl.json");
3476        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
3477        value["data"][0]["execType"] = serde_json::Value::String(exec_type.to_string());
3478        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
3479            serde_json::from_value(value).unwrap();
3480        let execution = &msg.data[0];
3481
3482        assert!(execution.order_link_id.is_empty());
3483
3484        dispatch_ws_message(
3485            &BybitWsMessage::AccountExecution(msg),
3486            test_account_id(),
3487            &instruments,
3488            clock,
3489            &state,
3490            &emitter,
3491        );
3492
3493        let event = rx.try_recv().unwrap();
3494        match event {
3495            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
3496                assert_eq!(report.client_order_id, None);
3497                assert_eq!(
3498                    report.venue_order_id,
3499                    VenueOrderId::from("9aac161b-8ed6-450d-9cab-c5cc67c21785")
3500                );
3501            }
3502            other => panic!("Expected FillReport, found {other:?}"),
3503        }
3504        assert!(rx.try_recv().is_err());
3505    }
3506
3507    #[rstest]
3508    fn test_dispatch_wallet_emits_account_state() {
3509        let instruments = AHashMap::new();
3510        let (emitter, mut rx) = create_emitter();
3511        let clock = get_atomic_clock_realtime();
3512        let state = WsDispatchState::default();
3513
3514        let json = load_test_json("ws_account_wallet.json");
3515        let msg: crate::websocket::messages::BybitWsAccountWalletMsg =
3516            serde_json::from_str(&json).unwrap();
3517        let ws_msg = BybitWsMessage::AccountWallet(msg);
3518
3519        dispatch_ws_message(
3520            &ws_msg,
3521            test_account_id(),
3522            &instruments,
3523            clock,
3524            &state,
3525            &emitter,
3526        );
3527
3528        let event = rx.try_recv().unwrap();
3529        assert!(matches!(event, ExecutionEvent::Account(_)));
3530    }
3531
3532    #[rstest]
3533    fn test_dispatch_data_message_ignored() {
3534        let instruments = AHashMap::new();
3535        let (emitter, mut rx) = create_emitter();
3536        let clock = get_atomic_clock_realtime();
3537        let state = WsDispatchState::default();
3538
3539        let json = load_test_json("ws_public_trade.json");
3540        let msg: crate::websocket::messages::BybitWsTradeMsg = serde_json::from_str(&json).unwrap();
3541        let ws_msg = BybitWsMessage::Trade(msg);
3542
3543        dispatch_ws_message(
3544            &ws_msg,
3545            test_account_id(),
3546            &instruments,
3547            clock,
3548            &state,
3549            &emitter,
3550        );
3551
3552        rx.try_recv().unwrap_err();
3553    }
3554
3555    #[rstest]
3556    fn test_accepted_dedup_prevents_duplicate() {
3557        let instrument = linear_instrument();
3558        let instruments = build_instruments(std::slice::from_ref(&instrument));
3559        let (emitter, mut rx) = create_emitter();
3560        let clock = get_atomic_clock_realtime();
3561        let state = WsDispatchState::default();
3562
3563        // Fixture has orderStatus=Cancelled. Patch to New for this dedup test.
3564        let json = load_test_json("ws_account_order.json");
3565        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
3566        value["data"][0]["orderStatus"] = serde_json::Value::String("New".to_string());
3567        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
3568            serde_json::from_value(value).unwrap();
3569
3570        if let Some(order) = msg.data.first()
3571            && !order.order_link_id.is_empty()
3572        {
3573            let cid = ClientOrderId::new(order.order_link_id);
3574            state.order_identities.insert(cid, default_identity());
3575        }
3576
3577        let ws_msg = BybitWsMessage::AccountOrder(msg.clone());
3578        dispatch_ws_message(
3579            &ws_msg,
3580            test_account_id(),
3581            &instruments,
3582            clock,
3583            &state,
3584            &emitter,
3585        );
3586
3587        let event = rx.try_recv().unwrap();
3588        assert!(matches!(
3589            event,
3590            ExecutionEvent::Order(OrderEventAny::Accepted(_))
3591        ));
3592
3593        // Dispatch the same message again: dedup should suppress the duplicate
3594        let ws_msg2 = BybitWsMessage::AccountOrder(msg);
3595        dispatch_ws_message(
3596            &ws_msg2,
3597            test_account_id(),
3598            &instruments,
3599            clock,
3600            &state,
3601            &emitter,
3602        );
3603
3604        rx.try_recv().unwrap_err();
3605    }
3606
3607    fn new_order_value() -> serde_json::Value {
3608        let json = load_test_json("ws_account_order.json");
3609        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
3610        value["data"][0]["orderStatus"] = serde_json::Value::String("New".to_string());
3611        value
3612    }
3613
3614    struct DispatchTestContext {
3615        instruments: AHashMap<Ustr, InstrumentAny>,
3616        emitter: ExecutionEventEmitter,
3617        rx: tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
3618        clock: &'static AtomicTime,
3619        state: WsDispatchState,
3620    }
3621
3622    impl DispatchTestContext {
3623        fn new() -> Self {
3624            let instrument = linear_instrument();
3625            let instruments = build_instruments(std::slice::from_ref(&instrument));
3626            let (emitter, rx) = create_emitter();
3627            let clock = get_atomic_clock_realtime();
3628            let state = WsDispatchState::default();
3629            Self {
3630                instruments,
3631                emitter,
3632                rx,
3633                clock,
3634                state,
3635            }
3636        }
3637
3638        fn accept_order(&mut self, value: &serde_json::Value) {
3639            let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
3640                serde_json::from_value(value.clone()).unwrap();
3641
3642            if let Some(order) = msg.data.first()
3643                && !order.order_link_id.is_empty()
3644                && !self
3645                    .state
3646                    .order_identities
3647                    .contains_key(&ClientOrderId::new(order.order_link_id))
3648            {
3649                let cid = ClientOrderId::new(order.order_link_id);
3650                self.state.order_identities.insert(cid, default_identity());
3651            }
3652
3653            self.dispatch_value(value);
3654
3655            let event = self.rx.try_recv().unwrap();
3656            assert!(
3657                matches!(event, ExecutionEvent::Order(OrderEventAny::Accepted(_))),
3658                "Expected Accepted, found {event:?}"
3659            );
3660        }
3661
3662        fn dispatch_value(&self, value: &serde_json::Value) {
3663            let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
3664                serde_json::from_value(value.clone()).unwrap();
3665            let ws_msg = BybitWsMessage::AccountOrder(msg);
3666            dispatch_ws_message(
3667                &ws_msg,
3668                test_account_id(),
3669                &self.instruments,
3670                self.clock,
3671                &self.state,
3672                &self.emitter,
3673            );
3674        }
3675
3676        fn recv_updated(&mut self) -> OrderUpdated {
3677            let event = self.rx.try_recv().unwrap();
3678            match event {
3679                ExecutionEvent::Order(OrderEventAny::Updated(updated)) => updated,
3680                other => panic!("Expected Updated event, found {other:?}"),
3681            }
3682        }
3683    }
3684
3685    #[rstest]
3686    fn test_dispatch_order_updated_on_price_change() {
3687        let mut ctx = DispatchTestContext::new();
3688        let value = new_order_value();
3689        ctx.accept_order(&value);
3690
3691        let mut amended = value;
3692        amended["data"][0]["price"] = serde_json::Value::String("31000".to_string());
3693        ctx.dispatch_value(&amended);
3694
3695        let updated = ctx.recv_updated();
3696        assert_eq!(updated.client_order_id, ClientOrderId::from("client-1"));
3697        assert_eq!(updated.price, Some(Price::from("31000.00")));
3698        assert_eq!(updated.quantity, Quantity::from("0.010"));
3699        assert_eq!(updated.trigger_price, None);
3700        assert!(updated.venue_order_id.is_some());
3701    }
3702
3703    #[rstest]
3704    fn test_dispatch_order_updated_on_quantity_change() {
3705        let mut ctx = DispatchTestContext::new();
3706        let value = new_order_value();
3707        ctx.accept_order(&value);
3708
3709        let mut amended = value;
3710        amended["data"][0]["qty"] = serde_json::Value::String("0.020".to_string());
3711        ctx.dispatch_value(&amended);
3712
3713        let updated = ctx.recv_updated();
3714        assert_eq!(updated.quantity, Quantity::from("0.020"));
3715        assert_eq!(updated.price, Some(Price::from("30000.00")));
3716    }
3717
3718    #[rstest]
3719    fn test_dispatch_order_updated_on_trigger_price_change() {
3720        let mut ctx = DispatchTestContext::new();
3721        let mut value = new_order_value();
3722        value["data"][0]["triggerPrice"] = serde_json::Value::String("29000".to_string());
3723        ctx.accept_order(&value);
3724
3725        let mut amended = value;
3726        amended["data"][0]["triggerPrice"] = serde_json::Value::String("28000".to_string());
3727        ctx.dispatch_value(&amended);
3728
3729        let updated = ctx.recv_updated();
3730        assert_eq!(updated.trigger_price, Some(Price::from("28000.00")));
3731        assert_eq!(updated.price, Some(Price::from("30000.00")));
3732    }
3733
3734    #[rstest]
3735    fn test_dispatch_dedup_suppresses_identical_after_snapshot() {
3736        let mut ctx = DispatchTestContext::new();
3737        let value = new_order_value();
3738        ctx.accept_order(&value);
3739
3740        ctx.dispatch_value(&value);
3741
3742        assert!(
3743            ctx.rx.try_recv().is_err(),
3744            "Expected no event for identical redelivery"
3745        );
3746    }
3747
3748    #[rstest]
3749    fn test_dispatch_order_updated_stores_snapshot_for_subsequent_change() {
3750        let mut ctx = DispatchTestContext::new();
3751        let value = new_order_value();
3752        ctx.accept_order(&value);
3753
3754        let mut amended1 = value.clone();
3755        amended1["data"][0]["price"] = serde_json::Value::String("31000".to_string());
3756        ctx.dispatch_value(&amended1);
3757        let _result = ctx.recv_updated();
3758
3759        let mut amended2 = value;
3760        amended2["data"][0]["price"] = serde_json::Value::String("32000".to_string());
3761        ctx.dispatch_value(&amended2);
3762
3763        let updated = ctx.recv_updated();
3764        assert_eq!(updated.price, Some(Price::from("32000.00")));
3765    }
3766
3767    #[rstest]
3768    fn test_dispatch_accepted_with_seeded_snapshot_emits_updated_for_bbo() {
3769        let mut ctx = DispatchTestContext::new();
3770        let value = new_order_value();
3771        let cid = ClientOrderId::from("client-1");
3772        ctx.state.order_identities.insert(cid, default_identity());
3773        ctx.state.order_snapshots.insert(
3774            cid,
3775            OrderStateSnapshot {
3776                quantity: Quantity::from("0.010"),
3777                price: Some(Price::from("29000.00")),
3778                trigger_price: None,
3779            },
3780        );
3781
3782        ctx.dispatch_value(&value);
3783
3784        let accepted = ctx.rx.try_recv().unwrap();
3785        assert!(
3786            matches!(accepted, ExecutionEvent::Order(OrderEventAny::Accepted(_))),
3787            "Expected Accepted first, found {accepted:?}"
3788        );
3789
3790        let updated = ctx.recv_updated();
3791        assert_eq!(updated.client_order_id, cid);
3792        assert_eq!(updated.price, Some(Price::from("30000.00")));
3793        assert_eq!(updated.quantity, Quantity::from("0.010"));
3794        assert!(updated.venue_order_id.is_some());
3795    }
3796
3797    #[rstest]
3798    fn test_emit_rejection_for_place_clears_snapshot() {
3799        let ctx = DispatchTestContext::new();
3800        let cid = ClientOrderId::from("client-1");
3801        let identity = default_identity();
3802        ctx.state.order_identities.insert(cid, identity.clone());
3803        ctx.state.order_snapshots.insert(
3804            cid,
3805            OrderStateSnapshot {
3806                quantity: Quantity::from("0.010"),
3807                price: Some(Price::from("30000.00")),
3808                trigger_price: None,
3809            },
3810        );
3811
3812        emit_rejection_for_op(
3813            &PendingOperation::Place,
3814            cid,
3815            &identity,
3816            None,
3817            "rejected",
3818            &ctx.emitter,
3819            &ctx.state,
3820            UnixNanos::from(1u64),
3821            None,
3822        );
3823
3824        assert!(!ctx.state.order_identities.contains_key(&cid));
3825        assert!(!ctx.state.order_snapshots.contains_key(&cid));
3826    }
3827
3828    fn order_response(
3829        op: &str,
3830        ret_code: i64,
3831        ret_msg: &str,
3832        req_id: &str,
3833        data: serde_json::Value,
3834        ret_ext_info: Option<serde_json::Value>,
3835    ) -> BybitWsOrderResponse {
3836        BybitWsOrderResponse {
3837            op: Ustr::from(op),
3838            conn_id: Some("test-conn-id".to_string()),
3839            ret_code,
3840            ret_msg: ret_msg.to_string(),
3841            data,
3842            req_id: Some(req_id.to_string()),
3843            header: None,
3844            ret_ext_info,
3845        }
3846    }
3847
3848    #[rstest]
3849    fn test_dispatch_local_not_sent_emits_order_rejected() {
3850        let mut ctx = DispatchTestContext::new();
3851        let cid = ClientOrderId::from("not-sent-1");
3852        ctx.state.order_identities.insert(cid, default_identity());
3853        ctx.state.pending_requests.insert(
3854            "req-not-sent".to_string(),
3855            (vec![cid], vec![None], PendingOperation::Place, Vec::new()),
3856        );
3857        dispatch_order_not_sent(
3858            "req-not-sent",
3859            "Order command was not written",
3860            &ctx.emitter,
3861            &ctx.state,
3862            UnixNanos::from(1u64),
3863        );
3864
3865        let event = ctx.rx.try_recv().expect("expected OrderRejected event");
3866        assert!(
3867            matches!(event, ExecutionEvent::Order(OrderEventAny::Rejected(ref rejected))
3868                if rejected.client_order_id == cid
3869                    && rejected.reason == "Order command was not written"),
3870            "Expected OrderRejected for {cid}, found {event:?}"
3871        );
3872        assert!(!ctx.state.order_identities.contains_key(&cid));
3873        assert!(!ctx.state.pending_requests.contains_key("req-not-sent"));
3874    }
3875
3876    #[rstest]
3877    #[case::modify(PendingOperation::Amend)]
3878    #[case::cancel(PendingOperation::Cancel)]
3879    fn test_dispatch_local_refusal_preserves_each_command(#[case] operation: PendingOperation) {
3880        let mut ctx = DispatchTestContext::new();
3881        let first = ClientOrderId::from("O-LOCAL-FIRST");
3882        let second = ClientOrderId::from("O-LOCAL-SECOND");
3883        let first_cause = UUID4::new();
3884        let second_cause = UUID4::new();
3885        let venue_order_id = VenueOrderId::from("V-LOCAL-FIRST");
3886        ctx.state.order_identities.insert(first, default_identity());
3887        ctx.state
3888            .order_identities
3889            .insert(second, default_identity());
3890        ctx.state.pending_requests.insert(
3891            "req-local".to_string(),
3892            (
3893                vec![first, second],
3894                vec![Some(venue_order_id), None],
3895                operation,
3896                vec![Some(first_cause), Some(second_cause)],
3897            ),
3898        );
3899        dispatch_order_not_sent(
3900            "req-local",
3901            "Command was not written",
3902            &ctx.emitter,
3903            &ctx.state,
3904            UnixNanos::from(17),
3905        );
3906
3907        for (client_order_id, cause, venue) in [
3908            (first, first_cause, Some(venue_order_id)),
3909            (second, second_cause, None),
3910        ] {
3911            let ExecutionEvent::Order(event) = ctx.rx.try_recv().unwrap() else {
3912                panic!("expected order outcome")
3913            };
3914
3915            let (actual_cause, reason) = match (operation, &event) {
3916                (PendingOperation::Amend, OrderEventAny::ModifyDenied(event)) => {
3917                    (event.causation_id, event.reason.as_str())
3918                }
3919                (PendingOperation::Cancel, OrderEventAny::CancelDenied(event)) => {
3920                    (event.causation_id, event.reason.as_str())
3921                }
3922                _ => panic!("unexpected refusal {event:?}"),
3923            };
3924
3925            assert_eq!(actual_cause, Some(cause));
3926            assert_eq!(reason, "Command was not written");
3927            assert_eq!(event.client_order_id(), client_order_id);
3928            assert_eq!(event.venue_order_id(), venue);
3929            assert_eq!(event.strategy_id(), default_identity().strategy_id);
3930            assert_eq!(event.instrument_id(), default_identity().instrument_id);
3931            assert_eq!(event.ts_event(), UnixNanos::from(17));
3932        }
3933
3934        assert!(ctx.rx.try_recv().is_err());
3935        assert!(!ctx.state.pending_requests.contains_key("req-local"));
3936        assert!(ctx.state.order_identities.contains_key(&first));
3937        assert!(ctx.state.order_identities.contains_key(&second));
3938    }
3939
3940    #[rstest]
3941    fn test_dispatch_single_cancel_rejection_emits_cancel_rejected() {
3942        let mut ctx = DispatchTestContext::new();
3943        let cause = UUID4::new();
3944        let cid = ClientOrderId::from("cancel-reject-1");
3945        let venue_order_id = VenueOrderId::from("venue-cancel-1");
3946        ctx.state.order_identities.insert(cid, default_identity());
3947        ctx.state.pending_requests.insert(
3948            "req-cancel".to_string(),
3949            (
3950                vec![cid],
3951                vec![Some(venue_order_id)],
3952                PendingOperation::Cancel,
3953                vec![Some(cause)],
3954            ),
3955        );
3956
3957        let response = order_response(
3958            BYBIT_OP_ORDER_CANCEL,
3959            110001,
3960            "Order does not exist.",
3961            "req-cancel",
3962            serde_json::json!({
3963                "orderId": venue_order_id.to_string(),
3964                "orderLinkId": cid.to_string(),
3965            }),
3966            None,
3967        );
3968
3969        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
3970
3971        let event = ctx.rx.try_recv().expect("expected CancelRejected event");
3972        assert!(
3973            matches!(event, ExecutionEvent::Order(OrderEventAny::CancelRejected(ref rejected)) if rejected.client_order_id == cid && rejected.causation_id == Some(cause)),
3974            "Expected CancelRejected for {cid}, found {event:?}"
3975        );
3976        assert!(
3977            ctx.rx.try_recv().is_err(),
3978            "Expected no extra events for single cancel rejection"
3979        );
3980    }
3981
3982    #[rstest]
3983    fn test_dispatch_single_modify_rejection_emits_modify_rejected() {
3984        let mut ctx = DispatchTestContext::new();
3985        let cause = UUID4::new();
3986        let cid = ClientOrderId::from("modify-reject-1");
3987        let venue_order_id = VenueOrderId::from("venue-modify-1");
3988        ctx.state.order_identities.insert(cid, default_identity());
3989        ctx.state.pending_requests.insert(
3990            "req-modify".to_string(),
3991            (
3992                vec![cid],
3993                vec![Some(venue_order_id)],
3994                PendingOperation::Amend,
3995                vec![Some(cause)],
3996            ),
3997        );
3998
3999        let response = order_response(
4000            BYBIT_OP_ORDER_AMEND,
4001            110003,
4002            "Order price exceeds allowable range.",
4003            "req-modify",
4004            serde_json::json!({
4005                "orderId": venue_order_id.to_string(),
4006                "orderLinkId": cid.to_string(),
4007            }),
4008            None,
4009        );
4010
4011        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4012
4013        let event = ctx.rx.try_recv().expect("expected ModifyRejected event");
4014        assert!(
4015            matches!(event, ExecutionEvent::Order(OrderEventAny::ModifyRejected(ref rejected)) if rejected.client_order_id == cid && rejected.causation_id == Some(cause)),
4016            "Expected ModifyRejected for {cid}, found {event:?}"
4017        );
4018        assert!(
4019            ctx.rx.try_recv().is_err(),
4020            "Expected no extra events for single modify rejection"
4021        );
4022    }
4023
4024    #[rstest]
4025    fn test_dispatch_single_place_rejection_emits_order_rejected() {
4026        let mut ctx = DispatchTestContext::new();
4027        let cid = ClientOrderId::from("place-reject-1");
4028        ctx.state.order_identities.insert(cid, default_identity());
4029        ctx.state.pending_requests.insert(
4030            "req-place".to_string(),
4031            (vec![cid], vec![None], PendingOperation::Place, Vec::new()),
4032        );
4033
4034        let response = order_response(
4035            BYBIT_OP_ORDER_CREATE,
4036            110017,
4037            "orderQty will be truncated to zero",
4038            "req-place",
4039            serde_json::json!({
4040                "orderLinkId": cid.to_string(),
4041            }),
4042            None,
4043        );
4044
4045        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4046
4047        let event = ctx.rx.try_recv().expect("expected OrderRejected event");
4048        assert!(
4049            matches!(event, ExecutionEvent::Order(OrderEventAny::Rejected(ref rejected))
4050                if rejected.client_order_id == cid
4051                    && rejected.reason == "orderQty will be truncated to zero"),
4052            "Expected OrderRejected for {cid}, found {event:?}"
4053        );
4054        assert!(ctx.rx.try_recv().is_err());
4055        assert!(!ctx.state.order_identities.contains_key(&cid));
4056    }
4057
4058    #[rstest]
4059    #[case::place_frequency(PendingOperation::Place, BYBIT_OP_ORDER_CREATE, 10429)]
4060    #[case::amend_frequency(PendingOperation::Amend, BYBIT_OP_ORDER_AMEND, 10429)]
4061    #[case::cancel_frequency(PendingOperation::Cancel, BYBIT_OP_ORDER_CANCEL, 10429)]
4062    #[case::place_visits(PendingOperation::Place, BYBIT_OP_ORDER_CREATE, 10006)]
4063    #[case::amend_visits(PendingOperation::Amend, BYBIT_OP_ORDER_AMEND, 10006)]
4064    #[case::cancel_visits(PendingOperation::Cancel, BYBIT_OP_ORDER_CANCEL, 10006)]
4065    fn test_dispatch_single_rate_limit_emits_no_terminal_rejection(
4066        #[case] operation: PendingOperation,
4067        #[case] op: &str,
4068        #[case] ret_code: i64,
4069    ) {
4070        let mut ctx = DispatchTestContext::new();
4071        let cid = ClientOrderId::from("rate-limit-1");
4072        let venue_order_id = VenueOrderId::from("venue-rate-limit-1");
4073        ctx.state.order_identities.insert(cid, default_identity());
4074        ctx.state.pending_requests.insert(
4075            "req-rate-limit".to_string(),
4076            (vec![cid], vec![Some(venue_order_id)], operation, Vec::new()),
4077        );
4078
4079        let response = order_response(
4080            op,
4081            ret_code,
4082            "rate limit",
4083            "req-rate-limit",
4084            serde_json::json!({
4085                "orderId": venue_order_id.to_string(),
4086                "orderLinkId": cid.to_string(),
4087            }),
4088            None,
4089        );
4090
4091        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4092
4093        assert!(
4094            ctx.rx.try_recv().is_err(),
4095            "Rate-limit response must not emit a terminal rejection"
4096        );
4097        assert!(ctx.state.order_identities.contains_key(&cid));
4098        assert!(!ctx.state.pending_requests.contains_key("req-rate-limit"));
4099    }
4100
4101    #[rstest]
4102    fn test_dispatch_single_modify_server_error_keeps_outcome_unresolved() {
4103        let mut ctx = DispatchTestContext::new();
4104        let cid = ClientOrderId::from("modify-server-error-1");
4105        let venue_order_id = VenueOrderId::from("venue-modify-server-error-1");
4106        ctx.state.order_identities.insert(cid, default_identity());
4107        ctx.state.pending_requests.insert(
4108            "req-modify-server-error".to_string(),
4109            (
4110                vec![cid],
4111                vec![Some(venue_order_id)],
4112                PendingOperation::Amend,
4113                Vec::new(),
4114            ),
4115        );
4116
4117        let response = order_response(
4118            BYBIT_OP_ORDER_AMEND,
4119            10016,
4120            "Internal server error.",
4121            "req-modify-server-error",
4122            serde_json::json!({
4123                "orderId": venue_order_id.to_string(),
4124                "orderLinkId": cid.to_string(),
4125            }),
4126            None,
4127        );
4128
4129        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4130
4131        assert!(
4132            ctx.rx.try_recv().is_err(),
4133            "Expected no ModifyRejected event for server error response"
4134        );
4135        assert!(ctx.state.order_identities.contains_key(&cid));
4136    }
4137
4138    #[rstest]
4139    fn test_dispatch_batch_cancel_top_level_failure_does_not_emit_cancel_rejected() {
4140        let mut ctx = DispatchTestContext::new();
4141        let cid_1 = ClientOrderId::from("batch-cancel-1");
4142        let cid_2 = ClientOrderId::from("batch-cancel-2");
4143        ctx.state.order_identities.insert(cid_1, default_identity());
4144        ctx.state.order_identities.insert(cid_2, default_identity());
4145        ctx.state.pending_requests.insert(
4146            "req-batch-cancel".to_string(),
4147            (
4148                vec![cid_1, cid_2],
4149                vec![
4150                    Some(VenueOrderId::from("venue-batch-1")),
4151                    Some(VenueOrderId::from("venue-batch-2")),
4152                ],
4153                PendingOperation::Cancel,
4154                Vec::new(),
4155            ),
4156        );
4157
4158        let response = order_response(
4159            BYBIT_OP_ORDER_CANCEL_BATCH,
4160            10016,
4161            "Internal server error.",
4162            "req-batch-cancel",
4163            serde_json::json!({}),
4164            None,
4165        );
4166
4167        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4168
4169        assert!(
4170            ctx.rx.try_recv().is_err(),
4171            "Expected no CancelRejected events for ambiguous batch failure"
4172        );
4173        assert!(ctx.state.order_identities.contains_key(&cid_1));
4174        assert!(ctx.state.order_identities.contains_key(&cid_2));
4175    }
4176
4177    #[rstest]
4178    fn test_dispatch_single_item_batch_cancel_top_level_failure_does_not_emit_cancel_rejected() {
4179        let mut ctx = DispatchTestContext::new();
4180        let cid = ClientOrderId::from("batch-cancel-single");
4181        ctx.state.order_identities.insert(cid, default_identity());
4182        ctx.state.pending_requests.insert(
4183            "req-batch-cancel-single".to_string(),
4184            (
4185                vec![cid],
4186                vec![Some(VenueOrderId::from("venue-batch-single"))],
4187                PendingOperation::Cancel,
4188                Vec::new(),
4189            ),
4190        );
4191
4192        let response = order_response(
4193            BYBIT_OP_ORDER_CANCEL_BATCH,
4194            10016,
4195            "Internal server error.",
4196            "req-batch-cancel-single",
4197            serde_json::json!({}),
4198            None,
4199        );
4200
4201        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4202
4203        assert!(
4204            ctx.rx.try_recv().is_err(),
4205            "Expected no CancelRejected event for ambiguous one-item batch failure"
4206        );
4207        assert!(ctx.state.order_identities.contains_key(&cid));
4208    }
4209
4210    #[rstest]
4211    #[case::place(PendingOperation::Place, BYBIT_OP_ORDER_CREATE_BATCH, 10429)]
4212    #[case::amend(PendingOperation::Amend, BYBIT_OP_ORDER_AMEND_BATCH, 10429)]
4213    #[case::cancel(PendingOperation::Cancel, BYBIT_OP_ORDER_CANCEL_BATCH, 10006)]
4214    fn test_dispatch_batch_top_level_rate_limit_emits_no_terminal_rejection(
4215        #[case] operation: PendingOperation,
4216        #[case] op: &str,
4217        #[case] ret_code: i64,
4218    ) {
4219        let mut ctx = DispatchTestContext::new();
4220        let cid_1 = ClientOrderId::from("batch-rate-1");
4221        let cid_2 = ClientOrderId::from("batch-rate-2");
4222        ctx.state.order_identities.insert(cid_1, default_identity());
4223        ctx.state.order_identities.insert(cid_2, default_identity());
4224        ctx.state.pending_requests.insert(
4225            "req-batch-rate".to_string(),
4226            (
4227                vec![cid_1, cid_2],
4228                vec![
4229                    Some(VenueOrderId::from("venue-rate-1")),
4230                    Some(VenueOrderId::from("venue-rate-2")),
4231                ],
4232                operation,
4233                Vec::new(),
4234            ),
4235        );
4236
4237        let response = order_response(
4238            op,
4239            ret_code,
4240            "rate limit",
4241            "req-batch-rate",
4242            serde_json::json!({}),
4243            None,
4244        );
4245
4246        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4247
4248        assert!(
4249            ctx.rx.try_recv().is_err(),
4250            "Batch rate-limit response must not emit a terminal rejection"
4251        );
4252        assert!(ctx.state.order_identities.contains_key(&cid_1));
4253        assert!(ctx.state.order_identities.contains_key(&cid_2));
4254        assert!(!ctx.state.pending_requests.contains_key("req-batch-rate"));
4255    }
4256
4257    #[rstest]
4258    fn test_dispatch_batch_cancel_per_item_error_emits_only_failed_item(
4259        #[values(false, true)] repeated: bool,
4260    ) {
4261        let mut ctx = DispatchTestContext::new();
4262        let cid_1 = ClientOrderId::from("batch-cancel-ok");
4263        let cid_2 = if repeated {
4264            cid_1
4265        } else {
4266            ClientOrderId::from("batch-cancel-reject")
4267        };
4268
4269        let causes = [UUID4::new(), UUID4::new()];
4270        ctx.state.order_identities.insert(cid_1, default_identity());
4271        ctx.state.order_identities.insert(cid_2, default_identity());
4272        ctx.state.pending_requests.insert(
4273            "req-batch-mixed".to_string(),
4274            (
4275                vec![cid_1, cid_2],
4276                vec![
4277                    Some(VenueOrderId::from("venue-batch-ok")),
4278                    Some(VenueOrderId::from("venue-batch-reject")),
4279                ],
4280                PendingOperation::Cancel,
4281                causes.into_iter().map(Some).collect(),
4282            ),
4283        );
4284
4285        let response = order_response(
4286            BYBIT_OP_ORDER_CANCEL_BATCH,
4287            0,
4288            "OK",
4289            "req-batch-mixed",
4290            serde_json::json!({
4291                "list": [
4292                    {"orderId": "venue-batch-ok", "orderLinkId": cid_1.to_string()},
4293                    {"orderId": "venue-batch-reject", "orderLinkId": cid_2.to_string()}
4294                ]
4295            }),
4296            Some(serde_json::json!({
4297                "list": [
4298                    {"code": 0, "msg": "OK"},
4299                    {"code": 170213, "msg": "Order does not exist."}
4300                ]
4301            })),
4302        );
4303
4304        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4305
4306        let event = ctx.rx.try_recv().expect("expected CancelRejected event");
4307        assert!(
4308            matches!(event, ExecutionEvent::Order(OrderEventAny::CancelRejected(ref rejected)) if rejected.client_order_id == cid_2 && rejected.causation_id == Some(causes[1])),
4309            "Expected CancelRejected for failed batch item {cid_2}, found {event:?}"
4310        );
4311        assert!(
4312            ctx.rx.try_recv().is_err(),
4313            "Expected no CancelRejected event for successful batch item"
4314        );
4315    }
4316
4317    #[rstest]
4318    #[case::place(PendingOperation::Place, BYBIT_OP_ORDER_CREATE_BATCH, 10006)]
4319    #[case::amend(PendingOperation::Amend, BYBIT_OP_ORDER_AMEND_BATCH, 10429)]
4320    #[case::cancel(PendingOperation::Cancel, BYBIT_OP_ORDER_CANCEL_BATCH, 10006)]
4321    fn test_dispatch_batch_per_item_rate_limit_emits_no_terminal_rejection(
4322        #[case] operation: PendingOperation,
4323        #[case] op: &str,
4324        #[case] code: i64,
4325    ) {
4326        let mut ctx = DispatchTestContext::new();
4327        let cid = ClientOrderId::from("batch-item-rate-limit");
4328        let venue_order_id = VenueOrderId::from("venue-batch-rate-limit");
4329        ctx.state.order_identities.insert(cid, default_identity());
4330        ctx.state.pending_requests.insert(
4331            "req-batch-item-rate-limit".to_string(),
4332            (vec![cid], vec![Some(venue_order_id)], operation, Vec::new()),
4333        );
4334
4335        let response = order_response(
4336            op,
4337            0,
4338            "OK",
4339            "req-batch-item-rate-limit",
4340            serde_json::json!({
4341                "list": [
4342                    {"orderId": venue_order_id.to_string(), "orderLinkId": cid.to_string()}
4343                ]
4344            }),
4345            Some(serde_json::json!({
4346                "list": [
4347                    {"code": code, "msg": "rate limit"}
4348                ]
4349            })),
4350        );
4351
4352        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4353
4354        assert!(
4355            ctx.rx.try_recv().is_err(),
4356            "Per-item rate-limit response must not emit a terminal rejection"
4357        );
4358        assert!(ctx.state.order_identities.contains_key(&cid));
4359        assert!(
4360            !ctx.state
4361                .pending_requests
4362                .contains_key("req-batch-item-rate-limit")
4363        );
4364    }
4365
4366    #[rstest]
4367    fn test_dispatch_filled_with_seeded_snapshot_emits_updated_for_bbo() {
4368        let mut ctx = DispatchTestContext::new();
4369        let mut value = new_order_value();
4370        value["data"][0]["orderStatus"] = serde_json::Value::String("Filled".to_string());
4371        value["data"][0]["cumExecQty"] = serde_json::Value::String("0.010".to_string());
4372        let cid = ClientOrderId::from("client-1");
4373        ctx.state.order_identities.insert(cid, default_identity());
4374        ctx.state.order_snapshots.insert(
4375            cid,
4376            OrderStateSnapshot {
4377                quantity: Quantity::from("0.010"),
4378                price: Some(Price::from("29000.00")),
4379                trigger_price: None,
4380            },
4381        );
4382
4383        ctx.dispatch_value(&value);
4384
4385        let accepted_event = ctx.rx.try_recv().unwrap();
4386        let accepted = match accepted_event {
4387            ExecutionEvent::Order(OrderEventAny::Accepted(accepted)) => accepted,
4388            other => panic!("Expected Accepted first, found {other:?}"),
4389        };
4390        assert_eq!(accepted.client_order_id, cid);
4391        assert!(!accepted.venue_order_id.to_string().is_empty());
4392
4393        let updated = ctx.recv_updated();
4394        assert_eq!(updated.client_order_id, cid);
4395        assert_eq!(updated.price, Some(Price::from("30000.00")));
4396        assert_eq!(updated.quantity, Quantity::from("0.010"));
4397        assert_eq!(updated.trigger_price, None);
4398        assert_eq!(updated.venue_order_id, Some(accepted.venue_order_id));
4399
4400        let stored = ctx.state.order_snapshots.get(&cid).unwrap();
4401        assert_eq!(stored.price, Some(Price::from("30000.00")));
4402    }
4403
4404    #[rstest]
4405    fn test_dispatch_accepted_with_matching_seeded_snapshot_no_updated() {
4406        let mut ctx = DispatchTestContext::new();
4407        let value = new_order_value();
4408        let cid = ClientOrderId::from("client-1");
4409        ctx.state.order_identities.insert(cid, default_identity());
4410        ctx.state.order_snapshots.insert(
4411            cid,
4412            OrderStateSnapshot {
4413                quantity: Quantity::from("0.010"),
4414                price: Some(Price::from("30000.00")),
4415                trigger_price: None,
4416            },
4417        );
4418
4419        ctx.dispatch_value(&value);
4420
4421        let accepted = ctx.rx.try_recv().unwrap();
4422        assert!(matches!(
4423            accepted,
4424            ExecutionEvent::Order(OrderEventAny::Accepted(_))
4425        ));
4426
4427        assert!(
4428            ctx.rx.try_recv().is_err(),
4429            "Expected no OrderUpdated when seed matches venue snapshot"
4430        );
4431    }
4432
4433    #[rstest]
4434    #[case::price_changed(
4435        Some(Price::from("100.00")),
4436        None,
4437        Quantity::from("1.000"),
4438        Some(Price::from("200.00")),
4439        None,
4440        Quantity::from("1.000"),
4441        true
4442    )]
4443    #[case::trigger_changed(
4444        None,
4445        Some(Price::from("100.00")),
4446        Quantity::from("1.000"),
4447        None,
4448        Some(Price::from("90.00")),
4449        Quantity::from("1.000"),
4450        true
4451    )]
4452    #[case::qty_changed(
4453        Some(Price::from("100.00")),
4454        None,
4455        Quantity::from("1.000"),
4456        Some(Price::from("100.00")),
4457        None,
4458        Quantity::from("2.000"),
4459        true
4460    )]
4461    #[case::no_change(
4462        Some(Price::from("100.00")),
4463        None,
4464        Quantity::from("1.000"),
4465        Some(Price::from("100.00")),
4466        None,
4467        Quantity::from("1.000"),
4468        false
4469    )]
4470    fn test_is_snapshot_updated(
4471        #[case] prev_price: Option<Price>,
4472        #[case] prev_trigger: Option<Price>,
4473        #[case] prev_qty: Quantity,
4474        #[case] new_price: Option<Price>,
4475        #[case] new_trigger: Option<Price>,
4476        #[case] new_qty: Quantity,
4477        #[case] expected: bool,
4478    ) {
4479        let state = WsDispatchState::default();
4480        let cid = ClientOrderId::from("test-1");
4481        state.order_snapshots.insert(
4482            cid,
4483            OrderStateSnapshot {
4484                quantity: prev_qty,
4485                price: prev_price,
4486                trigger_price: prev_trigger,
4487            },
4488        );
4489
4490        let new_snapshot = OrderStateSnapshot {
4491            quantity: new_qty,
4492            price: new_price,
4493            trigger_price: new_trigger,
4494        };
4495        assert_eq!(is_snapshot_updated(&new_snapshot, &cid, &state), expected);
4496    }
4497
4498    #[rstest]
4499    fn test_is_snapshot_updated_no_previous() {
4500        let state = WsDispatchState::default();
4501        let cid = ClientOrderId::from("test-1");
4502
4503        let new_snapshot = OrderStateSnapshot {
4504            quantity: Quantity::from("1.000"),
4505            price: Some(Price::from("100.00")),
4506            trigger_price: None,
4507        };
4508        assert!(!is_snapshot_updated(&new_snapshot, &cid, &state));
4509    }
4510
4511    #[rstest]
4512    #[case::limit_order("30000", "0", Some(Price::from("30000.00")), None)]
4513    #[case::conditional("0", "29000", None, Some(Price::from("29000.00")))]
4514    #[case::both(
4515        "30000",
4516        "29000",
4517        Some(Price::from("30000.00")),
4518        Some(Price::from("29000.00"))
4519    )]
4520    fn test_parse_order_snapshot(
4521        #[case] price: &str,
4522        #[case] trigger: &str,
4523        #[case] expected_price: Option<Price>,
4524        #[case] expected_trigger: Option<Price>,
4525    ) {
4526        let instrument = linear_instrument();
4527        let json = load_test_json("ws_account_order.json");
4528        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
4529        value["data"][0]["price"] = serde_json::Value::String(price.to_string());
4530        value["data"][0]["triggerPrice"] = serde_json::Value::String(trigger.to_string());
4531        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
4532            serde_json::from_value(value).unwrap();
4533
4534        let snapshot = parse_order_snapshot(&msg.data[0], &instrument).unwrap();
4535        assert_eq!(snapshot.price, expected_price);
4536        assert_eq!(snapshot.trigger_price, expected_trigger);
4537        assert_eq!(snapshot.quantity, Quantity::from("0.010"));
4538    }
4539
4540    #[rstest]
4541    fn test_parse_order_snapshot_invalid_qty_returns_none() {
4542        let instrument = linear_instrument();
4543        let json = load_test_json("ws_account_order.json");
4544        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
4545        value["data"][0]["qty"] = serde_json::Value::String(String::new());
4546        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
4547            serde_json::from_value(value).unwrap();
4548
4549        assert!(parse_order_snapshot(&msg.data[0], &instrument).is_none());
4550    }
4551
4552    #[rstest]
4553    fn test_dispatch_order_updated_on_partially_filled_price_change() {
4554        let mut ctx = DispatchTestContext::new();
4555        let value = new_order_value();
4556        ctx.accept_order(&value);
4557
4558        let mut amended = value;
4559        amended["data"][0]["orderStatus"] =
4560            serde_json::Value::String("PartiallyFilled".to_string());
4561        amended["data"][0]["cumExecQty"] = serde_json::Value::String("0.005".to_string());
4562        amended["data"][0]["price"] = serde_json::Value::String("31000".to_string());
4563        ctx.dispatch_value(&amended);
4564
4565        let updated = ctx.recv_updated();
4566        assert_eq!(updated.client_order_id, ClientOrderId::from("client-1"));
4567        assert_eq!(updated.price, Some(Price::from("31000.00")));
4568    }
4569}