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. A fill whose
1061/// commission cannot be derived emits no report and releases its trade ID, leaving the
1062/// fill to execution reconciliation. Liquidity side is derived from
1063/// the payload's `isMaker` flag. Subscribe to the standard `execution` channel for
1064/// venue-authoritative fees.
1065fn dispatch_execution_fill_fast(
1066    exec: &BybitWsAccountExecutionFast,
1067    instrument: &InstrumentAny,
1068    account_id: AccountId,
1069    ts_init: UnixNanos,
1070    defer_untracked: bool,
1071    state: &WsDispatchState,
1072    emitter: &ExecutionEventEmitter,
1073) {
1074    let Ok(trade_id) = TradeId::new_checked(exec.exec_id.as_str()) else {
1075        log::error!(
1076            "Invalid execId in Bybit WebSocket fast-execution payload: {}",
1077            exec.exec_id
1078        );
1079        return;
1080    };
1081
1082    if defer_untracked && !state.insert_fast_execution(trade_id) {
1083        log::debug!("Skipping duplicate fast execution: {trade_id}");
1084        return;
1085    }
1086
1087    let venue_order_id = VenueOrderId::new(exec.order_id);
1088    let client_order_id = if exec.order_link_id.is_empty() {
1089        let venue_mapping = state.venue_order_ids.entry(venue_order_id);
1090
1091        let client_order_id = match &venue_mapping {
1092            Entry::Occupied(entry) => Some(*entry.get()),
1093            Entry::Vacant(_) => None,
1094        };
1095
1096        // Hold the mapping guard through any pending enqueue so REST correlation cannot interleave
1097        if client_order_id.is_none()
1098            && defer_untracked
1099            && !state.untracked_order_ids.contains(&venue_order_id)
1100        {
1101            state
1102                .pending_fast_executions
1103                .entry(venue_order_id)
1104                .or_default()
1105                .push(exec.clone());
1106            return;
1107        }
1108
1109        client_order_id
1110    } else {
1111        Some(ClientOrderId::new(exec.order_link_id))
1112    };
1113
1114    let identity = client_order_id
1115        .as_ref()
1116        .and_then(|cid| state.order_identities.get(cid).map(|r| r.clone()));
1117
1118    let venue_position_id =
1119        if let (Some(client_order_id), Some(identity)) = (client_order_id, identity.as_ref()) {
1120            ensure_accepted_emitted(
1121                client_order_id,
1122                account_id,
1123                venue_order_id,
1124                identity,
1125                ts_init,
1126                state,
1127                emitter,
1128            );
1129            identity.venue_position_id
1130        } else {
1131            None
1132        };
1133
1134    let fee_rates = state.fee_rates.get(&instrument.id()).map(|rates| *rates);
1135
1136    match parse_ws_fill_report_fast(
1137        exec,
1138        account_id,
1139        instrument,
1140        fee_rates,
1141        client_order_id,
1142        venue_position_id,
1143        ts_init,
1144    ) {
1145        Ok(report) => {
1146            let last_qty = report.last_qty;
1147            emitter.send_fill_report(report);
1148
1149            if let Some(client_order_id) = client_order_id
1150                && identity.is_some()
1151            {
1152                state.insert_filled(client_order_id);
1153                record_fast_fill(client_order_id, last_qty, state);
1154            }
1155        }
1156        Err(e) => {
1157            state.remove_fast_execution(trade_id);
1158            log::error!("Failed to parse fast fill report for {trade_id}: {e:#}");
1159        }
1160    }
1161}
1162
1163/// Parses a Bybit execution message directly into an [`OrderFilled`] event.
1164fn parse_order_filled(
1165    exec: &BybitWsAccountExecution,
1166    instrument: &InstrumentAny,
1167    identity: &OrderIdentity,
1168    emitter: &ExecutionEventEmitter,
1169    account_id: AccountId,
1170    ts_init: UnixNanos,
1171) -> anyhow::Result<OrderFilled> {
1172    let client_order_id = ClientOrderId::new(exec.order_link_id);
1173    let venue_order_id = VenueOrderId::new(exec.order_id);
1174    let trade_id =
1175        TradeId::new_checked(exec.exec_id.as_str()).context("invalid execId in Bybit execution")?;
1176
1177    let last_qty = parse_quantity_with_precision(
1178        &exec.exec_qty,
1179        instrument.size_precision(),
1180        "execution.execQty",
1181    )?;
1182    let last_px = parse_price_with_precision(
1183        &exec.exec_price,
1184        instrument.price_precision(),
1185        "execution.execPrice",
1186    )?;
1187
1188    let liquidity_side = if exec.is_maker {
1189        LiquiditySide::Maker
1190    } else {
1191        LiquiditySide::Taker
1192    };
1193
1194    let fee_decimal: Decimal = exec
1195        .exec_fee
1196        .parse()
1197        .with_context(|| format!("failed to parse execFee='{}'", exec.exec_fee))?;
1198    let price_currency = instrument.quote_currency();
1199    let commission_currency = get_currency(&exec.fee_currency);
1200
1201    let commission = Money::from_decimal(fee_decimal, commission_currency).with_context(|| {
1202        format!(
1203            "failed to create commission from execFee='{}'",
1204            exec.exec_fee
1205        )
1206    })?;
1207
1208    let ts_event = parse_millis_timestamp(&exec.exec_time, "execution.execTime")?;
1209
1210    Ok(OrderFilled::new(
1211        emitter.trader_id(),
1212        identity.strategy_id,
1213        identity.instrument_id,
1214        client_order_id,
1215        venue_order_id,
1216        account_id,
1217        trade_id,
1218        identity.order_side,
1219        identity.order_type,
1220        last_qty,
1221        last_px,
1222        price_currency,
1223        liquidity_side,
1224        UUID4::new(),
1225        ts_event,
1226        ts_init,
1227        false,
1228        identity.venue_position_id,
1229        Some(commission),
1230        None,
1231    ))
1232}
1233
1234/// Handles a Bybit WS order command response.
1235fn dispatch_order_response(
1236    resp: &super::messages::BybitWsOrderResponse,
1237    emitter: &ExecutionEventEmitter,
1238    state: &WsDispatchState,
1239    ts_init: UnixNanos,
1240) {
1241    if resp.ret_code == 0 {
1242        // Check for per-order failures in batch retExtInfo even on success
1243        let pending = resp
1244            .req_id
1245            .as_ref()
1246            .and_then(|rid| state.pending_requests.remove(rid))
1247            .map(|(_, v)| v);
1248
1249        if let Some((cids, voids, pending_op, command_ids)) = pending {
1250            let batch_errors = resp.extract_batch_errors();
1251            let data_array = resp.data.as_array();
1252
1253            for (idx, error) in batch_errors.iter().enumerate() {
1254                if error.code == 0 {
1255                    continue;
1256                }
1257
1258                if is_bybit_ambiguous_order_error_code(error.code) {
1259                    log::warn!(
1260                        "Ambiguous batch order item failure at index {idx}: code={}, msg={}; awaiting reconciliation",
1261                        error.code,
1262                        error.msg,
1263                    );
1264                    continue;
1265                }
1266
1267                // Extract orderLinkId from the corresponding data entry
1268                let cid = data_array
1269                    .and_then(|arr| arr.get(idx))
1270                    .and_then(extract_order_link_id_from_data)
1271                    .or_else(|| cids.get(idx).copied());
1272
1273                let Some(cid) = cid else {
1274                    log::warn!(
1275                        "Batch error at index {idx} without correlation: code={}, msg={}",
1276                        error.code,
1277                        error.msg,
1278                    );
1279                    continue;
1280                };
1281
1282                let Some(identity) = state.order_identities.get(&cid).map(|r| r.clone()) else {
1283                    log::warn!(
1284                        "Batch error for untracked order: client_order_id={cid}, msg={}",
1285                        error.msg,
1286                    );
1287                    continue;
1288                };
1289
1290                let stored_void = voids.get(idx).and_then(|v| *v);
1291
1292                emit_rejection_for_op(
1293                    &pending_op,
1294                    cid,
1295                    &identity,
1296                    stored_void,
1297                    &error.msg,
1298                    emitter,
1299                    state,
1300                    ts_init,
1301                    command_ids.get(idx).copied().flatten(),
1302                );
1303            }
1304        }
1305
1306        return;
1307    }
1308
1309    // Remove the pending request entry (if any) to get client_order_ids and op
1310    let pending = resp
1311        .req_id
1312        .as_ref()
1313        .and_then(|rid| state.pending_requests.remove(rid))
1314        .map(|(_, v)| v);
1315
1316    let is_batch_response = is_batch_order_op(resp.op.as_str())
1317        || pending
1318            .as_ref()
1319            .is_some_and(|(cids, _, _, _)| cids.len() > 1);
1320
1321    if is_batch_response {
1322        if is_bybit_ambiguous_order_error_code(resp.ret_code) {
1323            let order_count = pending.as_ref().map_or(0, |(cids, _, _, _)| cids.len());
1324            log::warn!(
1325                "Ambiguous batch order response failure for {order_count} orders: op={}, ret_code={}, ret_msg={}; awaiting reconciliation",
1326                resp.op,
1327                resp.ret_code,
1328                resp.ret_msg,
1329            );
1330            return;
1331        }
1332
1333        let Some((client_order_ids, venue_order_ids, pending_op, command_ids)) = pending else {
1334            log::warn!(
1335                "Batch order response error without correlation: op={}, ret_code={}, ret_msg={}, req_id={:?}",
1336                resp.op,
1337                resp.ret_code,
1338                resp.ret_msg,
1339                resp.req_id,
1340            );
1341            return;
1342        };
1343
1344        for (index, client_order_id) in client_order_ids.into_iter().enumerate() {
1345            let Some(identity) = state
1346                .order_identities
1347                .get(&client_order_id)
1348                .map(|identity| identity.clone())
1349            else {
1350                log::warn!(
1351                    "Batch order response error for untracked order: op={}, client_order_id={client_order_id}, ret_msg={}",
1352                    resp.op,
1353                    resp.ret_msg,
1354                );
1355                continue;
1356            };
1357
1358            emit_rejection_for_op(
1359                &pending_op,
1360                client_order_id,
1361                &identity,
1362                venue_order_ids.get(index).copied().flatten(),
1363                &resp.ret_msg,
1364                emitter,
1365                state,
1366                ts_init,
1367                command_ids.get(index).copied().flatten(),
1368            );
1369        }
1370
1371        return;
1372    }
1373
1374    if is_bybit_ambiguous_order_error_code(resp.ret_code) {
1375        log::warn!(
1376            "Ambiguous order response failure: op={}, ret_code={}, ret_msg={}; awaiting reconciliation",
1377            resp.op,
1378            resp.ret_code,
1379            resp.ret_msg,
1380        );
1381        return;
1382    }
1383
1384    let effective_op = pending
1385        .as_ref()
1386        .map(|(_, _, op, _)| *op)
1387        .or_else(|| pending_op_from_str(resp.op.as_str()))
1388        .unwrap_or_else(|| {
1389            log::warn!("Unknown order operation '{}', defaulting to Place", resp.op);
1390            PendingOperation::Place
1391        });
1392
1393    // Single-order rejection path
1394    let client_order_id = extract_order_link_id_from_data(&resp.data).or_else(|| {
1395        pending
1396            .as_ref()
1397            .and_then(|(cids, _, _, _)| cids.first().copied())
1398    });
1399
1400    let stored_venue_order_id = pending
1401        .as_ref()
1402        .and_then(|(_, voids, _, _)| voids.first().and_then(|v| *v));
1403
1404    let Some(client_order_id) = client_order_id else {
1405        log::warn!(
1406            "Order response error without correlation: op={}, ret_code={}, ret_msg={}, req_id={:?}",
1407            resp.op,
1408            resp.ret_code,
1409            resp.ret_msg,
1410            resp.req_id,
1411        );
1412        return;
1413    };
1414
1415    let Some(identity) = state
1416        .order_identities
1417        .get(&client_order_id)
1418        .map(|r| r.clone())
1419    else {
1420        log::warn!(
1421            "Order response error for untracked order: op={}, client_order_id={client_order_id}, ret_msg={}",
1422            resp.op,
1423            resp.ret_msg,
1424        );
1425        return;
1426    };
1427
1428    let venue_order_id = extract_venue_order_id_from_data(&resp.data).or(stored_venue_order_id);
1429
1430    emit_rejection_for_op(
1431        &effective_op,
1432        client_order_id,
1433        &identity,
1434        venue_order_id,
1435        &resp.ret_msg,
1436        emitter,
1437        state,
1438        ts_init,
1439        pending.as_ref().and_then(|(cids, _, _, command_ids)| {
1440            cids.iter()
1441                .position(|id| *id == client_order_id)
1442                .and_then(|index| command_ids.get(index).copied().flatten())
1443        }),
1444    );
1445}
1446
1447fn dispatch_order_not_sent(
1448    request_id: &str,
1449    reason: &str,
1450    emitter: &ExecutionEventEmitter,
1451    state: &WsDispatchState,
1452    ts_init: UnixNanos,
1453) {
1454    let Some((_, (client_order_ids, venue_order_ids, operation, command_ids))) =
1455        state.pending_requests.remove(request_id)
1456    else {
1457        log::warn!("Unsent order command has no request correlation: {request_id}");
1458        return;
1459    };
1460
1461    for (index, client_order_id) in client_order_ids.into_iter().enumerate() {
1462        let Some(identity) = state
1463            .order_identities
1464            .get(&client_order_id)
1465            .map(|entry| entry.clone())
1466        else {
1467            continue;
1468        };
1469
1470        let venue_order_id = venue_order_ids.get(index).copied().flatten();
1471        let causation_id = command_ids.get(index).copied().flatten();
1472
1473        match operation {
1474            PendingOperation::Place => emit_rejection_for_op(
1475                &operation,
1476                client_order_id,
1477                &identity,
1478                venue_order_id,
1479                reason,
1480                emitter,
1481                state,
1482                ts_init,
1483                causation_id,
1484            ),
1485            PendingOperation::Amend => emitter.emit_order_modify_denied_event(
1486                identity.strategy_id,
1487                identity.instrument_id,
1488                client_order_id,
1489                venue_order_id,
1490                reason,
1491                ts_init,
1492                causation_id,
1493            ),
1494            PendingOperation::Cancel => emitter.emit_order_cancel_denied_event(
1495                identity.strategy_id,
1496                identity.instrument_id,
1497                client_order_id,
1498                venue_order_id,
1499                reason,
1500                ts_init,
1501                causation_id,
1502            ),
1503        }
1504    }
1505}
1506
1507/// Emits the appropriate rejection event based on the pending operation type.
1508#[expect(clippy::too_many_arguments)]
1509fn emit_rejection_for_op(
1510    pending_op: &PendingOperation,
1511    client_order_id: ClientOrderId,
1512    identity: &OrderIdentity,
1513    venue_order_id: Option<VenueOrderId>,
1514    reason: &str,
1515    emitter: &ExecutionEventEmitter,
1516    state: &WsDispatchState,
1517    ts_init: UnixNanos,
1518    causation_id: Option<UUID4>,
1519) {
1520    match pending_op {
1521        PendingOperation::Place => {
1522            state.order_identities.remove(&client_order_id);
1523            state.order_snapshots.remove(&client_order_id);
1524            emitter.emit_order_rejected_event(
1525                identity.strategy_id,
1526                identity.instrument_id,
1527                client_order_id,
1528                reason,
1529                ts_init,
1530                false,
1531            );
1532        }
1533        PendingOperation::Cancel => {
1534            emitter.emit_order_cancel_rejected_event(
1535                identity.strategy_id,
1536                identity.instrument_id,
1537                client_order_id,
1538                venue_order_id,
1539                reason,
1540                ts_init,
1541                causation_id,
1542            );
1543        }
1544        PendingOperation::Amend => {
1545            emitter.emit_order_modify_rejected_event(
1546                identity.strategy_id,
1547                identity.instrument_id,
1548                client_order_id,
1549                venue_order_id,
1550                reason,
1551                ts_init,
1552                causation_id,
1553            );
1554        }
1555    }
1556}
1557
1558/// Maps an operation string to a `PendingOperation`.
1559fn pending_op_from_str(op: &str) -> Option<PendingOperation> {
1560    match op {
1561        BYBIT_OP_ORDER_CREATE => Some(PendingOperation::Place),
1562        BYBIT_OP_ORDER_CANCEL => Some(PendingOperation::Cancel),
1563        BYBIT_OP_ORDER_AMEND => Some(PendingOperation::Amend),
1564        _ => None,
1565    }
1566}
1567
1568fn is_batch_order_op(op: &str) -> bool {
1569    matches!(
1570        op,
1571        BYBIT_OP_ORDER_CREATE_BATCH | BYBIT_OP_ORDER_AMEND_BATCH | BYBIT_OP_ORDER_CANCEL_BATCH
1572    )
1573}
1574
1575/// Parses an order snapshot from a WS order message for modification detection.
1576fn parse_order_snapshot(
1577    order: &BybitWsAccountOrder,
1578    instrument: &InstrumentAny,
1579) -> Option<OrderStateSnapshot> {
1580    let quantity =
1581        parse_quantity_with_precision(&order.qty, instrument.size_precision(), "order.qty").ok()?;
1582    let price = if !order.price.is_empty() && order.price != "0" {
1583        parse_price_with_precision(&order.price, instrument.price_precision(), "order.price").ok()
1584    } else {
1585        None
1586    };
1587
1588    let trigger_price = if !order.trigger_price.is_empty() && order.trigger_price != "0" {
1589        parse_price_with_precision(
1590            &order.trigger_price,
1591            instrument.price_precision(),
1592            "order.triggerPrice",
1593        )
1594        .ok()
1595    } else {
1596        None
1597    };
1598
1599    Some(OrderStateSnapshot {
1600        quantity,
1601        price,
1602        trigger_price,
1603    })
1604}
1605
1606/// Returns whether the incoming snapshot differs from the stored snapshot.
1607fn is_snapshot_updated(
1608    snapshot: &OrderStateSnapshot,
1609    client_order_id: &ClientOrderId,
1610    state: &WsDispatchState,
1611) -> bool {
1612    let Some(previous) = state.order_snapshots.get(client_order_id) else {
1613        return false;
1614    };
1615
1616    if let (Some(prev_price), Some(new_price)) = (previous.price, snapshot.price)
1617        && prev_price != new_price
1618    {
1619        return true;
1620    }
1621
1622    if let (Some(prev_trigger), Some(new_trigger)) =
1623        (previous.trigger_price, snapshot.trigger_price)
1624        && prev_trigger != new_trigger
1625    {
1626        return true;
1627    }
1628
1629    previous.quantity != snapshot.quantity
1630}
1631
1632#[expect(
1633    clippy::too_many_arguments,
1634    reason = "updates share the dispatcher's order context"
1635)]
1636fn emit_order_updated_if_changed(
1637    order: &BybitWsAccountOrder,
1638    instrument: &InstrumentAny,
1639    client_order_id: ClientOrderId,
1640    identity: &OrderIdentity,
1641    account_id: AccountId,
1642    ts_init: UnixNanos,
1643    force: bool,
1644    state: &WsDispatchState,
1645    emitter: &ExecutionEventEmitter,
1646) -> bool {
1647    let Some(snapshot) = parse_order_snapshot(order, instrument) else {
1648        return false;
1649    };
1650
1651    if !force && !is_snapshot_updated(&snapshot, &client_order_id, state) {
1652        return false;
1653    }
1654
1655    let venue_order_id = VenueOrderId::new(order.order_id);
1656
1657    let updated = OrderUpdated::new(
1658        emitter.trader_id(),
1659        identity.strategy_id,
1660        identity.instrument_id,
1661        client_order_id,
1662        snapshot.quantity,
1663        UUID4::new(),
1664        ts_init,
1665        ts_init,
1666        false,
1667        Some(venue_order_id),
1668        Some(account_id),
1669        snapshot.price,
1670        snapshot.trigger_price,
1671        None,
1672        false,
1673    );
1674    state.order_snapshots.insert(client_order_id, snapshot);
1675    emitter.send_order_event(OrderEventAny::Updated(updated));
1676    true
1677}
1678
1679pub(crate) fn record_venue_order_id(
1680    client_order_id: ClientOrderId,
1681    venue_order_id: VenueOrderId,
1682    state: &WsDispatchState,
1683) {
1684    state
1685        .order_venue_ids
1686        .insert(client_order_id, venue_order_id);
1687    state
1688        .venue_order_ids
1689        .insert(venue_order_id, client_order_id);
1690}
1691
1692/// Synthesizes and emits `OrderAccepted` if one has not yet been emitted for
1693/// this order. Handles fast-filling orders that skip the `New` state on Bybit.
1694fn ensure_accepted_emitted(
1695    client_order_id: ClientOrderId,
1696    account_id: AccountId,
1697    venue_order_id: VenueOrderId,
1698    identity: &OrderIdentity,
1699    ts_init: UnixNanos,
1700    state: &WsDispatchState,
1701    emitter: &ExecutionEventEmitter,
1702) {
1703    record_venue_order_id(client_order_id, venue_order_id, state);
1704    if state.emitted_accepted.contains(&client_order_id) {
1705        return;
1706    }
1707
1708    state.insert_accepted(client_order_id);
1709
1710    let accepted = OrderAccepted::new(
1711        emitter.trader_id(),
1712        identity.strategy_id,
1713        identity.instrument_id,
1714        client_order_id,
1715        venue_order_id,
1716        account_id,
1717        UUID4::new(),
1718        ts_init,
1719        ts_init,
1720        false,
1721    );
1722    emitter.send_order_event(OrderEventAny::Accepted(accepted));
1723}
1724
1725pub(crate) fn cleanup_terminal_when_ready(
1726    client_order_id: ClientOrderId,
1727    terminal_qty: Quantity,
1728    state: &WsDispatchState,
1729) {
1730    state
1731        .terminal_order_quantities
1732        .insert(client_order_id, terminal_qty);
1733    if state.fast_execution && !fast_fill_is_terminal(client_order_id, state) {
1734        return;
1735    }
1736
1737    cleanup_terminal(client_order_id, state);
1738}
1739
1740fn record_fast_fill(client_order_id: ClientOrderId, last_qty: Quantity, state: &WsDispatchState) {
1741    let mut overflow = false;
1742    state
1743        .fast_filled_quantities
1744        .entry(client_order_id)
1745        .and_modify(|total| {
1746            if let Some(new_total) = total.checked_add(last_qty) {
1747                *total = new_total;
1748            } else {
1749                overflow = true;
1750            }
1751        })
1752        .or_insert(last_qty);
1753
1754    if overflow {
1755        log::warn!("Fast fill quantity overflow for {client_order_id}, retaining order state");
1756        return;
1757    }
1758
1759    if fast_fill_is_terminal(client_order_id, state) {
1760        cleanup_terminal(client_order_id, state);
1761    }
1762}
1763
1764fn fast_fill_is_terminal(client_order_id: ClientOrderId, state: &WsDispatchState) -> bool {
1765    let Some(terminal_qty) = state.terminal_order_quantities.get(&client_order_id) else {
1766        return false;
1767    };
1768
1769    if terminal_qty.is_zero() {
1770        return true;
1771    }
1772
1773    state
1774        .fast_filled_quantities
1775        .get(&client_order_id)
1776        .is_some_and(|filled_qty| *filled_qty >= *terminal_qty)
1777}
1778
1779/// Removes a terminal order from all tracking sets.
1780pub(crate) fn cleanup_terminal(client_order_id: ClientOrderId, state: &WsDispatchState) {
1781    if let Some((_, venue_order_id)) = state.order_venue_ids.remove(&client_order_id) {
1782        state.venue_order_ids.remove(&venue_order_id);
1783    }
1784
1785    state.order_identities.remove(&client_order_id);
1786    state.order_snapshots.remove(&client_order_id);
1787    state.emitted_accepted.remove(&client_order_id);
1788    state.triggered_orders.remove(&client_order_id);
1789    state.filled_orders.remove(&client_order_id);
1790    state.fast_filled_quantities.remove(&client_order_id);
1791    state.terminal_order_quantities.remove(&client_order_id);
1792    state.spot_repay_fills.remove(&client_order_id);
1793}
1794
1795/// Tries to extract `orderLinkId` from the response data Value.
1796fn extract_order_link_id_from_data(data: &serde_json::Value) -> Option<ClientOrderId> {
1797    data.get("orderLinkId")
1798        .and_then(|v| v.as_str())
1799        .filter(|s| !s.is_empty())
1800        .map(ClientOrderId::new)
1801}
1802
1803/// Tries to extract `orderId` from the response data Value.
1804fn extract_venue_order_id_from_data(data: &serde_json::Value) -> Option<VenueOrderId> {
1805    data.get("orderId")
1806        .and_then(|v| v.as_str())
1807        .filter(|s| !s.is_empty())
1808        .map(VenueOrderId::new)
1809}
1810
1811fn record_spot_repay_fill(
1812    client_order_id: ClientOrderId,
1813    filled: &OrderFilled,
1814    instrument: &InstrumentAny,
1815    state: &WsDispatchState,
1816) {
1817    let Some(base_currency) = instrument.base_currency() else {
1818        return;
1819    };
1820
1821    let base_fee = filled
1822        .commission
1823        .filter(|fee| fee.currency.code == base_currency.code)
1824        .map_or(Decimal::ZERO, |fee| fee.as_decimal().max(Decimal::ZERO));
1825
1826    let fill = SpotRepayFill {
1827        quantity: filled.last_qty,
1828        base_fee,
1829    };
1830
1831    state
1832        .spot_repay_fills
1833        .entry(client_order_id)
1834        .and_modify(|total| {
1835            total.quantity = total.quantity + fill.quantity;
1836            total.base_fee += fill.base_fee;
1837        })
1838        .or_insert(fill);
1839}
1840
1841/// Enqueues an auto-repay for a fully-filled SPOT BUY.
1842fn enqueue_spot_repay(
1843    client_order_id: ClientOrderId,
1844    instrument: &InstrumentAny,
1845    state: &WsDispatchState,
1846) {
1847    let Some(base_currency) = instrument.base_currency() else {
1848        return;
1849    };
1850
1851    let Some((_, fill)) = state.spot_repay_fills.remove(&client_order_id) else {
1852        return;
1853    };
1854
1855    state.enqueue_repay(RepayRequest {
1856        coin: base_currency.code,
1857        quantity: fill.quantity,
1858        base_fee: fill.base_fee,
1859        repayment_precision: fill.quantity.precision.max(base_currency.precision),
1860    });
1861}
1862
1863#[cfg(test)]
1864mod tests {
1865    use ahash::AHashMap;
1866    use nautilus_common::messages::{ExecutionEvent, execution::ExecutionReport};
1867    use nautilus_core::{
1868        UnixNanos,
1869        time::{AtomicTime, get_atomic_clock_realtime},
1870    };
1871    use nautilus_live::{emitter::ExecutionEventEmitter, testing::ExecutionHarness};
1872    use nautilus_model::{
1873        accounts::MarginAccount,
1874        enums::{AccountType, OrderSide, OrderStatus, OrderType},
1875        events::OrderEventAny,
1876        identifiers::{
1877            AccountId, ClientOrderId, InstrumentId, PositionId, StrategyId, TraderId, VenueOrderId,
1878        },
1879        instruments::{Instrument, InstrumentAny},
1880        orders::{Order, builder::OrderTestBuilder, stubs::TestOrderEventStubs},
1881        reports::FillReport,
1882        types::Currency,
1883    };
1884    use rstest::rstest;
1885    use rust_decimal_macros::dec;
1886    use ustr::Ustr;
1887
1888    use super::*;
1889    use crate::{
1890        common::{
1891            enums::{BybitExecType, BybitOrderSide, BybitProductType},
1892            parse::{
1893                parse_inverse_instrument, parse_linear_instrument, parse_option_instrument,
1894                parse_spot_instrument,
1895            },
1896            testing::load_test_json,
1897        },
1898        http::models::{
1899            BybitInstrumentInverseResponse, BybitInstrumentLinearResponse,
1900            BybitInstrumentOptionResponse, BybitInstrumentSpotResponse,
1901        },
1902        websocket::messages::{
1903            BybitWsAccountExecutionFastMsg, BybitWsMessage, BybitWsOrderResponse,
1904        },
1905    };
1906
1907    fn linear_instrument() -> InstrumentAny {
1908        let json = load_test_json("http_get_instruments_linear.json");
1909        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
1910        let instrument = &response.result.list[0];
1911        let ts = UnixNanos::new(1_700_000_000_000_000_000);
1912        parse_linear_instrument(instrument, ts, ts).unwrap()
1913    }
1914
1915    fn spot_instrument() -> InstrumentAny {
1916        let json = load_test_json("http_get_instruments_spot.json");
1917        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
1918        let instrument = &response.result.list[0];
1919        let ts = UnixNanos::new(1_700_000_000_000_000_000);
1920        parse_spot_instrument(instrument, ts, ts).unwrap()
1921    }
1922
1923    fn inverse_instrument() -> InstrumentAny {
1924        let json = load_test_json("http_get_instruments_inverse.json");
1925        let response: BybitInstrumentInverseResponse = serde_json::from_str(&json).unwrap();
1926        let instrument = &response.result.list[0];
1927        let ts = UnixNanos::new(1_700_000_000_000_000_000);
1928        parse_inverse_instrument(instrument, ts, ts).unwrap()
1929    }
1930
1931    fn option_instrument_with_distinct_settlement() -> InstrumentAny {
1932        let json = load_test_json("http_get_instruments_option_symbol_id.json");
1933        let response: BybitInstrumentOptionResponse = serde_json::from_str(&json).unwrap();
1934        let instrument = &response.result.list[0];
1935        let ts = UnixNanos::new(1_700_000_000_000_000_000);
1936        parse_option_instrument(instrument, ts, ts).unwrap()
1937    }
1938
1939    fn build_instruments(instruments: &[InstrumentAny]) -> AHashMap<Ustr, InstrumentAny> {
1940        let mut map = AHashMap::new();
1941        for inst in instruments {
1942            map.insert(inst.id().symbol.inner(), inst.clone());
1943        }
1944
1945        map
1946    }
1947
1948    fn test_account_id() -> AccountId {
1949        AccountId::from("BYBIT-001")
1950    }
1951
1952    fn create_emitter() -> (
1953        ExecutionEventEmitter,
1954        tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
1955    ) {
1956        let clock = get_atomic_clock_realtime();
1957        let trader_id = TraderId::from("TESTER-001");
1958        let account_id = test_account_id();
1959        let mut emitter =
1960            ExecutionEventEmitter::new(clock, trader_id, account_id, AccountType::Margin, None);
1961        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
1962        emitter.set_sender(tx);
1963        (emitter, rx)
1964    }
1965
1966    fn default_identity() -> OrderIdentity {
1967        OrderIdentity {
1968            instrument_id: InstrumentId::from("BTCUSDT-LINEAR.BYBIT"),
1969            strategy_id: StrategyId::from("S-001"),
1970            order_side: OrderSide::Buy,
1971            order_type: OrderType::Limit,
1972            venue_position_id: None,
1973        }
1974    }
1975
1976    #[rstest]
1977    #[case::base_fee("BTC", "0.0000015", "0.0000025", "0.000004")]
1978    #[case::base_rebate("BTC", "-0.0000015", "-0.0000025", "0")]
1979    #[case::quote_fee("USDT", "0.075", "0.125", "0")]
1980    fn test_spot_repay_uses_accumulated_execution_quantity(
1981        #[case] fee_currency: &str,
1982        #[case] first_fee: &str,
1983        #[case] second_fee: &str,
1984        #[case] expected_base_fee: &str,
1985    ) {
1986        let instrument = spot_instrument();
1987        let instruments = build_instruments(std::slice::from_ref(&instrument));
1988        let (emitter, _rx) = create_emitter();
1989        let clock = get_atomic_clock_realtime();
1990        let state = WsDispatchState::default();
1991        let (repay_tx, mut repay_rx) = tokio::sync::mpsc::unbounded_channel();
1992        state.set_repay_sender(repay_tx);
1993
1994        let json = load_test_json("ws_account_execution.json");
1995        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
1996        value["data"][0]["category"] = serde_json::Value::String("spot".to_string());
1997        value["data"][0]["symbol"] = serde_json::Value::String("BTCUSDT".to_string());
1998        value["data"][0]["side"] = serde_json::Value::String("Buy".to_string());
1999        value["data"][0]["orderType"] = serde_json::Value::String("Market".to_string());
2000        value["data"][0]["orderQty"] = serde_json::Value::String("100".to_string());
2001        value["data"][0]["execQty"] = serde_json::Value::String("0.0015".to_string());
2002        value["data"][0]["leavesQty"] = serde_json::Value::String("0.0025".to_string());
2003        value["data"][0]["execFee"] = serde_json::Value::String(first_fee.to_string());
2004        value["data"][0]["feeCurrency"] = serde_json::Value::String(fee_currency.to_string());
2005
2006        let first: crate::websocket::messages::BybitWsAccountExecutionMsg =
2007            serde_json::from_value(value.clone()).unwrap();
2008        let client_order_id = ClientOrderId::new(first.data[0].order_link_id);
2009        state.order_identities.insert(
2010            client_order_id,
2011            OrderIdentity {
2012                instrument_id: InstrumentId::from("BTCUSDT-SPOT.BYBIT"),
2013                order_type: OrderType::Market,
2014                ..default_identity()
2015            },
2016        );
2017
2018        dispatch_ws_message(
2019            &BybitWsMessage::AccountExecution(first),
2020            test_account_id(),
2021            &instruments,
2022            clock,
2023            &state,
2024            &emitter,
2025        );
2026        assert!(repay_rx.try_recv().is_err());
2027
2028        value["data"][0]["execId"] = serde_json::Value::String("second-execution".to_string());
2029        value["data"][0]["execQty"] = serde_json::Value::String("0.0025".to_string());
2030        value["data"][0]["leavesQty"] = serde_json::Value::String("0".to_string());
2031        value["data"][0]["execFee"] = serde_json::Value::String(second_fee.to_string());
2032        let second: crate::websocket::messages::BybitWsAccountExecutionMsg =
2033            serde_json::from_value(value).unwrap();
2034
2035        dispatch_ws_message(
2036            &BybitWsMessage::AccountExecution(second),
2037            test_account_id(),
2038            &instruments,
2039            clock,
2040            &state,
2041            &emitter,
2042        );
2043
2044        let repay = repay_rx.try_recv().expect("expected a repay request");
2045        assert_eq!(repay.coin, "BTC");
2046        assert_eq!(repay.quantity, Quantity::from("0.0040"));
2047        assert_eq!(
2048            repay.base_fee,
2049            expected_base_fee.parse::<Decimal>().unwrap()
2050        );
2051        assert_eq!(repay.repayment_precision, 8);
2052        assert!(repay_rx.try_recv().is_err());
2053    }
2054
2055    #[rstest]
2056    fn test_dispatch_tracked_canceled_order_emits_accepted_then_canceled() {
2057        let instrument = linear_instrument();
2058        let instruments = build_instruments(std::slice::from_ref(&instrument));
2059        let (emitter, mut rx) = create_emitter();
2060        let clock = get_atomic_clock_realtime();
2061        let state = WsDispatchState::default();
2062
2063        // Fixture has orderStatus=Cancelled
2064        let json = load_test_json("ws_account_order.json");
2065        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2066            serde_json::from_str(&json).unwrap();
2067
2068        if let Some(order) = msg.data.first()
2069            && !order.order_link_id.is_empty()
2070        {
2071            let cid = ClientOrderId::new(order.order_link_id);
2072            state.order_identities.insert(cid, default_identity());
2073        }
2074
2075        let ws_msg = BybitWsMessage::AccountOrder(msg);
2076        dispatch_ws_message(
2077            &ws_msg,
2078            test_account_id(),
2079            &instruments,
2080            clock,
2081            &state,
2082            &emitter,
2083        );
2084
2085        // First: synthesized Accepted
2086        let event1 = rx.try_recv().unwrap();
2087        assert!(
2088            matches!(event1, ExecutionEvent::Order(OrderEventAny::Accepted(ref a)) if a.strategy_id == StrategyId::from("S-001")),
2089            "Expected Accepted, found {event1:?}"
2090        );
2091
2092        // Second: Canceled (from Cancelled status)
2093        let event2 = rx.try_recv().unwrap();
2094        assert!(
2095            matches!(event2, ExecutionEvent::Order(OrderEventAny::Canceled(_))),
2096            "Expected Canceled, found {event2:?}"
2097        );
2098    }
2099
2100    #[rstest]
2101    fn test_dispatch_tracked_post_only_cancel_emits_rejected() {
2102        const BYBIT_POST_ONLY_REJECT_REASON: &str = "EC_PostOnlyWillTakeLiquidity";
2103
2104        let instrument = linear_instrument();
2105        let instruments = build_instruments(std::slice::from_ref(&instrument));
2106        let (emitter, mut rx) = create_emitter();
2107        let clock = get_atomic_clock_realtime();
2108        let state = WsDispatchState::default();
2109
2110        // Bybit reports a post-only order that would take liquidity as
2111        // orderStatus=Cancelled with rejectReason=EC_PostOnlyWillTakeLiquidity.
2112        let json = load_test_json("ws_account_order.json");
2113        let mut msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2114            serde_json::from_str(&json).unwrap();
2115
2116        let order = msg.data.first_mut().expect("fixture has an order");
2117        order.reject_reason = Ustr::from(BYBIT_POST_ONLY_REJECT_REASON);
2118        order.cum_exec_qty = "0".to_string();
2119        let cid = ClientOrderId::new(order.order_link_id);
2120        state.order_identities.insert(cid, default_identity());
2121
2122        let ws_msg = BybitWsMessage::AccountOrder(msg);
2123        dispatch_ws_message(
2124            &ws_msg,
2125            test_account_id(),
2126            &instruments,
2127            clock,
2128            &state,
2129            &emitter,
2130        );
2131
2132        let event = rx.try_recv().unwrap();
2133
2134        let ExecutionEvent::Order(OrderEventAny::Rejected(rejected)) = event else {
2135            panic!("Expected Rejected, found {event:?}");
2136        };
2137
2138        assert!(rejected.due_post_only);
2139        assert_eq!(rejected.reason, BYBIT_POST_ONLY_REJECT_REASON);
2140        assert_eq!(rejected.client_order_id, cid);
2141        assert!(rx.try_recv().is_err(), "expected only a single event");
2142    }
2143
2144    #[rstest]
2145    fn test_dispatch_untracked_order_emits_report() {
2146        let instrument = linear_instrument();
2147        let instruments = build_instruments(std::slice::from_ref(&instrument));
2148        let (emitter, mut rx) = create_emitter();
2149        let clock = get_atomic_clock_realtime();
2150        let state = WsDispatchState::default();
2151
2152        let json = load_test_json("ws_account_order.json");
2153        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
2154            serde_json::from_str(&json).unwrap();
2155
2156        // No identity registered → untracked
2157        let ws_msg = BybitWsMessage::AccountOrder(msg);
2158        dispatch_ws_message(
2159            &ws_msg,
2160            test_account_id(),
2161            &instruments,
2162            clock,
2163            &state,
2164            &emitter,
2165        );
2166
2167        let event = rx.try_recv().unwrap();
2168        assert!(matches!(
2169            event,
2170            ExecutionEvent::Report(ExecutionReport::Order(_))
2171        ));
2172    }
2173
2174    #[rstest]
2175    fn test_dispatch_tracked_execution_emits_order_filled() {
2176        let instrument = linear_instrument();
2177        let instruments = build_instruments(std::slice::from_ref(&instrument));
2178        let (emitter, mut rx) = create_emitter();
2179        let clock = get_atomic_clock_realtime();
2180        let state = WsDispatchState::default();
2181
2182        let json = load_test_json("ws_account_execution.json");
2183        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2184            serde_json::from_str(&json).unwrap();
2185
2186        // Register identity for the execution's orderLinkId
2187        if let Some(exec) = msg.data.first()
2188            && !exec.order_link_id.is_empty()
2189        {
2190            let cid = ClientOrderId::new(exec.order_link_id);
2191            state.order_identities.insert(cid, default_identity());
2192        }
2193
2194        let ws_msg = BybitWsMessage::AccountExecution(msg);
2195        dispatch_ws_message(
2196            &ws_msg,
2197            test_account_id(),
2198            &instruments,
2199            clock,
2200            &state,
2201            &emitter,
2202        );
2203
2204        // First event should be synthesized Accepted
2205        let event1 = rx.try_recv().unwrap();
2206        assert!(
2207            matches!(event1, ExecutionEvent::Order(OrderEventAny::Accepted(_))),
2208            "Expected Accepted, found {event1:?}"
2209        );
2210
2211        // Second event should be OrderFilled
2212        let event2 = rx.try_recv().unwrap();
2213        match event2 {
2214            ExecutionEvent::Order(OrderEventAny::Filled(filled)) => {
2215                assert_eq!(filled.strategy_id, StrategyId::from("S-001"));
2216                assert_eq!(filled.order_side, OrderSide::Buy);
2217                assert_eq!(filled.order_type, OrderType::Limit);
2218            }
2219            other => panic!("Expected Filled event, found {other:?}"),
2220        }
2221    }
2222
2223    #[rstest]
2224    #[case::commission_overflow("execFee", "9999999999999999999999999999")]
2225    #[case::commission_parse("execFee", "invalid")]
2226    #[case::qty("execQty", "invalid")]
2227    #[case::price("execPrice", "invalid")]
2228    #[case::timestamp("execTime", "invalid")]
2229    #[case::trade_id("execId", "")]
2230    fn test_dispatch_invalid_execution_preserves_state(
2231        #[case] field: &str,
2232        #[case] value: &str,
2233        #[values(false, true)] spot: bool,
2234    ) {
2235        let instrument = if spot {
2236            spot_instrument()
2237        } else {
2238            linear_instrument()
2239        };
2240
2241        let instruments = build_instruments(std::slice::from_ref(&instrument));
2242        let (emitter, mut rx) = create_emitter();
2243        let state = WsDispatchState::default();
2244        let (repay_tx, mut repay_rx) = tokio::sync::mpsc::unbounded_channel();
2245        state.set_repay_sender(repay_tx);
2246        let mut payload: serde_json::Value =
2247            serde_json::from_str(&load_test_json("ws_account_execution.json")).unwrap();
2248        payload["data"][0][field] = serde_json::Value::String(value.to_string());
2249        payload["data"][0]["side"] = serde_json::Value::String("Buy".to_string());
2250        if spot {
2251            payload["data"][0]["category"] = serde_json::Value::String("spot".to_string());
2252        }
2253
2254        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2255            serde_json::from_value(payload).unwrap();
2256        let cid = ClientOrderId::new(msg.data[0].order_link_id);
2257
2258        let identity = OrderIdentity {
2259            instrument_id: instrument.id(),
2260            venue_position_id: Some(PositionId::from("P-001")),
2261            ..default_identity()
2262        };
2263
2264        state.order_identities.insert(cid, identity.clone());
2265        state.order_snapshots.insert(
2266            cid,
2267            OrderStateSnapshot {
2268                quantity: Quantity::from("0.500"),
2269                price: Some(Price::from("95900.1")),
2270                trigger_price: Some(Price::from("95800.2")),
2271            },
2272        );
2273
2274        state.insert_triggered(cid);
2275
2276        dispatch_ws_message(
2277            &BybitWsMessage::AccountExecution(msg),
2278            test_account_id(),
2279            &instruments,
2280            get_atomic_clock_realtime(),
2281            &state,
2282            &emitter,
2283        );
2284
2285        assert!(rx.try_recv().is_err());
2286        assert!(repay_rx.try_recv().is_err());
2287        assert!(state.emitted_accepted.is_empty());
2288        assert!(state.filled_orders.is_empty());
2289        assert!(state.spot_repay_fills.is_empty());
2290        assert!(state.pending_requests.is_empty());
2291        assert_eq!(state.triggered_orders.len(), 1);
2292        assert!(state.triggered_orders.contains(&cid));
2293        assert_eq!(state.order_identities.len(), 1);
2294        let retained = state.order_identities.get(&cid).unwrap();
2295        assert_eq!(retained.instrument_id, identity.instrument_id);
2296        assert_eq!(retained.strategy_id, identity.strategy_id);
2297        assert_eq!(retained.order_side, identity.order_side);
2298        assert_eq!(retained.order_type, identity.order_type);
2299        assert_eq!(retained.venue_position_id, identity.venue_position_id);
2300        assert_eq!(state.order_snapshots.len(), 1);
2301        let snapshot = state.order_snapshots.get(&cid).unwrap();
2302        assert_eq!(snapshot.quantity, Quantity::from("0.500"));
2303        assert_eq!(snapshot.price, Some(Price::from("95900.1")));
2304        assert_eq!(snapshot.trigger_price, Some(Price::from("95800.2")));
2305    }
2306
2307    #[rstest]
2308    #[case::partial("0.5", "1.000", OrderStatus::PartiallyFilled)]
2309    #[case::terminal("0", "0.500", OrderStatus::Filled)]
2310    fn test_dispatch_execution_commission_failure_recovery_and_replay(
2311        #[case] leaves_qty: &str,
2312        #[case] order_qty: &str,
2313        #[case] expected_status: OrderStatus,
2314    ) {
2315        let instrument = linear_instrument();
2316        let instruments = build_instruments(std::slice::from_ref(&instrument));
2317        let (emitter, mut rx) = create_emitter();
2318        let state = WsDispatchState::default();
2319        let clock = AtomicTime::new(false, UnixNanos::new(1_746_270_400_400_000_000));
2320        let mut msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2321            serde_json::from_str(&load_test_json("ws_account_execution.json")).unwrap();
2322        msg.data[0].leaves_qty = leaves_qty.to_string();
2323        msg.data[0].side = BybitOrderSide::Buy;
2324        msg.data[0].exec_fee = "9999999999999999999999999999".to_string();
2325        let cid = ClientOrderId::new(msg.data[0].order_link_id);
2326        let identity = default_identity();
2327        state.order_identities.insert(cid, identity.clone());
2328
2329        let harness = ExecutionHarness::new(
2330            emitter.trader_id(),
2331            *crate::common::consts::BYBIT_CLIENT_ID,
2332            test_account_id(),
2333            instrument.clone(),
2334        );
2335        let wallet: crate::websocket::messages::BybitWsAccountWalletMsg =
2336            serde_json::from_str(&load_test_json("ws_account_wallet.json")).unwrap();
2337        let account_state = parse_ws_account_state(
2338            &wallet.data[0],
2339            test_account_id(),
2340            UnixNanos::default(),
2341            UnixNanos::default(),
2342        )
2343        .unwrap();
2344        let account = MarginAccount::new(account_state, false);
2345        harness
2346            .cache()
2347            .borrow_mut()
2348            .add_account(account.into())
2349            .unwrap();
2350        let mut order = OrderTestBuilder::new(identity.order_type)
2351            .trader_id(emitter.trader_id())
2352            .strategy_id(identity.strategy_id)
2353            .instrument_id(instrument.id())
2354            .client_order_id(cid)
2355            .side(identity.order_side)
2356            .quantity(Quantity::from(order_qty))
2357            .price(Price::from("94942.5"))
2358            .build();
2359        let submitted = TestOrderEventStubs::submitted(&order, test_account_id());
2360        order.apply(submitted).unwrap();
2361        harness
2362            .cache()
2363            .borrow_mut()
2364            .add_order(order, None, None, false)
2365            .unwrap();
2366
2367        dispatch_ws_message(
2368            &BybitWsMessage::AccountExecution(msg.clone()),
2369            test_account_id(),
2370            &instruments,
2371            &clock,
2372            &state,
2373            &emitter,
2374        );
2375
2376        assert!(rx.try_recv().is_err());
2377        assert!(state.emitted_accepted.is_empty());
2378        assert!(state.filled_orders.is_empty());
2379        assert_eq!(state.order_identities.len(), 1);
2380
2381        msg.data[0].exec_fee = "0.01234567".to_string();
2382        let message = BybitWsMessage::AccountExecution(msg);
2383        dispatch_ws_message(
2384            &message,
2385            test_account_id(),
2386            &instruments,
2387            &clock,
2388            &state,
2389            &emitter,
2390        );
2391
2392        let ExecutionEvent::Order(OrderEventAny::Accepted(accepted)) = rx.try_recv().unwrap()
2393        else {
2394            panic!("expected Accepted before Filled");
2395        };
2396
2397        let expected_accepted = OrderAccepted::new(
2398            emitter.trader_id(),
2399            identity.strategy_id,
2400            instrument.id(),
2401            cid,
2402            VenueOrderId::from("9aac161b-8ed6-450d-9cab-c5cc67c21784"),
2403            test_account_id(),
2404            accepted.event_id,
2405            clock.get_time_ns(),
2406            clock.get_time_ns(),
2407            false,
2408        );
2409        assert_eq!(accepted, expected_accepted);
2410        harness
2411            .exec_engine()
2412            .borrow_mut()
2413            .process(&OrderEventAny::Accepted(accepted));
2414
2415        let ExecutionEvent::Order(OrderEventAny::Filled(filled)) = rx.try_recv().unwrap() else {
2416            panic!("expected Filled after Accepted");
2417        };
2418
2419        let commission = Money::from("0.01234567 USDT");
2420
2421        let expected_filled = OrderFilled::new(
2422            emitter.trader_id(),
2423            identity.strategy_id,
2424            instrument.id(),
2425            cid,
2426            VenueOrderId::from("9aac161b-8ed6-450d-9cab-c5cc67c21784"),
2427            test_account_id(),
2428            TradeId::from("0ab1bdf7-4219-438b-b30a-32ec863018f7"),
2429            OrderSide::Buy,
2430            OrderType::Limit,
2431            Quantity::from("0.500"),
2432            Price::from("95900.1"),
2433            Currency::USDT(),
2434            LiquiditySide::Taker,
2435            filled.event_id,
2436            UnixNanos::new(1_746_270_400_353_000_000),
2437            clock.get_time_ns(),
2438            false,
2439            None,
2440            Some(commission),
2441            None,
2442        );
2443        assert_eq!(filled, expected_filled);
2444        assert!(rx.try_recv().is_err());
2445        harness
2446            .exec_engine()
2447            .borrow_mut()
2448            .process(&OrderEventAny::Filled(filled.clone()));
2449        let applied = harness.cache().borrow().order(&cid).unwrap().clone();
2450        assert_eq!(applied.status(), expected_status);
2451        assert_eq!(applied.filled_qty(), Quantity::from("0.500"));
2452        assert_eq!(
2453            applied.commissions().get(&Currency::USDT()),
2454            Some(&commission)
2455        );
2456        assert_eq!(applied.trade_ids(), vec![&filled.trade_id]);
2457        let position_id = *harness.cache().borrow().position_id(&cid).unwrap();
2458        let position = harness
2459            .cache()
2460            .borrow()
2461            .position(&position_id)
2462            .unwrap()
2463            .clone();
2464        assert_eq!(position.quantity, Quantity::from("0.500"));
2465        assert_eq!(position.commissions(), vec![commission]);
2466        let mut expected_position_fill = filled.clone();
2467        expected_position_fill.position_id = Some(position_id);
2468        assert_eq!(position.events, vec![expected_position_fill]);
2469
2470        dispatch_ws_message(
2471            &message,
2472            test_account_id(),
2473            &instruments,
2474            &clock,
2475            &state,
2476            &emitter,
2477        );
2478        let replay = rx.try_recv().unwrap();
2479        match replay {
2480            ExecutionEvent::Order(OrderEventAny::Filled(replayed)) => {
2481                let expected_replay = OrderFilled {
2482                    event_id: replayed.event_id,
2483                    ..filled.clone()
2484                };
2485
2486                assert_eq!(replayed, expected_replay);
2487                assert_eq!(leaves_qty, "0.5");
2488                harness
2489                    .exec_engine()
2490                    .borrow_mut()
2491                    .process(&OrderEventAny::Filled(replayed));
2492            }
2493            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
2494                let expected_report = FillReport::new(
2495                    filled.account_id,
2496                    filled.instrument_id,
2497                    filled.venue_order_id,
2498                    filled.trade_id,
2499                    filled.order_side,
2500                    filled.last_qty,
2501                    filled.last_px,
2502                    commission,
2503                    filled.liquidity_side,
2504                    Some(cid),
2505                    None,
2506                    filled.ts_event,
2507                    filled.ts_init,
2508                    Some(report.report_id),
2509                );
2510                assert_eq!(*report, expected_report);
2511                assert_eq!(leaves_qty, "0");
2512                harness
2513                    .exec_engine()
2514                    .borrow_mut()
2515                    .reconcile_fill_report(&report);
2516            }
2517            other => panic!("unexpected replay: {other:?}"),
2518        }
2519
2520        harness
2521            .exec_engine()
2522            .borrow_mut()
2523            .process(&OrderEventAny::Filled(filled));
2524
2525        assert!(rx.try_recv().is_err());
2526        assert_eq!(
2527            serde_json::to_value(harness.cache().borrow().order(&cid).unwrap().clone()).unwrap(),
2528            serde_json::to_value(&applied).unwrap()
2529        );
2530        assert_eq!(
2531            serde_json::to_value(
2532                harness
2533                    .cache()
2534                    .borrow()
2535                    .position(&position_id)
2536                    .unwrap()
2537                    .clone()
2538            )
2539            .unwrap(),
2540            serde_json::to_value(&position).unwrap()
2541        );
2542    }
2543
2544    #[rstest]
2545    fn parse_order_filled_uses_payload_fee_currency() {
2546        let instrument = linear_instrument();
2547        let (emitter, _rx) = create_emitter();
2548
2549        let json = load_test_json("ws_account_execution.json");
2550        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2551            serde_json::from_str(&json).unwrap();
2552
2553        let mut exec = msg.data[0].clone();
2554        exec.fee_currency = Ustr::from("BTC");
2555
2556        let filled = parse_order_filled(
2557            &exec,
2558            &instrument,
2559            &default_identity(),
2560            &emitter,
2561            test_account_id(),
2562            UnixNanos::default(),
2563        )
2564        .unwrap();
2565
2566        let commission = filled.commission.expect("commission present");
2567        assert_eq!(commission.currency.code, "BTC");
2568    }
2569
2570    #[rstest]
2571    #[case::spot_base_fee(BybitProductType::Spot, "BTC", "0.000001", "USDT")]
2572    #[case::spot_quote_fee(BybitProductType::Spot, "USDT", "0.1", "USDT")]
2573    #[case::linear_fee(BybitProductType::Linear, "USDT", "0.1", "USDT")]
2574    #[case::inverse_fee(BybitProductType::Inverse, "BTC", "0.000001", "USD")]
2575    #[case::spot_zero_fee(BybitProductType::Spot, "BTC", "0", "USDT")]
2576    #[case::inverse_rebate(BybitProductType::Inverse, "BTC", "-0.000001", "USD")]
2577    fn parse_order_filled_separates_price_and_commission_currencies(
2578        #[case] category: BybitProductType,
2579        #[case] fee_currency: &str,
2580        #[case] fee: &str,
2581        #[case] expected_price_currency: &str,
2582    ) {
2583        let instrument = match category {
2584            BybitProductType::Spot => spot_instrument(),
2585            BybitProductType::Linear => linear_instrument(),
2586            BybitProductType::Inverse => inverse_instrument(),
2587            _ => unreachable!("unsupported test product"),
2588        };
2589
2590        let (emitter, _rx) = create_emitter();
2591        let json = load_test_json("ws_account_execution.json");
2592        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2593            serde_json::from_str(&json).unwrap();
2594        let mut exec = msg.data[0].clone();
2595        exec.category = category;
2596        exec.symbol = instrument.raw_symbol().inner();
2597        exec.exec_qty = "1".to_string();
2598        exec.exec_fee = fee.to_string();
2599        exec.fee_currency = Ustr::from(fee_currency);
2600
2601        let identity = OrderIdentity {
2602            instrument_id: instrument.id(),
2603            order_side: OrderSide::Sell,
2604            order_type: OrderType::Market,
2605            ..default_identity()
2606        };
2607
2608        let filled = parse_order_filled(
2609            &exec,
2610            &instrument,
2611            &identity,
2612            &emitter,
2613            test_account_id(),
2614            UnixNanos::default(),
2615        )
2616        .unwrap();
2617
2618        let commission = filled.commission.expect("commission present");
2619        assert_eq!(commission.currency.code, fee_currency);
2620        assert_eq!(commission.as_decimal(), fee.parse::<Decimal>().unwrap());
2621        assert_eq!(filled.currency.code, expected_price_currency);
2622    }
2623
2624    #[rstest]
2625    fn test_dispatch_tracked_execution_preserves_venue_position_id() {
2626        let instrument = linear_instrument();
2627        let instruments = build_instruments(std::slice::from_ref(&instrument));
2628        let (emitter, mut rx) = create_emitter();
2629        let clock = get_atomic_clock_realtime();
2630        let state = WsDispatchState::default();
2631
2632        let json = load_test_json("ws_account_execution.json");
2633        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
2634            serde_json::from_str(&json).unwrap();
2635        let venue_position_id = PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG");
2636
2637        if let Some(exec) = msg.data.first()
2638            && !exec.order_link_id.is_empty()
2639        {
2640            let cid = ClientOrderId::new(exec.order_link_id);
2641            state.order_identities.insert(
2642                cid,
2643                OrderIdentity {
2644                    venue_position_id: Some(venue_position_id),
2645                    ..default_identity()
2646                },
2647            );
2648        }
2649
2650        let ws_msg = BybitWsMessage::AccountExecution(msg);
2651        dispatch_ws_message(
2652            &ws_msg,
2653            test_account_id(),
2654            &instruments,
2655            clock,
2656            &state,
2657            &emitter,
2658        );
2659
2660        let _accepted = rx.try_recv().unwrap();
2661        let event = rx.try_recv().unwrap();
2662        match event {
2663            ExecutionEvent::Order(OrderEventAny::Filled(filled)) => {
2664                assert_eq!(filled.position_id, Some(venue_position_id));
2665            }
2666            other => panic!("Expected Filled event, found {other:?}"),
2667        }
2668    }
2669
2670    fn fee_rate(symbol: &str, base_coin: Option<&str>, maker: &str, taker: &str) -> BybitFeeRate {
2671        BybitFeeRate {
2672            symbol: Ustr::from(symbol),
2673            taker_fee_rate: taker.to_string(),
2674            maker_fee_rate: maker.to_string(),
2675            base_coin: base_coin.map(Ustr::from),
2676        }
2677    }
2678
2679    #[rstest]
2680    fn test_cache_execution_fee_rates_scopes_products_and_fans_out_options() {
2681        let linear = linear_instrument();
2682        let spot = spot_instrument();
2683        let option_1 = option_instrument_with_distinct_settlement();
2684        let mut option_2 = option_instrument_with_distinct_settlement();
2685
2686        let InstrumentAny::CryptoOption(ref mut option) = option_2 else {
2687            panic!("expected crypto option");
2688        };
2689
2690        option.id = InstrumentId::from("BTC-30JUN25-110000-C-OPTION.BYBIT");
2691        let instruments = build_instruments(&[
2692            linear.clone(),
2693            spot.clone(),
2694            option_1.clone(),
2695            option_2.clone(),
2696        ]);
2697        let state = WsDispatchState::default();
2698
2699        let linear_cached = cache_execution_fee_rates(
2700            &state,
2701            &instruments,
2702            BybitProductType::Linear,
2703            vec![fee_rate("BTCUSDT", None, "0.0001", "0.0006")],
2704        );
2705        assert_eq!(linear_cached, 1);
2706        assert_eq!(
2707            *state.fee_rates.get(&linear.id()).unwrap(),
2708            MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006),)
2709        );
2710        assert!(!state.fee_rates.contains_key(&spot.id()));
2711
2712        let spot_cached = cache_execution_fee_rates(
2713            &state,
2714            &instruments,
2715            BybitProductType::Spot,
2716            vec![fee_rate("BTCUSDT", None, "0.001", "0.002")],
2717        );
2718        assert_eq!(spot_cached, 1);
2719        assert_eq!(
2720            *state.fee_rates.get(&spot.id()).unwrap(),
2721            MakerTakerFeeRates::new(dec!(0.001), dec!(0.002),)
2722        );
2723        assert_eq!(
2724            *state.fee_rates.get(&linear.id()).unwrap(),
2725            MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006),)
2726        );
2727
2728        let option_cached = cache_execution_fee_rates(
2729            &state,
2730            &instruments,
2731            BybitProductType::Option,
2732            vec![fee_rate("", Some("BTC"), "0.0002", "0.0003")],
2733        );
2734        assert_eq!(option_cached, 2);
2735        assert!(state.fee_rates.contains_key(&option_1.id()));
2736        assert!(state.fee_rates.contains_key(&option_2.id()));
2737    }
2738
2739    #[rstest]
2740    fn test_cache_execution_fee_rates_skips_malformed_rates() {
2741        let instrument = linear_instrument();
2742        let instruments = build_instruments(std::slice::from_ref(&instrument));
2743        let state = WsDispatchState::default();
2744
2745        let cached = cache_execution_fee_rates(
2746            &state,
2747            &instruments,
2748            BybitProductType::Linear,
2749            vec![fee_rate("BTCUSDT", None, "invalid", "0.0006")],
2750        );
2751
2752        assert_eq!(cached, 0);
2753        assert!(state.fee_rates.is_empty());
2754    }
2755
2756    fn fast_execution_msg(is_maker: bool, order_link_id: &str) -> BybitWsAccountExecutionFastMsg {
2757        BybitWsAccountExecutionFastMsg {
2758            topic: Ustr::from("execution.fast"),
2759            id: String::new(),
2760            creation_time: 1_716_800_399_338,
2761            data: vec![BybitWsAccountExecutionFast {
2762                category: BybitProductType::Linear,
2763                symbol: Ustr::from("BTCUSDT"),
2764                exec_id: "fast-1".to_string(),
2765                exec_price: "50000.0".to_string(),
2766                exec_qty: "0.5".to_string(),
2767                order_id: Ustr::from("ord-1"),
2768                order_link_id: Ustr::from(order_link_id),
2769                side: BybitOrderSide::Buy,
2770                exec_time: "1716800399334".to_string(),
2771                is_maker,
2772                seq: 42,
2773            }],
2774        }
2775    }
2776
2777    fn cache_fee_rates(state: &WsDispatchState, instrument: &InstrumentAny) {
2778        state.fee_rates.insert(
2779            instrument.id(),
2780            MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006)),
2781        );
2782    }
2783
2784    #[rstest]
2785    fn test_dispatch_tracked_fast_execution_preserves_venue_position_id() {
2786        let instrument = linear_instrument();
2787        let instruments = build_instruments(std::slice::from_ref(&instrument));
2788        let (emitter, mut rx) = create_emitter();
2789        let clock = get_atomic_clock_realtime();
2790        let state = WsDispatchState::default();
2791        cache_fee_rates(&state, &instrument);
2792        let venue_position_id = PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG");
2793
2794        // Taker fast fill (orderLinkId populated) so the identity lookup hits.
2795        let msg = fast_execution_msg(false, "link-1");
2796        let cid = ClientOrderId::new(msg.data[0].order_link_id);
2797        state.order_identities.insert(
2798            cid,
2799            OrderIdentity {
2800                venue_position_id: Some(venue_position_id),
2801                ..default_identity()
2802            },
2803        );
2804
2805        let ws_msg = BybitWsMessage::AccountExecutionFast(msg);
2806        dispatch_ws_message(
2807            &ws_msg,
2808            test_account_id(),
2809            &instruments,
2810            clock,
2811            &state,
2812            &emitter,
2813        );
2814
2815        // First event: synthesized OrderAccepted from the identity hit.
2816        let event1 = rx.try_recv().unwrap();
2817        assert!(
2818            matches!(event1, ExecutionEvent::Order(OrderEventAny::Accepted(_))),
2819            "Expected Accepted, found {event1:?}",
2820        );
2821
2822        // Second event: FillReport carrying the hedge venue_position_id.
2823        let event2 = rx.try_recv().unwrap();
2824        match event2 {
2825            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
2826                assert_eq!(report.venue_position_id, Some(venue_position_id));
2827                assert_eq!(report.client_order_id, Some(cid));
2828            }
2829            other => panic!("Expected FillReport, found {other:?}"),
2830        }
2831    }
2832
2833    fn order_msg(
2834        order_link_id: &str,
2835        status: &str,
2836        cum_exec_qty: &str,
2837    ) -> crate::websocket::messages::BybitWsAccountOrderMsg {
2838        let json = load_test_json("ws_account_order.json");
2839        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
2840        value["data"][0]["orderId"] = serde_json::Value::String("ord-1".to_string());
2841        value["data"][0]["orderLinkId"] = serde_json::Value::String(order_link_id.to_string());
2842        value["data"][0]["orderStatus"] = serde_json::Value::String(status.to_string());
2843        value["data"][0]["price"] = serde_json::Value::String("50000.0".to_string());
2844        value["data"][0]["qty"] = serde_json::Value::String("0.5".to_string());
2845        value["data"][0]["cumExecQty"] = serde_json::Value::String(cum_exec_qty.to_string());
2846        serde_json::from_value(value).unwrap()
2847    }
2848
2849    fn assert_fast_state_cleared(state: &WsDispatchState, client_order_id: ClientOrderId) {
2850        assert!(!state.order_identities.contains_key(&client_order_id));
2851        assert!(!state.order_venue_ids.contains_key(&client_order_id));
2852        assert!(
2853            !state
2854                .venue_order_ids
2855                .contains_key(&VenueOrderId::from("ord-1"))
2856        );
2857        assert!(!state.filled_orders.contains(&client_order_id));
2858        assert!(!state.fast_filled_quantities.contains_key(&client_order_id));
2859        assert!(
2860            !state
2861                .terminal_order_quantities
2862                .contains_key(&client_order_id)
2863        );
2864        assert!(state.pending_fast_executions.is_empty());
2865    }
2866
2867    #[rstest]
2868    #[case::fast_first(true)]
2869    #[case::order_first(false)]
2870    fn test_dispatch_untracked_fast_execution_emits_fill_report_without_position(
2871        #[case] fast_first: bool,
2872    ) {
2873        let instrument = linear_instrument();
2874        let instruments = build_instruments(std::slice::from_ref(&instrument));
2875        let (emitter, mut rx) = create_emitter();
2876        let clock = get_atomic_clock_realtime();
2877        let state = WsDispatchState::default();
2878        cache_fee_rates(&state, &instrument);
2879
2880        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
2881        let order_msg = BybitWsMessage::AccountOrder(order_msg("", "Filled", "0.5"));
2882
2883        if fast_first {
2884            dispatch_ws_message(
2885                &fast_msg,
2886                test_account_id(),
2887                &instruments,
2888                clock,
2889                &state,
2890                &emitter,
2891            );
2892            assert!(rx.try_recv().is_err());
2893            assert_eq!(state.pending_fast_executions.len(), 1);
2894        }
2895
2896        dispatch_ws_message(
2897            &order_msg,
2898            test_account_id(),
2899            &instruments,
2900            clock,
2901            &state,
2902            &emitter,
2903        );
2904
2905        if !fast_first {
2906            dispatch_ws_message(
2907                &fast_msg,
2908                test_account_id(),
2909                &instruments,
2910                clock,
2911                &state,
2912                &emitter,
2913            );
2914        }
2915
2916        let first = rx.try_recv().unwrap();
2917        let second = rx.try_recv().unwrap();
2918
2919        let report = if fast_first {
2920            assert!(matches!(
2921                second,
2922                ExecutionEvent::Report(ExecutionReport::Order(_))
2923            ));
2924
2925            match first {
2926                ExecutionEvent::Report(ExecutionReport::Fill(report)) => report,
2927                other => panic!("Expected FillReport first, found {other:?}"),
2928            }
2929        } else {
2930            assert!(matches!(
2931                first,
2932                ExecutionEvent::Report(ExecutionReport::Order(_))
2933            ));
2934
2935            match second {
2936                ExecutionEvent::Report(ExecutionReport::Fill(report)) => report,
2937                other => panic!("Expected FillReport second, found {other:?}"),
2938            }
2939        };
2940
2941        assert_eq!(report.client_order_id, None);
2942        assert_eq!(report.venue_position_id, None);
2943        assert_eq!(report.liquidity_side, LiquiditySide::Maker);
2944        assert_eq!(report.commission, Money::from("2.50000000 USDT"));
2945        assert!(state.pending_fast_executions.is_empty());
2946    }
2947
2948    #[rstest]
2949    fn test_dispatch_reconnected_flushes_pending_fast_execution() {
2950        let instrument = linear_instrument();
2951        let instruments = build_instruments(std::slice::from_ref(&instrument));
2952        let (emitter, mut rx) = create_emitter();
2953        let clock = get_atomic_clock_realtime();
2954        let state = WsDispatchState::new(true);
2955        cache_fee_rates(&state, &instrument);
2956        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
2957        dispatch_ws_message(
2958            &fast_msg,
2959            test_account_id(),
2960            &instruments,
2961            clock,
2962            &state,
2963            &emitter,
2964        );
2965        assert!(rx.try_recv().is_err());
2966        assert_eq!(state.pending_fast_executions.len(), 1);
2967
2968        dispatch_ws_message(
2969            &BybitWsMessage::Reconnected,
2970            test_account_id(),
2971            &instruments,
2972            clock,
2973            &state,
2974            &emitter,
2975        );
2976
2977        match rx.try_recv().unwrap() {
2978            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
2979                assert_eq!(report.client_order_id, None);
2980                assert_eq!(report.last_qty, Quantity::from("0.5"));
2981            }
2982            other => panic!("Expected FillReport, found {other:?}"),
2983        }
2984
2985        assert!(state.pending_fast_executions.is_empty());
2986    }
2987
2988    #[rstest]
2989    #[case::rejected("Rejected")]
2990    #[case::partially_filled_canceled("PartiallyFilledCanceled")]
2991    fn test_dispatch_partially_filled_terminal_defers_cleanup_until_fast_fill(
2992        #[case] status: &str,
2993    ) {
2994        let instrument = linear_instrument();
2995        let instruments = build_instruments(std::slice::from_ref(&instrument));
2996        let (emitter, _rx) = create_emitter();
2997        let clock = get_atomic_clock_realtime();
2998
2999        let state = WsDispatchState {
3000            fast_execution: true,
3001            ..Default::default()
3002        };
3003
3004        cache_fee_rates(&state, &instrument);
3005
3006        let client_order_id = ClientOrderId::from("link-1");
3007        state
3008            .order_identities
3009            .insert(client_order_id, default_identity());
3010        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", status, "0.5"));
3011        dispatch_ws_message(
3012            &order_msg,
3013            test_account_id(),
3014            &instruments,
3015            clock,
3016            &state,
3017            &emitter,
3018        );
3019
3020        assert!(state.order_identities.contains_key(&client_order_id));
3021        assert_eq!(
3022            *state
3023                .terminal_order_quantities
3024                .get(&client_order_id)
3025                .unwrap(),
3026            Quantity::from("0.5")
3027        );
3028
3029        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
3030        dispatch_ws_message(
3031            &fast_msg,
3032            test_account_id(),
3033            &instruments,
3034            clock,
3035            &state,
3036            &emitter,
3037        );
3038
3039        assert_fast_state_cleared(&state, client_order_id);
3040    }
3041
3042    #[rstest]
3043    fn test_dispatch_tracked_terminal_emits_deferred_fill_before_cancel() {
3044        let instrument = linear_instrument();
3045        let instruments = build_instruments(std::slice::from_ref(&instrument));
3046        let (emitter, mut rx) = create_emitter();
3047        let clock = get_atomic_clock_realtime();
3048        let state = WsDispatchState::new(true);
3049        cache_fee_rates(&state, &instrument);
3050        let client_order_id = ClientOrderId::from("link-1");
3051        state
3052            .order_identities
3053            .insert(client_order_id, default_identity());
3054        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
3055        dispatch_ws_message(
3056            &fast_msg,
3057            test_account_id(),
3058            &instruments,
3059            clock,
3060            &state,
3061            &emitter,
3062        );
3063        assert!(rx.try_recv().is_err());
3064
3065        let order_msg =
3066            BybitWsMessage::AccountOrder(order_msg("link-1", "PartiallyFilledCanceled", "0.5"));
3067        dispatch_ws_message(
3068            &order_msg,
3069            test_account_id(),
3070            &instruments,
3071            clock,
3072            &state,
3073            &emitter,
3074        );
3075
3076        assert!(matches!(
3077            rx.try_recv().unwrap(),
3078            ExecutionEvent::Order(OrderEventAny::Accepted(_))
3079        ));
3080        assert!(matches!(
3081            rx.try_recv().unwrap(),
3082            ExecutionEvent::Report(ExecutionReport::Fill(_))
3083        ));
3084        assert!(matches!(
3085            rx.try_recv().unwrap(),
3086            ExecutionEvent::Order(OrderEventAny::Canceled(_))
3087        ));
3088        assert_fast_state_cleared(&state, client_order_id);
3089    }
3090
3091    #[rstest]
3092    fn test_dispatch_zero_terminal_cleans_immediately() {
3093        let instrument = linear_instrument();
3094        let instruments = build_instruments(std::slice::from_ref(&instrument));
3095        let (emitter, _rx) = create_emitter();
3096        let clock = get_atomic_clock_realtime();
3097
3098        let state = WsDispatchState {
3099            fast_execution: true,
3100            ..Default::default()
3101        };
3102
3103        let client_order_id = ClientOrderId::from("link-1");
3104        state
3105            .order_identities
3106            .insert(client_order_id, default_identity());
3107        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", "Cancelled", "0"));
3108
3109        dispatch_ws_message(
3110            &order_msg,
3111            test_account_id(),
3112            &instruments,
3113            clock,
3114            &state,
3115            &emitter,
3116        );
3117
3118        assert_fast_state_cleared(&state, client_order_id);
3119    }
3120
3121    #[rstest]
3122    fn test_dispatch_standard_rejected_cleans_venue_correlation() {
3123        let instrument = linear_instrument();
3124        let instruments = build_instruments(std::slice::from_ref(&instrument));
3125        let (emitter, _rx) = create_emitter();
3126        let clock = get_atomic_clock_realtime();
3127        let state = WsDispatchState::default();
3128        let client_order_id = ClientOrderId::from("link-1");
3129        state
3130            .order_identities
3131            .insert(client_order_id, default_identity());
3132        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", "Rejected", "0"));
3133
3134        dispatch_ws_message(
3135            &order_msg,
3136            test_account_id(),
3137            &instruments,
3138            clock,
3139            &state,
3140            &emitter,
3141        );
3142
3143        assert_fast_state_cleared(&state, client_order_id);
3144    }
3145
3146    #[rstest]
3147    fn test_dispatch_fast_execution_parse_failure_allows_valid_replay() {
3148        let instrument = linear_instrument();
3149        let instruments = build_instruments(std::slice::from_ref(&instrument));
3150        let (emitter, mut rx) = create_emitter();
3151        let clock = get_atomic_clock_realtime();
3152        let state = WsDispatchState::default();
3153        cache_fee_rates(&state, &instrument);
3154        let mut invalid = fast_execution_msg(false, "link-1");
3155        invalid.data[0].exec_qty = "invalid".to_string();
3156        let invalid = BybitWsMessage::AccountExecutionFast(invalid);
3157
3158        dispatch_ws_message(
3159            &invalid,
3160            test_account_id(),
3161            &instruments,
3162            clock,
3163            &state,
3164            &emitter,
3165        );
3166        assert!(rx.try_recv().is_err());
3167
3168        let valid = BybitWsMessage::AccountExecutionFast(fast_execution_msg(false, "link-1"));
3169        dispatch_ws_message(
3170            &valid,
3171            test_account_id(),
3172            &instruments,
3173            clock,
3174            &state,
3175            &emitter,
3176        );
3177
3178        match rx.try_recv().unwrap() {
3179            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
3180                assert_eq!(report.trade_id.to_string(), "fast-1");
3181                assert_eq!(report.last_qty, Quantity::from("0.5"));
3182            }
3183            other => panic!("Expected FillReport, found {other:?}"),
3184        }
3185
3186        assert!(rx.try_recv().is_err());
3187    }
3188
3189    #[rstest]
3190    #[case::missing_rates(BybitProductType::Linear, None)]
3191    #[case::failed_derivation(
3192        BybitProductType::Linear,
3193        Some(MakerTakerFeeRates::new(dec!(0.0001), Decimal::MAX))
3194    )]
3195    #[case::option(
3196        BybitProductType::Option,
3197        Some(MakerTakerFeeRates::new(dec!(0.0001), dec!(0.0006)))
3198    )]
3199    fn test_dispatch_fast_execution_without_derivable_commission_releases_trade_id(
3200        #[case] category: BybitProductType,
3201        #[case] fee_rates: Option<MakerTakerFeeRates>,
3202    ) {
3203        let instrument = if category == BybitProductType::Option {
3204            option_instrument_with_distinct_settlement()
3205        } else {
3206            linear_instrument()
3207        };
3208
3209        let instruments = build_instruments(std::slice::from_ref(&instrument));
3210        let (emitter, mut rx) = create_emitter();
3211        let clock = get_atomic_clock_realtime();
3212        let state = WsDispatchState::new(true);
3213        if let Some(fee_rates) = fee_rates {
3214            state.fee_rates.insert(instrument.id(), fee_rates);
3215        }
3216
3217        let client_order_id = ClientOrderId::from("link-1");
3218        state
3219            .order_identities
3220            .insert(client_order_id, default_identity());
3221        let mut msg = fast_execution_msg(false, "link-1");
3222        msg.data[0].category = category;
3223        msg.data[0].symbol = instrument.raw_symbol().inner();
3224
3225        dispatch_ws_message(
3226            &BybitWsMessage::AccountExecutionFast(msg),
3227            test_account_id(),
3228            &instruments,
3229            clock,
3230            &state,
3231            &emitter,
3232        );
3233
3234        assert!(matches!(
3235            rx.try_recv().unwrap(),
3236            ExecutionEvent::Order(OrderEventAny::Accepted(_))
3237        ));
3238        assert!(rx.try_recv().is_err());
3239        assert!(!state.fast_execution_ids.contains(&TradeId::from("fast-1")));
3240        assert!(!state.filled_orders.contains(&client_order_id));
3241        assert!(!state.fast_filled_quantities.contains_key(&client_order_id));
3242    }
3243
3244    #[rstest]
3245    fn test_dispatch_fast_execution_replays_after_fee_rates_cached() {
3246        let instrument = linear_instrument();
3247        let instruments = build_instruments(std::slice::from_ref(&instrument));
3248        let (emitter, mut rx) = create_emitter();
3249        let clock = get_atomic_clock_realtime();
3250        let state = WsDispatchState::default();
3251        let msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(false, "link-1"));
3252
3253        dispatch_ws_message(
3254            &msg,
3255            test_account_id(),
3256            &instruments,
3257            clock,
3258            &state,
3259            &emitter,
3260        );
3261        assert!(rx.try_recv().is_err());
3262
3263        cache_fee_rates(&state, &instrument);
3264        dispatch_ws_message(
3265            &msg,
3266            test_account_id(),
3267            &instruments,
3268            clock,
3269            &state,
3270            &emitter,
3271        );
3272
3273        match rx.try_recv().unwrap() {
3274            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
3275                assert_eq!(report.trade_id, TradeId::from("fast-1"));
3276                assert_eq!(report.commission, Money::from("15.00000000 USDT"));
3277            }
3278            other => panic!("Expected FillReport, found {other:?}"),
3279        }
3280
3281        assert!(rx.try_recv().is_err());
3282        assert!(state.fast_execution_ids.contains(&TradeId::from("fast-1")));
3283    }
3284
3285    #[rstest]
3286    fn test_recent_ids_evicts_oldest_without_clearing_history() {
3287        let state = WsDispatchState::default();
3288        let first = TradeId::from("first");
3289        assert!(state.insert_fast_execution(first));
3290
3291        for index in 0..DEDUP_CAPACITY {
3292            assert!(state.insert_fast_execution(TradeId::from(format!("id-{index}"))));
3293        }
3294
3295        assert!(!state.fast_execution_ids.contains(&first));
3296        assert_eq!(state.fast_execution_ids.ids.len(), DEDUP_CAPACITY);
3297        assert!(state.insert_fast_execution(first));
3298        assert_eq!(state.fast_execution_ids.ids.len(), DEDUP_CAPACITY);
3299        assert!(!state.insert_fast_execution(first));
3300    }
3301
3302    #[rstest]
3303    fn test_fast_execution_correlation_and_enqueue_are_atomic() {
3304        for _ in 0..32 {
3305            let instrument = linear_instrument();
3306            let instruments = build_instruments(std::slice::from_ref(&instrument));
3307            let (emitter, mut rx) = create_emitter();
3308            let clock = get_atomic_clock_realtime();
3309            let state = Arc::new(WsDispatchState::new(true));
3310            cache_fee_rates(&state, &instrument);
3311            let client_order_id = ClientOrderId::from("link-1");
3312            state
3313                .order_identities
3314                .insert(client_order_id, default_identity());
3315            let venue_order_id = VenueOrderId::from("ord-1");
3316            let barrier = Arc::new(std::sync::Barrier::new(2));
3317
3318            std::thread::scope(|scope| {
3319                let state_ws = Arc::clone(&state);
3320                let barrier_ws = Arc::clone(&barrier);
3321                let emitter_ws = emitter.clone();
3322                let instruments_ws = &instruments;
3323
3324                scope.spawn(move || {
3325                    barrier_ws.wait();
3326                    let msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
3327                    dispatch_ws_message(
3328                        &msg,
3329                        test_account_id(),
3330                        instruments_ws,
3331                        clock,
3332                        &state_ws,
3333                        &emitter_ws,
3334                    );
3335                });
3336
3337                let state_rest = Arc::clone(&state);
3338                let barrier_rest = Arc::clone(&barrier);
3339                let emitter_rest = emitter.clone();
3340
3341                scope.spawn(move || {
3342                    barrier_rest.wait();
3343                    record_venue_order_id(client_order_id, venue_order_id, &state_rest);
3344                    drain_pending_fast_executions(
3345                        venue_order_id,
3346                        &instrument,
3347                        test_account_id(),
3348                        clock.get_time_ns(),
3349                        &state_rest,
3350                        &emitter_rest,
3351                    );
3352                });
3353            });
3354
3355            assert!(state.pending_fast_executions.is_empty());
3356            let mut fill_count = 0;
3357
3358            while let Ok(event) = rx.try_recv() {
3359                if matches!(event, ExecutionEvent::Report(ExecutionReport::Fill(_))) {
3360                    fill_count += 1;
3361                }
3362            }
3363
3364            assert_eq!(fill_count, 1);
3365        }
3366    }
3367
3368    #[rstest]
3369    #[case::fast_first(true)]
3370    #[case::order_first(false)]
3371    fn test_dispatch_maker_fast_execution_correlates_and_cleans_terminal_state(
3372        #[case] fast_first: bool,
3373    ) {
3374        let instrument = linear_instrument();
3375        let instruments = build_instruments(std::slice::from_ref(&instrument));
3376        let (emitter, mut rx) = create_emitter();
3377        let clock = get_atomic_clock_realtime();
3378        let state = WsDispatchState::new(true);
3379        cache_fee_rates(&state, &instrument);
3380        let client_order_id = ClientOrderId::from("link-1");
3381        let venue_position_id = PositionId::from("BTCUSDT-LINEAR.BYBIT-LONG");
3382        state.order_identities.insert(
3383            client_order_id,
3384            OrderIdentity {
3385                venue_position_id: Some(venue_position_id),
3386                ..default_identity()
3387            },
3388        );
3389
3390        let fast_msg = BybitWsMessage::AccountExecutionFast(fast_execution_msg(true, ""));
3391        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", "Filled", "0.5"));
3392
3393        if fast_first {
3394            dispatch_ws_message(
3395                &fast_msg,
3396                test_account_id(),
3397                &instruments,
3398                clock,
3399                &state,
3400                &emitter,
3401            );
3402            assert!(rx.try_recv().is_err());
3403        }
3404
3405        dispatch_ws_message(
3406            &order_msg,
3407            test_account_id(),
3408            &instruments,
3409            clock,
3410            &state,
3411            &emitter,
3412        );
3413
3414        if !fast_first {
3415            dispatch_ws_message(
3416                &fast_msg,
3417                test_account_id(),
3418                &instruments,
3419                clock,
3420                &state,
3421                &emitter,
3422            );
3423        }
3424
3425        assert!(matches!(
3426            rx.try_recv().unwrap(),
3427            ExecutionEvent::Order(OrderEventAny::Accepted(_))
3428        ));
3429
3430        match rx.try_recv().unwrap() {
3431            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
3432                assert_eq!(report.client_order_id, Some(client_order_id));
3433                assert_eq!(report.venue_position_id, Some(venue_position_id));
3434            }
3435            other => panic!("Expected FillReport, found {other:?}"),
3436        }
3437
3438        assert_fast_state_cleared(&state, client_order_id);
3439    }
3440
3441    #[rstest]
3442    fn test_dispatch_fast_execution_waits_for_terminal_quantity_and_dedups() {
3443        let instrument = linear_instrument();
3444        let instruments = build_instruments(std::slice::from_ref(&instrument));
3445        let (emitter, _rx) = create_emitter();
3446        let clock = get_atomic_clock_realtime();
3447        let state = WsDispatchState::default();
3448        cache_fee_rates(&state, &instrument);
3449        let client_order_id = ClientOrderId::from("link-1");
3450        state
3451            .order_identities
3452            .insert(client_order_id, default_identity());
3453        let mut first = fast_execution_msg(false, "link-1");
3454        first.data[0].exec_qty = "0.25".to_string();
3455        let first = BybitWsMessage::AccountExecutionFast(first);
3456
3457        dispatch_ws_message(
3458            &first,
3459            test_account_id(),
3460            &instruments,
3461            clock,
3462            &state,
3463            &emitter,
3464        );
3465        dispatch_ws_message(
3466            &first,
3467            test_account_id(),
3468            &instruments,
3469            clock,
3470            &state,
3471            &emitter,
3472        );
3473        assert_eq!(
3474            *state.fast_filled_quantities.get(&client_order_id).unwrap(),
3475            Quantity::from("0.25")
3476        );
3477
3478        let order_msg = BybitWsMessage::AccountOrder(order_msg("link-1", "Filled", "0.5"));
3479        dispatch_ws_message(
3480            &order_msg,
3481            test_account_id(),
3482            &instruments,
3483            clock,
3484            &state,
3485            &emitter,
3486        );
3487        assert!(state.order_identities.contains_key(&client_order_id));
3488
3489        let mut second = fast_execution_msg(false, "link-1");
3490        second.data[0].exec_id = "fast-2".to_string();
3491        second.data[0].exec_qty = "0.25".to_string();
3492        let second = BybitWsMessage::AccountExecutionFast(second);
3493        dispatch_ws_message(
3494            &second,
3495            test_account_id(),
3496            &instruments,
3497            clock,
3498            &state,
3499            &emitter,
3500        );
3501
3502        assert_fast_state_cleared(&state, client_order_id);
3503        assert_eq!(state.fast_execution_ids.ids.len(), 2);
3504    }
3505
3506    #[rstest]
3507    fn test_dispatch_untracked_execution_emits_fill_report() {
3508        let instrument = linear_instrument();
3509        let instruments = build_instruments(std::slice::from_ref(&instrument));
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_execution.json");
3515        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
3516            serde_json::from_str(&json).unwrap();
3517
3518        // No identity registered → untracked
3519        let ws_msg = BybitWsMessage::AccountExecution(msg);
3520        dispatch_ws_message(
3521            &ws_msg,
3522            test_account_id(),
3523            &instruments,
3524            clock,
3525            &state,
3526            &emitter,
3527        );
3528
3529        let event = rx.try_recv().unwrap();
3530        assert!(matches!(
3531            event,
3532            ExecutionEvent::Report(ExecutionReport::Fill(_))
3533        ));
3534    }
3535
3536    #[rstest]
3537    #[case::untracked("")]
3538    #[case::tracked("test-order-link-001")]
3539    fn test_dispatch_funding_execution_emits_no_event(#[case] order_link_id: &str) {
3540        let instrument = linear_instrument();
3541        let instruments = build_instruments(std::slice::from_ref(&instrument));
3542        let (emitter, mut rx) = create_emitter();
3543        let clock = get_atomic_clock_realtime();
3544        let state = WsDispatchState::default();
3545
3546        let json = load_test_json("ws_account_execution_funding.json");
3547        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
3548        value["data"][0]["orderLinkId"] = serde_json::Value::String(order_link_id.to_string());
3549        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
3550            serde_json::from_value(value).unwrap();
3551        let execution = &msg.data[0];
3552
3553        assert_eq!(execution.exec_type, BybitExecType::Funding);
3554
3555        if !execution.order_link_id.is_empty() {
3556            state.order_identities.insert(
3557                ClientOrderId::new(execution.order_link_id),
3558                default_identity(),
3559            );
3560        }
3561
3562        dispatch_ws_message(
3563            &BybitWsMessage::AccountExecution(msg),
3564            test_account_id(),
3565            &instruments,
3566            clock,
3567            &state,
3568            &emitter,
3569        );
3570
3571        assert!(matches!(
3572            rx.try_recv(),
3573            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
3574        ));
3575    }
3576
3577    #[rstest]
3578    #[case::corporate_action("CorporateAction")]
3579    #[case::forward_split_settle("ForwardSplitSettle")]
3580    #[case::reverse_split_settle("ReverseSplitSettle")]
3581    #[case::dividend("Dividend")]
3582    #[case::unrecognized("StockMerger")]
3583    fn test_dispatch_venue_initiated_execution_emits_only_fill_report(#[case] exec_type: &str) {
3584        let instrument = linear_instrument();
3585        let instruments = build_instruments(std::slice::from_ref(&instrument));
3586        let (emitter, mut rx) = create_emitter();
3587        let clock = get_atomic_clock_realtime();
3588        let state = WsDispatchState::default();
3589
3590        let json = load_test_json("ws_account_execution_adl.json");
3591        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
3592        value["data"][0]["execType"] = serde_json::Value::String(exec_type.to_string());
3593        let msg: crate::websocket::messages::BybitWsAccountExecutionMsg =
3594            serde_json::from_value(value).unwrap();
3595        let execution = &msg.data[0];
3596
3597        assert!(execution.order_link_id.is_empty());
3598
3599        dispatch_ws_message(
3600            &BybitWsMessage::AccountExecution(msg),
3601            test_account_id(),
3602            &instruments,
3603            clock,
3604            &state,
3605            &emitter,
3606        );
3607
3608        let event = rx.try_recv().unwrap();
3609        match event {
3610            ExecutionEvent::Report(ExecutionReport::Fill(report)) => {
3611                assert_eq!(report.client_order_id, None);
3612                assert_eq!(
3613                    report.venue_order_id,
3614                    VenueOrderId::from("9aac161b-8ed6-450d-9cab-c5cc67c21785")
3615                );
3616            }
3617            other => panic!("Expected FillReport, found {other:?}"),
3618        }
3619        assert!(rx.try_recv().is_err());
3620    }
3621
3622    #[rstest]
3623    fn test_dispatch_wallet_emits_account_state() {
3624        let instruments = AHashMap::new();
3625        let (emitter, mut rx) = create_emitter();
3626        let clock = get_atomic_clock_realtime();
3627        let state = WsDispatchState::default();
3628
3629        let json = load_test_json("ws_account_wallet.json");
3630        let msg: crate::websocket::messages::BybitWsAccountWalletMsg =
3631            serde_json::from_str(&json).unwrap();
3632        let ws_msg = BybitWsMessage::AccountWallet(msg);
3633
3634        dispatch_ws_message(
3635            &ws_msg,
3636            test_account_id(),
3637            &instruments,
3638            clock,
3639            &state,
3640            &emitter,
3641        );
3642
3643        let event = rx.try_recv().unwrap();
3644        assert!(matches!(event, ExecutionEvent::Account(_)));
3645    }
3646
3647    #[rstest]
3648    fn test_dispatch_data_message_ignored() {
3649        let instruments = AHashMap::new();
3650        let (emitter, mut rx) = create_emitter();
3651        let clock = get_atomic_clock_realtime();
3652        let state = WsDispatchState::default();
3653
3654        let json = load_test_json("ws_public_trade.json");
3655        let msg: crate::websocket::messages::BybitWsTradeMsg = serde_json::from_str(&json).unwrap();
3656        let ws_msg = BybitWsMessage::Trade(msg);
3657
3658        dispatch_ws_message(
3659            &ws_msg,
3660            test_account_id(),
3661            &instruments,
3662            clock,
3663            &state,
3664            &emitter,
3665        );
3666
3667        rx.try_recv().unwrap_err();
3668    }
3669
3670    #[rstest]
3671    fn test_accepted_dedup_prevents_duplicate() {
3672        let instrument = linear_instrument();
3673        let instruments = build_instruments(std::slice::from_ref(&instrument));
3674        let (emitter, mut rx) = create_emitter();
3675        let clock = get_atomic_clock_realtime();
3676        let state = WsDispatchState::default();
3677
3678        // Fixture has orderStatus=Cancelled. Patch to New for this dedup test.
3679        let json = load_test_json("ws_account_order.json");
3680        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
3681        value["data"][0]["orderStatus"] = serde_json::Value::String("New".to_string());
3682        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
3683            serde_json::from_value(value).unwrap();
3684
3685        if let Some(order) = msg.data.first()
3686            && !order.order_link_id.is_empty()
3687        {
3688            let cid = ClientOrderId::new(order.order_link_id);
3689            state.order_identities.insert(cid, default_identity());
3690        }
3691
3692        let ws_msg = BybitWsMessage::AccountOrder(msg.clone());
3693        dispatch_ws_message(
3694            &ws_msg,
3695            test_account_id(),
3696            &instruments,
3697            clock,
3698            &state,
3699            &emitter,
3700        );
3701
3702        let event = rx.try_recv().unwrap();
3703        assert!(matches!(
3704            event,
3705            ExecutionEvent::Order(OrderEventAny::Accepted(_))
3706        ));
3707
3708        // Dispatch the same message again: dedup should suppress the duplicate
3709        let ws_msg2 = BybitWsMessage::AccountOrder(msg);
3710        dispatch_ws_message(
3711            &ws_msg2,
3712            test_account_id(),
3713            &instruments,
3714            clock,
3715            &state,
3716            &emitter,
3717        );
3718
3719        rx.try_recv().unwrap_err();
3720    }
3721
3722    fn new_order_value() -> serde_json::Value {
3723        let json = load_test_json("ws_account_order.json");
3724        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
3725        value["data"][0]["orderStatus"] = serde_json::Value::String("New".to_string());
3726        value
3727    }
3728
3729    struct DispatchTestContext {
3730        instruments: AHashMap<Ustr, InstrumentAny>,
3731        emitter: ExecutionEventEmitter,
3732        rx: tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
3733        clock: &'static AtomicTime,
3734        state: WsDispatchState,
3735    }
3736
3737    impl DispatchTestContext {
3738        fn new() -> Self {
3739            let instrument = linear_instrument();
3740            let instruments = build_instruments(std::slice::from_ref(&instrument));
3741            let (emitter, rx) = create_emitter();
3742            let clock = get_atomic_clock_realtime();
3743            let state = WsDispatchState::default();
3744            Self {
3745                instruments,
3746                emitter,
3747                rx,
3748                clock,
3749                state,
3750            }
3751        }
3752
3753        fn accept_order(&mut self, value: &serde_json::Value) {
3754            let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
3755                serde_json::from_value(value.clone()).unwrap();
3756
3757            if let Some(order) = msg.data.first()
3758                && !order.order_link_id.is_empty()
3759                && !self
3760                    .state
3761                    .order_identities
3762                    .contains_key(&ClientOrderId::new(order.order_link_id))
3763            {
3764                let cid = ClientOrderId::new(order.order_link_id);
3765                self.state.order_identities.insert(cid, default_identity());
3766            }
3767
3768            self.dispatch_value(value);
3769
3770            let event = self.rx.try_recv().unwrap();
3771            assert!(
3772                matches!(event, ExecutionEvent::Order(OrderEventAny::Accepted(_))),
3773                "Expected Accepted, found {event:?}"
3774            );
3775        }
3776
3777        fn dispatch_value(&self, value: &serde_json::Value) {
3778            let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
3779                serde_json::from_value(value.clone()).unwrap();
3780            let ws_msg = BybitWsMessage::AccountOrder(msg);
3781            dispatch_ws_message(
3782                &ws_msg,
3783                test_account_id(),
3784                &self.instruments,
3785                self.clock,
3786                &self.state,
3787                &self.emitter,
3788            );
3789        }
3790
3791        fn recv_updated(&mut self) -> OrderUpdated {
3792            let event = self.rx.try_recv().unwrap();
3793            match event {
3794                ExecutionEvent::Order(OrderEventAny::Updated(updated)) => updated,
3795                other => panic!("Expected Updated event, found {other:?}"),
3796            }
3797        }
3798    }
3799
3800    #[rstest]
3801    fn test_dispatch_order_updated_on_price_change() {
3802        let mut ctx = DispatchTestContext::new();
3803        let value = new_order_value();
3804        ctx.accept_order(&value);
3805
3806        let mut amended = value;
3807        amended["data"][0]["price"] = serde_json::Value::String("31000".to_string());
3808        ctx.dispatch_value(&amended);
3809
3810        let updated = ctx.recv_updated();
3811        assert_eq!(updated.client_order_id, ClientOrderId::from("client-1"));
3812        assert_eq!(updated.price, Some(Price::from("31000.00")));
3813        assert_eq!(updated.quantity, Quantity::from("0.010"));
3814        assert_eq!(updated.trigger_price, None);
3815        assert!(updated.venue_order_id.is_some());
3816    }
3817
3818    #[rstest]
3819    fn test_dispatch_order_updated_on_quantity_change() {
3820        let mut ctx = DispatchTestContext::new();
3821        let value = new_order_value();
3822        ctx.accept_order(&value);
3823
3824        let mut amended = value;
3825        amended["data"][0]["qty"] = serde_json::Value::String("0.020".to_string());
3826        ctx.dispatch_value(&amended);
3827
3828        let updated = ctx.recv_updated();
3829        assert_eq!(updated.quantity, Quantity::from("0.020"));
3830        assert_eq!(updated.price, Some(Price::from("30000.00")));
3831    }
3832
3833    #[rstest]
3834    fn test_dispatch_order_updated_on_trigger_price_change() {
3835        let mut ctx = DispatchTestContext::new();
3836        let mut value = new_order_value();
3837        value["data"][0]["triggerPrice"] = serde_json::Value::String("29000".to_string());
3838        ctx.accept_order(&value);
3839
3840        let mut amended = value;
3841        amended["data"][0]["triggerPrice"] = serde_json::Value::String("28000".to_string());
3842        ctx.dispatch_value(&amended);
3843
3844        let updated = ctx.recv_updated();
3845        assert_eq!(updated.trigger_price, Some(Price::from("28000.00")));
3846        assert_eq!(updated.price, Some(Price::from("30000.00")));
3847    }
3848
3849    #[rstest]
3850    fn test_dispatch_dedup_suppresses_identical_after_snapshot() {
3851        let mut ctx = DispatchTestContext::new();
3852        let value = new_order_value();
3853        ctx.accept_order(&value);
3854
3855        ctx.dispatch_value(&value);
3856
3857        assert!(
3858            ctx.rx.try_recv().is_err(),
3859            "Expected no event for identical redelivery"
3860        );
3861    }
3862
3863    #[rstest]
3864    fn test_dispatch_order_updated_stores_snapshot_for_subsequent_change() {
3865        let mut ctx = DispatchTestContext::new();
3866        let value = new_order_value();
3867        ctx.accept_order(&value);
3868
3869        let mut amended1 = value.clone();
3870        amended1["data"][0]["price"] = serde_json::Value::String("31000".to_string());
3871        ctx.dispatch_value(&amended1);
3872        let _result = ctx.recv_updated();
3873
3874        let mut amended2 = value;
3875        amended2["data"][0]["price"] = serde_json::Value::String("32000".to_string());
3876        ctx.dispatch_value(&amended2);
3877
3878        let updated = ctx.recv_updated();
3879        assert_eq!(updated.price, Some(Price::from("32000.00")));
3880    }
3881
3882    #[rstest]
3883    fn test_dispatch_accepted_with_seeded_snapshot_emits_updated_for_bbo() {
3884        let mut ctx = DispatchTestContext::new();
3885        let value = new_order_value();
3886        let cid = ClientOrderId::from("client-1");
3887        ctx.state.order_identities.insert(cid, default_identity());
3888        ctx.state.order_snapshots.insert(
3889            cid,
3890            OrderStateSnapshot {
3891                quantity: Quantity::from("0.010"),
3892                price: Some(Price::from("29000.00")),
3893                trigger_price: None,
3894            },
3895        );
3896
3897        ctx.dispatch_value(&value);
3898
3899        let accepted = ctx.rx.try_recv().unwrap();
3900        assert!(
3901            matches!(accepted, ExecutionEvent::Order(OrderEventAny::Accepted(_))),
3902            "Expected Accepted first, found {accepted:?}"
3903        );
3904
3905        let updated = ctx.recv_updated();
3906        assert_eq!(updated.client_order_id, cid);
3907        assert_eq!(updated.price, Some(Price::from("30000.00")));
3908        assert_eq!(updated.quantity, Quantity::from("0.010"));
3909        assert!(updated.venue_order_id.is_some());
3910    }
3911
3912    #[rstest]
3913    fn test_emit_rejection_for_place_clears_snapshot() {
3914        let ctx = DispatchTestContext::new();
3915        let cid = ClientOrderId::from("client-1");
3916        let identity = default_identity();
3917        ctx.state.order_identities.insert(cid, identity.clone());
3918        ctx.state.order_snapshots.insert(
3919            cid,
3920            OrderStateSnapshot {
3921                quantity: Quantity::from("0.010"),
3922                price: Some(Price::from("30000.00")),
3923                trigger_price: None,
3924            },
3925        );
3926
3927        emit_rejection_for_op(
3928            &PendingOperation::Place,
3929            cid,
3930            &identity,
3931            None,
3932            "rejected",
3933            &ctx.emitter,
3934            &ctx.state,
3935            UnixNanos::from(1u64),
3936            None,
3937        );
3938
3939        assert!(!ctx.state.order_identities.contains_key(&cid));
3940        assert!(!ctx.state.order_snapshots.contains_key(&cid));
3941    }
3942
3943    fn order_response(
3944        op: &str,
3945        ret_code: i64,
3946        ret_msg: &str,
3947        req_id: &str,
3948        data: serde_json::Value,
3949        ret_ext_info: Option<serde_json::Value>,
3950    ) -> BybitWsOrderResponse {
3951        BybitWsOrderResponse {
3952            op: Ustr::from(op),
3953            conn_id: Some("test-conn-id".to_string()),
3954            ret_code,
3955            ret_msg: ret_msg.to_string(),
3956            data,
3957            req_id: Some(req_id.to_string()),
3958            header: None,
3959            ret_ext_info,
3960        }
3961    }
3962
3963    #[rstest]
3964    fn test_dispatch_local_not_sent_emits_order_rejected() {
3965        let mut ctx = DispatchTestContext::new();
3966        let cid = ClientOrderId::from("not-sent-1");
3967        ctx.state.order_identities.insert(cid, default_identity());
3968        ctx.state.pending_requests.insert(
3969            "req-not-sent".to_string(),
3970            (vec![cid], vec![None], PendingOperation::Place, Vec::new()),
3971        );
3972        dispatch_order_not_sent(
3973            "req-not-sent",
3974            "Order command was not written",
3975            &ctx.emitter,
3976            &ctx.state,
3977            UnixNanos::from(1u64),
3978        );
3979
3980        let event = ctx.rx.try_recv().expect("expected OrderRejected event");
3981        assert!(
3982            matches!(event, ExecutionEvent::Order(OrderEventAny::Rejected(ref rejected))
3983                if rejected.client_order_id == cid
3984                    && rejected.reason == "Order command was not written"),
3985            "Expected OrderRejected for {cid}, found {event:?}"
3986        );
3987        assert!(!ctx.state.order_identities.contains_key(&cid));
3988        assert!(!ctx.state.pending_requests.contains_key("req-not-sent"));
3989    }
3990
3991    #[rstest]
3992    #[case::modify(PendingOperation::Amend)]
3993    #[case::cancel(PendingOperation::Cancel)]
3994    fn test_dispatch_local_refusal_preserves_each_command(#[case] operation: PendingOperation) {
3995        let mut ctx = DispatchTestContext::new();
3996        let first = ClientOrderId::from("O-LOCAL-FIRST");
3997        let second = ClientOrderId::from("O-LOCAL-SECOND");
3998        let first_cause = UUID4::new();
3999        let second_cause = UUID4::new();
4000        let venue_order_id = VenueOrderId::from("V-LOCAL-FIRST");
4001        ctx.state.order_identities.insert(first, default_identity());
4002        ctx.state
4003            .order_identities
4004            .insert(second, default_identity());
4005        ctx.state.pending_requests.insert(
4006            "req-local".to_string(),
4007            (
4008                vec![first, second],
4009                vec![Some(venue_order_id), None],
4010                operation,
4011                vec![Some(first_cause), Some(second_cause)],
4012            ),
4013        );
4014        dispatch_order_not_sent(
4015            "req-local",
4016            "Command was not written",
4017            &ctx.emitter,
4018            &ctx.state,
4019            UnixNanos::from(17),
4020        );
4021
4022        for (client_order_id, cause, venue) in [
4023            (first, first_cause, Some(venue_order_id)),
4024            (second, second_cause, None),
4025        ] {
4026            let ExecutionEvent::Order(event) = ctx.rx.try_recv().unwrap() else {
4027                panic!("expected order outcome")
4028            };
4029
4030            let (actual_cause, reason) = match (operation, &event) {
4031                (PendingOperation::Amend, OrderEventAny::ModifyDenied(event)) => {
4032                    (event.causation_id, event.reason.as_str())
4033                }
4034                (PendingOperation::Cancel, OrderEventAny::CancelDenied(event)) => {
4035                    (event.causation_id, event.reason.as_str())
4036                }
4037                _ => panic!("unexpected refusal {event:?}"),
4038            };
4039
4040            assert_eq!(actual_cause, Some(cause));
4041            assert_eq!(reason, "Command was not written");
4042            assert_eq!(event.client_order_id(), client_order_id);
4043            assert_eq!(event.venue_order_id(), venue);
4044            assert_eq!(event.strategy_id(), default_identity().strategy_id);
4045            assert_eq!(event.instrument_id(), default_identity().instrument_id);
4046            assert_eq!(event.ts_event(), UnixNanos::from(17));
4047        }
4048
4049        assert!(ctx.rx.try_recv().is_err());
4050        assert!(!ctx.state.pending_requests.contains_key("req-local"));
4051        assert!(ctx.state.order_identities.contains_key(&first));
4052        assert!(ctx.state.order_identities.contains_key(&second));
4053    }
4054
4055    #[rstest]
4056    fn test_dispatch_single_cancel_rejection_emits_cancel_rejected() {
4057        let mut ctx = DispatchTestContext::new();
4058        let cause = UUID4::new();
4059        let cid = ClientOrderId::from("cancel-reject-1");
4060        let venue_order_id = VenueOrderId::from("venue-cancel-1");
4061        ctx.state.order_identities.insert(cid, default_identity());
4062        ctx.state.pending_requests.insert(
4063            "req-cancel".to_string(),
4064            (
4065                vec![cid],
4066                vec![Some(venue_order_id)],
4067                PendingOperation::Cancel,
4068                vec![Some(cause)],
4069            ),
4070        );
4071
4072        let response = order_response(
4073            BYBIT_OP_ORDER_CANCEL,
4074            110001,
4075            "Order does not exist.",
4076            "req-cancel",
4077            serde_json::json!({
4078                "orderId": venue_order_id.to_string(),
4079                "orderLinkId": cid.to_string(),
4080            }),
4081            None,
4082        );
4083
4084        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4085
4086        let event = ctx.rx.try_recv().expect("expected CancelRejected event");
4087        assert!(
4088            matches!(event, ExecutionEvent::Order(OrderEventAny::CancelRejected(ref rejected)) if rejected.client_order_id == cid && rejected.causation_id == Some(cause)),
4089            "Expected CancelRejected for {cid}, found {event:?}"
4090        );
4091        assert!(
4092            ctx.rx.try_recv().is_err(),
4093            "Expected no extra events for single cancel rejection"
4094        );
4095    }
4096
4097    #[rstest]
4098    fn test_dispatch_single_modify_rejection_emits_modify_rejected() {
4099        let mut ctx = DispatchTestContext::new();
4100        let cause = UUID4::new();
4101        let cid = ClientOrderId::from("modify-reject-1");
4102        let venue_order_id = VenueOrderId::from("venue-modify-1");
4103        ctx.state.order_identities.insert(cid, default_identity());
4104        ctx.state.pending_requests.insert(
4105            "req-modify".to_string(),
4106            (
4107                vec![cid],
4108                vec![Some(venue_order_id)],
4109                PendingOperation::Amend,
4110                vec![Some(cause)],
4111            ),
4112        );
4113
4114        let response = order_response(
4115            BYBIT_OP_ORDER_AMEND,
4116            110003,
4117            "Order price exceeds allowable range.",
4118            "req-modify",
4119            serde_json::json!({
4120                "orderId": venue_order_id.to_string(),
4121                "orderLinkId": cid.to_string(),
4122            }),
4123            None,
4124        );
4125
4126        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4127
4128        let event = ctx.rx.try_recv().expect("expected ModifyRejected event");
4129        assert!(
4130            matches!(event, ExecutionEvent::Order(OrderEventAny::ModifyRejected(ref rejected)) if rejected.client_order_id == cid && rejected.causation_id == Some(cause)),
4131            "Expected ModifyRejected for {cid}, found {event:?}"
4132        );
4133        assert!(
4134            ctx.rx.try_recv().is_err(),
4135            "Expected no extra events for single modify rejection"
4136        );
4137    }
4138
4139    #[rstest]
4140    fn test_dispatch_single_place_rejection_emits_order_rejected() {
4141        let mut ctx = DispatchTestContext::new();
4142        let cid = ClientOrderId::from("place-reject-1");
4143        ctx.state.order_identities.insert(cid, default_identity());
4144        ctx.state.pending_requests.insert(
4145            "req-place".to_string(),
4146            (vec![cid], vec![None], PendingOperation::Place, Vec::new()),
4147        );
4148
4149        let response = order_response(
4150            BYBIT_OP_ORDER_CREATE,
4151            110017,
4152            "orderQty will be truncated to zero",
4153            "req-place",
4154            serde_json::json!({
4155                "orderLinkId": cid.to_string(),
4156            }),
4157            None,
4158        );
4159
4160        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4161
4162        let event = ctx.rx.try_recv().expect("expected OrderRejected event");
4163        assert!(
4164            matches!(event, ExecutionEvent::Order(OrderEventAny::Rejected(ref rejected))
4165                if rejected.client_order_id == cid
4166                    && rejected.reason == "orderQty will be truncated to zero"),
4167            "Expected OrderRejected for {cid}, found {event:?}"
4168        );
4169        assert!(ctx.rx.try_recv().is_err());
4170        assert!(!ctx.state.order_identities.contains_key(&cid));
4171    }
4172
4173    #[rstest]
4174    #[case::place_frequency(PendingOperation::Place, BYBIT_OP_ORDER_CREATE, 10429)]
4175    #[case::amend_frequency(PendingOperation::Amend, BYBIT_OP_ORDER_AMEND, 10429)]
4176    #[case::cancel_frequency(PendingOperation::Cancel, BYBIT_OP_ORDER_CANCEL, 10429)]
4177    #[case::place_visits(PendingOperation::Place, BYBIT_OP_ORDER_CREATE, 10006)]
4178    #[case::amend_visits(PendingOperation::Amend, BYBIT_OP_ORDER_AMEND, 10006)]
4179    #[case::cancel_visits(PendingOperation::Cancel, BYBIT_OP_ORDER_CANCEL, 10006)]
4180    fn test_dispatch_single_rate_limit_emits_no_terminal_rejection(
4181        #[case] operation: PendingOperation,
4182        #[case] op: &str,
4183        #[case] ret_code: i64,
4184    ) {
4185        let mut ctx = DispatchTestContext::new();
4186        let cid = ClientOrderId::from("rate-limit-1");
4187        let venue_order_id = VenueOrderId::from("venue-rate-limit-1");
4188        ctx.state.order_identities.insert(cid, default_identity());
4189        ctx.state.pending_requests.insert(
4190            "req-rate-limit".to_string(),
4191            (vec![cid], vec![Some(venue_order_id)], operation, Vec::new()),
4192        );
4193
4194        let response = order_response(
4195            op,
4196            ret_code,
4197            "rate limit",
4198            "req-rate-limit",
4199            serde_json::json!({
4200                "orderId": venue_order_id.to_string(),
4201                "orderLinkId": cid.to_string(),
4202            }),
4203            None,
4204        );
4205
4206        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4207
4208        assert!(
4209            ctx.rx.try_recv().is_err(),
4210            "Rate-limit response must not emit a terminal rejection"
4211        );
4212        assert!(ctx.state.order_identities.contains_key(&cid));
4213        assert!(!ctx.state.pending_requests.contains_key("req-rate-limit"));
4214    }
4215
4216    #[rstest]
4217    fn test_dispatch_single_modify_server_error_keeps_outcome_unresolved() {
4218        let mut ctx = DispatchTestContext::new();
4219        let cid = ClientOrderId::from("modify-server-error-1");
4220        let venue_order_id = VenueOrderId::from("venue-modify-server-error-1");
4221        ctx.state.order_identities.insert(cid, default_identity());
4222        ctx.state.pending_requests.insert(
4223            "req-modify-server-error".to_string(),
4224            (
4225                vec![cid],
4226                vec![Some(venue_order_id)],
4227                PendingOperation::Amend,
4228                Vec::new(),
4229            ),
4230        );
4231
4232        let response = order_response(
4233            BYBIT_OP_ORDER_AMEND,
4234            10016,
4235            "Internal server error.",
4236            "req-modify-server-error",
4237            serde_json::json!({
4238                "orderId": venue_order_id.to_string(),
4239                "orderLinkId": cid.to_string(),
4240            }),
4241            None,
4242        );
4243
4244        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4245
4246        assert!(
4247            ctx.rx.try_recv().is_err(),
4248            "Expected no ModifyRejected event for server error response"
4249        );
4250        assert!(ctx.state.order_identities.contains_key(&cid));
4251    }
4252
4253    #[rstest]
4254    fn test_dispatch_batch_cancel_top_level_failure_does_not_emit_cancel_rejected() {
4255        let mut ctx = DispatchTestContext::new();
4256        let cid_1 = ClientOrderId::from("batch-cancel-1");
4257        let cid_2 = ClientOrderId::from("batch-cancel-2");
4258        ctx.state.order_identities.insert(cid_1, default_identity());
4259        ctx.state.order_identities.insert(cid_2, default_identity());
4260        ctx.state.pending_requests.insert(
4261            "req-batch-cancel".to_string(),
4262            (
4263                vec![cid_1, cid_2],
4264                vec![
4265                    Some(VenueOrderId::from("venue-batch-1")),
4266                    Some(VenueOrderId::from("venue-batch-2")),
4267                ],
4268                PendingOperation::Cancel,
4269                Vec::new(),
4270            ),
4271        );
4272
4273        let response = order_response(
4274            BYBIT_OP_ORDER_CANCEL_BATCH,
4275            10016,
4276            "Internal server error.",
4277            "req-batch-cancel",
4278            serde_json::json!({}),
4279            None,
4280        );
4281
4282        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4283
4284        assert!(
4285            ctx.rx.try_recv().is_err(),
4286            "Expected no CancelRejected events for ambiguous batch failure"
4287        );
4288        assert!(ctx.state.order_identities.contains_key(&cid_1));
4289        assert!(ctx.state.order_identities.contains_key(&cid_2));
4290    }
4291
4292    #[rstest]
4293    fn test_dispatch_single_item_batch_cancel_top_level_failure_does_not_emit_cancel_rejected() {
4294        let mut ctx = DispatchTestContext::new();
4295        let cid = ClientOrderId::from("batch-cancel-single");
4296        ctx.state.order_identities.insert(cid, default_identity());
4297        ctx.state.pending_requests.insert(
4298            "req-batch-cancel-single".to_string(),
4299            (
4300                vec![cid],
4301                vec![Some(VenueOrderId::from("venue-batch-single"))],
4302                PendingOperation::Cancel,
4303                Vec::new(),
4304            ),
4305        );
4306
4307        let response = order_response(
4308            BYBIT_OP_ORDER_CANCEL_BATCH,
4309            10016,
4310            "Internal server error.",
4311            "req-batch-cancel-single",
4312            serde_json::json!({}),
4313            None,
4314        );
4315
4316        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4317
4318        assert!(
4319            ctx.rx.try_recv().is_err(),
4320            "Expected no CancelRejected event for ambiguous one-item batch failure"
4321        );
4322        assert!(ctx.state.order_identities.contains_key(&cid));
4323    }
4324
4325    #[rstest]
4326    #[case::place(PendingOperation::Place, BYBIT_OP_ORDER_CREATE_BATCH, 10429)]
4327    #[case::amend(PendingOperation::Amend, BYBIT_OP_ORDER_AMEND_BATCH, 10429)]
4328    #[case::cancel(PendingOperation::Cancel, BYBIT_OP_ORDER_CANCEL_BATCH, 10006)]
4329    fn test_dispatch_batch_top_level_rate_limit_emits_no_terminal_rejection(
4330        #[case] operation: PendingOperation,
4331        #[case] op: &str,
4332        #[case] ret_code: i64,
4333    ) {
4334        let mut ctx = DispatchTestContext::new();
4335        let cid_1 = ClientOrderId::from("batch-rate-1");
4336        let cid_2 = ClientOrderId::from("batch-rate-2");
4337        ctx.state.order_identities.insert(cid_1, default_identity());
4338        ctx.state.order_identities.insert(cid_2, default_identity());
4339        ctx.state.pending_requests.insert(
4340            "req-batch-rate".to_string(),
4341            (
4342                vec![cid_1, cid_2],
4343                vec![
4344                    Some(VenueOrderId::from("venue-rate-1")),
4345                    Some(VenueOrderId::from("venue-rate-2")),
4346                ],
4347                operation,
4348                Vec::new(),
4349            ),
4350        );
4351
4352        let response = order_response(
4353            op,
4354            ret_code,
4355            "rate limit",
4356            "req-batch-rate",
4357            serde_json::json!({}),
4358            None,
4359        );
4360
4361        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4362
4363        assert!(
4364            ctx.rx.try_recv().is_err(),
4365            "Batch rate-limit response must not emit a terminal rejection"
4366        );
4367        assert!(ctx.state.order_identities.contains_key(&cid_1));
4368        assert!(ctx.state.order_identities.contains_key(&cid_2));
4369        assert!(!ctx.state.pending_requests.contains_key("req-batch-rate"));
4370    }
4371
4372    #[rstest]
4373    fn test_dispatch_batch_cancel_per_item_error_emits_only_failed_item(
4374        #[values(false, true)] repeated: bool,
4375    ) {
4376        let mut ctx = DispatchTestContext::new();
4377        let cid_1 = ClientOrderId::from("batch-cancel-ok");
4378        let cid_2 = if repeated {
4379            cid_1
4380        } else {
4381            ClientOrderId::from("batch-cancel-reject")
4382        };
4383
4384        let causes = [UUID4::new(), UUID4::new()];
4385        ctx.state.order_identities.insert(cid_1, default_identity());
4386        ctx.state.order_identities.insert(cid_2, default_identity());
4387        ctx.state.pending_requests.insert(
4388            "req-batch-mixed".to_string(),
4389            (
4390                vec![cid_1, cid_2],
4391                vec![
4392                    Some(VenueOrderId::from("venue-batch-ok")),
4393                    Some(VenueOrderId::from("venue-batch-reject")),
4394                ],
4395                PendingOperation::Cancel,
4396                causes.into_iter().map(Some).collect(),
4397            ),
4398        );
4399
4400        let response = order_response(
4401            BYBIT_OP_ORDER_CANCEL_BATCH,
4402            0,
4403            "OK",
4404            "req-batch-mixed",
4405            serde_json::json!({
4406                "list": [
4407                    {"orderId": "venue-batch-ok", "orderLinkId": cid_1.to_string()},
4408                    {"orderId": "venue-batch-reject", "orderLinkId": cid_2.to_string()}
4409                ]
4410            }),
4411            Some(serde_json::json!({
4412                "list": [
4413                    {"code": 0, "msg": "OK"},
4414                    {"code": 170213, "msg": "Order does not exist."}
4415                ]
4416            })),
4417        );
4418
4419        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4420
4421        let event = ctx.rx.try_recv().expect("expected CancelRejected event");
4422        assert!(
4423            matches!(event, ExecutionEvent::Order(OrderEventAny::CancelRejected(ref rejected)) if rejected.client_order_id == cid_2 && rejected.causation_id == Some(causes[1])),
4424            "Expected CancelRejected for failed batch item {cid_2}, found {event:?}"
4425        );
4426        assert!(
4427            ctx.rx.try_recv().is_err(),
4428            "Expected no CancelRejected event for successful batch item"
4429        );
4430    }
4431
4432    #[rstest]
4433    #[case::place(PendingOperation::Place, BYBIT_OP_ORDER_CREATE_BATCH, 10006)]
4434    #[case::amend(PendingOperation::Amend, BYBIT_OP_ORDER_AMEND_BATCH, 10429)]
4435    #[case::cancel(PendingOperation::Cancel, BYBIT_OP_ORDER_CANCEL_BATCH, 10006)]
4436    fn test_dispatch_batch_per_item_rate_limit_emits_no_terminal_rejection(
4437        #[case] operation: PendingOperation,
4438        #[case] op: &str,
4439        #[case] code: i64,
4440    ) {
4441        let mut ctx = DispatchTestContext::new();
4442        let cid = ClientOrderId::from("batch-item-rate-limit");
4443        let venue_order_id = VenueOrderId::from("venue-batch-rate-limit");
4444        ctx.state.order_identities.insert(cid, default_identity());
4445        ctx.state.pending_requests.insert(
4446            "req-batch-item-rate-limit".to_string(),
4447            (vec![cid], vec![Some(venue_order_id)], operation, Vec::new()),
4448        );
4449
4450        let response = order_response(
4451            op,
4452            0,
4453            "OK",
4454            "req-batch-item-rate-limit",
4455            serde_json::json!({
4456                "list": [
4457                    {"orderId": venue_order_id.to_string(), "orderLinkId": cid.to_string()}
4458                ]
4459            }),
4460            Some(serde_json::json!({
4461                "list": [
4462                    {"code": code, "msg": "rate limit"}
4463                ]
4464            })),
4465        );
4466
4467        dispatch_order_response(&response, &ctx.emitter, &ctx.state, UnixNanos::from(1u64));
4468
4469        assert!(
4470            ctx.rx.try_recv().is_err(),
4471            "Per-item rate-limit response must not emit a terminal rejection"
4472        );
4473        assert!(ctx.state.order_identities.contains_key(&cid));
4474        assert!(
4475            !ctx.state
4476                .pending_requests
4477                .contains_key("req-batch-item-rate-limit")
4478        );
4479    }
4480
4481    #[rstest]
4482    fn test_dispatch_filled_with_seeded_snapshot_emits_updated_for_bbo() {
4483        let mut ctx = DispatchTestContext::new();
4484        let mut value = new_order_value();
4485        value["data"][0]["orderStatus"] = serde_json::Value::String("Filled".to_string());
4486        value["data"][0]["cumExecQty"] = serde_json::Value::String("0.010".to_string());
4487        let cid = ClientOrderId::from("client-1");
4488        ctx.state.order_identities.insert(cid, default_identity());
4489        ctx.state.order_snapshots.insert(
4490            cid,
4491            OrderStateSnapshot {
4492                quantity: Quantity::from("0.010"),
4493                price: Some(Price::from("29000.00")),
4494                trigger_price: None,
4495            },
4496        );
4497
4498        ctx.dispatch_value(&value);
4499
4500        let accepted_event = ctx.rx.try_recv().unwrap();
4501        let accepted = match accepted_event {
4502            ExecutionEvent::Order(OrderEventAny::Accepted(accepted)) => accepted,
4503            other => panic!("Expected Accepted first, found {other:?}"),
4504        };
4505        assert_eq!(accepted.client_order_id, cid);
4506        assert!(!accepted.venue_order_id.to_string().is_empty());
4507
4508        let updated = ctx.recv_updated();
4509        assert_eq!(updated.client_order_id, cid);
4510        assert_eq!(updated.price, Some(Price::from("30000.00")));
4511        assert_eq!(updated.quantity, Quantity::from("0.010"));
4512        assert_eq!(updated.trigger_price, None);
4513        assert_eq!(updated.venue_order_id, Some(accepted.venue_order_id));
4514
4515        let stored = ctx.state.order_snapshots.get(&cid).unwrap();
4516        assert_eq!(stored.price, Some(Price::from("30000.00")));
4517    }
4518
4519    #[rstest]
4520    fn test_dispatch_accepted_with_matching_seeded_snapshot_no_updated() {
4521        let mut ctx = DispatchTestContext::new();
4522        let value = new_order_value();
4523        let cid = ClientOrderId::from("client-1");
4524        ctx.state.order_identities.insert(cid, default_identity());
4525        ctx.state.order_snapshots.insert(
4526            cid,
4527            OrderStateSnapshot {
4528                quantity: Quantity::from("0.010"),
4529                price: Some(Price::from("30000.00")),
4530                trigger_price: None,
4531            },
4532        );
4533
4534        ctx.dispatch_value(&value);
4535
4536        let accepted = ctx.rx.try_recv().unwrap();
4537        assert!(matches!(
4538            accepted,
4539            ExecutionEvent::Order(OrderEventAny::Accepted(_))
4540        ));
4541
4542        assert!(
4543            ctx.rx.try_recv().is_err(),
4544            "Expected no OrderUpdated when seed matches venue snapshot"
4545        );
4546    }
4547
4548    #[rstest]
4549    #[case::price_changed(
4550        Some(Price::from("100.00")),
4551        None,
4552        Quantity::from("1.000"),
4553        Some(Price::from("200.00")),
4554        None,
4555        Quantity::from("1.000"),
4556        true
4557    )]
4558    #[case::trigger_changed(
4559        None,
4560        Some(Price::from("100.00")),
4561        Quantity::from("1.000"),
4562        None,
4563        Some(Price::from("90.00")),
4564        Quantity::from("1.000"),
4565        true
4566    )]
4567    #[case::qty_changed(
4568        Some(Price::from("100.00")),
4569        None,
4570        Quantity::from("1.000"),
4571        Some(Price::from("100.00")),
4572        None,
4573        Quantity::from("2.000"),
4574        true
4575    )]
4576    #[case::no_change(
4577        Some(Price::from("100.00")),
4578        None,
4579        Quantity::from("1.000"),
4580        Some(Price::from("100.00")),
4581        None,
4582        Quantity::from("1.000"),
4583        false
4584    )]
4585    fn test_is_snapshot_updated(
4586        #[case] prev_price: Option<Price>,
4587        #[case] prev_trigger: Option<Price>,
4588        #[case] prev_qty: Quantity,
4589        #[case] new_price: Option<Price>,
4590        #[case] new_trigger: Option<Price>,
4591        #[case] new_qty: Quantity,
4592        #[case] expected: bool,
4593    ) {
4594        let state = WsDispatchState::default();
4595        let cid = ClientOrderId::from("test-1");
4596        state.order_snapshots.insert(
4597            cid,
4598            OrderStateSnapshot {
4599                quantity: prev_qty,
4600                price: prev_price,
4601                trigger_price: prev_trigger,
4602            },
4603        );
4604
4605        let new_snapshot = OrderStateSnapshot {
4606            quantity: new_qty,
4607            price: new_price,
4608            trigger_price: new_trigger,
4609        };
4610        assert_eq!(is_snapshot_updated(&new_snapshot, &cid, &state), expected);
4611    }
4612
4613    #[rstest]
4614    fn test_is_snapshot_updated_no_previous() {
4615        let state = WsDispatchState::default();
4616        let cid = ClientOrderId::from("test-1");
4617
4618        let new_snapshot = OrderStateSnapshot {
4619            quantity: Quantity::from("1.000"),
4620            price: Some(Price::from("100.00")),
4621            trigger_price: None,
4622        };
4623        assert!(!is_snapshot_updated(&new_snapshot, &cid, &state));
4624    }
4625
4626    #[rstest]
4627    #[case::limit_order("30000", "0", Some(Price::from("30000.00")), None)]
4628    #[case::conditional("0", "29000", None, Some(Price::from("29000.00")))]
4629    #[case::both(
4630        "30000",
4631        "29000",
4632        Some(Price::from("30000.00")),
4633        Some(Price::from("29000.00"))
4634    )]
4635    fn test_parse_order_snapshot(
4636        #[case] price: &str,
4637        #[case] trigger: &str,
4638        #[case] expected_price: Option<Price>,
4639        #[case] expected_trigger: Option<Price>,
4640    ) {
4641        let instrument = linear_instrument();
4642        let json = load_test_json("ws_account_order.json");
4643        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
4644        value["data"][0]["price"] = serde_json::Value::String(price.to_string());
4645        value["data"][0]["triggerPrice"] = serde_json::Value::String(trigger.to_string());
4646        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
4647            serde_json::from_value(value).unwrap();
4648
4649        let snapshot = parse_order_snapshot(&msg.data[0], &instrument).unwrap();
4650        assert_eq!(snapshot.price, expected_price);
4651        assert_eq!(snapshot.trigger_price, expected_trigger);
4652        assert_eq!(snapshot.quantity, Quantity::from("0.010"));
4653    }
4654
4655    #[rstest]
4656    fn test_parse_order_snapshot_invalid_qty_returns_none() {
4657        let instrument = linear_instrument();
4658        let json = load_test_json("ws_account_order.json");
4659        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
4660        value["data"][0]["qty"] = serde_json::Value::String(String::new());
4661        let msg: crate::websocket::messages::BybitWsAccountOrderMsg =
4662            serde_json::from_value(value).unwrap();
4663
4664        assert!(parse_order_snapshot(&msg.data[0], &instrument).is_none());
4665    }
4666
4667    #[rstest]
4668    fn test_dispatch_order_updated_on_partially_filled_price_change() {
4669        let mut ctx = DispatchTestContext::new();
4670        let value = new_order_value();
4671        ctx.accept_order(&value);
4672
4673        let mut amended = value;
4674        amended["data"][0]["orderStatus"] =
4675            serde_json::Value::String("PartiallyFilled".to_string());
4676        amended["data"][0]["cumExecQty"] = serde_json::Value::String("0.005".to_string());
4677        amended["data"][0]["price"] = serde_json::Value::String("31000".to_string());
4678        ctx.dispatch_value(&amended);
4679
4680        let updated = ctx.recv_updated();
4681        assert_eq!(updated.client_order_id, ClientOrderId::from("client-1"));
4682        assert_eq!(updated.price, Some(Price::from("31000.00")));
4683    }
4684}