Skip to main content

nautilus_execution/reconciliation/
positions.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//! Position-state reconciliation.
17//!
18//! Position simulation, partial-window fill reconstruction, mass-status processing,
19//! and final position-match checks. The core invariant maintained here is that the
20//! reconstructed position matches the venue's reported position within tolerance
21//! (default 0.01%) after reconciliation is applied.
22
23use indexmap::{IndexMap, IndexSet};
24use nautilus_common::cache::Cache;
25use nautilus_core::UnixNanos;
26use nautilus_model::{
27    enums::{
28        AvgPxReconciliation, LiquiditySide, OrderSide, OrderStatus, OrderType, PositionSide,
29        TimeInForce,
30    },
31    identifiers::{AccountId, InstrumentId, TradeId, VenueOrderId},
32    instruments::{Instrument, InstrumentAny},
33    orders::Order,
34    position::Position,
35    reports::{ExecutionMassStatus, FillReport, OrderStatusReport, PositionStatusReport},
36    types::{Money, Quantity},
37};
38use rust_decimal::{Decimal, RoundingStrategy};
39
40use super::{
41    RECONCILIATION_ORDER_TAG,
42    ids::{create_synthetic_trade_id, create_synthetic_venue_order_id},
43    reconciliation_price,
44    types::{FillAdjustmentResult, FillSnapshot, ReconciliationResult, VenuePositionSnapshot},
45};
46
47const DEFAULT_TOLERANCE: Decimal = Decimal::from_parts(1, 0, 0, false, 4); // 0.0001
48
49/// Process fill reports from a mass status for position reconciliation.
50///
51/// This is the main entry point for position reconciliation. It:
52/// 1. Extracts fills and position for the given instrument
53/// 2. Detects position discrepancies
54/// 3. Returns adjusted order/fill reports ready for processing
55///
56/// # Errors
57///
58/// Returns an error if synthetic report creation fails.
59pub fn process_mass_status_for_reconciliation(
60    mass_status: &ExecutionMassStatus,
61    instrument: &InstrumentAny,
62    tolerance: Option<Decimal>,
63) -> anyhow::Result<ReconciliationResult> {
64    process_mass_status_for_reconciliation_inner(mass_status, instrument, tolerance, true)
65}
66
67/// Process fill reports without generating synthetic order or fill reports.
68///
69/// Non-generating adjustments, such as filtering completed position lifecycles, are still applied.
70///
71/// # Errors
72///
73/// Returns an error if report processing fails.
74pub fn process_mass_status_for_reconciliation_without_synthetic_reports(
75    mass_status: &ExecutionMassStatus,
76    instrument: &InstrumentAny,
77    tolerance: Option<Decimal>,
78) -> anyhow::Result<ReconciliationResult> {
79    process_mass_status_for_reconciliation_inner(mass_status, instrument, tolerance, false)
80}
81
82fn process_mass_status_for_reconciliation_inner(
83    mass_status: &ExecutionMassStatus,
84    instrument: &InstrumentAny,
85    tolerance: Option<Decimal>,
86    generate_synthetic_reports: bool,
87) -> anyhow::Result<ReconciliationResult> {
88    let instrument_id = instrument.id();
89    let account_id = mass_status.account_id;
90    let tol = tolerance.unwrap_or(DEFAULT_TOLERANCE);
91
92    let position_reports = mass_status.position_reports();
93
94    let venue_position = match position_reports.get(&instrument_id).and_then(|r| r.first()) {
95        Some(report) if report.avg_px_open.is_some() => position_report_to_snapshot(report),
96        _ => {
97            // Preserve real history when the report cannot price synthetic recovery
98            return Ok(extract_instrument_reports(mass_status, instrument_id));
99        }
100    };
101
102    let extracted = extract_fills_for_instrument(mass_status, instrument_id);
103    let fill_snapshots = extracted.snapshots;
104    let mut order_map = extracted.orders;
105    let mut fill_map = extracted.fills;
106    let mut order_only_ids = IndexSet::new();
107    let mut order_only_fill_keys = IndexSet::new();
108
109    if fill_snapshots.is_empty() {
110        return Ok(ReconciliationResult {
111            orders: order_map,
112            fills: fill_map,
113            order_only_ids,
114            order_only_fill_keys,
115        });
116    }
117
118    let result = adjust_fills_for_partial_window(&fill_snapshots, &venue_position, tol);
119
120    match result {
121        FillAdjustmentResult::NoAdjustment => {}
122
123        FillAdjustmentResult::AddSyntheticOpening {
124            synthetic_fill,
125            existing_fills: _,
126        } if generate_synthetic_reports => {
127            let venue_order_id = create_synthetic_venue_order_id(&synthetic_fill, instrument_id);
128
129            let order = create_synthetic_order_report(
130                &synthetic_fill,
131                account_id,
132                instrument_id,
133                instrument,
134                venue_order_id,
135            )?;
136            let fill = create_synthetic_fill_report(
137                &synthetic_fill,
138                account_id,
139                instrument_id,
140                instrument,
141                venue_order_id,
142            )?;
143
144            order_map.insert(venue_order_id, order);
145            fill_map.entry(venue_order_id).or_default().insert(0, fill);
146        }
147
148        FillAdjustmentResult::ReplaceCurrentLifecycle { synthetic_fill }
149            if generate_synthetic_reports =>
150        {
151            let venue_order_id = create_synthetic_venue_order_id(&synthetic_fill, instrument_id);
152
153            let order = create_synthetic_order_report(
154                &synthetic_fill,
155                account_id,
156                instrument_id,
157                instrument,
158                venue_order_id,
159            )?;
160            let fill = create_synthetic_fill_report(
161                &synthetic_fill,
162                account_id,
163                instrument_id,
164                instrument,
165                venue_order_id,
166            )?;
167
168            // Preserve reported orders for replay deduplication, their prior fills
169            // must not add exposure on top of the synthetic fill.
170            order_only_ids.extend(order_map.keys().copied());
171            fill_map.retain(|id, _| order_only_ids.contains(id));
172            order_map.insert(venue_order_id, order);
173            fill_map.insert(venue_order_id, vec![fill]);
174        }
175
176        FillAdjustmentResult::FilterToCurrentLifecycle {
177            last_zero_crossing_ts,
178            current_lifecycle_fills: _,
179        } => {
180            // Drop orders filled entirely before the current lifecycle. A spanning order keeps
181            // its earlier fills as order-only: they settle its filled quantity, not the position
182            fill_map.retain(|_, fills| {
183                if !fills
184                    .iter()
185                    .any(|f| f.ts_event.as_u64() > last_zero_crossing_ts)
186                {
187                    return false;
188                }
189                order_only_fill_keys.extend(
190                    fills
191                        .iter()
192                        .filter(|f| f.ts_event.as_u64() <= last_zero_crossing_ts)
193                        .map(|f| (f.account_id, f.instrument_id, f.trade_id)),
194                );
195                true
196            });
197
198            // Keep only orders that have fills or are still working
199            order_map.retain(|id, order| {
200                fill_map.contains_key(id)
201                    || !matches!(
202                        order.order_status,
203                        OrderStatus::Denied
204                            | OrderStatus::Rejected
205                            | OrderStatus::Canceled
206                            | OrderStatus::Expired
207                            | OrderStatus::Filled
208                    )
209            });
210        }
211
212        FillAdjustmentResult::AddSyntheticOpening { .. }
213        | FillAdjustmentResult::ReplaceCurrentLifecycle { .. } => {}
214    }
215
216    Ok(ReconciliationResult {
217        orders: order_map,
218        fills: fill_map,
219        order_only_ids,
220        order_only_fill_keys,
221    })
222}
223
224/// Adjust fills for partial reconciliation window to handle incomplete position lifecycles.
225///
226/// This function analyzes fills and determines if adjustments are needed when the reconciliation
227/// window doesn't capture the complete position history (missing opening fills).
228///
229/// # Returns
230///
231/// Returns `FillAdjustmentResult` indicating what adjustments (if any) are needed.
232#[must_use]
233pub(super) fn adjust_fills_for_partial_window(
234    fills: &[FillSnapshot],
235    venue_position: &VenuePositionSnapshot,
236    tolerance: Decimal,
237) -> FillAdjustmentResult {
238    let Some(first_fill) = fills.first() else {
239        return FillAdjustmentResult::NoAdjustment;
240    };
241
242    if venue_position.qty == Decimal::ZERO {
243        return FillAdjustmentResult::NoAdjustment;
244    }
245
246    let zero_crossings = detect_zero_crossings(fills);
247    let venue_qty_signed = venue_position.signed_qty();
248
249    // Focus on the current lifecycle after the last zero-crossing
250    if let Some(&last_zero_crossing_ts) = zero_crossings.last() {
251        // Find the last zero-crossing that lands on FLAT (qty==0)
252        // This separates lifecycles; flips within a lifecycle don't count
253        let mut last_flat_crossing_ts = None;
254        let mut running_qty = Decimal::ZERO;
255
256        for fill in fills {
257            let prev_qty = running_qty;
258            running_qty += Decimal::from(fill.direction()) * fill.qty;
259
260            if prev_qty != Decimal::ZERO && running_qty == Decimal::ZERO {
261                last_flat_crossing_ts = Some(fill.ts_event);
262            }
263        }
264
265        let lifecycle_boundary_ts = last_flat_crossing_ts.unwrap_or(last_zero_crossing_ts);
266
267        // Get fills from current lifecycle (after lifecycle boundary)
268        let current_lifecycle_fills: Vec<FillSnapshot> = fills
269            .iter()
270            .filter(|f| f.ts_event > lifecycle_boundary_ts)
271            .cloned()
272            .collect();
273
274        let Some(first_fill) = current_lifecycle_fills.first() else {
275            return FillAdjustmentResult::NoAdjustment;
276        };
277
278        let (current_qty, current_value) = simulate_position(&current_lifecycle_fills);
279
280        if check_position_match(current_qty, current_value, venue_position, tolerance) {
281            // Current lifecycle matches - filter out old lifecycles
282            return FillAdjustmentResult::FilterToCurrentLifecycle {
283                last_zero_crossing_ts: lifecycle_boundary_ts,
284                current_lifecycle_fills,
285            };
286        }
287
288        // Current lifecycle doesn't match - replace with synthetic fill
289        let synthetic_fill = FillSnapshot::new(
290            first_fill.venue_order_id,
291            position_to_order_side(venue_position.side),
292            venue_position.qty,
293            venue_position.avg_px,
294            first_fill.ts_event.saturating_sub(1), // Timestamp before first fill
295        );
296
297        return FillAdjustmentResult::ReplaceCurrentLifecycle { synthetic_fill };
298    }
299
300    let (oldest_qty, oldest_value) = simulate_position(fills);
301
302    if check_position_match(oldest_qty, oldest_value, venue_position, tolerance) {
303        return FillAdjustmentResult::NoAdjustment;
304    }
305
306    // Use the simulated position as current and the venue position as target
307    let oldest_avg_px = if oldest_qty == Decimal::ZERO {
308        None
309    } else {
310        Some(oldest_value / oldest_qty.abs())
311    };
312
313    let Some(opening_px) = synthetic_opening_price(oldest_qty, oldest_avg_px, venue_position)
314    else {
315        return FillAdjustmentResult::NoAdjustment;
316    };
317
318    let opening_qty = if oldest_qty == Decimal::ZERO {
319        venue_qty_signed
320    } else {
321        // Work backwards: venue = opening + current fills
322        venue_qty_signed - oldest_qty
323    };
324
325    if opening_qty.abs() == Decimal::ZERO {
326        return FillAdjustmentResult::NoAdjustment;
327    }
328
329    let synthetic_side = if opening_qty > Decimal::ZERO {
330        OrderSide::Buy
331    } else {
332        OrderSide::Sell
333    };
334
335    let synthetic_fill = FillSnapshot::new(
336        first_fill.venue_order_id,
337        synthetic_side,
338        opening_qty.abs(),
339        opening_px,
340        first_fill.ts_event.saturating_sub(1),
341    );
342
343    FillAdjustmentResult::AddSyntheticOpening {
344        synthetic_fill,
345        existing_fills: fills.to_vec(),
346    }
347}
348
349fn synthetic_opening_price(
350    window_qty: Decimal,
351    window_avg_px: Option<Decimal>,
352    venue_position: &VenuePositionSnapshot,
353) -> Option<Decimal> {
354    match venue_position.avg_px_reconciliation {
355        // The synthetic fill opens the position before the window's fills
356        AvgPxReconciliation::OpeningOnly => Some(venue_position.avg_px),
357        AvgPxReconciliation::Match => calculate_reconciliation_price(
358            window_qty,
359            window_avg_px,
360            venue_position.signed_qty(),
361            Some(venue_position.avg_px),
362            AvgPxReconciliation::Match,
363            venue_position.avg_px_precision,
364        ),
365    }
366}
367
368/// Check if a cached position matches the venue position report within tolerance.
369///
370/// Compares the cached signed quantity against the venue-reported signed quantity,
371/// allowing a single-unit tolerance at the instrument's size precision when provided.
372///
373/// # Returns
374///
375/// Returns `true` when positions match (within tolerance), `false` otherwise. Logs
376/// a debug message when values differ but fall within tolerance, and a warning
377/// when they fail to reconcile.
378pub fn check_position_reconciliation(
379    report: &PositionStatusReport,
380    cached_signed_qty: Decimal,
381    size_precision: Option<u8>,
382) -> bool {
383    let venue_signed_qty = report.signed_decimal_qty;
384
385    if venue_signed_qty == Decimal::ZERO && cached_signed_qty == Decimal::ZERO {
386        return true;
387    }
388
389    if let Some(precision) = size_precision
390        && is_within_single_unit_tolerance(cached_signed_qty, venue_signed_qty, precision)
391    {
392        log::debug!(
393            "Position for {} within tolerance: cached={}, venue={}",
394            report.instrument_id,
395            cached_signed_qty,
396            venue_signed_qty
397        );
398        return true;
399    }
400
401    if cached_signed_qty == venue_signed_qty {
402        return true;
403    }
404
405    log::warn!(
406        "Position discrepancy for {}: cached={}, venue={}",
407        report.instrument_id,
408        cached_signed_qty,
409        venue_signed_qty
410    );
411
412    false
413}
414
415/// Returns whether a fill report predates a synthetic correction for its instrument and account.
416///
417/// The venue position report behind that correction already includes the fill, so applying it
418/// to the position would count the execution twice.
419#[must_use]
420pub fn fill_precedes_snapshot_reconciled_position(cache: &Cache, report: &FillReport) -> bool {
421    cache
422        .positions_refs(
423            None,
424            Some(&report.instrument_id),
425            None,
426            Some(&report.account_id),
427            None,
428        )
429        .into_iter()
430        .any(|position| {
431            fill_precedes_reconciled_position(cache, &position, report.trade_id, report.ts_event)
432        })
433}
434
435pub(crate) fn fill_precedes_reconciled_position(
436    cache: &Cache,
437    position: &Position,
438    trade_id: TradeId,
439    ts_event: UnixNanos,
440) -> bool {
441    !position.trade_ids.contains(&trade_id)
442        && position.events.iter().rev().any(|fill| {
443            ts_event < fill.ts_event
444                && cache.order(&fill.client_order_id).is_some_and(|order| {
445                    order.tags().is_some_and(|tags| {
446                        tags.iter()
447                            .any(|tag| tag.as_str() == RECONCILIATION_ORDER_TAG)
448                    })
449                })
450        })
451}
452
453/// Caps a price at the instrument's maximum price.
454///
455/// Reconciliation derives synthetic prices by dividing a notional by a
456/// quantity; when that quantity is a dust rounding residual the result blows up
457/// far above the instrument's tradeable range. Capping at `max_price` keeps
458/// synthetic reports, and the positions derived from them, within range.
459/// Because the blown-up price always pairs with a dust quantity (the
460/// denominator) the PnL impact is negligible. Only the upper bound is enforced:
461/// the blow-up is always on the high side, so the lower bound is left untouched
462/// and legitimate negative-price and zero-cost fills pass through unchanged. A
463/// missing `max_price` leaves the price unmodified.
464///
465/// The cap is `max_price` floored to the instrument's price precision, so that
466/// rebuilding a `Price` at that precision (which rounds) cannot lift the result
467/// back above `max_price`. For example a 2 dp instrument with `max_price = 0.999`
468/// caps at `0.99`, since `0.999` (or any value in `(0.99, 1.00)`) rebuilt at 2 dp
469/// would round to `1.00`.
470pub(super) fn cap_price_at_instrument_max(px: Decimal, instrument: &InstrumentAny) -> Decimal {
471    let Some(max) = instrument.max_price() else {
472        return px;
473    };
474    let cap = max.as_decimal().round_dp_with_strategy(
475        u32::from(instrument.price_precision()),
476        RoundingStrategy::ToZero,
477    );
478    px.min(cap)
479}
480
481/// Create a synthetic `OrderStatusReport` from a `FillSnapshot`.
482///
483/// Populates `avg_px` from the fill's price so downstream reconciliation paths
484/// (e.g. [`crate::reconciliation::orders::create_inferred_fill`]) can resolve a
485/// fill price without falling back to the "no `avg_px`, report price, or order price" warning.
486///
487/// # Errors
488///
489/// Returns an error if the fill quantity cannot be converted to f64.
490pub(super) fn create_synthetic_order_report(
491    fill: &FillSnapshot,
492    account_id: AccountId,
493    instrument_id: InstrumentId,
494    instrument: &InstrumentAny,
495    venue_order_id: VenueOrderId,
496) -> anyhow::Result<OrderStatusReport> {
497    let order_qty = Quantity::from_decimal_dp(fill.qty, instrument.size_precision())?;
498
499    let mut report = OrderStatusReport::new(
500        account_id,
501        instrument_id,
502        None, // client_order_id
503        venue_order_id,
504        fill.side.into(),
505        OrderType::Market,
506        TimeInForce::Gtc,
507        OrderStatus::Filled,
508        order_qty,
509        order_qty, // filled_qty = order_qty (fully filled)
510        UnixNanos::from(fill.ts_event),
511        UnixNanos::from(fill.ts_event),
512        UnixNanos::from(fill.ts_event),
513        None, // report_id
514    );
515    report.avg_px = Some(cap_price_at_instrument_max(fill.px, instrument));
516    Ok(report)
517}
518
519/// Create a synthetic `FillReport` from a `FillSnapshot`.
520///
521/// # Errors
522///
523/// Returns an error if the fill quantity or price cannot be converted.
524pub(super) fn create_synthetic_fill_report(
525    fill: &FillSnapshot,
526    account_id: AccountId,
527    instrument_id: InstrumentId,
528    instrument: &InstrumentAny,
529    venue_order_id: VenueOrderId,
530) -> anyhow::Result<FillReport> {
531    let trade_id = create_synthetic_trade_id(fill);
532    let qty = Quantity::from_decimal_dp(fill.qty, instrument.size_precision())?;
533    let px = reconciliation_price(cap_price_at_instrument_max(fill.px, instrument), instrument)?;
534
535    Ok(FillReport::new(
536        account_id,
537        instrument_id,
538        venue_order_id,
539        trade_id,
540        fill.side,
541        qty,
542        px,
543        Money::zero(instrument.quote_currency()),
544        LiquiditySide::NoLiquiditySide,
545        None, // client_order_id
546        None, // venue_position_id
547        fill.ts_event.into(),
548        fill.ts_event.into(),
549        None, // report_id
550    ))
551}
552
553/// Convert a position status report to a venue position snapshot.
554fn position_report_to_snapshot(report: &PositionStatusReport) -> VenuePositionSnapshot {
555    VenuePositionSnapshot {
556        side: report.position_side,
557        qty: report.quantity.into(),
558        avg_px: report.avg_px_open.unwrap_or(Decimal::ZERO),
559        avg_px_reconciliation: report.avg_px_open_reconciliation,
560        avg_px_precision: report.avg_px_open_precision,
561    }
562}
563
564/// Map a position side to the order side that would open it.
565///
566/// Callers must guard `Flat` upstream; reaching it here means a flat venue
567/// position slipped past the qty==0 early returns in
568/// [`adjust_fills_for_partial_window`].
569fn position_to_order_side(side: PositionSide) -> OrderSide {
570    match side {
571        PositionSide::Long => OrderSide::Buy,
572        PositionSide::Short => OrderSide::Sell,
573        PositionSide::Flat => {
574            unreachable!("flat venue position must be guarded by an earlier check")
575        }
576    }
577}
578
579/// Extract orders and fills for a specific instrument from mass status.
580fn extract_instrument_reports(
581    mass_status: &ExecutionMassStatus,
582    instrument_id: InstrumentId,
583) -> ReconciliationResult {
584    let mut orders = IndexMap::new();
585    let mut fills = IndexMap::new();
586
587    for (id, order) in mass_status.order_reports() {
588        if order.instrument_id == instrument_id {
589            orders.insert(id, order.clone());
590        }
591    }
592
593    for (id, fill_list) in mass_status.fill_reports() {
594        let filtered: Vec<_> = fill_list
595            .iter()
596            .filter(|f| {
597                if f.instrument_id != instrument_id {
598                    return false;
599                }
600
601                if f.last_qty.is_zero() {
602                    log::warn!("Skipping zero-quantity fill report: {f}");
603                    return false;
604                }
605
606                true
607            })
608            .cloned()
609            .collect();
610
611        if !filtered.is_empty() {
612            fills.insert(id, filtered);
613        }
614    }
615
616    ReconciliationResult {
617        orders,
618        fills,
619        order_only_ids: IndexSet::new(),
620        order_only_fill_keys: IndexSet::new(),
621    }
622}
623
624/// Extracted fills and reports for an instrument.
625struct ExtractedFills {
626    snapshots: Vec<FillSnapshot>,
627    orders: IndexMap<VenueOrderId, OrderStatusReport>,
628    fills: IndexMap<VenueOrderId, Vec<FillReport>>,
629}
630
631/// Extract fills for an instrument and convert to snapshots.
632fn extract_fills_for_instrument(
633    mass_status: &ExecutionMassStatus,
634    instrument_id: InstrumentId,
635) -> ExtractedFills {
636    let mut snapshots = Vec::new();
637    let mut order_map = IndexMap::new();
638    let mut fill_map = IndexMap::new();
639
640    // Seed order_map
641    for (id, order) in mass_status.order_reports() {
642        if order.instrument_id == instrument_id {
643            order_map.insert(id, order.clone());
644        }
645    }
646
647    // Extract fills
648    for (venue_order_id, fill_reports) in mass_status.fill_reports() {
649        for fill in fill_reports {
650            if fill.instrument_id == instrument_id {
651                if fill.last_qty.is_zero() {
652                    log::warn!("Skipping zero-quantity fill report: {fill}");
653                    continue;
654                }
655
656                let side = mass_status
657                    .order_reports()
658                    .get(&venue_order_id)
659                    .and_then(|order| order.order_side)
660                    .unwrap_or(fill.order_side);
661
662                snapshots.push(FillSnapshot::new(
663                    venue_order_id,
664                    side,
665                    fill.last_qty.into(),
666                    fill.last_px.into(),
667                    fill.ts_event.as_u64(),
668                ));
669
670                fill_map
671                    .entry(venue_order_id)
672                    .or_insert_with(Vec::new)
673                    .push(fill.clone());
674            }
675        }
676    }
677
678    // Sort chronologically
679    snapshots.sort_by_key(|f| f.ts_event);
680
681    ExtractedFills {
682        snapshots,
683        orders: order_map,
684        fills: fill_map,
685    }
686}
687
688/// Simulate position from chronologically ordered fills using netting logic.
689///
690/// # Returns
691///
692/// Returns a tuple of (quantity, value) after applying all fills.
693#[must_use]
694pub(super) fn simulate_position(fills: &[FillSnapshot]) -> (Decimal, Decimal) {
695    let mut qty = Decimal::ZERO;
696    let mut value = Decimal::ZERO;
697
698    for fill in fills {
699        debug_assert!(
700            fill.qty > Decimal::ZERO,
701            "fill snapshot qty must be positive, received {}",
702            fill.qty,
703        );
704        let direction = Decimal::from(fill.direction());
705        let new_qty = qty + (direction * fill.qty);
706
707        // Check if we're accumulating or crossing zero (flip/close)
708        if (qty >= Decimal::ZERO && direction > Decimal::ZERO)
709            || (qty <= Decimal::ZERO && direction < Decimal::ZERO)
710        {
711            // Accumulating in same direction
712            value += fill.qty * fill.px;
713            qty = new_qty;
714        } else {
715            // Closing or flipping position
716            if qty.abs() >= fill.qty {
717                // Partial close - maintain average price by reducing value proportionally
718                let close_ratio = fill.qty / qty.abs();
719                value *= Decimal::ONE - close_ratio;
720                qty = new_qty;
721            } else {
722                // Close and flip - reset value to opening position
723                let remaining = fill.qty - qty.abs();
724                qty = direction * remaining;
725                value = remaining * fill.px;
726            }
727        }
728    }
729
730    debug_assert!(
731        value >= Decimal::ZERO,
732        "simulated position value must be non-negative, was {value}",
733    );
734    debug_assert!(
735        !(qty != Decimal::ZERO && value.is_sign_negative()),
736        "simulated avg price invariant: qty={qty}, value={value}",
737    );
738
739    (qty, value)
740}
741
742/// Detect zero-crossing timestamps in a sequence of fills.
743///
744/// A zero-crossing occurs when position quantity crosses through zero (FLAT).
745/// This includes both landing exactly on zero and flipping from long to short or vice versa.
746///
747/// # Returns
748///
749/// Returns a list of timestamps where position crosses through zero.
750#[must_use]
751pub(super) fn detect_zero_crossings(fills: &[FillSnapshot]) -> Vec<u64> {
752    let mut running_qty = Decimal::ZERO;
753    let mut zero_crossings = Vec::new();
754
755    for fill in fills {
756        let prev_qty = running_qty;
757        running_qty += Decimal::from(fill.direction()) * fill.qty;
758
759        // Detect when position crosses zero
760        if prev_qty != Decimal::ZERO {
761            if running_qty == Decimal::ZERO {
762                // Landed exactly on zero
763                zero_crossings.push(fill.ts_event);
764            } else if (prev_qty > Decimal::ZERO) != (running_qty > Decimal::ZERO) {
765                // Sign changed - crossed through zero (flip)
766                zero_crossings.push(fill.ts_event);
767            }
768        }
769    }
770
771    zero_crossings
772}
773
774/// Check if simulated position matches venue position within tolerance.
775///
776/// An [`AvgPxReconciliation::OpeningOnly`] venue average is not comparable, so only
777/// quantities must match.
778///
779/// # Returns
780///
781/// Returns true if quantities and average prices match within tolerance.
782#[must_use]
783pub(super) fn check_position_match(
784    simulated_qty: Decimal,
785    simulated_value: Decimal,
786    venue_position: &VenuePositionSnapshot,
787    tolerance: Decimal,
788) -> bool {
789    if simulated_qty != venue_position.signed_qty() {
790        return false;
791    }
792
793    if simulated_qty == Decimal::ZERO {
794        return true; // Both FLAT
795    }
796
797    if venue_position.avg_px_reconciliation == AvgPxReconciliation::OpeningOnly {
798        return true;
799    }
800
801    let simulated_avg_px = simulated_value / simulated_qty.abs();
802
803    position_prices_match(
804        simulated_avg_px,
805        venue_position.avg_px,
806        Some(tolerance),
807        venue_position.avg_px_precision,
808    )
809}
810
811/// Compares average entry prices using relative tolerance (default 0.01%).
812///
813/// Average entry prices need not fall on instrument price ticks. A zero reported
814/// average cannot establish a relative comparison and returns `false`. When the venue
815/// rounds or truncates its average to `venue_precision` decimal places, the difference may
816/// also span one unit at that precision on top of the relative tolerance; a precision above
817/// 28 adds no allowance.
818#[must_use]
819pub fn position_prices_match(
820    cached_avg_px: Decimal,
821    venue_avg_px: Decimal,
822    tolerance: Option<Decimal>,
823    venue_precision: Option<u8>,
824) -> bool {
825    if venue_avg_px.is_zero() {
826        return false;
827    }
828
829    let tolerance = tolerance.unwrap_or(DEFAULT_TOLERANCE);
830    let diff = (cached_avg_px - venue_avg_px).abs();
831
832    if diff / venue_avg_px.abs() <= tolerance {
833        return true;
834    }
835
836    venue_precision.is_some_and(|precision| {
837        let unit = Decimal::try_new(1, u32::from(precision)).unwrap_or(Decimal::ZERO);
838        diff <= tolerance * venue_avg_px.abs() + unit
839    })
840}
841
842/// Calculate the price needed for a reconciliation order to achieve target position.
843///
844/// This is a pure function that calculates what price a fill would need to have
845/// to move from the current position state to the target position state. By default, a
846/// reduction uses the reported average price but cannot change the remaining position's entry
847/// average.
848///
849/// A same-side reduction or accumulation instead keeps the current average as its price when the
850/// target average is [`AvgPxReconciliation::OpeningOnly`], or when the target average carries a
851/// precision and already matches the current average, so neither a different averaging method
852/// nor venue rounding fabricates a fill price. This override takes precedence over scenarios 4
853/// and 5 below.
854///
855/// # Returns
856///
857/// Returns `Some(Decimal)` if a valid reconciliation price can be calculated, `None` otherwise.
858///
859/// # Notes
860///
861/// The function handles five scenarios:
862/// 1. Position to flat: `reconciliation_px` = `current_avg_px` (close at current average)
863/// 2. Flat to position: `reconciliation_px` = `target_avg_px`
864/// 3. Position flip (sign change): `reconciliation_px` = `target_avg_px` (due to value reset in simulation)
865/// 4. Reduction: target average price by default (remaining entry average is unchanged)
866/// 5. Accumulation: weighted average formula by default
867pub fn calculate_reconciliation_price(
868    current_position_qty: Decimal,
869    current_position_avg_px: Option<Decimal>,
870    target_position_qty: Decimal,
871    target_position_avg_px: Option<Decimal>,
872    target_avg_px_reconciliation: AvgPxReconciliation,
873    target_avg_px_precision: Option<u8>,
874) -> Option<Decimal> {
875    let qty_diff = target_position_qty - current_position_qty;
876
877    if qty_diff == Decimal::ZERO {
878        return None; // No reconciliation needed
879    }
880
881    let is_same_side = current_position_qty != Decimal::ZERO
882        && target_position_qty != Decimal::ZERO
883        && (current_position_qty > Decimal::ZERO) == (target_position_qty > Decimal::ZERO);
884
885    if is_same_side
886        && let Some(current_avg_px) = current_position_avg_px
887        && keeps_current_avg_px(
888            current_avg_px,
889            target_position_avg_px,
890            target_avg_px_reconciliation,
891            target_avg_px_precision,
892        )
893    {
894        return Some(current_avg_px);
895    }
896
897    // Special case: closing to flat (target_position_qty == 0)
898    // When flattening, the reconciliation price equals the current position's average price
899    if target_position_qty == Decimal::ZERO {
900        return current_position_avg_px;
901    }
902
903    // If target average price is not provided or zero, we cannot calculate
904    let target_avg_px = target_position_avg_px?;
905    if target_avg_px == Decimal::ZERO {
906        return None;
907    }
908
909    // If current position is flat, the reconciliation price equals target avg price
910    if current_position_qty == Decimal::ZERO || current_position_avg_px.is_none() {
911        return Some(target_avg_px);
912    }
913
914    let current_avg_px = current_position_avg_px?;
915
916    // Check if this is a flip scenario (sign change)
917    // In simulation, flips reset value to remaining * px, so reconciliation_px = target_avg_px
918    let is_flip = (current_position_qty > Decimal::ZERO) != (target_position_qty > Decimal::ZERO)
919        && target_position_qty != Decimal::ZERO;
920
921    if is_flip {
922        return Some(target_avg_px);
923    }
924
925    if target_position_qty.abs() < current_position_qty.abs() {
926        return Some(target_avg_px);
927    }
928
929    // For accumulation, use weighted average formula
930    // Formula: (target_qty * target_avg_px) = (current_qty * current_avg_px) + (qty_diff * reconciliation_px)
931    let target_value = target_position_qty * target_avg_px;
932    let current_value = current_position_qty * current_avg_px;
933    let diff_value = target_value - current_value;
934
935    // qty_diff is guaranteed non-zero by the early return above
936    let reconciliation_px = diff_value / qty_diff;
937
938    // Ensure price is positive
939    if reconciliation_px > Decimal::ZERO {
940        return Some(reconciliation_px);
941    }
942
943    None
944}
945
946fn keeps_current_avg_px(
947    current_avg_px: Decimal,
948    target_avg_px: Option<Decimal>,
949    target_avg_px_reconciliation: AvgPxReconciliation,
950    target_avg_px_precision: Option<u8>,
951) -> bool {
952    match target_avg_px_reconciliation {
953        AvgPxReconciliation::OpeningOnly => true,
954        AvgPxReconciliation::Match => {
955            target_avg_px_precision.is_some()
956                && target_avg_px.is_some_and(|target_avg_px| {
957                    position_prices_match(
958                        current_avg_px,
959                        target_avg_px,
960                        None,
961                        target_avg_px_precision,
962                    )
963                })
964        }
965    }
966}
967
968/// Checks if two decimal values are within a single unit of tolerance for the given precision.
969///
970/// For integer precision (0), requires exact match.
971/// For fractional precision, allows difference of 1 unit at that precision.
972#[must_use]
973pub(super) fn is_within_single_unit_tolerance(
974    value1: Decimal,
975    value2: Decimal,
976    precision: u8,
977) -> bool {
978    if precision == 0 {
979        return value1 == value2;
980    }
981
982    let tolerance = Decimal::new(1, u32::from(precision));
983    let difference = (value1 - value2).abs();
984    difference <= tolerance
985}