Skip to main content

nautilus_execution/reconciliation/
orders.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//! Order and fill reconciliation.
17//!
18//! Event construction, order state reconciliation, and fill reconciliation. Venue-sourced
19//! reports become zero or more `OrderEventAny`s that are safe to apply to the local order model.
20
21use std::{borrow::Cow, collections::HashSet};
22
23use nautilus_common::enums::LogColor;
24use nautilus_core::{UUID4, UnixNanos};
25use nautilus_model::{
26    enums::{LiquiditySide, OrderStatus, OrderType},
27    events::{
28        OrderAccepted, OrderCanceled, OrderEventAny, OrderExpired, OrderFillVoided, OrderFilled,
29        OrderRejected, OrderTriggered, OrderUpdated,
30    },
31    identifiers::{AccountId, PositionId, TradeId},
32    instruments::{Instrument, InstrumentAny},
33    orders::{LIMIT_ORDER_TYPES, Order, OrderAny, TRIGGERABLE_ORDER_TYPES},
34    reports::{FillReport, OrderStatusReport},
35    types::{Money, Price, Quantity},
36};
37use rust_decimal::Decimal;
38use ustr::Ustr;
39
40use super::{
41    ids::create_inferred_reconciliation_trade_id,
42    positions::{cap_price_at_instrument_max, is_within_single_unit_tolerance},
43    reconciliation_price,
44};
45
46/// Generates reconciliation events for a live order status report.
47///
48/// Events are produced in venue-temporal order: any missing `Accepted` event
49/// first, then an `OrderUpdated` if the venue snapshot shows a confirmed
50/// quantity/price amendment, then any status/fill events from
51/// [`reconcile_order_report`]. Emitting the amendment before the fill matters
52/// when the venue increased the total quantity and reported a fill that would
53/// otherwise close the order under the stale local quantity. The `Updated`
54/// step is suppressed for pending venue states so a still-unconfirmed amend
55/// cannot mutate the local projection ahead of venue confirmation. A confirmed `Filled`
56/// report whose filled quantity exceeds the local order quantity still raises that quantity
57/// while a cancel or modify is in flight, so the fill can apply.
58#[must_use]
59pub fn generate_reconciliation_order_events(
60    order: &OrderAny,
61    report: &OrderStatusReport,
62    instrument: Option<&InstrumentAny>,
63    ts_now: UnixNanos,
64) -> Vec<OrderEventAny> {
65    generate_reconciliation_order_events_inner(
66        order,
67        report,
68        instrument,
69        ts_now,
70        report.order_status == OrderStatus::Voided,
71        None,
72    )
73}
74
75/// Generates reconciliation events for an authoritative venue snapshot.
76///
77/// Unlike [`generate_reconciliation_order_events`], a material decrease in cumulative filled
78/// quantity is treated as evidence that previously applied fills were voided. The caller establishes
79/// snapshot freshness and applies any companion fills before generating corrections. A snapshot can
80/// correct retained fills even when it contains no new trades.
81#[must_use]
82pub fn generate_reconciliation_order_snapshot_events(
83    order: &OrderAny,
84    report: &OrderStatusReport,
85    instrument: Option<&InstrumentAny>,
86    ts_now: UnixNanos,
87) -> Vec<OrderEventAny> {
88    generate_reconciliation_order_events_inner(order, report, instrument, ts_now, true, None)
89}
90
91/// Generates reconciliation events for an authoritative venue snapshot with an inferred-fill
92/// commission supplied by the responsible execution client.
93#[must_use]
94pub fn generate_reconciliation_order_snapshot_events_with_commission(
95    order: &OrderAny,
96    report: &OrderStatusReport,
97    instrument: Option<&InstrumentAny>,
98    ts_now: UnixNanos,
99    commission: Option<Money>,
100) -> Vec<OrderEventAny> {
101    generate_reconciliation_order_events_inner(order, report, instrument, ts_now, true, commission)
102}
103
104fn generate_reconciliation_order_events_inner(
105    order: &OrderAny,
106    report: &OrderStatusReport,
107    instrument: Option<&InstrumentAny>,
108    ts_now: UnixNanos,
109    allow_fill_decrease: bool,
110    commission: Option<Money>,
111) -> Vec<OrderEventAny> {
112    if is_superseded_terminal_report(order, report) {
113        let _ = reconcile_order_report(order, report, instrument, ts_now);
114        return Vec::new();
115    }
116
117    if has_material_fill_decrease(order, report) {
118        if !allow_fill_decrease {
119            log::warn!(
120                "Ignoring fill decrease without explicit void evidence for {}: cached={}, venue={}",
121                order.client_order_id(),
122                order.filled_qty(),
123                report.filled_qty,
124            );
125            return reconcile_fill_decrease_terminal(order, report, instrument, ts_now);
126        }
127
128        let mut working = order.clone();
129        let mut events = create_reconciliation_fill_voids(&working, report, ts_now);
130        if events.is_empty() {
131            return reconcile_fill_decrease_terminal(order, report, instrument, ts_now);
132        }
133
134        for event in &events {
135            if let Err(e) = working.apply(event.clone()) {
136                log::warn!(
137                    "Cannot project reconciliation fill void for {}: {e}",
138                    order.client_order_id()
139                );
140                return reconcile_fill_decrease_terminal(order, report, instrument, ts_now);
141            }
142        }
143
144        if is_working(report.order_status) && should_reconciliation_update(&working, report) {
145            let updated = create_reconciliation_updated(&working, report, ts_now);
146            if let Err(e) = working.apply(updated.clone()) {
147                log::warn!(
148                    "Cannot project reopening reconciliation update for {}: {e}",
149                    order.client_order_id()
150                );
151            } else {
152                events.push(updated);
153            }
154        }
155
156        if let Some(terminal) = reconcile_order_report(&working, report, instrument, ts_now) {
157            events.push(terminal);
158        }
159        return events;
160    }
161
162    let (mut working, mut events) = prepare_reconciliation_order(order, report, ts_now);
163
164    if matches!(
165        report.order_status,
166        OrderStatus::Canceled | OrderStatus::Expired,
167    ) && report.filled_qty > working.filled_qty()
168        && let Some(instrument) = instrument
169        && let Some(filled) = create_incremental_inferred_fill(
170            &working,
171            report,
172            &report.account_id,
173            instrument,
174            ts_now,
175            commission,
176        )
177    {
178        if let Err(e) = working.apply(filled.clone()) {
179            log::warn!(
180                "Failed to pre-apply reconciliation fill for {}: {e}",
181                order.client_order_id(),
182            );
183        } else {
184            events.push(filled);
185        }
186    }
187
188    if working.status() == OrderStatus::Filled
189        && matches!(
190            report.order_status,
191            OrderStatus::Canceled | OrderStatus::Expired,
192        )
193    {
194        return events;
195    }
196
197    if let Some(event) =
198        reconcile_order_report_with_commission(&working, report, instrument, ts_now, commission)
199    {
200        events.push(event);
201    }
202
203    events
204}
205
206fn has_material_fill_decrease(order: &OrderAny, report: &OrderStatusReport) -> bool {
207    if report.filled_qty >= order.filled_qty() {
208        return false;
209    }
210
211    let precision = order
212        .filled_qty()
213        .precision
214        .max(report.filled_qty.precision);
215    !is_within_single_unit_tolerance(
216        report.filled_qty.as_decimal(),
217        order.filled_qty().as_decimal(),
218        precision,
219    )
220}
221
222fn reconcile_fill_decrease_terminal(
223    order: &OrderAny,
224    report: &OrderStatusReport,
225    instrument: Option<&InstrumentAny>,
226    ts_now: UnixNanos,
227) -> Vec<OrderEventAny> {
228    let should_reconcile = report.order_status == OrderStatus::Voided
229        || (!order.is_closed()
230            && matches!(
231                report.order_status,
232                OrderStatus::Canceled | OrderStatus::Expired
233            ));
234
235    if !should_reconcile {
236        return Vec::new();
237    }
238
239    reconcile_order_report(order, report, instrument, ts_now)
240        .into_iter()
241        .collect()
242}
243
244/// Generates acceptance, amendment, and triggering events for a report paired with real fills.
245#[must_use]
246pub fn generate_reconciliation_order_pre_fill_events(
247    order: &OrderAny,
248    report: &OrderStatusReport,
249    ts_now: UnixNanos,
250) -> Vec<OrderEventAny> {
251    if is_superseded_terminal_report(order, report) {
252        return Vec::new();
253    }
254
255    let (working, mut events) = prepare_reconciliation_order(order, report, ts_now);
256    if report.order_status == OrderStatus::Triggered
257        && working.status() != OrderStatus::Triggered
258        && let Some(triggered) = reconcile_order_report(&working, report, None, ts_now)
259    {
260        events.push(triggered);
261    }
262
263    events
264}
265
266fn prepare_reconciliation_order(
267    order: &OrderAny,
268    report: &OrderStatusReport,
269    ts_now: UnixNanos,
270) -> (OrderAny, Vec<OrderEventAny>) {
271    let mut working = order.clone();
272    let mut events: Vec<OrderEventAny> = Vec::new();
273
274    if should_accept_before_reconciliation(&working, report) {
275        let Some(accepted) = create_reconciliation_accepted(&working, report, ts_now) else {
276            log::warn!(
277                "Cannot create reconciliation acceptance for {}: missing account_id",
278                order.client_order_id(),
279            );
280            return (working, events);
281        };
282
283        if let Err(e) = working.apply(accepted.clone()) {
284            log::warn!(
285                "Failed to pre-apply reconciliation acceptance for {}: {e}",
286                order.client_order_id(),
287            );
288            return (working, events);
289        }
290        events.push(accepted);
291    }
292
293    if report_is_confirmed_state(report)
294        && (is_working(working.status())
295            || working.status() == OrderStatus::PendingUpdate && is_working(report.order_status)
296            || pending_terminal_quantity_update(&working, report))
297        && should_reconciliation_update(&working, report)
298    {
299        let updated = create_reconciliation_updated(&working, report, ts_now);
300        if let Err(e) = working.apply(updated.clone()) {
301            log::warn!(
302                "Failed to pre-apply reconciliation update for {}: {e}",
303                order.client_order_id(),
304            );
305        } else {
306            events.push(updated);
307        }
308    }
309
310    (working, events)
311}
312
313/// Reconciles an order with a venue status report, generating appropriate events.
314///
315/// This is the core reconciliation logic that handles all order status transitions.
316/// For the higher-level wrapper that emits a venue-temporal sequence of events,
317/// use [`generate_reconciliation_order_events`].
318///
319/// Returns `None` for pending venue states (`PendingUpdate`, `PendingCancel`)
320/// regardless of local state, since an unconfirmed amend or cancel must not
321/// drive any local mutation until the venue surfaces a confirmed status.
322///
323/// Returns `None` for a `Canceled`, `Expired`, or `Filled` report on a known superseded
324/// `venue_order_id`. Its native terminal state does not change the logical order's current
325/// state or cumulative quantities; its companion fills reconcile separately.
326#[must_use]
327pub fn reconcile_order_report(
328    order: &OrderAny,
329    report: &OrderStatusReport,
330    instrument: Option<&InstrumentAny>,
331    ts_now: UnixNanos,
332) -> Option<OrderEventAny> {
333    reconcile_order_report_with_commission(order, report, instrument, ts_now, None)
334}
335
336/// Reconciles an order with a venue status report using a precomputed inferred-fill commission.
337#[must_use]
338pub fn reconcile_order_report_with_commission(
339    order: &OrderAny,
340    report: &OrderStatusReport,
341    instrument: Option<&InstrumentAny>,
342    ts_now: UnixNanos,
343    commission: Option<Money>,
344) -> Option<OrderEventAny> {
345    if matches!(
346        report.order_status,
347        OrderStatus::PendingUpdate | OrderStatus::PendingCancel
348    ) {
349        log::debug!(
350            "Order {} venue report in pending state: {:?}",
351            order.client_order_id(),
352            report.order_status,
353        );
354        return None;
355    }
356
357    if is_unchanged_accepted_report_during_pending_command(order, report) {
358        log::debug!(
359            "Order {} remains inflight while venue reports an unchanged accepted snapshot",
360            order.client_order_id(),
361        );
362        return None;
363    }
364
365    if is_superseded_terminal_report(order, report) {
366        let cached_venue_order_id = order.venue_order_id().unwrap_or(report.venue_order_id);
367        log::info!(
368            "Suppressing {:?} for {} on previously-promoted venue_order_id {}: \
369             current venue_order_id is {}",
370            report.order_status,
371            order.client_order_id(),
372            report.venue_order_id,
373            cached_venue_order_id,
374        );
375        return None;
376    }
377
378    if order.status() == report.order_status && order.filled_qty() == report.filled_qty {
379        if should_reconciliation_update(order, report) {
380            log::info!(
381                "Order {} has been updated at venue: qty={}->{}, price={:?}->{:?}",
382                order.client_order_id(),
383                order.quantity(),
384                report.quantity,
385                order.price(),
386                report.price
387            );
388            return Some(create_reconciliation_updated(order, report, ts_now));
389        }
390        return None; // Already in sync
391    }
392
393    match report.order_status {
394        OrderStatus::Accepted => reconcile_accepted_report(order, report, ts_now),
395        OrderStatus::Rejected => {
396            create_reconciliation_rejected(order, report.cancel_reason.as_deref(), ts_now)
397        }
398        OrderStatus::Triggered => {
399            if TRIGGERABLE_ORDER_TYPES.contains(&order.order_type()) {
400                Some(create_reconciliation_triggered(order, report, ts_now))
401            } else {
402                log::debug!(
403                    "Skipping OrderTriggered for {} order {}: market-style stops have no TRIGGERED state",
404                    order.order_type(),
405                    order.client_order_id(),
406                );
407                None
408            }
409        }
410        OrderStatus::Canceled => Some(create_reconciliation_canceled(order, report, ts_now)),
411        OrderStatus::Expired => Some(create_reconciliation_expired(order, report, ts_now)),
412
413        OrderStatus::PartiallyFilled | OrderStatus::Filled => {
414            reconcile_fill_quantity_mismatch(order, report, instrument, ts_now, commission)
415        }
416
417        OrderStatus::Voided => {
418            create_reconciliation_terminal_fill_void(order, report, instrument, ts_now)
419        }
420
421        OrderStatus::PendingUpdate | OrderStatus::PendingCancel => None,
422
423        // Internal states - should not appear in venue reports
424        OrderStatus::Initialized
425        | OrderStatus::Submitted
426        | OrderStatus::Denied
427        | OrderStatus::Emulated
428        | OrderStatus::Released => {
429            log::warn!(
430                "Unexpected order status in venue report for {}: {:?}",
431                order.client_order_id(),
432                report.order_status
433            );
434            None
435        }
436    }
437}
438
439fn reconcile_accepted_report(
440    order: &OrderAny,
441    report: &OrderStatusReport,
442    ts_now: UnixNanos,
443) -> Option<OrderEventAny> {
444    if order.filled_qty().is_positive()
445        || matches!(
446            order.status(),
447            OrderStatus::PartiallyFilled
448                | OrderStatus::Filled
449                | OrderStatus::Rejected
450                | OrderStatus::Canceled
451        )
452    {
453        return None;
454    }
455
456    if matches!(
457        order.status(),
458        OrderStatus::Accepted | OrderStatus::PendingUpdate
459    ) && should_reconciliation_update(order, report)
460    {
461        return Some(create_reconciliation_updated(order, report, ts_now));
462    }
463
464    create_reconciliation_accepted(order, report, ts_now)
465}
466
467fn is_unchanged_accepted_report_during_pending_command(
468    order: &OrderAny,
469    report: &OrderStatusReport,
470) -> bool {
471    matches!(
472        order.status(),
473        OrderStatus::PendingUpdate | OrderStatus::PendingCancel
474    ) && report.order_status == OrderStatus::Accepted
475        && order.venue_order_id() == Some(report.venue_order_id)
476        && order.filled_qty() == report.filled_qty
477        && !should_reconciliation_update(order, report)
478}
479
480/// Generates the appropriate order events for an external order and order status report.
481///
482/// After creating an external order, we need to transition it to its actual state
483/// based on the order status report from the venue. For terminal states like
484/// Canceled/Expired/Filled, we return multiple events to properly transition
485/// the order through Accepted before reaching the terminal state.
486pub fn generate_external_order_status_events(
487    order: &OrderAny,
488    report: &OrderStatusReport,
489    account_id: &AccountId,
490    instrument: &InstrumentAny,
491    ts_now: UnixNanos,
492) -> Vec<OrderEventAny> {
493    generate_external_order_status_events_with_commission(
494        order, report, account_id, instrument, ts_now, None,
495    )
496}
497
498/// Generates external-order status events with a precomputed inferred-fill commission.
499#[must_use]
500pub fn generate_external_order_status_events_with_commission(
501    order: &OrderAny,
502    report: &OrderStatusReport,
503    account_id: &AccountId,
504    instrument: &InstrumentAny,
505    ts_now: UnixNanos,
506    commission: Option<Money>,
507) -> Vec<OrderEventAny> {
508    let accepted = OrderEventAny::Accepted(OrderAccepted::new(
509        order.trader_id(),
510        order.strategy_id(),
511        order.instrument_id(),
512        order.client_order_id(),
513        report.venue_order_id,
514        *account_id,
515        UUID4::new(),
516        report.ts_accepted,
517        ts_now,
518        true, // reconciliation
519    ));
520
521    match report.order_status {
522        OrderStatus::Accepted | OrderStatus::Triggered => vec![accepted],
523        OrderStatus::PartiallyFilled | OrderStatus::Filled => {
524            let mut events = vec![accepted];
525
526            if !report.filled_qty.is_zero()
527                && let Some(filled) =
528                    create_inferred_fill(order, report, *account_id, instrument, ts_now, commission)
529            {
530                events.push(filled);
531            }
532
533            events
534        }
535        OrderStatus::Voided => {
536            let mut working = order.clone();
537            if let Err(e) = working.apply(accepted.clone()) {
538                log::warn!(
539                    "Cannot project external order acceptance for {}: {e}",
540                    order.client_order_id()
541                );
542                return vec![accepted];
543            }
544            let mut events = vec![accepted];
545
546            if !report.filled_qty.is_zero()
547                && let Some(filled) =
548                    create_inferred_fill(order, report, *account_id, instrument, ts_now, commission)
549            {
550                if let Err(e) = working.apply(filled.clone()) {
551                    log::warn!(
552                        "Cannot project external order fill for {}: {e}",
553                        order.client_order_id()
554                    );
555                } else {
556                    events.push(filled);
557                }
558            }
559
560            if let Some(voided) =
561                create_reconciliation_terminal_fill_void(&working, report, Some(instrument), ts_now)
562            {
563                events.push(voided);
564            }
565            events
566        }
567        OrderStatus::Canceled | OrderStatus::Expired => {
568            let terminal = create_external_terminal_event(order, report, *account_id, ts_now);
569            let mut events = vec![accepted];
570
571            let inferred_fill = if report.filled_qty.is_zero() {
572                None
573            } else {
574                create_inferred_fill(order, report, *account_id, instrument, ts_now, commission)
575            };
576            let filled_to_quantity =
577                inferred_fill.is_some() && report.filled_qty >= report.quantity;
578            if let Some(filled) = inferred_fill {
579                events.push(filled);
580            }
581
582            if !filled_to_quantity {
583                events.push(terminal);
584            }
585            events
586        }
587        OrderStatus::Rejected => {
588            // Rejected goes directly to terminal state without acceptance
589            let reason = report.cancel_reason.as_deref().unwrap_or("UNKNOWN");
590            vec![OrderEventAny::Rejected(OrderRejected::new(
591                order.trader_id(),
592                order.strategy_id(),
593                order.instrument_id(),
594                order.client_order_id(),
595                *account_id,
596                Ustr::from(reason),
597                UUID4::new(),
598                report.ts_last,
599                ts_now,
600                true, // reconciliation
601                reason_indicates_post_only_rejection(reason),
602            ))]
603        }
604        _ => {
605            log::warn!(
606                "Unhandled order status {} for external order {}",
607                report.order_status,
608                order.client_order_id()
609            );
610            Vec::new()
611        }
612    }
613}
614
615fn create_reconciliation_fill_voids(
616    order: &OrderAny,
617    report: &OrderStatusReport,
618    ts_now: UnixNanos,
619) -> Vec<OrderEventAny> {
620    let mut remaining = order.filled_qty() - report.filled_qty;
621    let order_events = order.events();
622    let mut corrections = Vec::new();
623
624    // A repeated `trade_id` in the event log restates that trade's price and carries no
625    // quantity; a void must price against the original fill so the order accepts it.
626    let mut seen = HashSet::new();
627
628    let quantity_fills: Vec<&OrderFilled> = order_events
629        .iter()
630        .filter_map(|event| match event {
631            OrderEventAny::Filled(fill) if seen.insert(fill.trade_id) => Some(fill),
632            _ => None,
633        })
634        .collect();
635
636    for fill in quantity_fills.iter().rev() {
637        if remaining.is_zero() {
638            break;
639        }
640        let previous = order_events.iter().rev().find_map(|event| match event {
641            OrderEventAny::FillVoided(voided) if voided.trade_id == fill.trade_id => Some(voided),
642            _ => None,
643        });
644        let prior_qty = previous.map_or_else(
645            || Quantity::zero(fill.last_qty.precision),
646            |voided| voided.voided_qty.min(fill.last_qty),
647        );
648        let effective = fill.last_qty - prior_qty;
649        if effective.is_zero() {
650            continue;
651        }
652        let removed = remaining.min(effective);
653        let voided_qty = prior_qty + removed;
654        let commission_voided = fill.commission.and_then(|commission| {
655            let fraction = voided_qty.as_decimal() / fill.last_qty.as_decimal();
656            Money::from_decimal(commission.as_decimal() * fraction, commission.currency).ok()
657        });
658        let mut event = OrderFillVoided::new(
659            fill.trader_id,
660            fill.strategy_id,
661            fill.instrument_id,
662            fill.client_order_id,
663            fill.venue_order_id,
664            fill.account_id,
665            Ustr::from(&format!(
666                "reconciliation-{}-{}",
667                report.report_id, fill.trade_id
668            )),
669            fill.trade_id,
670            voided_qty,
671            commission_voided,
672            fill.order_side,
673            fill.order_type,
674            fill.last_px,
675            fill.currency,
676            fill.liquidity_side,
677            fill.position_id,
678            report.cancel_reason.as_deref().map(Ustr::from),
679            None,
680            UUID4::new(),
681            report.ts_last,
682            ts_now,
683            true,
684            is_working(report.order_status),
685        );
686        event.causation_id = Some(report.report_id);
687        corrections.push(OrderEventAny::FillVoided(event));
688        remaining = remaining - removed;
689    }
690
691    if !remaining.is_zero() {
692        log::warn!(
693            "Cannot reconcile fill decrease for {}: {} is outside retained fill history",
694            order.client_order_id(),
695            remaining
696        );
697        return Vec::new();
698    }
699    corrections
700}
701
702/// Creates a fill void reversing the remaining leaves of a terminally voided order.
703///
704/// An unresolved price falls back to zero rather than `None`: the price is a placeholder that
705/// never reaches `Position::avg_px_open`, whereas suppressing the void would leave the order
706/// open locally against a venue that considers it gone.
707fn create_reconciliation_terminal_fill_void(
708    order: &OrderAny,
709    report: &OrderStatusReport,
710    instrument: Option<&InstrumentAny>,
711    ts_now: UnixNanos,
712) -> Option<OrderEventAny> {
713    let voided_qty = order.leaves_qty();
714    if voided_qty.is_zero() {
715        return None;
716    }
717    let instrument = instrument?;
718    let order_side = order.order_side();
719
720    let last_px = resolve_fill_price(order, report, instrument)
721        .unwrap_or_else(|| Price::zero(instrument.price_precision()));
722
723    let mut event = OrderFillVoided::new(
724        order.trader_id(),
725        order.strategy_id(),
726        order.instrument_id(),
727        order.client_order_id(),
728        report.venue_order_id,
729        report.account_id,
730        Ustr::from(&format!("reconciliation-{}", report.report_id)),
731        TradeId::new(format!("VOID-{}", report.venue_order_id)),
732        voided_qty,
733        None,
734        order_side,
735        order.order_type(),
736        last_px,
737        instrument.quote_currency(),
738        LiquiditySide::NoLiquiditySide,
739        None,
740        report.cancel_reason.as_deref().map(Ustr::from),
741        None,
742        UUID4::new(),
743        report.ts_last,
744        ts_now,
745        true,
746        false,
747    );
748    event.causation_id = Some(report.report_id);
749    Some(OrderEventAny::FillVoided(event))
750}
751
752fn create_external_terminal_event(
753    order: &OrderAny,
754    report: &OrderStatusReport,
755    account_id: AccountId,
756    ts_now: UnixNanos,
757) -> OrderEventAny {
758    match report.order_status {
759        OrderStatus::Canceled => OrderEventAny::Canceled(OrderCanceled::new(
760            order.trader_id(),
761            order.strategy_id(),
762            order.instrument_id(),
763            order.client_order_id(),
764            UUID4::new(),
765            report.ts_last,
766            ts_now,
767            true, // reconciliation
768            Some(report.venue_order_id),
769            Some(account_id),
770            report.cancel_reason.as_deref().map(Ustr::from),
771        )),
772        OrderStatus::Expired => OrderEventAny::Expired(OrderExpired::new(
773            order.trader_id(),
774            order.strategy_id(),
775            order.instrument_id(),
776            order.client_order_id(),
777            UUID4::new(),
778            report.ts_last,
779            ts_now,
780            true, // reconciliation
781            Some(report.venue_order_id),
782            Some(account_id),
783        )),
784        status => unreachable!("cannot create external terminal event for {status}"),
785    }
786}
787
788/// Creates an `OrderFilled` event from a `FillReport`.
789///
790/// This is used during reconciliation when a fill report is received from the venue.
791/// Returns `None` if the fill is a duplicate or would cause an overfill.
792pub fn reconcile_fill_report(
793    order: &OrderAny,
794    report: &FillReport,
795    instrument: &InstrumentAny,
796    ts_now: UnixNanos,
797    allow_overfills: bool,
798) -> Option<OrderEventAny> {
799    if report.last_qty.is_zero() {
800        log::warn!("Skipping zero-quantity fill report: {report}");
801        return None;
802    }
803
804    if order.trade_ids().iter().any(|id| **id == report.trade_id) {
805        log::debug!(
806            "Duplicate fill detected: trade_id {} already exists for order {}",
807            report.trade_id,
808            order.client_order_id()
809        );
810        return None;
811    }
812
813    if order.is_fill_report_order()
814        && (report.instrument_id != order.instrument_id()
815            || report.order_side != order.order_side()
816            || Some(report.account_id) != order.account_id()
817            || Some(report.venue_order_id) != order.venue_order_id()
818            || report
819                .client_order_id
820                .is_some_and(|id| id != order.client_order_id()))
821    {
822        log::warn!(
823            "Skipping fill report with mismatched identity for {}",
824            order.client_order_id()
825        );
826        return None;
827    }
828
829    let potential_filled_qty = order.filled_qty() + report.last_qty;
830    if potential_filled_qty > order.quantity() && !order.is_fill_report_order() {
831        if !allow_overfills {
832            log::warn!(
833                "Rejecting fill that would cause overfill for {}: order.quantity={}, order.filled_qty={}, fill.last_qty={}, would result in filled_qty={}",
834                order.client_order_id(),
835                order.quantity(),
836                order.filled_qty(),
837                report.last_qty,
838                potential_filled_qty
839            );
840            return None;
841        }
842        log::warn!(
843            "Allowing overfill during reconciliation for {}: order.quantity={}, order.filled_qty={}, fill.last_qty={}, will result in filled_qty={}",
844            order.client_order_id(),
845            order.quantity(),
846            order.filled_qty(),
847            report.last_qty,
848            potential_filled_qty
849        );
850    }
851
852    let account_id = report.account_id;
853    let venue_order_id = if order.venue_order_id() == Some(report.venue_order_id)
854        || order.venue_order_ids().contains(&&report.venue_order_id)
855    {
856        report.venue_order_id
857    } else {
858        order.venue_order_id().unwrap_or(report.venue_order_id)
859    };
860
861    log::info!(
862        color = LogColor::Blue as u8;
863        "Reconciling fill for {}: qty={}, px={}, trade_id={}",
864        order.client_order_id(),
865        report.last_qty,
866        report.last_px,
867        report.trade_id,
868    );
869
870    Some(OrderEventAny::Filled(OrderFilled::new(
871        order.trader_id(),
872        order.strategy_id(),
873        order.instrument_id(),
874        order.client_order_id(),
875        venue_order_id,
876        account_id,
877        report.trade_id,
878        order.order_side(),
879        order.order_type(),
880        report.last_qty,
881        report.last_px,
882        instrument.quote_currency(),
883        report.liquidity_side,
884        UUID4::new(),
885        report.ts_event,
886        ts_now,
887        true, // reconciliation
888        report.venue_position_id,
889        Some(report.commission),
890        None,
891    )))
892}
893
894/// Checks if the order should be updated based on quantity, price, or trigger price
895/// differences from the venue report.
896///
897/// A `None` value in `report.price` or `report.trigger_price` is treated as
898/// "venue did not include this field" rather than as drift, so a partial
899/// snapshot (for example, a Filled report that omits price but supplies
900/// `avg_px`) does not trigger a spurious `OrderUpdated`.
901pub fn should_reconciliation_update(order: &OrderAny, report: &OrderStatusReport) -> bool {
902    if report.quantity != order.quantity() && report.quantity >= order.filled_qty() {
903        return true;
904    }
905
906    let price_drift = report.price.is_some() && report.price != order.price();
907    let trigger_drift =
908        report.trigger_price.is_some() && report.trigger_price != order.trigger_price();
909
910    match order.order_type() {
911        OrderType::Limit => price_drift,
912        OrderType::StopMarket | OrderType::TrailingStopMarket | OrderType::MarketIfTouched => {
913            trigger_drift
914        }
915        OrderType::StopLimit | OrderType::TrailingStopLimit | OrderType::LimitIfTouched => {
916            trigger_drift || price_drift
917        }
918        _ => false,
919    }
920}
921
922/// Preserves later confirmed amendments for clients requiring authoritative fills.
923#[must_use]
924pub fn preserve_order_amendment<'a>(
925    order: &OrderAny,
926    report: &'a OrderStatusReport,
927    requires_authoritative_fills: bool,
928) -> Cow<'a, OrderStatusReport> {
929    if !requires_authoritative_fills || !should_reconciliation_update(order, report) {
930        return Cow::Borrowed(report);
931    }
932
933    if !order.events().iter().any(|event| {
934        matches!(event, OrderEventAny::Updated(updated) if updated.ts_event > report.ts_last)
935    }) {
936        return Cow::Borrowed(report);
937    }
938
939    let mut current = report.clone();
940    current.quantity = order.quantity();
941    current.price = order.price();
942    current.trigger_price = order.trigger_price();
943    Cow::Owned(current)
944}
945
946/// Creates an `OrderAccepted` event for reconciliation.
947#[must_use]
948pub(super) fn create_reconciliation_accepted(
949    order: &OrderAny,
950    report: &OrderStatusReport,
951    ts_now: UnixNanos,
952) -> Option<OrderEventAny> {
953    let account_id = order.account_id()?;
954
955    Some(OrderEventAny::Accepted(OrderAccepted::new(
956        order.trader_id(),
957        order.strategy_id(),
958        order.instrument_id(),
959        order.client_order_id(),
960        order.venue_order_id().unwrap_or(report.venue_order_id),
961        account_id,
962        UUID4::new(),
963        report.ts_accepted,
964        ts_now,
965        true, // reconciliation
966    )))
967}
968
969/// Creates an `OrderRejected` event for reconciliation.
970#[must_use]
971pub fn create_reconciliation_rejected(
972    order: &OrderAny,
973    reason: Option<&str>,
974    ts_now: UnixNanos,
975) -> Option<OrderEventAny> {
976    let account_id = order.account_id()?;
977    let reason = reason.unwrap_or("UNKNOWN");
978
979    Some(OrderEventAny::Rejected(OrderRejected::new(
980        order.trader_id(),
981        order.strategy_id(),
982        order.instrument_id(),
983        order.client_order_id(),
984        account_id,
985        Ustr::from(reason),
986        UUID4::new(),
987        ts_now,
988        ts_now,
989        true, // reconciliation
990        reason_indicates_post_only_rejection(reason),
991    )))
992}
993
994fn reason_indicates_post_only_rejection(reason: &str) -> bool {
995    let normalized: String = reason
996        .chars()
997        .filter_map(|ch| {
998            if ch == '-' || ch == '_' || ch.is_whitespace() {
999                None
1000            } else {
1001                Some(ch.to_ascii_lowercase())
1002            }
1003        })
1004        .collect();
1005
1006    normalized.contains("postonly") || normalized.contains("postwouldexecute")
1007}
1008
1009/// Creates an `OrderTriggered` event for reconciliation.
1010#[must_use]
1011pub fn create_reconciliation_triggered(
1012    order: &OrderAny,
1013    report: &OrderStatusReport,
1014    ts_now: UnixNanos,
1015) -> OrderEventAny {
1016    OrderEventAny::Triggered(OrderTriggered::new(
1017        order.trader_id(),
1018        order.strategy_id(),
1019        order.instrument_id(),
1020        order.client_order_id(),
1021        UUID4::new(),
1022        report.ts_triggered.unwrap_or(ts_now),
1023        ts_now,
1024        true, // reconciliation
1025        order.venue_order_id(),
1026        order.account_id(),
1027    ))
1028}
1029
1030/// Creates an `OrderCanceled` event for reconciliation.
1031#[must_use]
1032pub(super) fn create_reconciliation_canceled(
1033    order: &OrderAny,
1034    report: &OrderStatusReport,
1035    ts_now: UnixNanos,
1036) -> OrderEventAny {
1037    OrderEventAny::Canceled(OrderCanceled::new(
1038        order.trader_id(),
1039        order.strategy_id(),
1040        order.instrument_id(),
1041        order.client_order_id(),
1042        UUID4::new(),
1043        report.ts_last,
1044        ts_now,
1045        true, // reconciliation
1046        order.venue_order_id(),
1047        order.account_id(),
1048        report.cancel_reason.as_deref().map(Ustr::from),
1049    ))
1050}
1051
1052/// Creates an `OrderExpired` event for reconciliation.
1053#[must_use]
1054pub(super) fn create_reconciliation_expired(
1055    order: &OrderAny,
1056    report: &OrderStatusReport,
1057    ts_now: UnixNanos,
1058) -> OrderEventAny {
1059    OrderEventAny::Expired(OrderExpired::new(
1060        order.trader_id(),
1061        order.strategy_id(),
1062        order.instrument_id(),
1063        order.client_order_id(),
1064        UUID4::new(),
1065        report.ts_last,
1066        ts_now,
1067        true, // reconciliation
1068        order.venue_order_id(),
1069        order.account_id(),
1070    ))
1071}
1072
1073/// Creates an `OrderUpdated` event for reconciliation.
1074#[must_use]
1075pub(super) fn create_reconciliation_updated(
1076    order: &OrderAny,
1077    report: &OrderStatusReport,
1078    ts_now: UnixNanos,
1079) -> OrderEventAny {
1080    // Only pass trigger_price for order types that support it.
1081    // Limit, Market, and MarketToLimit orders assert trigger_price.is_none()
1082    // in their update() methods - passing a spurious trigger_price from the
1083    // venue report (e.g. Bybit sends "0.00" for non-conditional orders)
1084    // causes a panic. Positive list ensures new order types without
1085    // trigger_price support won't accidentally receive one.
1086    let trigger_price = match order.order_type() {
1087        OrderType::StopMarket
1088        | OrderType::StopLimit
1089        | OrderType::MarketIfTouched
1090        | OrderType::LimitIfTouched
1091        | OrderType::TrailingStopMarket
1092        | OrderType::TrailingStopLimit => report.trigger_price,
1093        _ => None,
1094    };
1095
1096    // Market-style reports can carry an execution cap instead of a limit price
1097    let price = if LIMIT_ORDER_TYPES.contains(&order.order_type())
1098        || order.order_type() == OrderType::MarketToLimit
1099    {
1100        report.price
1101    } else {
1102        None
1103    };
1104
1105    OrderEventAny::Updated(OrderUpdated::new(
1106        order.trader_id(),
1107        order.strategy_id(),
1108        order.instrument_id(),
1109        order.client_order_id(),
1110        report.quantity,
1111        UUID4::new(),
1112        report.ts_last,
1113        ts_now,
1114        true, // reconciliation
1115        order.venue_order_id(),
1116        order.account_id(),
1117        price,
1118        trigger_price,
1119        None, // protection_price
1120        order.is_quote_quantity(),
1121    ))
1122}
1123
1124/// Creates an inferred fill event for reconciliation when fill reports are missing.
1125pub(super) fn create_inferred_fill(
1126    order: &OrderAny,
1127    report: &OrderStatusReport,
1128    account_id: AccountId,
1129    instrument: &InstrumentAny,
1130    ts_now: UnixNanos,
1131    commission: Option<Money>,
1132) -> Option<OrderEventAny> {
1133    let cached_order_side = order.order_side();
1134    let order_side = report.order_side.unwrap_or(cached_order_side);
1135    if order_side != cached_order_side {
1136        log::warn!(
1137            "Order side mismatch for {}: cached={:?}, venue={order_side:?}",
1138            order.client_order_id(),
1139            cached_order_side,
1140        );
1141    }
1142
1143    let liquidity_side = inferred_fill_liquidity_side(order);
1144
1145    let Some(last_px) = resolve_fill_price(order, report, instrument) else {
1146        log::warn!(
1147            "Cannot create inferred fill for {}: no avg_px, report price, or order price",
1148            order.client_order_id()
1149        );
1150
1151        return None;
1152    };
1153    let last_px = clamp_inferred_fill_price(last_px, instrument);
1154
1155    let position_id = reconciliation_position_id(report, instrument);
1156    let trade_id = create_inferred_reconciliation_trade_id(
1157        account_id,
1158        order.instrument_id(),
1159        order.client_order_id(),
1160        Some(report.venue_order_id),
1161        order_side,
1162        order.order_type(),
1163        report.filled_qty,
1164        report.filled_qty,
1165        last_px,
1166        position_id,
1167        report.ts_last,
1168    );
1169
1170    log::info!(
1171        "Generated inferred fill for {} ({}) qty={} px={}",
1172        order.client_order_id(),
1173        report.venue_order_id,
1174        report.filled_qty,
1175        last_px,
1176    );
1177
1178    Some(OrderEventAny::Filled(OrderFilled::new(
1179        order.trader_id(),
1180        order.strategy_id(),
1181        order.instrument_id(),
1182        order.client_order_id(),
1183        report.venue_order_id,
1184        account_id,
1185        trade_id,
1186        order_side,
1187        order.order_type(),
1188        report.filled_qty,
1189        last_px,
1190        instrument.quote_currency(),
1191        liquidity_side,
1192        UUID4::new(),
1193        report.ts_last,
1194        ts_now,
1195        true, // reconciliation
1196        report.venue_position_id,
1197        commission,
1198        None,
1199    )))
1200}
1201
1202/// Creates an inferred fill for the quantity difference between order and report.
1203///
1204/// Orders reconstructed from fill reports wait for explicit trades instead.
1205pub fn create_incremental_inferred_fill(
1206    order: &OrderAny,
1207    report: &OrderStatusReport,
1208    account_id: &AccountId,
1209    instrument: &InstrumentAny,
1210    ts_now: UnixNanos,
1211    commission: Option<Money>,
1212) -> Option<OrderEventAny> {
1213    if order.is_fill_report_order() {
1214        return None;
1215    }
1216
1217    let order_side = order.order_side();
1218
1219    let order_filled_qty = order.filled_qty();
1220    debug_assert!(
1221        report.filled_qty >= order_filled_qty,
1222        "incremental inferred fill requires report.filled_qty ({}) >= order.filled_qty ({}) for {}",
1223        report.filled_qty,
1224        order_filled_qty,
1225        order.client_order_id(),
1226    );
1227    let last_qty = report.filled_qty - order_filled_qty;
1228
1229    if last_qty <= Quantity::zero(instrument.size_precision()) {
1230        return None;
1231    }
1232
1233    let (last_px, liquidity_side) =
1234        incremental_inferred_fill_price_and_liquidity(order, report, instrument)?;
1235
1236    let venue_order_id = order.venue_order_id().unwrap_or(report.venue_order_id);
1237    let position_id = reconciliation_position_id(report, instrument);
1238    let trade_id = create_inferred_reconciliation_trade_id(
1239        *account_id,
1240        order.instrument_id(),
1241        order.client_order_id(),
1242        Some(venue_order_id),
1243        order_side,
1244        order.order_type(),
1245        report.filled_qty,
1246        last_qty,
1247        last_px,
1248        position_id,
1249        report.ts_last,
1250    );
1251
1252    log::info!(
1253        color = LogColor::Blue as u8;
1254        "Generated inferred fill for {}: qty={}, px={}",
1255        order.client_order_id(),
1256        last_qty,
1257        last_px,
1258    );
1259
1260    Some(OrderEventAny::Filled(OrderFilled::new(
1261        order.trader_id(),
1262        order.strategy_id(),
1263        order.instrument_id(),
1264        order.client_order_id(),
1265        venue_order_id,
1266        *account_id,
1267        trade_id,
1268        order_side,
1269        order.order_type(),
1270        last_qty,
1271        last_px,
1272        instrument.quote_currency(),
1273        liquidity_side,
1274        UUID4::new(),
1275        report.ts_last,
1276        ts_now,
1277        true, // reconciliation
1278        report.venue_position_id,
1279        commission,
1280        None,
1281    )))
1282}
1283
1284/// Resolves the price and liquidity side that an incremental inferred fill will carry.
1285///
1286/// This uses the cached order's filled quantity and average price to derive the price of only the
1287/// unbooked quantity. Callers that calculate commission for an incremental fill must use these
1288/// values rather than the venue report's cumulative average.
1289///
1290/// Returns `None` when no fill price can be determined from the order, report, or instrument.
1291#[must_use]
1292pub fn incremental_inferred_fill_price_and_liquidity(
1293    order: &OrderAny,
1294    report: &OrderStatusReport,
1295    instrument: &InstrumentAny,
1296) -> Option<(Price, LiquiditySide)> {
1297    let last_px = calculate_incremental_fill_price(order, report, instrument)?;
1298
1299    Some((
1300        clamp_inferred_fill_price(last_px, instrument),
1301        inferred_fill_liquidity_side(order),
1302    ))
1303}
1304
1305/// Resolves the price and liquidity side that an inferred fill will carry.
1306///
1307/// Callers that need the venue commission for an inferred fill resolve these values first, so the
1308/// price and liquidity rules stay defined here rather than being restated at each call site.
1309///
1310/// Returns `None` when no fill price can be determined from the order, report, or instrument.
1311#[must_use]
1312pub fn inferred_fill_price_and_liquidity(
1313    order: &OrderAny,
1314    report: &OrderStatusReport,
1315    instrument: &InstrumentAny,
1316) -> Option<(Price, LiquiditySide)> {
1317    let last_px = resolve_fill_price(order, report, instrument)?;
1318
1319    Some((
1320        clamp_inferred_fill_price(last_px, instrument),
1321        inferred_fill_liquidity_side(order),
1322    ))
1323}
1324
1325fn inferred_fill_liquidity_side(order: &OrderAny) -> LiquiditySide {
1326    match order.order_type() {
1327        OrderType::Market
1328        | OrderType::StopMarket
1329        | OrderType::MarketToLimit
1330        | OrderType::TrailingStopMarket => LiquiditySide::Taker,
1331        _ if order.is_post_only() => LiquiditySide::Maker,
1332        _ => LiquiditySide::NoLiquiditySide,
1333    }
1334}
1335
1336/// Creates an inferred fill with a specific quantity.
1337///
1338/// Unlike `create_incremental_inferred_fill`, this takes the fill quantity directly
1339/// rather than calculating it from order state. Useful when order state hasn't been
1340/// updated yet (e.g., during external order processing).
1341pub fn create_inferred_fill_for_qty(
1342    order: &OrderAny,
1343    report: &OrderStatusReport,
1344    account_id: &AccountId,
1345    instrument: &InstrumentAny,
1346    fill_qty: Quantity,
1347    ts_now: UnixNanos,
1348    commission: Option<Money>,
1349) -> Option<OrderEventAny> {
1350    if fill_qty.is_zero() {
1351        return None;
1352    }
1353
1354    let order_side = order.order_side();
1355
1356    let Some((last_px, liquidity_side)) =
1357        inferred_fill_price_and_liquidity(order, report, instrument)
1358    else {
1359        log::warn!(
1360            "Cannot determine fill price for {}: no avg_px, report price, or order price",
1361            order.client_order_id()
1362        );
1363
1364        return None;
1365    };
1366
1367    let venue_order_id = order.venue_order_id().unwrap_or(report.venue_order_id);
1368    let position_id = reconciliation_position_id(report, instrument);
1369    let trade_id = create_inferred_reconciliation_trade_id(
1370        *account_id,
1371        order.instrument_id(),
1372        order.client_order_id(),
1373        Some(venue_order_id),
1374        order_side,
1375        order.order_type(),
1376        report.filled_qty,
1377        fill_qty,
1378        last_px,
1379        position_id,
1380        report.ts_last,
1381    );
1382
1383    log::info!(
1384        color = LogColor::Blue as u8;
1385        "Generated inferred fill for {}: qty={}, px={}",
1386        order.client_order_id(),
1387        fill_qty,
1388        last_px,
1389    );
1390
1391    Some(OrderEventAny::Filled(OrderFilled::new(
1392        order.trader_id(),
1393        order.strategy_id(),
1394        order.instrument_id(),
1395        order.client_order_id(),
1396        venue_order_id,
1397        *account_id,
1398        trade_id,
1399        order_side,
1400        order.order_type(),
1401        fill_qty,
1402        last_px,
1403        instrument.quote_currency(),
1404        liquidity_side,
1405        UUID4::new(),
1406        report.ts_last,
1407        ts_now,
1408        true, // reconciliation
1409        report.venue_position_id,
1410        commission,
1411        None,
1412    )))
1413}
1414
1415fn report_is_confirmed_state(report: &OrderStatusReport) -> bool {
1416    matches!(
1417        report.order_status,
1418        OrderStatus::Accepted
1419            | OrderStatus::Triggered
1420            | OrderStatus::PartiallyFilled
1421            | OrderStatus::Filled
1422            | OrderStatus::Canceled
1423            | OrderStatus::Expired
1424    )
1425}
1426
1427fn is_working(status: OrderStatus) -> bool {
1428    matches!(
1429        status,
1430        OrderStatus::Accepted | OrderStatus::Triggered | OrderStatus::PartiallyFilled
1431    )
1432}
1433
1434pub(crate) fn is_superseded_terminal_report(order: &OrderAny, report: &OrderStatusReport) -> bool {
1435    if !matches!(
1436        report.order_status,
1437        OrderStatus::Canceled | OrderStatus::Expired | OrderStatus::Filled
1438    ) {
1439        return false;
1440    }
1441
1442    let Some(cached_venue_order_id) = order.venue_order_id() else {
1443        return false;
1444    };
1445
1446    cached_venue_order_id != report.venue_order_id
1447        && order
1448            .venue_order_ids()
1449            .iter()
1450            .any(|venue_order_id| **venue_order_id == report.venue_order_id)
1451}
1452
1453fn pending_terminal_quantity_update(order: &OrderAny, report: &OrderStatusReport) -> bool {
1454    if !matches!(
1455        order.status(),
1456        OrderStatus::PendingUpdate | OrderStatus::PendingCancel
1457    ) {
1458        return false;
1459    }
1460
1461    if matches!(
1462        report.order_status,
1463        OrderStatus::Canceled | OrderStatus::Expired
1464    ) {
1465        return true;
1466    }
1467
1468    report.order_status == OrderStatus::Filled
1469        && report.filled_qty > order.quantity()
1470        && report.quantity >= report.filled_qty
1471}
1472
1473fn should_accept_before_reconciliation(order: &OrderAny, report: &OrderStatusReport) -> bool {
1474    order.status() == OrderStatus::Submitted && report.order_status != OrderStatus::Rejected
1475}
1476
1477/// Handles fill quantity mismatch between cached order and venue report.
1478///
1479/// Returns an inferred fill event if the venue reports more filled quantity than we have.
1480fn reconcile_fill_quantity_mismatch(
1481    order: &OrderAny,
1482    report: &OrderStatusReport,
1483    instrument: Option<&InstrumentAny>,
1484    ts_now: UnixNanos,
1485    commission: Option<Money>,
1486) -> Option<OrderEventAny> {
1487    let order_filled_qty = order.filled_qty();
1488    let report_filled_qty = report.filled_qty;
1489
1490    if report_filled_qty < order_filled_qty {
1491        // Venue cumulative below cached: apply no event so cached state is
1492        // preserved. Suppress sub-unit gaps as precision noise.
1493        let precision = order_filled_qty.precision.max(report_filled_qty.precision);
1494        if is_within_single_unit_tolerance(
1495            report_filled_qty.as_decimal(),
1496            order_filled_qty.as_decimal(),
1497            precision,
1498        ) {
1499            return None;
1500        }
1501
1502        log::warn!(
1503            "Fill qty mismatch for {} ({}): cached={}, venue={}, order_qty={} (venue < cached)",
1504            order.client_order_id(),
1505            report.venue_order_id,
1506            order_filled_qty,
1507            report_filled_qty,
1508            order.quantity(),
1509        );
1510        return None;
1511    }
1512
1513    if report_filled_qty > order_filled_qty {
1514        // Check if order is already closed - skip inferred fill to avoid invalid state
1515        // (matching Python behavior in _handle_fill_quantity_mismatch)
1516        if order.is_closed() {
1517            let precision = order_filled_qty.precision.max(report_filled_qty.precision);
1518
1519            if is_within_single_unit_tolerance(
1520                report_filled_qty.as_decimal(),
1521                order_filled_qty.as_decimal(),
1522                precision,
1523            ) {
1524                return None;
1525            }
1526
1527            log::debug!(
1528                "{} {} already closed but reported difference in filled_qty: \
1529                report={}, cached={}, skipping inferred fill generation for closed order",
1530                order.instrument_id(),
1531                order.client_order_id(),
1532                report_filled_qty,
1533                order_filled_qty,
1534            );
1535            return None;
1536        }
1537
1538        // Venue has more fills - generate inferred fill for the difference
1539        let Some(instrument) = instrument else {
1540            log::warn!(
1541                "Cannot generate inferred fill for {}: instrument not available",
1542                order.client_order_id()
1543            );
1544            return None;
1545        };
1546
1547        let account_id = order.account_id()?;
1548        return create_incremental_inferred_fill(
1549            order,
1550            report,
1551            &account_id,
1552            instrument,
1553            ts_now,
1554            commission,
1555        );
1556    }
1557
1558    // Quantities match but status differs: if the venue reduced the order
1559    // quantity (e.g. partial cancel leaving filled_qty==quantity), emit
1560    // OrderUpdated so the local state machine can transition; do not
1561    // synthesize a fill since filled_qty already matches.
1562    if order.status() != report.order_status {
1563        if should_reconciliation_update(order, report) {
1564            log::info!(
1565                "Status mismatch with matching fill qty for {}: local={:?}, venue={:?}, \
1566                 filled_qty={}, updating quantity {}->{}",
1567                order.client_order_id(),
1568                order.status(),
1569                report.order_status,
1570                report.filled_qty,
1571                order.quantity(),
1572                report.quantity,
1573            );
1574            return Some(create_reconciliation_updated(order, report, ts_now));
1575        }
1576
1577        log::warn!(
1578            "Status mismatch with matching fill qty for {}: local={:?}, venue={:?}, filled_qty={}",
1579            order.client_order_id(),
1580            order.status(),
1581            report.order_status,
1582            report.filled_qty
1583        );
1584    }
1585
1586    None
1587}
1588
1589/// Calculates the fill price for an incremental inferred fill.
1590///
1591/// The back-solve is guarded because nothing downstream rejects a negative price:
1592/// [`Price`] admits negatives, [`clamp_inferred_fill_price`] caps only the upper bound,
1593/// and `Position` takes `OrderFilled::last_px` straight into `avg_px_open` and PnL.
1594fn calculate_incremental_fill_price(
1595    order: &OrderAny,
1596    report: &OrderStatusReport,
1597    instrument: &InstrumentAny,
1598) -> Option<Price> {
1599    let order_filled_qty = order.filled_qty();
1600    debug_assert!(
1601        report.filled_qty >= order_filled_qty,
1602        "incremental fill price requires report.filled_qty ({}) >= order.filled_qty ({}) for {}",
1603        report.filled_qty,
1604        order_filled_qty,
1605        order.client_order_id(),
1606    );
1607
1608    // First fill - nothing booked locally to difference against
1609    if order_filled_qty.is_zero() {
1610        let last_px = resolve_fill_price(order, report, instrument);
1611        if last_px.is_none() {
1612            log::warn!(
1613                "Cannot determine fill price for {}: no avg_px, report price, or order price",
1614                order.client_order_id()
1615            );
1616        }
1617
1618        return last_px;
1619    }
1620
1621    // Incremental fill - calculate price using weighted average
1622    if let Some(report_avg_px) = report.avg_px {
1623        let last_px_decimal = match order.avg_px() {
1624            // No previous average to difference against
1625            None => report_avg_px,
1626            Some(order_avg_px) => {
1627                let report_filled_qty = report.filled_qty;
1628                let last_qty = report_filled_qty - order_filled_qty;
1629
1630                let report_notional = report_avg_px * report_filled_qty.as_decimal();
1631                let order_notional = order_avg_px * order_filled_qty.as_decimal();
1632                let last_notional = report_notional - order_notional;
1633                let back_solved = last_notional / last_qty.as_decimal();
1634
1635                if back_solved < Decimal::ZERO && !instrument.allows_negative_price() {
1636                    if report_avg_px < Decimal::ZERO {
1637                        log::warn!(
1638                            "Cannot price inferred fill for {}: back-solved {back_solved} and venue average {report_avg_px} are both negative on an instrument that disallows negative prices",
1639                            order.client_order_id(),
1640                        );
1641
1642                        return None;
1643                    }
1644
1645                    log::warn!(
1646                        "Negative back-solved fill price {back_solved} for {}, using venue average {report_avg_px}",
1647                        order.client_order_id(),
1648                    );
1649
1650                    report_avg_px
1651                } else {
1652                    back_solved
1653                }
1654            }
1655        };
1656
1657        return reconciliation_price(last_px_decimal, instrument)
1658            .inspect_err(|e| {
1659                log::warn!(
1660                    "Cannot price {} from incremental {last_px_decimal}, falling back: {e}",
1661                    order.client_order_id(),
1662                );
1663            })
1664            .ok()
1665            .or_else(|| resolve_fill_price(order, report, instrument));
1666    }
1667
1668    resolve_fill_price(order, report, instrument)
1669}
1670
1671/// Resolves a fill price from the venue report, falling back to the order.
1672///
1673/// Rungs run from most to least direct evidence of what executed. Callers decide what an
1674/// unresolved price means: booking a fill at an invented price corrupts position averages,
1675/// whereas a void event only needs a placeholder.
1676fn resolve_fill_price(
1677    order: &OrderAny,
1678    report: &OrderStatusReport,
1679    instrument: &InstrumentAny,
1680) -> Option<Price> {
1681    report
1682        .avg_px
1683        .and_then(|avg_px| {
1684            reconciliation_price(avg_px, instrument)
1685                .inspect_err(|e| {
1686                    log::warn!(
1687                        "Cannot price {} from venue average {avg_px}, trying next source: {e}",
1688                        order.client_order_id(),
1689                    );
1690                })
1691                .ok()
1692        })
1693        .or(report.price)
1694        .or_else(|| order.price())
1695}
1696
1697/// Caps an inferred fill price at the instrument's maximum price.
1698///
1699/// Thin `Price` wrapper over [`cap_price_at_instrument_max`]; see that
1700/// function for why reconciliation needs to bound synthetic fill prices.
1701fn clamp_inferred_fill_price(price: Price, instrument: &InstrumentAny) -> Price {
1702    let px = cap_price_at_instrument_max(price.as_decimal(), instrument);
1703    Price::from_decimal_dp(px, price.precision.max(instrument.price_precision())).unwrap_or(price)
1704}
1705
1706fn reconciliation_position_id(
1707    report: &OrderStatusReport,
1708    instrument: &InstrumentAny,
1709) -> PositionId {
1710    report
1711        .venue_position_id
1712        .unwrap_or_else(|| PositionId::new(format!("{}-EXTERNAL", instrument.id())))
1713}