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::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 => {
395            if matches!(
396                order.status(),
397                OrderStatus::Accepted | OrderStatus::PendingUpdate
398            ) && should_reconciliation_update(order, report)
399            {
400                return Some(create_reconciliation_updated(order, report, ts_now));
401            }
402            create_reconciliation_accepted(order, report, ts_now)
403        }
404        OrderStatus::Rejected => {
405            create_reconciliation_rejected(order, report.cancel_reason.as_deref(), ts_now)
406        }
407        OrderStatus::Triggered => {
408            if TRIGGERABLE_ORDER_TYPES.contains(&order.order_type()) {
409                Some(create_reconciliation_triggered(order, report, ts_now))
410            } else {
411                log::debug!(
412                    "Skipping OrderTriggered for {} order {}: market-style stops have no TRIGGERED state",
413                    order.order_type(),
414                    order.client_order_id(),
415                );
416                None
417            }
418        }
419        OrderStatus::Canceled => Some(create_reconciliation_canceled(order, report, ts_now)),
420        OrderStatus::Expired => Some(create_reconciliation_expired(order, report, ts_now)),
421
422        OrderStatus::PartiallyFilled | OrderStatus::Filled => {
423            reconcile_fill_quantity_mismatch(order, report, instrument, ts_now, commission)
424        }
425
426        OrderStatus::Voided => {
427            create_reconciliation_terminal_fill_void(order, report, instrument, ts_now)
428        }
429
430        OrderStatus::PendingUpdate | OrderStatus::PendingCancel => None,
431
432        // Internal states - should not appear in venue reports
433        OrderStatus::Initialized
434        | OrderStatus::Submitted
435        | OrderStatus::Denied
436        | OrderStatus::Emulated
437        | OrderStatus::Released => {
438            log::warn!(
439                "Unexpected order status in venue report for {}: {:?}",
440                order.client_order_id(),
441                report.order_status
442            );
443            None
444        }
445    }
446}
447
448fn is_unchanged_accepted_report_during_pending_command(
449    order: &OrderAny,
450    report: &OrderStatusReport,
451) -> bool {
452    matches!(
453        order.status(),
454        OrderStatus::PendingUpdate | OrderStatus::PendingCancel
455    ) && report.order_status == OrderStatus::Accepted
456        && order.venue_order_id() == Some(report.venue_order_id)
457        && order.filled_qty() == report.filled_qty
458        && !should_reconciliation_update(order, report)
459}
460
461/// Generates the appropriate order events for an external order and order status report.
462///
463/// After creating an external order, we need to transition it to its actual state
464/// based on the order status report from the venue. For terminal states like
465/// Canceled/Expired/Filled, we return multiple events to properly transition
466/// the order through Accepted before reaching the terminal state.
467pub fn generate_external_order_status_events(
468    order: &OrderAny,
469    report: &OrderStatusReport,
470    account_id: &AccountId,
471    instrument: &InstrumentAny,
472    ts_now: UnixNanos,
473) -> Vec<OrderEventAny> {
474    generate_external_order_status_events_with_commission(
475        order, report, account_id, instrument, ts_now, None,
476    )
477}
478
479/// Generates external-order status events with a precomputed inferred-fill commission.
480#[must_use]
481pub fn generate_external_order_status_events_with_commission(
482    order: &OrderAny,
483    report: &OrderStatusReport,
484    account_id: &AccountId,
485    instrument: &InstrumentAny,
486    ts_now: UnixNanos,
487    commission: Option<Money>,
488) -> Vec<OrderEventAny> {
489    let accepted = OrderEventAny::Accepted(OrderAccepted::new(
490        order.trader_id(),
491        order.strategy_id(),
492        order.instrument_id(),
493        order.client_order_id(),
494        report.venue_order_id,
495        *account_id,
496        UUID4::new(),
497        report.ts_accepted,
498        ts_now,
499        true, // reconciliation
500    ));
501
502    match report.order_status {
503        OrderStatus::Accepted | OrderStatus::Triggered => vec![accepted],
504        OrderStatus::PartiallyFilled | OrderStatus::Filled => {
505            let mut events = vec![accepted];
506
507            if !report.filled_qty.is_zero()
508                && let Some(filled) =
509                    create_inferred_fill(order, report, *account_id, instrument, ts_now, commission)
510            {
511                events.push(filled);
512            }
513
514            events
515        }
516        OrderStatus::Voided => {
517            let mut working = order.clone();
518            if let Err(e) = working.apply(accepted.clone()) {
519                log::warn!(
520                    "Cannot project external order acceptance for {}: {e}",
521                    order.client_order_id()
522                );
523                return vec![accepted];
524            }
525            let mut events = vec![accepted];
526
527            if !report.filled_qty.is_zero()
528                && let Some(filled) =
529                    create_inferred_fill(order, report, *account_id, instrument, ts_now, commission)
530            {
531                if let Err(e) = working.apply(filled.clone()) {
532                    log::warn!(
533                        "Cannot project external order fill for {}: {e}",
534                        order.client_order_id()
535                    );
536                } else {
537                    events.push(filled);
538                }
539            }
540
541            if let Some(voided) =
542                create_reconciliation_terminal_fill_void(&working, report, Some(instrument), ts_now)
543            {
544                events.push(voided);
545            }
546            events
547        }
548        OrderStatus::Canceled | OrderStatus::Expired => {
549            let terminal = create_external_terminal_event(order, report, *account_id, ts_now);
550            let mut events = vec![accepted];
551
552            let inferred_fill = if report.filled_qty.is_zero() {
553                None
554            } else {
555                create_inferred_fill(order, report, *account_id, instrument, ts_now, commission)
556            };
557            let filled_to_quantity =
558                inferred_fill.is_some() && report.filled_qty >= report.quantity;
559            if let Some(filled) = inferred_fill {
560                events.push(filled);
561            }
562
563            if !filled_to_quantity {
564                events.push(terminal);
565            }
566            events
567        }
568        OrderStatus::Rejected => {
569            // Rejected goes directly to terminal state without acceptance
570            let reason = report.cancel_reason.as_deref().unwrap_or("UNKNOWN");
571            vec![OrderEventAny::Rejected(OrderRejected::new(
572                order.trader_id(),
573                order.strategy_id(),
574                order.instrument_id(),
575                order.client_order_id(),
576                *account_id,
577                Ustr::from(reason),
578                UUID4::new(),
579                report.ts_last,
580                ts_now,
581                true, // reconciliation
582                reason_indicates_post_only_rejection(reason),
583            ))]
584        }
585        _ => {
586            log::warn!(
587                "Unhandled order status {} for external order {}",
588                report.order_status,
589                order.client_order_id()
590            );
591            Vec::new()
592        }
593    }
594}
595
596fn create_reconciliation_fill_voids(
597    order: &OrderAny,
598    report: &OrderStatusReport,
599    ts_now: UnixNanos,
600) -> Vec<OrderEventAny> {
601    let mut remaining = order.filled_qty() - report.filled_qty;
602    let order_events = order.events();
603    let mut corrections = Vec::new();
604
605    // A repeated `trade_id` in the event log restates that trade's price and carries no
606    // quantity; a void must price against the original fill so the order accepts it.
607    let mut seen = HashSet::new();
608
609    let quantity_fills: Vec<&OrderFilled> = order_events
610        .iter()
611        .filter_map(|event| match event {
612            OrderEventAny::Filled(fill) if seen.insert(fill.trade_id) => Some(fill),
613            _ => None,
614        })
615        .collect();
616
617    for fill in quantity_fills.iter().rev() {
618        if remaining.is_zero() {
619            break;
620        }
621        let previous = order_events.iter().rev().find_map(|event| match event {
622            OrderEventAny::FillVoided(voided) if voided.trade_id == fill.trade_id => Some(voided),
623            _ => None,
624        });
625        let prior_qty = previous.map_or_else(
626            || Quantity::zero(fill.last_qty.precision),
627            |voided| voided.voided_qty.min(fill.last_qty),
628        );
629        let effective = fill.last_qty - prior_qty;
630        if effective.is_zero() {
631            continue;
632        }
633        let removed = remaining.min(effective);
634        let voided_qty = prior_qty + removed;
635        let commission_voided = fill.commission.and_then(|commission| {
636            let fraction = voided_qty.as_decimal() / fill.last_qty.as_decimal();
637            Money::from_decimal(commission.as_decimal() * fraction, commission.currency).ok()
638        });
639        let mut event = OrderFillVoided::new(
640            fill.trader_id,
641            fill.strategy_id,
642            fill.instrument_id,
643            fill.client_order_id,
644            fill.venue_order_id,
645            fill.account_id,
646            Ustr::from(&format!(
647                "reconciliation-{}-{}",
648                report.report_id, fill.trade_id
649            )),
650            fill.trade_id,
651            voided_qty,
652            commission_voided,
653            fill.order_side,
654            fill.order_type,
655            fill.last_px,
656            fill.currency,
657            fill.liquidity_side,
658            fill.position_id,
659            report.cancel_reason.as_deref().map(Ustr::from),
660            None,
661            UUID4::new(),
662            report.ts_last,
663            ts_now,
664            true,
665            is_working(report.order_status),
666        );
667        event.causation_id = Some(report.report_id);
668        corrections.push(OrderEventAny::FillVoided(event));
669        remaining = remaining - removed;
670    }
671
672    if !remaining.is_zero() {
673        log::warn!(
674            "Cannot reconcile fill decrease for {}: {} is outside retained fill history",
675            order.client_order_id(),
676            remaining
677        );
678        return Vec::new();
679    }
680    corrections
681}
682
683/// Creates a fill void reversing the remaining leaves of a terminally voided order.
684///
685/// An unresolved price falls back to zero rather than `None`: the price is a placeholder that
686/// never reaches `Position::avg_px_open`, whereas suppressing the void would leave the order
687/// open locally against a venue that considers it gone.
688fn create_reconciliation_terminal_fill_void(
689    order: &OrderAny,
690    report: &OrderStatusReport,
691    instrument: Option<&InstrumentAny>,
692    ts_now: UnixNanos,
693) -> Option<OrderEventAny> {
694    let voided_qty = order.leaves_qty();
695    if voided_qty.is_zero() {
696        return None;
697    }
698    let instrument = instrument?;
699    let order_side = order.order_side();
700
701    let last_px = resolve_fill_price(order, report, instrument)
702        .unwrap_or_else(|| Price::zero(instrument.price_precision()));
703
704    let mut event = OrderFillVoided::new(
705        order.trader_id(),
706        order.strategy_id(),
707        order.instrument_id(),
708        order.client_order_id(),
709        report.venue_order_id,
710        report.account_id,
711        Ustr::from(&format!("reconciliation-{}", report.report_id)),
712        TradeId::new(format!("VOID-{}", report.venue_order_id)),
713        voided_qty,
714        None,
715        order_side,
716        order.order_type(),
717        last_px,
718        instrument.quote_currency(),
719        LiquiditySide::NoLiquiditySide,
720        None,
721        report.cancel_reason.as_deref().map(Ustr::from),
722        None,
723        UUID4::new(),
724        report.ts_last,
725        ts_now,
726        true,
727        false,
728    );
729    event.causation_id = Some(report.report_id);
730    Some(OrderEventAny::FillVoided(event))
731}
732
733fn create_external_terminal_event(
734    order: &OrderAny,
735    report: &OrderStatusReport,
736    account_id: AccountId,
737    ts_now: UnixNanos,
738) -> OrderEventAny {
739    match report.order_status {
740        OrderStatus::Canceled => OrderEventAny::Canceled(OrderCanceled::new(
741            order.trader_id(),
742            order.strategy_id(),
743            order.instrument_id(),
744            order.client_order_id(),
745            UUID4::new(),
746            report.ts_last,
747            ts_now,
748            true, // reconciliation
749            Some(report.venue_order_id),
750            Some(account_id),
751            report.cancel_reason.as_deref().map(Ustr::from),
752        )),
753        OrderStatus::Expired => OrderEventAny::Expired(OrderExpired::new(
754            order.trader_id(),
755            order.strategy_id(),
756            order.instrument_id(),
757            order.client_order_id(),
758            UUID4::new(),
759            report.ts_last,
760            ts_now,
761            true, // reconciliation
762            Some(report.venue_order_id),
763            Some(account_id),
764        )),
765        status => unreachable!("cannot create external terminal event for {status}"),
766    }
767}
768
769/// Creates an `OrderFilled` event from a `FillReport`.
770///
771/// This is used during reconciliation when a fill report is received from the venue.
772/// Returns `None` if the fill is a duplicate or would cause an overfill.
773pub fn reconcile_fill_report(
774    order: &OrderAny,
775    report: &FillReport,
776    instrument: &InstrumentAny,
777    ts_now: UnixNanos,
778    allow_overfills: bool,
779) -> Option<OrderEventAny> {
780    if report.last_qty.is_zero() {
781        log::warn!("Skipping zero-quantity fill report: {report}");
782        return None;
783    }
784
785    if order.trade_ids().iter().any(|id| **id == report.trade_id) {
786        log::debug!(
787            "Duplicate fill detected: trade_id {} already exists for order {}",
788            report.trade_id,
789            order.client_order_id()
790        );
791        return None;
792    }
793
794    let potential_filled_qty = order.filled_qty() + report.last_qty;
795    if potential_filled_qty > order.quantity() {
796        if !allow_overfills {
797            log::warn!(
798                "Rejecting fill that would cause overfill for {}: order.quantity={}, order.filled_qty={}, fill.last_qty={}, would result in filled_qty={}",
799                order.client_order_id(),
800                order.quantity(),
801                order.filled_qty(),
802                report.last_qty,
803                potential_filled_qty
804            );
805            return None;
806        }
807        log::warn!(
808            "Allowing overfill during reconciliation for {}: order.quantity={}, order.filled_qty={}, fill.last_qty={}, will result in filled_qty={}",
809            order.client_order_id(),
810            order.quantity(),
811            order.filled_qty(),
812            report.last_qty,
813            potential_filled_qty
814        );
815    }
816
817    let account_id = report.account_id;
818    let venue_order_id = if order.venue_order_id() == Some(report.venue_order_id)
819        || order.venue_order_ids().contains(&&report.venue_order_id)
820    {
821        report.venue_order_id
822    } else {
823        order.venue_order_id().unwrap_or(report.venue_order_id)
824    };
825
826    log::info!(
827        color = LogColor::Blue as u8;
828        "Reconciling fill for {}: qty={}, px={}, trade_id={}",
829        order.client_order_id(),
830        report.last_qty,
831        report.last_px,
832        report.trade_id,
833    );
834
835    Some(OrderEventAny::Filled(OrderFilled::new(
836        order.trader_id(),
837        order.strategy_id(),
838        order.instrument_id(),
839        order.client_order_id(),
840        venue_order_id,
841        account_id,
842        report.trade_id,
843        order.order_side(),
844        order.order_type(),
845        report.last_qty,
846        report.last_px,
847        instrument.quote_currency(),
848        report.liquidity_side,
849        UUID4::new(),
850        report.ts_event,
851        ts_now,
852        true, // reconciliation
853        report.venue_position_id,
854        Some(report.commission),
855        None,
856    )))
857}
858
859/// Checks if the order should be updated based on quantity, price, or trigger price
860/// differences from the venue report.
861///
862/// A `None` value in `report.price` or `report.trigger_price` is treated as
863/// "venue did not include this field" rather than as drift, so a partial
864/// snapshot (for example, a Filled report that omits price but supplies
865/// `avg_px`) does not trigger a spurious `OrderUpdated`.
866pub fn should_reconciliation_update(order: &OrderAny, report: &OrderStatusReport) -> bool {
867    if report.quantity != order.quantity() && report.quantity >= order.filled_qty() {
868        return true;
869    }
870
871    let price_drift = report.price.is_some() && report.price != order.price();
872    let trigger_drift =
873        report.trigger_price.is_some() && report.trigger_price != order.trigger_price();
874
875    match order.order_type() {
876        OrderType::Limit => price_drift,
877        OrderType::StopMarket | OrderType::TrailingStopMarket | OrderType::MarketIfTouched => {
878            trigger_drift
879        }
880        OrderType::StopLimit | OrderType::TrailingStopLimit | OrderType::LimitIfTouched => {
881            trigger_drift || price_drift
882        }
883        _ => false,
884    }
885}
886
887/// Creates an `OrderAccepted` event for reconciliation.
888#[must_use]
889pub(super) fn create_reconciliation_accepted(
890    order: &OrderAny,
891    report: &OrderStatusReport,
892    ts_now: UnixNanos,
893) -> Option<OrderEventAny> {
894    let account_id = order.account_id()?;
895
896    Some(OrderEventAny::Accepted(OrderAccepted::new(
897        order.trader_id(),
898        order.strategy_id(),
899        order.instrument_id(),
900        order.client_order_id(),
901        order.venue_order_id().unwrap_or(report.venue_order_id),
902        account_id,
903        UUID4::new(),
904        report.ts_accepted,
905        ts_now,
906        true, // reconciliation
907    )))
908}
909
910/// Creates an `OrderRejected` event for reconciliation.
911#[must_use]
912pub fn create_reconciliation_rejected(
913    order: &OrderAny,
914    reason: Option<&str>,
915    ts_now: UnixNanos,
916) -> Option<OrderEventAny> {
917    let account_id = order.account_id()?;
918    let reason = reason.unwrap_or("UNKNOWN");
919
920    Some(OrderEventAny::Rejected(OrderRejected::new(
921        order.trader_id(),
922        order.strategy_id(),
923        order.instrument_id(),
924        order.client_order_id(),
925        account_id,
926        Ustr::from(reason),
927        UUID4::new(),
928        ts_now,
929        ts_now,
930        true, // reconciliation
931        reason_indicates_post_only_rejection(reason),
932    )))
933}
934
935fn reason_indicates_post_only_rejection(reason: &str) -> bool {
936    let normalized: String = reason
937        .chars()
938        .filter_map(|ch| {
939            if ch == '-' || ch == '_' || ch.is_whitespace() {
940                None
941            } else {
942                Some(ch.to_ascii_lowercase())
943            }
944        })
945        .collect();
946
947    normalized.contains("postonly") || normalized.contains("postwouldexecute")
948}
949
950/// Creates an `OrderTriggered` event for reconciliation.
951#[must_use]
952pub fn create_reconciliation_triggered(
953    order: &OrderAny,
954    report: &OrderStatusReport,
955    ts_now: UnixNanos,
956) -> OrderEventAny {
957    OrderEventAny::Triggered(OrderTriggered::new(
958        order.trader_id(),
959        order.strategy_id(),
960        order.instrument_id(),
961        order.client_order_id(),
962        UUID4::new(),
963        report.ts_triggered.unwrap_or(ts_now),
964        ts_now,
965        true, // reconciliation
966        order.venue_order_id(),
967        order.account_id(),
968    ))
969}
970
971/// Creates an `OrderCanceled` event for reconciliation.
972#[must_use]
973pub(super) fn create_reconciliation_canceled(
974    order: &OrderAny,
975    report: &OrderStatusReport,
976    ts_now: UnixNanos,
977) -> OrderEventAny {
978    OrderEventAny::Canceled(OrderCanceled::new(
979        order.trader_id(),
980        order.strategy_id(),
981        order.instrument_id(),
982        order.client_order_id(),
983        UUID4::new(),
984        report.ts_last,
985        ts_now,
986        true, // reconciliation
987        order.venue_order_id(),
988        order.account_id(),
989        report.cancel_reason.as_deref().map(Ustr::from),
990    ))
991}
992
993/// Creates an `OrderExpired` event for reconciliation.
994#[must_use]
995pub(super) fn create_reconciliation_expired(
996    order: &OrderAny,
997    report: &OrderStatusReport,
998    ts_now: UnixNanos,
999) -> OrderEventAny {
1000    OrderEventAny::Expired(OrderExpired::new(
1001        order.trader_id(),
1002        order.strategy_id(),
1003        order.instrument_id(),
1004        order.client_order_id(),
1005        UUID4::new(),
1006        report.ts_last,
1007        ts_now,
1008        true, // reconciliation
1009        order.venue_order_id(),
1010        order.account_id(),
1011    ))
1012}
1013
1014/// Creates an `OrderUpdated` event for reconciliation.
1015#[must_use]
1016pub(super) fn create_reconciliation_updated(
1017    order: &OrderAny,
1018    report: &OrderStatusReport,
1019    ts_now: UnixNanos,
1020) -> OrderEventAny {
1021    // Only pass trigger_price for order types that support it.
1022    // Limit, Market, and MarketToLimit orders assert trigger_price.is_none()
1023    // in their update() methods - passing a spurious trigger_price from the
1024    // venue report (e.g. Bybit sends "0.00" for non-conditional orders)
1025    // causes a panic. Positive list ensures new order types without
1026    // trigger_price support won't accidentally receive one.
1027    let trigger_price = match order.order_type() {
1028        OrderType::StopMarket
1029        | OrderType::StopLimit
1030        | OrderType::MarketIfTouched
1031        | OrderType::LimitIfTouched
1032        | OrderType::TrailingStopMarket
1033        | OrderType::TrailingStopLimit => report.trigger_price,
1034        _ => None,
1035    };
1036
1037    // Market-style reports can carry an execution cap instead of a limit price
1038    let price = if LIMIT_ORDER_TYPES.contains(&order.order_type())
1039        || order.order_type() == OrderType::MarketToLimit
1040    {
1041        report.price
1042    } else {
1043        None
1044    };
1045
1046    OrderEventAny::Updated(OrderUpdated::new(
1047        order.trader_id(),
1048        order.strategy_id(),
1049        order.instrument_id(),
1050        order.client_order_id(),
1051        report.quantity,
1052        UUID4::new(),
1053        report.ts_last,
1054        ts_now,
1055        true, // reconciliation
1056        order.venue_order_id(),
1057        order.account_id(),
1058        price,
1059        trigger_price,
1060        None, // protection_price
1061        order.is_quote_quantity(),
1062    ))
1063}
1064
1065/// Creates an inferred fill event for reconciliation when fill reports are missing.
1066pub(super) fn create_inferred_fill(
1067    order: &OrderAny,
1068    report: &OrderStatusReport,
1069    account_id: AccountId,
1070    instrument: &InstrumentAny,
1071    ts_now: UnixNanos,
1072    commission: Option<Money>,
1073) -> Option<OrderEventAny> {
1074    let cached_order_side = order.order_side();
1075    let order_side = report.order_side.unwrap_or(cached_order_side);
1076    if order_side != cached_order_side {
1077        log::warn!(
1078            "Order side mismatch for {}: cached={:?}, venue={order_side:?}",
1079            order.client_order_id(),
1080            cached_order_side,
1081        );
1082    }
1083
1084    let liquidity_side = inferred_fill_liquidity_side(order);
1085
1086    let Some(last_px) = resolve_fill_price(order, report, instrument) else {
1087        log::warn!(
1088            "Cannot create inferred fill for {}: no avg_px, report price, or order price",
1089            order.client_order_id()
1090        );
1091
1092        return None;
1093    };
1094    let last_px = clamp_inferred_fill_price(last_px, instrument);
1095
1096    let position_id = reconciliation_position_id(report, instrument);
1097    let trade_id = create_inferred_reconciliation_trade_id(
1098        account_id,
1099        order.instrument_id(),
1100        order.client_order_id(),
1101        Some(report.venue_order_id),
1102        order_side,
1103        order.order_type(),
1104        report.filled_qty,
1105        report.filled_qty,
1106        last_px,
1107        position_id,
1108        report.ts_last,
1109    );
1110
1111    log::info!(
1112        "Generated inferred fill for {} ({}) qty={} px={}",
1113        order.client_order_id(),
1114        report.venue_order_id,
1115        report.filled_qty,
1116        last_px,
1117    );
1118
1119    Some(OrderEventAny::Filled(OrderFilled::new(
1120        order.trader_id(),
1121        order.strategy_id(),
1122        order.instrument_id(),
1123        order.client_order_id(),
1124        report.venue_order_id,
1125        account_id,
1126        trade_id,
1127        order_side,
1128        order.order_type(),
1129        report.filled_qty,
1130        last_px,
1131        instrument.quote_currency(),
1132        liquidity_side,
1133        UUID4::new(),
1134        report.ts_last,
1135        ts_now,
1136        true, // reconciliation
1137        report.venue_position_id,
1138        commission,
1139        None,
1140    )))
1141}
1142
1143/// Creates an inferred fill for the quantity difference between order and report.
1144pub fn create_incremental_inferred_fill(
1145    order: &OrderAny,
1146    report: &OrderStatusReport,
1147    account_id: &AccountId,
1148    instrument: &InstrumentAny,
1149    ts_now: UnixNanos,
1150    commission: Option<Money>,
1151) -> Option<OrderEventAny> {
1152    let order_side = order.order_side();
1153
1154    let order_filled_qty = order.filled_qty();
1155    debug_assert!(
1156        report.filled_qty >= order_filled_qty,
1157        "incremental inferred fill requires report.filled_qty ({}) >= order.filled_qty ({}) for {}",
1158        report.filled_qty,
1159        order_filled_qty,
1160        order.client_order_id(),
1161    );
1162    let last_qty = report.filled_qty - order_filled_qty;
1163
1164    if last_qty <= Quantity::zero(instrument.size_precision()) {
1165        return None;
1166    }
1167
1168    let (last_px, liquidity_side) =
1169        incremental_inferred_fill_price_and_liquidity(order, report, instrument)?;
1170
1171    let venue_order_id = order.venue_order_id().unwrap_or(report.venue_order_id);
1172    let position_id = reconciliation_position_id(report, instrument);
1173    let trade_id = create_inferred_reconciliation_trade_id(
1174        *account_id,
1175        order.instrument_id(),
1176        order.client_order_id(),
1177        Some(venue_order_id),
1178        order_side,
1179        order.order_type(),
1180        report.filled_qty,
1181        last_qty,
1182        last_px,
1183        position_id,
1184        report.ts_last,
1185    );
1186
1187    log::info!(
1188        color = LogColor::Blue as u8;
1189        "Generated inferred fill for {}: qty={}, px={}",
1190        order.client_order_id(),
1191        last_qty,
1192        last_px,
1193    );
1194
1195    Some(OrderEventAny::Filled(OrderFilled::new(
1196        order.trader_id(),
1197        order.strategy_id(),
1198        order.instrument_id(),
1199        order.client_order_id(),
1200        venue_order_id,
1201        *account_id,
1202        trade_id,
1203        order_side,
1204        order.order_type(),
1205        last_qty,
1206        last_px,
1207        instrument.quote_currency(),
1208        liquidity_side,
1209        UUID4::new(),
1210        report.ts_last,
1211        ts_now,
1212        true, // reconciliation
1213        report.venue_position_id,
1214        commission,
1215        None,
1216    )))
1217}
1218
1219/// Resolves the price and liquidity side that an incremental inferred fill will carry.
1220///
1221/// This uses the cached order's filled quantity and average price to derive the price of only the
1222/// unbooked quantity. Callers that calculate commission for an incremental fill must use these
1223/// values rather than the venue report's cumulative average.
1224///
1225/// Returns `None` when no fill price can be determined from the order, report, or instrument.
1226#[must_use]
1227pub fn incremental_inferred_fill_price_and_liquidity(
1228    order: &OrderAny,
1229    report: &OrderStatusReport,
1230    instrument: &InstrumentAny,
1231) -> Option<(Price, LiquiditySide)> {
1232    let last_px = calculate_incremental_fill_price(order, report, instrument)?;
1233
1234    Some((
1235        clamp_inferred_fill_price(last_px, instrument),
1236        inferred_fill_liquidity_side(order),
1237    ))
1238}
1239
1240/// Resolves the price and liquidity side that an inferred fill will carry.
1241///
1242/// Callers that need the venue commission for an inferred fill resolve these values first, so the
1243/// price and liquidity rules stay defined here rather than being restated at each call site.
1244///
1245/// Returns `None` when no fill price can be determined from the order, report, or instrument.
1246#[must_use]
1247pub fn inferred_fill_price_and_liquidity(
1248    order: &OrderAny,
1249    report: &OrderStatusReport,
1250    instrument: &InstrumentAny,
1251) -> Option<(Price, LiquiditySide)> {
1252    let last_px = resolve_fill_price(order, report, instrument)?;
1253
1254    Some((
1255        clamp_inferred_fill_price(last_px, instrument),
1256        inferred_fill_liquidity_side(order),
1257    ))
1258}
1259
1260fn inferred_fill_liquidity_side(order: &OrderAny) -> LiquiditySide {
1261    match order.order_type() {
1262        OrderType::Market
1263        | OrderType::StopMarket
1264        | OrderType::MarketToLimit
1265        | OrderType::TrailingStopMarket => LiquiditySide::Taker,
1266        _ if order.is_post_only() => LiquiditySide::Maker,
1267        _ => LiquiditySide::NoLiquiditySide,
1268    }
1269}
1270
1271/// Creates an inferred fill with a specific quantity.
1272///
1273/// Unlike `create_incremental_inferred_fill`, this takes the fill quantity directly
1274/// rather than calculating it from order state. Useful when order state hasn't been
1275/// updated yet (e.g., during external order processing).
1276pub fn create_inferred_fill_for_qty(
1277    order: &OrderAny,
1278    report: &OrderStatusReport,
1279    account_id: &AccountId,
1280    instrument: &InstrumentAny,
1281    fill_qty: Quantity,
1282    ts_now: UnixNanos,
1283    commission: Option<Money>,
1284) -> Option<OrderEventAny> {
1285    if fill_qty.is_zero() {
1286        return None;
1287    }
1288
1289    let order_side = order.order_side();
1290
1291    let Some((last_px, liquidity_side)) =
1292        inferred_fill_price_and_liquidity(order, report, instrument)
1293    else {
1294        log::warn!(
1295            "Cannot determine fill price for {}: no avg_px, report price, or order price",
1296            order.client_order_id()
1297        );
1298
1299        return None;
1300    };
1301
1302    let venue_order_id = order.venue_order_id().unwrap_or(report.venue_order_id);
1303    let position_id = reconciliation_position_id(report, instrument);
1304    let trade_id = create_inferred_reconciliation_trade_id(
1305        *account_id,
1306        order.instrument_id(),
1307        order.client_order_id(),
1308        Some(venue_order_id),
1309        order_side,
1310        order.order_type(),
1311        report.filled_qty,
1312        fill_qty,
1313        last_px,
1314        position_id,
1315        report.ts_last,
1316    );
1317
1318    log::info!(
1319        color = LogColor::Blue as u8;
1320        "Generated inferred fill for {}: qty={}, px={}",
1321        order.client_order_id(),
1322        fill_qty,
1323        last_px,
1324    );
1325
1326    Some(OrderEventAny::Filled(OrderFilled::new(
1327        order.trader_id(),
1328        order.strategy_id(),
1329        order.instrument_id(),
1330        order.client_order_id(),
1331        venue_order_id,
1332        *account_id,
1333        trade_id,
1334        order_side,
1335        order.order_type(),
1336        fill_qty,
1337        last_px,
1338        instrument.quote_currency(),
1339        liquidity_side,
1340        UUID4::new(),
1341        report.ts_last,
1342        ts_now,
1343        true, // reconciliation
1344        report.venue_position_id,
1345        commission,
1346        None,
1347    )))
1348}
1349
1350fn report_is_confirmed_state(report: &OrderStatusReport) -> bool {
1351    matches!(
1352        report.order_status,
1353        OrderStatus::Accepted
1354            | OrderStatus::Triggered
1355            | OrderStatus::PartiallyFilled
1356            | OrderStatus::Filled
1357            | OrderStatus::Canceled
1358            | OrderStatus::Expired
1359    )
1360}
1361
1362fn is_working(status: OrderStatus) -> bool {
1363    matches!(
1364        status,
1365        OrderStatus::Accepted | OrderStatus::Triggered | OrderStatus::PartiallyFilled
1366    )
1367}
1368
1369pub(crate) fn is_superseded_terminal_report(order: &OrderAny, report: &OrderStatusReport) -> bool {
1370    if !matches!(
1371        report.order_status,
1372        OrderStatus::Canceled | OrderStatus::Expired | OrderStatus::Filled
1373    ) {
1374        return false;
1375    }
1376
1377    let Some(cached_venue_order_id) = order.venue_order_id() else {
1378        return false;
1379    };
1380
1381    cached_venue_order_id != report.venue_order_id
1382        && order
1383            .venue_order_ids()
1384            .iter()
1385            .any(|venue_order_id| **venue_order_id == report.venue_order_id)
1386}
1387
1388fn pending_terminal_quantity_update(order: &OrderAny, report: &OrderStatusReport) -> bool {
1389    if !matches!(
1390        order.status(),
1391        OrderStatus::PendingUpdate | OrderStatus::PendingCancel
1392    ) {
1393        return false;
1394    }
1395
1396    if matches!(
1397        report.order_status,
1398        OrderStatus::Canceled | OrderStatus::Expired
1399    ) {
1400        return true;
1401    }
1402
1403    report.order_status == OrderStatus::Filled
1404        && report.filled_qty > order.quantity()
1405        && report.quantity >= report.filled_qty
1406}
1407
1408fn should_accept_before_reconciliation(order: &OrderAny, report: &OrderStatusReport) -> bool {
1409    order.status() == OrderStatus::Submitted && report.order_status != OrderStatus::Rejected
1410}
1411
1412/// Handles fill quantity mismatch between cached order and venue report.
1413///
1414/// Returns an inferred fill event if the venue reports more filled quantity than we have.
1415fn reconcile_fill_quantity_mismatch(
1416    order: &OrderAny,
1417    report: &OrderStatusReport,
1418    instrument: Option<&InstrumentAny>,
1419    ts_now: UnixNanos,
1420    commission: Option<Money>,
1421) -> Option<OrderEventAny> {
1422    let order_filled_qty = order.filled_qty();
1423    let report_filled_qty = report.filled_qty;
1424
1425    if report_filled_qty < order_filled_qty {
1426        // Venue cumulative below cached: apply no event so cached state is
1427        // preserved. Suppress sub-unit gaps as precision noise.
1428        let precision = order_filled_qty.precision.max(report_filled_qty.precision);
1429        if is_within_single_unit_tolerance(
1430            report_filled_qty.as_decimal(),
1431            order_filled_qty.as_decimal(),
1432            precision,
1433        ) {
1434            return None;
1435        }
1436
1437        log::warn!(
1438            "Fill qty mismatch for {} ({}): cached={}, venue={}, order_qty={} (venue < cached)",
1439            order.client_order_id(),
1440            report.venue_order_id,
1441            order_filled_qty,
1442            report_filled_qty,
1443            order.quantity(),
1444        );
1445        return None;
1446    }
1447
1448    if report_filled_qty > order_filled_qty {
1449        // Check if order is already closed - skip inferred fill to avoid invalid state
1450        // (matching Python behavior in _handle_fill_quantity_mismatch)
1451        if order.is_closed() {
1452            let precision = order_filled_qty.precision.max(report_filled_qty.precision);
1453
1454            if is_within_single_unit_tolerance(
1455                report_filled_qty.as_decimal(),
1456                order_filled_qty.as_decimal(),
1457                precision,
1458            ) {
1459                return None;
1460            }
1461
1462            log::debug!(
1463                "{} {} already closed but reported difference in filled_qty: \
1464                report={}, cached={}, skipping inferred fill generation for closed order",
1465                order.instrument_id(),
1466                order.client_order_id(),
1467                report_filled_qty,
1468                order_filled_qty,
1469            );
1470            return None;
1471        }
1472
1473        // Venue has more fills - generate inferred fill for the difference
1474        let Some(instrument) = instrument else {
1475            log::warn!(
1476                "Cannot generate inferred fill for {}: instrument not available",
1477                order.client_order_id()
1478            );
1479            return None;
1480        };
1481
1482        let account_id = order.account_id()?;
1483        return create_incremental_inferred_fill(
1484            order,
1485            report,
1486            &account_id,
1487            instrument,
1488            ts_now,
1489            commission,
1490        );
1491    }
1492
1493    // Quantities match but status differs: if the venue reduced the order
1494    // quantity (e.g. partial cancel leaving filled_qty==quantity), emit
1495    // OrderUpdated so the local state machine can transition; do not
1496    // synthesize a fill since filled_qty already matches.
1497    if order.status() != report.order_status {
1498        if should_reconciliation_update(order, report) {
1499            log::info!(
1500                "Status mismatch with matching fill qty for {}: local={:?}, venue={:?}, \
1501                 filled_qty={}, updating quantity {}->{}",
1502                order.client_order_id(),
1503                order.status(),
1504                report.order_status,
1505                report.filled_qty,
1506                order.quantity(),
1507                report.quantity,
1508            );
1509            return Some(create_reconciliation_updated(order, report, ts_now));
1510        }
1511
1512        log::warn!(
1513            "Status mismatch with matching fill qty for {}: local={:?}, venue={:?}, filled_qty={}",
1514            order.client_order_id(),
1515            order.status(),
1516            report.order_status,
1517            report.filled_qty
1518        );
1519    }
1520
1521    None
1522}
1523
1524/// Calculates the fill price for an incremental inferred fill.
1525///
1526/// The back-solve is guarded because nothing downstream rejects a negative price:
1527/// [`Price`] admits negatives, [`clamp_inferred_fill_price`] caps only the upper bound,
1528/// and `Position` takes `OrderFilled::last_px` straight into `avg_px_open` and PnL.
1529fn calculate_incremental_fill_price(
1530    order: &OrderAny,
1531    report: &OrderStatusReport,
1532    instrument: &InstrumentAny,
1533) -> Option<Price> {
1534    let order_filled_qty = order.filled_qty();
1535    debug_assert!(
1536        report.filled_qty >= order_filled_qty,
1537        "incremental fill price requires report.filled_qty ({}) >= order.filled_qty ({}) for {}",
1538        report.filled_qty,
1539        order_filled_qty,
1540        order.client_order_id(),
1541    );
1542
1543    // First fill - nothing booked locally to difference against
1544    if order_filled_qty.is_zero() {
1545        let last_px = resolve_fill_price(order, report, instrument);
1546        if last_px.is_none() {
1547            log::warn!(
1548                "Cannot determine fill price for {}: no avg_px, report price, or order price",
1549                order.client_order_id()
1550            );
1551        }
1552
1553        return last_px;
1554    }
1555
1556    // Incremental fill - calculate price using weighted average
1557    if let Some(report_avg_px) = report.avg_px {
1558        let last_px_decimal = match order.avg_px() {
1559            // No previous average to difference against
1560            None => report_avg_px,
1561            Some(order_avg_px) => {
1562                let report_filled_qty = report.filled_qty;
1563                let last_qty = report_filled_qty - order_filled_qty;
1564
1565                let report_notional = report_avg_px * report_filled_qty.as_decimal();
1566                let order_notional = order_avg_px * order_filled_qty.as_decimal();
1567                let last_notional = report_notional - order_notional;
1568                let back_solved = last_notional / last_qty.as_decimal();
1569
1570                if back_solved < Decimal::ZERO && !instrument.allows_negative_price() {
1571                    if report_avg_px < Decimal::ZERO {
1572                        log::warn!(
1573                            "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",
1574                            order.client_order_id(),
1575                        );
1576
1577                        return None;
1578                    }
1579
1580                    log::warn!(
1581                        "Negative back-solved fill price {back_solved} for {}, using venue average {report_avg_px}",
1582                        order.client_order_id(),
1583                    );
1584
1585                    report_avg_px
1586                } else {
1587                    back_solved
1588                }
1589            }
1590        };
1591
1592        return reconciliation_price(last_px_decimal, instrument)
1593            .inspect_err(|e| {
1594                log::warn!(
1595                    "Cannot price {} from incremental {last_px_decimal}, falling back: {e}",
1596                    order.client_order_id(),
1597                );
1598            })
1599            .ok()
1600            .or_else(|| resolve_fill_price(order, report, instrument));
1601    }
1602
1603    resolve_fill_price(order, report, instrument)
1604}
1605
1606/// Resolves a fill price from the venue report, falling back to the order.
1607///
1608/// Rungs run from most to least direct evidence of what executed. Callers decide what an
1609/// unresolved price means: booking a fill at an invented price corrupts position averages,
1610/// whereas a void event only needs a placeholder.
1611fn resolve_fill_price(
1612    order: &OrderAny,
1613    report: &OrderStatusReport,
1614    instrument: &InstrumentAny,
1615) -> Option<Price> {
1616    report
1617        .avg_px
1618        .and_then(|avg_px| {
1619            reconciliation_price(avg_px, instrument)
1620                .inspect_err(|e| {
1621                    log::warn!(
1622                        "Cannot price {} from venue average {avg_px}, trying next source: {e}",
1623                        order.client_order_id(),
1624                    );
1625                })
1626                .ok()
1627        })
1628        .or(report.price)
1629        .or_else(|| order.price())
1630}
1631
1632/// Caps an inferred fill price at the instrument's maximum price.
1633///
1634/// Thin `Price` wrapper over [`cap_price_at_instrument_max`]; see that
1635/// function for why reconciliation needs to bound synthetic fill prices.
1636fn clamp_inferred_fill_price(price: Price, instrument: &InstrumentAny) -> Price {
1637    let px = cap_price_at_instrument_max(price.as_decimal(), instrument);
1638    Price::from_decimal_dp(px, price.precision.max(instrument.price_precision())).unwrap_or(price)
1639}
1640
1641fn reconciliation_position_id(
1642    report: &OrderStatusReport,
1643    instrument: &InstrumentAny,
1644) -> PositionId {
1645    report
1646        .venue_position_id
1647        .unwrap_or_else(|| PositionId::new(format!("{}-EXTERNAL", instrument.id())))
1648}