Skip to main content

nautilus_interactive_brokers/execution/
parse.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//! Parsing utilities for converting IB execution data to Nautilus reports.
17
18use std::str::FromStr;
19
20use ahash::{AHashMap, AHashSet};
21use anyhow::Context;
22use ibapi::orders::{Execution, Liquidity, OrderData, OrderStatus};
23use jiff::{
24    Timestamp,
25    civil::DateTime,
26    tz::{AmbiguousOffset, Offset},
27};
28use nautilus_core::{UnixNanos, datetime::get_timezone};
29use nautilus_model::{
30    enums::{
31        ContingencyType, LiquiditySide, OrderSide, OrderStatus as NautilusOrderStatus, OrderType,
32        TimeInForce, TrailingOffsetType,
33    },
34    identifiers::{AccountId, ClientOrderId, InstrumentId, TradeId, VenueOrderId},
35    instruments::Instrument,
36    reports::{FillReport, OrderStatusReport, PositionStatusReport},
37    types::{Currency, Money, Price, Quantity},
38};
39use rust_decimal::Decimal;
40
41use crate::{
42    common::{
43        enums::{IbAction, IbOrderStatus, IbOrderType, IbTimeInForce},
44        spreads::is_spread_instrument_id,
45    },
46    execution::transform::{from_ib_price, ib_trigger_method_to_trigger_type},
47    providers::instruments::InteractiveBrokersInstrumentProvider,
48};
49
50pub(super) fn parse_order_data_to_report(
51    data: &OrderData,
52    instrument_id: InstrumentId,
53    account_id: AccountId,
54    instrument_provider: &InteractiveBrokersInstrumentProvider,
55    ts_init: UnixNanos,
56) -> anyhow::Result<OrderStatusReport> {
57    anyhow::ensure!(
58        data.order.total_quantity.is_finite()
59            && data.order.total_quantity >= 0.0
60            && data.order.filled_quantity.is_finite()
61            && data.order.filled_quantity >= 0.0,
62        "IB order {} has invalid quantities",
63        data.order_id
64    );
65
66    let mut report = parse_order_status_to_report(
67        &OrderStatus {
68            order_id: data.order_id,
69            status: data.order_state.status.clone(),
70            filled: data.order.filled_quantity,
71            remaining: (data.order.total_quantity - data.order.filled_quantity).max(0.0),
72            average_fill_price: None,
73            perm_id: data.order.perm_id,
74            parent_id: 0,
75            last_fill_price: None,
76            client_id: data.order.client_id,
77            why_held: String::new(),
78            market_cap_price: None,
79        },
80        Some(&data.order),
81        instrument_id,
82        account_id,
83        instrument_provider,
84        ts_init,
85    )?;
86
87    // Open orders carry no venue time; a completed order reports when it finished
88    if !data.order_state.completed_time.is_empty() {
89        match parse_execution_time(&data.order_state.completed_time) {
90            Ok(completed) => report.ts_last = completed,
91            Err(e) => tracing::debug!(
92                "Cannot parse completed time of IB order {}: {e}",
93                data.order_id
94            ),
95        }
96    }
97
98    Ok(report)
99}
100
101/// Links the contingencies IB reports across one batch of order status reports.
102///
103/// IB keeps bracket parents (`parent_id`) and OCA groups on its side; a status report parsed on
104/// its own cannot name the related orders. Each report is matched to its IB order by index.
105/// Reports whose OCA type IB does not model keep no contingency, and a contingency is only set
106/// when at least one related order is present in the batch.
107/// Sets the average price of filled order reports that lack one from their fill reports.
108///
109/// IB completed orders carry no average fill price, which reconciliation needs to rebuild a
110/// filled order before applying its fills.
111pub(crate) fn fill_missing_avg_px(
112    order_reports: &mut [OrderStatusReport],
113    fill_reports: &[FillReport],
114) {
115    for report in order_reports
116        .iter_mut()
117        .filter(|report| report.avg_px.is_none() && !report.filled_qty.is_zero())
118    {
119        let (notional, quantity) = fill_reports
120            .iter()
121            .filter(|fill| fill.venue_order_id == report.venue_order_id)
122            .fold(
123                (Decimal::ZERO, Decimal::ZERO),
124                |(notional, quantity), fill| {
125                    (
126                        notional + fill.last_px.as_decimal() * fill.last_qty.as_decimal(),
127                        quantity + fill.last_qty.as_decimal(),
128                    )
129                },
130            );
131
132        if !quantity.is_zero() {
133            report.avg_px = Some(notional / quantity);
134        }
135    }
136}
137
138/// Fill reports for an execution window, with the evidence an entry price rebuild needs.
139#[derive(Debug, Default)]
140pub(crate) struct FillEvidence {
141    pub(crate) reports: Vec<FillReport>,
142    /// Leg executions of combo orders, which `reports` drops in favor of the spread fill. They
143    /// still change the leg positions.
144    pub(crate) combo_leg_reports: Vec<FillReport>,
145    /// Whether an execution of an unknown instrument could not be turned into a fill report.
146    pub(crate) missing_all: bool,
147    /// Instruments with an execution that could not be turned into a fill report.
148    pub(crate) missing_instruments: AHashSet<InstrumentId>,
149}
150
151impl FillEvidence {
152    fn is_complete_for(&self, instrument_id: &InstrumentId) -> bool {
153        !self.missing_all && !self.missing_instruments.contains(instrument_id)
154    }
155}
156
157/// Replaces IB's position average cost with the entry price of the fills that built the position.
158///
159/// IB's `avgCost` includes commissions, while a position rebuilt from fills has the average of
160/// their prices. The fills in the mass status cover only the current window, so the replay
161/// starts from the quantity the position must have held before the window: the reported
162/// quantity minus the window's net quantity. Once that replay passes through flat, or flips,
163/// every later fill is known, and the entry price is the netting average of the fills after the
164/// last flat crossing. Fill reports arrive in commission order, so fills sharing a timestamp
165/// have no known execution order: when they include opposite sides or flip the position, the
166/// entry price is unknown until a later fill opens from flat or flips.
167///
168/// The replay infers the pre-window quantity, so a missing execution would be read as part of
169/// it. The entry price therefore replaces IB's average cost only when every execution of the
170/// instrument was parsed and the entry price plus the opening commissions per unit reproduces
171/// IB's average cost, within the rounding of the average cost and of each commission. Otherwise
172/// the position keeps IB's average cost, which position recovery prices from, with the
173/// one-tick precision the report was built with. A replaced average is the fills' own,
174/// unrounded, so its precision is cleared and reconciliation uses only the relative tolerance.
175pub(crate) fn fill_position_avg_px_from_fills(
176    position_reports: &mut [PositionStatusReport],
177    evidence: &FillEvidence,
178    instrument_provider: &InteractiveBrokersInstrumentProvider,
179) {
180    for report in position_reports
181        .iter_mut()
182        .filter(|report| !report.signed_decimal_qty.is_zero())
183    {
184        let instrument_id = report.instrument_id;
185        let Some(venue_avg_px) = report.avg_px_open else {
186            continue;
187        };
188        let Some(instrument) = instrument_provider.find(&instrument_id) else {
189            continue;
190        };
191
192        if !evidence.is_complete_for(&instrument_id) {
193            continue;
194        }
195
196        let mut fills: Vec<_> = evidence
197            .reports
198            .iter()
199            .chain(&evidence.combo_leg_reports)
200            .filter(|fill| {
201                fill.account_id == report.account_id && fill.instrument_id == instrument_id
202            })
203            .collect();
204
205        // IB's average cost is in the instrument's quote currency
206        if fills
207            .iter()
208            .any(|fill| fill.commission.currency != instrument.quote_currency())
209        {
210            continue;
211        }
212
213        fills.sort_by_key(|fill| fill.ts_event);
214
215        let window_qty: Decimal = fills.iter().map(|fill| signed_fill_qty(fill)).sum();
216        let pre_window_qty = report.signed_decimal_qty - window_qty;
217
218        let Some(lot) = entry_after_window(pre_window_qty, &fills) else {
219            continue;
220        };
221
222        let units = report.signed_decimal_qty.abs() * instrument.multiplier().as_decimal();
223        let commission_px = lot.commission / units;
224        let venue_avg_px_expected = if report.signed_decimal_qty.is_sign_positive() {
225            lot.avg_px + commission_px
226        } else {
227            lot.avg_px - commission_px
228        };
229
230        // IB's average cost is rounded to the price precision, and each opening commission is
231        // rounded to its currency's precision, which moves the expected average cost by up to
232        // half an increment per retained commission over the lot's units
233        let tick = Decimal::new(1, u32::from(instrument.price_precision()));
234        let half_increment = Decimal::new(5, u32::from(instrument.quote_currency().precision) + 1);
235        let tolerance = tick + half_increment * lot.commissions / units;
236
237        if (venue_avg_px - venue_avg_px_expected).abs() <= tolerance {
238            report.avg_px_open = Some(lot.avg_px);
239            report.avg_px_open_precision = None;
240        } else {
241            tracing::debug!(
242                "Keeping IB average cost {venue_avg_px} for {instrument_id}: fills give entry \
243                 {} with average cost {venue_avg_px_expected}",
244                lot.avg_px,
245            );
246        }
247    }
248}
249
250fn signed_fill_qty(fill: &FillReport) -> Decimal {
251    let last_qty = fill.last_qty.as_decimal();
252
253    match fill.order_side {
254        OrderSide::Buy => last_qty,
255        OrderSide::Sell => -last_qty,
256    }
257}
258
259// The open lot left by the replay: its netting average price, the commissions IB includes in
260// its average cost, and how many fill commissions that sum carries, both scaled down as the lot
261// is reduced
262struct EntryLot {
263    avg_px: Decimal,
264    commission: Decimal,
265    commissions: Decimal,
266}
267
268// Replays the window fills with netting semantics from `pre_window_qty` and returns the lot
269// left at the end, when that lot was opened within the window. Fills on the open side average
270// in, reducing fills keep the entry price, and a flip opens at the flipping fill's price; a lot
271// that predates the window is unknown until the replay passes through flat. IB leaves the
272// commission of a flipping fill out of the new lot's average cost, so that lot starts with none. Fills sharing a timestamp have no known order, so a
273// group of them that mixes sides or flips the position leaves the lot unknown until a later
274// fill opens from flat or flips.
275fn entry_after_window(pre_window_qty: Decimal, fills: &[&FillReport]) -> Option<EntryLot> {
276    let mut quantity = pre_window_qty;
277    let mut lot: Option<EntryLot> = None;
278
279    for group in fills.chunk_by(|a, b| a.ts_event == b.ts_event) {
280        if group.len() > 1 {
281            let group_qty: Decimal = group.iter().map(|fill| signed_fill_qty(fill)).sum();
282            let end_qty = quantity + group_qty;
283            let mixes_sides = group
284                .iter()
285                .any(|fill| fill.order_side != group[0].order_side);
286            let flips = !quantity.is_zero()
287                && !end_qty.is_zero()
288                && quantity.is_sign_negative() != end_qty.is_sign_negative();
289
290            if mixes_sides || flips {
291                quantity = end_qty;
292                lot = None;
293                continue;
294            }
295        }
296
297        for fill in group {
298            let last_qty = fill.last_qty.as_decimal();
299            let last_px = fill.last_px.as_decimal();
300            let commission = fill.commission.as_decimal();
301            let signed_qty = signed_fill_qty(fill);
302            let open_qty = quantity.abs();
303
304            if quantity.is_zero() {
305                lot = Some(EntryLot {
306                    avg_px: last_px,
307                    commission,
308                    commissions: Decimal::ONE,
309                });
310            } else if quantity.is_sign_negative() == signed_qty.is_sign_negative() {
311                lot = lot.map(|lot| EntryLot {
312                    avg_px: (lot.avg_px * open_qty + last_px * last_qty) / (open_qty + last_qty),
313                    commission: lot.commission + commission,
314                    commissions: lot.commissions + Decimal::ONE,
315                });
316            } else if last_qty > open_qty {
317                lot = Some(EntryLot {
318                    avg_px: last_px,
319                    commission: Decimal::ZERO,
320                    commissions: Decimal::ZERO,
321                });
322            } else if last_qty < open_qty {
323                let retained = (open_qty - last_qty) / open_qty;
324                lot = lot.map(|lot| EntryLot {
325                    avg_px: lot.avg_px,
326                    commission: lot.commission * retained,
327                    commissions: lot.commissions * retained,
328                });
329            }
330
331            quantity += signed_qty;
332        }
333    }
334
335    if quantity.is_zero() {
336        return None;
337    }
338
339    lot
340}
341
342/// Returns whether an execution is the combo-level (BAG) execution of a spread order.
343///
344/// IB sends commission reports only for the leg executions of a combo; the combo-level
345/// execution carries none, so its fill has zero commission.
346pub(crate) fn is_combo_execution(exec_data: &ibapi::orders::ExecutionData) -> bool {
347    matches!(
348        exec_data.contract.security_type,
349        ibapi::contracts::SecurityType::Spread
350    )
351}
352
353pub(crate) fn link_order_contingencies(
354    reports: &mut [OrderStatusReport],
355    orders: &[ibapi::orders::Order],
356) {
357    debug_assert_eq!(reports.len(), orders.len());
358
359    let order_ids: Vec<ClientOrderId> = reports
360        .iter()
361        .map(|report| {
362            report
363                .client_order_id
364                .unwrap_or_else(|| ClientOrderId::from(report.venue_order_id.as_str()))
365        })
366        .collect();
367
368    let mut oca_groups: AHashMap<(&str, &str), Vec<usize>> = AHashMap::new();
369
370    for (index, order) in orders.iter().enumerate() {
371        if !order.oca_group.is_empty() {
372            oca_groups
373                .entry((order.account.as_str(), order.oca_group.as_str()))
374                .or_default()
375                .push(index);
376        }
377    }
378
379    let mut children: AHashMap<usize, Vec<usize>> = AHashMap::new();
380
381    for (index, order) in orders.iter().enumerate() {
382        let parent = orders.iter().position(|candidate| {
383            order
384                .parent_perm_id
385                .is_some_and(|perm_id| perm_id != 0 && candidate.perm_id == perm_id)
386                || (order.parent_id != 0
387                    && candidate.order_id == order.parent_id
388                    && candidate.client_id == order.client_id)
389        });
390
391        if let Some(parent) = parent.filter(|parent| *parent != index) {
392            reports[index].parent_order_id = Some(order_ids[parent]);
393            children.entry(parent).or_default().push(index);
394        }
395    }
396
397    for (index, order) in orders.iter().enumerate() {
398        if let Some(members) = oca_groups.get(&(order.account.as_str(), order.oca_group.as_str())) {
399            let contingency_type = match order.oca_type {
400                ibapi::orders::OcaType::CancelWithBlock => Some(ContingencyType::Oco),
401                ibapi::orders::OcaType::ReduceWithBlock
402                | ibapi::orders::OcaType::ReduceWithoutBlock => Some(ContingencyType::Ouo),
403                _ => None,
404            };
405
406            let linked: Vec<ClientOrderId> = members
407                .iter()
408                .filter(|member| **member != index)
409                .map(|member| order_ids[*member])
410                .collect();
411
412            if let Some(contingency_type) = contingency_type
413                && !linked.is_empty()
414            {
415                reports[index].contingency_type = Some(contingency_type);
416                reports[index].linked_order_ids = Some(linked);
417                continue;
418            }
419        }
420
421        if let Some(child_indices) = children.get(&index) {
422            reports[index].contingency_type = Some(ContingencyType::Oto);
423            reports[index].linked_order_ids = Some(
424                child_indices
425                    .iter()
426                    .map(|child| order_ids[*child])
427                    .collect(),
428            );
429        }
430    }
431}
432
433pub(crate) fn should_use_avg_fill_price(avg_fill_price: f64, instrument_id: &InstrumentId) -> bool {
434    avg_fill_price.is_finite()
435        && avg_fill_price != f64::MAX
436        && avg_fill_price != 0.0
437        && (avg_fill_price > 0.0 || is_spread_instrument_id(instrument_id))
438}
439
440pub(crate) fn ib_venue_order_id(order_id: i32, perm_id: i64) -> VenueOrderId {
441    if perm_id != 0 {
442        VenueOrderId::new(format!("PERM-{perm_id}"))
443    } else {
444        VenueOrderId::new(order_id.to_string())
445    }
446}
447
448pub(crate) fn normalized_order_ref(order_ref: &str) -> Option<&str> {
449    if order_ref.is_empty() {
450        return None;
451    }
452
453    Some(
454        order_ref
455            .rsplit_once(':')
456            .map_or(order_ref, |(base, _)| base),
457    )
458}
459
460/// Parse an IB execution to a Nautilus FillReport.
461///
462/// # Errors
463///
464/// Returns an error if parsing fails.
465///
466/// # Note
467///
468/// The `avg_px` parameter is stored from order status updates and is available for
469/// future use when FillReport supports additional metadata fields.
470#[allow(clippy::too_many_arguments)]
471pub fn parse_execution_to_fill_report(
472    execution: &Execution,
473    _contract: &ibapi::contracts::Contract,
474    commission: f64,
475    commission_currency: &str,
476    instrument_id: InstrumentId,
477    account_id: AccountId,
478    instrument_provider: &InteractiveBrokersInstrumentProvider,
479    ts_init: UnixNanos,
480    avg_px: Option<Price>,
481) -> anyhow::Result<FillReport> {
482    // Get price magnifier from instrument provider
483    let price_magnifier = instrument_provider.get_price_magnifier(&instrument_id);
484
485    // Convert execution price
486    let execution_price = from_ib_price(execution.price, price_magnifier);
487
488    // Determine order side
489    let order_side = IbAction::from_str(execution.side.as_str())?.order_side();
490
491    // Get instrument for precision
492    let instrument = instrument_provider
493        .find(&instrument_id)
494        .context("Instrument not found")?;
495
496    // Create quantities and prices
497    let last_qty = Quantity::new(execution.shares, instrument.size_precision());
498    let last_px = Price::new(execution_price, instrument.price_precision());
499
500    // Clamp only IB's -1 pending sentinel to 0.0 to preserve rebates
501    let commission_clamped = if commission == -1.0 { 0.0 } else { commission };
502    let commission_money = Money::new(commission_clamped, Currency::from_str(commission_currency)?);
503
504    // Parse execution time
505    let ts_event = parse_execution_time(&execution.time)?;
506
507    // Create trade ID
508    let trade_id = TradeId::new(&execution.execution_id);
509
510    let venue_order_id = ib_venue_order_id(execution.order_id, execution.perm_id);
511
512    let client_order_id = normalized_order_ref(&execution.order_reference).map(ClientOrderId::new);
513    let liquidity_side = execution_liquidity_side(&execution.last_liquidity);
514
515    let mut report = FillReport::new(
516        account_id,
517        instrument_id,
518        venue_order_id,
519        trade_id,
520        order_side,
521        last_qty,
522        last_px,
523        commission_money,
524        liquidity_side,
525        client_order_id,
526        None, // venue_position_id
527        ts_event,
528        ts_init,
529        Some(nautilus_core::UUID4::new()),
530    );
531    report.avg_px = avg_px.map(|price: Price| price.as_decimal());
532
533    Ok(report)
534}
535
536fn execution_liquidity_side(liquidity: &Liquidity) -> LiquiditySide {
537    match liquidity {
538        Liquidity::AddedLiquidity => LiquiditySide::Maker,
539        Liquidity::RemovedLiquidity => LiquiditySide::Taker,
540        Liquidity::None => LiquiditySide::NoLiquiditySide,
541        Liquidity::LiquidityRoutedOut => {
542            tracing::warn!(
543                "IB execution liquidity was routed out and has no maker/taker representation"
544            );
545            LiquiditySide::NoLiquiditySide
546        }
547        Liquidity::Unknown(code) => {
548            tracing::warn!("IB execution used unknown liquidity code {code}");
549            LiquiditySide::NoLiquiditySide
550        }
551    }
552}
553
554/// Parse an IB order status to a Nautilus OrderStatusReport.
555///
556/// # Errors
557///
558/// Returns an error if parsing fails.
559pub fn parse_order_status_to_report(
560    order_status: &OrderStatus,
561    order: Option<&ibapi::orders::Order>,
562    instrument_id: InstrumentId,
563    account_id: AccountId,
564    instrument_provider: &InteractiveBrokersInstrumentProvider,
565    ts_init: UnixNanos,
566) -> anyhow::Result<OrderStatusReport> {
567    // Get price magnifier from instrument provider
568    let price_magnifier = instrument_provider.get_price_magnifier(&instrument_id);
569
570    let mut nautilus_status = match IbOrderStatus::from_str(order_status.status.as_str()) {
571        Ok(status) => status.nautilus_status(),
572        _ => {
573            tracing::warn!(
574                "Unknown order status: {}, defaulting to SUBMITTED",
575                order_status.status.as_str()
576            );
577            NautilusOrderStatus::Submitted
578        }
579    };
580
581    // Get order side
582    let order_side = if let Some(order) = order {
583        IbAction::from(order.action).order_side()
584    } else {
585        // Default to Buy if order not available
586        OrderSide::Buy
587    };
588
589    let instrument = instrument_provider.find(&instrument_id);
590
591    // Get instrument for precision (use 0 as default if not available)
592    let size_precision = instrument
593        .as_ref()
594        .map_or(0, |instr| instr.size_precision());
595    let price_precision = instrument
596        .as_ref()
597        .map_or(0, |instr| instr.price_precision());
598
599    // Get quantity
600    let total_quantity = order.map_or(0.0, |order| order.total_quantity);
601
602    let quantity = Quantity::new(
603        total_quantity.max(order_status.filled + order_status.remaining),
604        size_precision,
605    );
606
607    // Get filled quantity
608    let filled_qty = Quantity::new(order_status.filled, size_precision);
609
610    // Get average price
611    let average_fill_price = order_status.average_fill_price.unwrap_or(0.0);
612    let include_avg_px = should_use_avg_fill_price(average_fill_price, &instrument_id);
613    let avg_px = if include_avg_px {
614        let avg_px = decimal_from_f64(average_fill_price)?
615            .checked_div(Decimal::from(price_magnifier.max(1)))
616            .context("IB average fill price out of range")?;
617        Some(avg_px)
618    } else {
619        None
620    };
621
622    if nautilus_status != NautilusOrderStatus::Canceled
623        && order_status.filled > 0.0
624        && (order_status.remaining > 0.0
625            || order.is_some_and(|order| order.total_quantity > order_status.filled))
626    {
627        nautilus_status = NautilusOrderStatus::PartiallyFilled;
628    }
629
630    let venue_order_id = ib_venue_order_id(order_status.order_id, order_status.perm_id);
631
632    let client_order_id = order
633        .and_then(|order| normalized_order_ref(&order.order_ref))
634        .map(ClientOrderId::new);
635
636    // Map order type from IB order if available
637    let order_type = order.map_or(OrderType::Market, |order| {
638        map_ib_order_type(&order.order_type, order.limit_price)
639    });
640
641    // A GTD order needs its expiry to be rebuilt from the report; IB still enforces the date,
642    // so an unparsable one degrades to GTC rather than failing the whole report set
643    let expire_time = order
644        .filter(|order| !order.good_till_date.is_empty())
645        .and_then(|order| match parse_execution_time(&order.good_till_date) {
646            Ok(expire_time) => Some(expire_time),
647            Err(e) => {
648                tracing::warn!(
649                    "Reporting IB order {} as GTC: cannot parse goodTillDate: {e}",
650                    order_status.order_id
651                );
652                None
653            }
654        });
655
656    // Map time in force from IB order if available
657    let time_in_force = if let Some(order) = order {
658        let ib_time_in_force = IbTimeInForce::from(order.tif.clone());
659
660        if expire_time.is_some() {
661            TimeInForce::Gtd
662        } else if ib_time_in_force == IbTimeInForce::GoodTilDate {
663            TimeInForce::Gtc
664        } else {
665            ib_time_in_force.nautilus_time_in_force()
666        }
667    } else {
668        TimeInForce::Day // Default when order not available
669    };
670
671    // Parse limit price if available
672    let mut report = OrderStatusReport::new(
673        account_id,
674        instrument_id,
675        client_order_id,
676        venue_order_id,
677        order_side.into(),
678        order_type,
679        time_in_force,
680        nautilus_status,
681        quantity,
682        filled_qty,
683        ts_init, // ts_accepted
684        ts_init, // ts_last
685        ts_init,
686        Some(nautilus_core::UUID4::new()), // report_id
687    );
688
689    if let Some(expire_time) = expire_time {
690        report = report.with_expire_time(expire_time);
691    }
692
693    // Set optional fields
694    if let Some(order) = order {
695        // IB reports a zero limit price on market-type orders, which reconciliation would
696        // otherwise take as the fill price of an order it has no fills for
697        if let Some(limit_price) = order.limit_price
698            && matches!(
699                order_type,
700                OrderType::Limit
701                    | OrderType::StopLimit
702                    | OrderType::LimitIfTouched
703                    | OrderType::TrailingStopLimit
704                    | OrderType::MarketToLimit
705            )
706        {
707            let converted = from_ib_price(limit_price, price_magnifier);
708            report = report.with_price(Price::new(converted, price_precision));
709        }
710
711        let (trigger_price, limit_offset, trailing_offset, trailing_offset_type) =
712            parse_ib_order_pricing_fields(order, order_type, price_magnifier, price_precision)?;
713
714        if let Some(trigger_price) = trigger_price {
715            report = report.with_trigger_price(trigger_price);
716        }
717
718        if matches!(
719            order_type,
720            OrderType::LimitIfTouched
721                | OrderType::MarketIfTouched
722                | OrderType::StopLimit
723                | OrderType::StopMarket
724                | OrderType::TrailingStopLimit
725                | OrderType::TrailingStopMarket
726        ) {
727            report =
728                report.with_trigger_type(ib_trigger_method_to_trigger_type(order.trigger_method));
729        }
730
731        if let Some(limit_offset) = limit_offset {
732            report = report.with_limit_offset(limit_offset);
733        }
734
735        if let Some(trailing_offset) = trailing_offset {
736            report = report.with_trailing_offset(trailing_offset);
737        }
738
739        if let Some(trailing_offset_type) = trailing_offset_type {
740            report = report.with_trailing_offset_type(trailing_offset_type);
741        }
742    }
743
744    if let Some(avg_px) = avg_px {
745        report = report.with_avg_px(avg_px);
746    }
747
748    if let Some(display_size) = order
749        .and_then(|order| order.display_size)
750        .filter(|size| *size > 0 && f64::from(*size) < quantity.as_f64())
751    {
752        report = report.with_display_qty(Quantity::new(f64::from(display_size), size_precision));
753    }
754
755    Ok(report)
756}
757
758fn map_ib_order_type(order_type: &str, limit_price: Option<f64>) -> OrderType {
759    if order_type == "IBALGO" && limit_price.is_some_and(|price| price != 0.0) {
760        OrderType::Limit
761    } else {
762        IbOrderType::from_str(order_type)
763            .map_or(OrderType::Market, IbOrderType::nautilus_order_type)
764    }
765}
766
767#[allow(clippy::type_complexity)] // The tuple mirrors the four optional IB pricing fields.
768fn parse_ib_order_pricing_fields(
769    order: &ibapi::orders::Order,
770    order_type: OrderType,
771    price_magnifier: i32,
772    price_precision: u8,
773) -> anyhow::Result<(
774    Option<Price>,
775    Option<Decimal>,
776    Option<Decimal>,
777    Option<TrailingOffsetType>,
778)> {
779    let mut trigger_price = None;
780    let mut limit_offset = None;
781    let mut trailing_offset = None;
782    let mut trailing_offset_type = None;
783
784    if matches!(
785        order_type,
786        OrderType::TrailingStopMarket | OrderType::TrailingStopLimit
787    ) {
788        if let Some(trail_stop_price) = order.trail_stop_price {
789            trigger_price = Some(Price::new(
790                from_ib_price(trail_stop_price, price_magnifier),
791                price_precision,
792            ));
793        }
794
795        if let Some(aux_price) = order.aux_price {
796            trailing_offset = Some(decimal_from_f64(aux_price)? / Decimal::from(price_magnifier));
797            trailing_offset_type = Some(TrailingOffsetType::Price);
798        } else if let Some(trailing_percent) = order.trailing_percent {
799            trailing_offset = Some(decimal_from_f64(trailing_percent)? * Decimal::from(100));
800            trailing_offset_type = Some(TrailingOffsetType::BasisPoints);
801        }
802
803        if order_type == OrderType::TrailingStopLimit
804            && let Some(limit_price_offset) = order.limit_price_offset
805        {
806            limit_offset =
807                Some(decimal_from_f64(limit_price_offset)? / Decimal::from(price_magnifier));
808            trailing_offset_type = Some(trailing_offset_type.unwrap_or(TrailingOffsetType::Price));
809        }
810
811        return Ok((
812            trigger_price,
813            limit_offset,
814            trailing_offset,
815            trailing_offset_type,
816        ));
817    }
818
819    if let Some(aux_price) = order.aux_price {
820        trigger_price = Some(Price::new(
821            from_ib_price(aux_price, price_magnifier),
822            price_precision,
823        ));
824    }
825
826    Ok((
827        trigger_price,
828        limit_offset,
829        trailing_offset,
830        trailing_offset_type,
831    ))
832}
833
834fn decimal_from_f64(value: f64) -> anyhow::Result<Decimal> {
835    Decimal::from_str(&value.to_string())
836        .with_context(|| format!("Failed to convert IB floating-point value {value} to Decimal"))
837}
838
839/// Parse execution time string to UnixNanos.
840///
841/// Parse IB execution time to UnixNanos.
842///
843/// Supported IB formats:
844/// - "20230223 00:43:36 Universal"
845/// - "20230223 00:43:36 UTC"
846/// - "20230223 00:43:36 MET"
847/// - "20230223 00:43:36 America/New_York"
848/// - "20230223 00:43:36" (assumed UTC)
849/// - "20250225-15:15:00" (assumed UTC)
850///
851/// Timezones are resolved through Jiff's bundled IANA tz database, so any
852/// region abbreviation or name that IB stamps the execution with (e.g. `MET`,
853/// `EST`, `America/New_York`) is honored, matching the v1 pandas-based parser.
854/// This matters because some IB accounts (e.g. European paper accounts) report a
855/// server timezone such as `MET` that the gateway cannot be coerced out of.
856///
857/// # Errors
858///
859/// Returns an error if the timestamp is malformed, the timezone is
860/// unrecognized, or the local time is non-existent (a DST spring-forward gap).
861/// DST fall-back folds resolve to the earliest matching instant.
862pub fn parse_execution_time(time_str: &str) -> anyhow::Result<UnixNanos> {
863    const NAIVE_FORMAT: &str = "%Y%m%d %H:%M:%S";
864
865    // Hyphenated, space-less form (e.g. "20250225-15:15:00") is always UTC.
866    if !time_str.contains(' ') {
867        let normalized = time_str.replace('-', " ");
868
869        let dt = DateTime::strptime(NAIVE_FORMAT, &normalized).map_err(|e| {
870            anyhow::anyhow!("Failed to parse execution timestamp '{time_str}': {e}")
871        })?;
872
873        return datetime_to_unix_nanos(Offset::UTC.to_timestamp(dt)?, time_str);
874    }
875
876    // Split into at most three parts: date, time, and optional timezone token.
877    // The timezone token itself never contains a space, so `splitn(3, ' ')`
878    // correctly groups IANA names such as "America/New_York".
879    let mut parts = time_str.splitn(3, ' ');
880
881    let (Some(date), Some(time)) = (parts.next(), parts.next()) else {
882        anyhow::bail!("Invalid execution time format: {time_str}");
883    };
884
885    let tz_str = parts.next().unwrap_or("").trim();
886
887    let naive_str = format!("{date} {time}");
888    let dt = DateTime::strptime(NAIVE_FORMAT, &naive_str)
889        .map_err(|e| anyhow::anyhow!("Failed to parse execution timestamp '{time_str}': {e}"))?;
890
891    let utc = if tz_str.is_empty() {
892        Offset::UTC.to_timestamp(dt)?
893    } else {
894        localize_with_zone(dt, tz_str, time_str)?
895    };
896
897    datetime_to_unix_nanos(utc, time_str)
898}
899
900/// Localize a naive timestamp against an IB timezone token and convert to UTC.
901///
902/// `Z` is normalized to `UTC`; everything else is resolved through the IANA tz
903/// database. Error and fold behavior is documented on [`parse_execution_time`].
904fn localize_with_zone(dt: DateTime, tz_str: &str, time_str: &str) -> anyhow::Result<Timestamp> {
905    let tz_name = if tz_str.eq_ignore_ascii_case("Z") {
906        "UTC"
907    } else {
908        tz_str
909    };
910
911    let zone = get_timezone(tz_name).map_err(|_| {
912        anyhow::anyhow!(
913            "Unrecognized execution timezone '{tz_str}' in '{time_str}'. Configure TWS / IB Gateway to emit a standard timezone (e.g. UTC)"
914        )
915    })?;
916
917    let ambiguous = zone.to_ambiguous_timestamp(dt);
918    match ambiguous.offset() {
919        AmbiguousOffset::Unambiguous { .. } => Ok(ambiguous.unambiguous()?),
920        // Fall-back fold: take the earliest instant (worst case ~1h skew).
921        AmbiguousOffset::Fold { .. } => Ok(ambiguous.earlier()?),
922        AmbiguousOffset::Gap { .. } => {
923            anyhow::bail!("Execution timestamp '{time_str}' is non-existent in timezone '{tz_str}'")
924        }
925    }
926}
927
928fn datetime_to_unix_nanos(dt: Timestamp, time_str: &str) -> anyhow::Result<UnixNanos> {
929    let nanos: u64 = dt
930        .as_nanosecond()
931        .try_into()
932        .map_err(|_| anyhow::anyhow!("Execution timestamp '{time_str}' was before Unix epoch"))?;
933    Ok(UnixNanos::new(nanos))
934}
935
936#[cfg(test)]
937mod tests {
938    use ibapi::{
939        contracts::Contract,
940        orders::{Action, ExecutionSide, Liquidity, Order, OrderStatusKind},
941    };
942    #[cfg(feature = "execution")]
943    use nautilus_execution::reconciliation::{
944        generate_external_order_status_events, generate_reconciliation_order_events,
945    };
946    use nautilus_model::{
947        enums::{AssetClass, PositionSide, TrailingOffsetType, TriggerType},
948        identifiers::{Symbol, Venue},
949        instruments::{
950            CurrencyPair, FuturesContract, InstrumentAny,
951            stubs::{equity_aapl, equity_aapl_itch},
952        },
953    };
954    #[cfg(feature = "execution")]
955    use nautilus_model::{
956        events::OrderEventAny,
957        orders::{Order as NautilusOrder, OrderTestBuilder},
958    };
959    use rust_decimal::Decimal;
960    use ustr::Ustr;
961
962    use super::*;
963    use crate::{
964        config::InteractiveBrokersInstrumentProviderConfig, execution::reports::IbReportContext,
965        providers::instruments::InteractiveBrokersInstrumentProvider,
966    };
967
968    fn create_test_instrument_provider() -> InteractiveBrokersInstrumentProvider {
969        let config = InteractiveBrokersInstrumentProviderConfig::default();
970        InteractiveBrokersInstrumentProvider::new(config).unwrap()
971    }
972
973    fn create_test_instrument_id() -> InstrumentId {
974        InstrumentId::new(Symbol::from("AAPL"), Venue::from("NASDAQ"))
975    }
976
977    use rstest::rstest;
978
979    fn create_test_avg_px_provider() -> InteractiveBrokersInstrumentProvider {
980        let provider = InteractiveBrokersInstrumentProvider::new(
981            crate::config::InteractiveBrokersInstrumentProviderConfig::default(),
982        )
983        .unwrap();
984        provider.insert_test_instrument(InstrumentAny::Equity(equity_aapl()), 265_598, 1);
985        provider
986    }
987
988    // A fill with a 1.00 commission, so IB's average cost differs from the entry price and a
989    // test tells an accepted entry price from a kept average cost
990    fn create_test_entry_fill(
991        side: OrderSide,
992        qty: &str,
993        px: &str,
994        trade_id: &str,
995        ts_event: u64,
996    ) -> FillReport {
997        FillReport::new(
998            AccountId::from("IB-DU001"),
999            equity_aapl().id,
1000            VenueOrderId::new(format!("PERM-{trade_id}")),
1001            TradeId::new(trade_id),
1002            side,
1003            Quantity::from(qty),
1004            Price::from(px),
1005            Money::from("1.00 USD"),
1006            LiquiditySide::Taker,
1007            None,
1008            None,
1009            UnixNanos::from(ts_event),
1010            UnixNanos::default(),
1011            None,
1012        )
1013    }
1014
1015    fn create_test_entry_position_report(
1016        side: PositionSide,
1017        qty: &str,
1018        venue_avg_px: &str,
1019    ) -> PositionStatusReport {
1020        PositionStatusReport::new(
1021            AccountId::from("IB-DU001"),
1022            equity_aapl().id,
1023            side,
1024            Quantity::from(qty),
1025            UnixNanos::default(),
1026            UnixNanos::default(),
1027            None,
1028            None,
1029            Some(Decimal::from_str(venue_avg_px).unwrap()),
1030        )
1031        // As `generate_position_status_reports` builds it: rounded to the price precision
1032        .with_avg_px_open_precision(equity_aapl().price_precision())
1033    }
1034
1035    fn rebuild_avg_px_open(
1036        position_report: PositionStatusReport,
1037        evidence: &FillEvidence,
1038    ) -> Option<Decimal> {
1039        let mut position_reports = vec![position_report];
1040        fill_position_avg_px_from_fills(
1041            &mut position_reports,
1042            evidence,
1043            &create_test_avg_px_provider(),
1044        );
1045        position_reports[0].avg_px_open
1046    }
1047
1048    #[rstest]
1049    // IB's average cost is the entry price plus the opening commissions per unit for a long,
1050    // minus them for a short, rounded to the price precision
1051    #[case::fills_open_position(
1052        PositionSide::Long,
1053        vec![(OrderSide::Buy, "7", "229.67")],
1054        "229.81",
1055        "229.67"
1056    )]
1057    #[case::fills_average_in(
1058        PositionSide::Long,
1059        vec![(OrderSide::Buy, "5", "229.00"), (OrderSide::Buy, "2", "232.50")],
1060        "230.29",
1061        "230.00"
1062    )]
1063    #[case::reduce_keeps_entry(
1064        PositionSide::Long,
1065        vec![(OrderSide::Buy, "4", "229.00"), (OrderSide::Buy, "4", "231.00"), (OrderSide::Sell, "1", "235.00")],
1066        "230.25",
1067        "230.00"
1068    )]
1069    #[case::flip_carries_no_commission(
1070        PositionSide::Short,
1071        vec![(OrderSide::Buy, "2", "230.00"), (OrderSide::Sell, "8", "228.00"), (OrderSide::Sell, "1", "221.00")],
1072        "226.86",
1073        "227.00"
1074    )]
1075    #[case::fills_partial_history(
1076        PositionSide::Long,
1077        vec![(OrderSide::Buy, "2", "230.00")],
1078        "229.81",
1079        "229.81"
1080    )]
1081    #[case::remnant_closed_then_reopened(
1082        PositionSide::Long,
1083        vec![(OrderSide::Sell, "7", "229.00"), (OrderSide::Buy, "7", "231.00")],
1084        "231.14",
1085        "231.00"
1086    )]
1087    #[case::remnant_flipped_in_window(
1088        PositionSide::Short,
1089        vec![(OrderSide::Sell, "7", "228.00"), (OrderSide::Sell, "1", "221.00")],
1090        "226.86",
1091        "227.00"
1092    )]
1093    #[case::remnant_reduced_in_window(
1094        PositionSide::Long,
1095        vec![(OrderSide::Sell, "2", "235.00")],
1096        "229.81",
1097        "229.81"
1098    )]
1099    #[case::no_fills(PositionSide::Long, vec![], "229.81", "229.81")]
1100    // A missing execution that IB never returned leaves no parse gap, but the fills then
1101    // disagree with IB's average cost
1102    #[case::average_cost_disagrees(
1103        PositionSide::Long,
1104        vec![(OrderSide::Buy, "7", "229.67")],
1105        "230.50",
1106        "230.50"
1107    )]
1108    fn test_fill_position_avg_px_from_fills(
1109        #[case] position_side: PositionSide,
1110        #[case] fills: Vec<(OrderSide, &str, &str)>,
1111        #[case] venue_avg_px: &str,
1112        #[case] expected: &str,
1113    ) {
1114        let other_fill = FillReport::new(
1115            AccountId::from("IB-DU001"),
1116            InstrumentId::from("MSFT.NASDAQ"),
1117            VenueOrderId::new("PERM-9"),
1118            TradeId::new("T-OTHER"),
1119            OrderSide::Sell,
1120            Quantity::from(7),
1121            Price::from("150.00"),
1122            Money::from("1.00 USD"),
1123            LiquiditySide::Taker,
1124            None,
1125            None,
1126            UnixNanos::from(1),
1127            UnixNanos::default(),
1128            None,
1129        );
1130        let mut reports: Vec<_> = fills
1131            .into_iter()
1132            .enumerate()
1133            .rev()
1134            .map(|(index, (side, qty, px))| {
1135                create_test_entry_fill(side, qty, px, &format!("T-{index}"), index as u64 + 10)
1136            })
1137            .collect();
1138        reports.push(other_fill);
1139        let evidence = FillEvidence {
1140            reports,
1141            ..Default::default()
1142        };
1143
1144        let avg_px_open = rebuild_avg_px_open(
1145            create_test_entry_position_report(position_side, "7", venue_avg_px),
1146            &evidence,
1147        );
1148
1149        assert_eq!(avg_px_open, Some(Decimal::from_str(expected).unwrap()));
1150    }
1151
1152    // A ZC-like contract: IB prices it in cents (magnifier 100) and its multiplier is 5000
1153    #[rstest]
1154    fn test_fill_position_avg_px_from_fills_for_magnified_contract() {
1155        let instrument = InstrumentAny::from(
1156            FuturesContract::builder()
1157                .instrument_id(InstrumentId::from("ZCZ6.CBOT"))
1158                .raw_symbol(Symbol::from("ZCZ6"))
1159                .asset_class(AssetClass::Commodity)
1160                .exchange(Ustr::from("CBOT"))
1161                .underlying(Ustr::from("ZC"))
1162                .activation_ns(UnixNanos::default())
1163                .expiration_ns(UnixNanos::from(1_800_000_000_000_000_000_u64))
1164                .currency(Currency::USD())
1165                .price_precision(4)
1166                .price_increment(Price::from("0.0025"))
1167                .multiplier(Quantity::from(5000))
1168                .lot_size(Quantity::from(1))
1169                .ts_event(UnixNanos::default())
1170                .ts_init(UnixNanos::default())
1171                .build()
1172                .unwrap(),
1173        );
1174        let instrument_id = instrument.id();
1175        let provider = create_test_instrument_provider();
1176        provider.insert_test_instrument(instrument.clone(), 265_598, 100);
1177
1178        // IB's average cost is the price in the contract's currency times the multiplier, so the
1179        // multiplier alone converts it, and the magnifier does not
1180        let avg_px_open = IbReportContext::position_avg_px_open(&instrument, 24_340.51);
1181        assert_eq!(avg_px_open, Some(Decimal::from_str("4.8681").unwrap()));
1182
1183        let fill = FillReport::new(
1184            AccountId::from("IB-DU001"),
1185            instrument_id,
1186            VenueOrderId::new("PERM-1"),
1187            TradeId::new("T-1"),
1188            OrderSide::Buy,
1189            Quantity::from(1),
1190            Price::from("4.8675"),
1191            Money::from("3.01 USD"),
1192            LiquiditySide::Taker,
1193            None,
1194            None,
1195            UnixNanos::from(10),
1196            UnixNanos::default(),
1197            None,
1198        );
1199        let mut position_reports = vec![PositionStatusReport::new(
1200            AccountId::from("IB-DU001"),
1201            instrument_id,
1202            PositionSide::Long,
1203            Quantity::from(1),
1204            UnixNanos::default(),
1205            UnixNanos::default(),
1206            None,
1207            None,
1208            avg_px_open,
1209        )];
1210
1211        let evidence = FillEvidence {
1212            reports: vec![fill],
1213            ..Default::default()
1214        };
1215
1216        fill_position_avg_px_from_fills(&mut position_reports, &evidence, &provider);
1217
1218        // The fill price plus 3.01 / 5000 = 0.000602 reproduces IB's 4.868102, within the rounding
1219        // of the average cost, so the entry price replaces it
1220        assert_eq!(
1221            position_reports[0].avg_px_open,
1222            Some(Decimal::from_str("4.8675").unwrap())
1223        );
1224    }
1225
1226    #[rstest]
1227    // The fills reproduce IB's average cost: their entry price replaces it, unrounded
1228    #[case::replaced(vec![(OrderSide::Buy, "7", "229.67")], "229.81", None)]
1229    // IB's rounded average cost is kept, and so is its one-tick precision
1230    #[case::kept_without_fills(vec![], "229.81", Some(2))]
1231    #[case::kept_when_fills_disagree(vec![(OrderSide::Buy, "7", "229.67")], "230.50", Some(2))]
1232    fn test_fill_position_avg_px_from_fills_sets_the_average_precision(
1233        #[case] fills: Vec<(OrderSide, &str, &str)>,
1234        #[case] venue_avg_px: &str,
1235        #[case] expected: Option<u8>,
1236    ) {
1237        let evidence = FillEvidence {
1238            reports: fills
1239                .into_iter()
1240                .enumerate()
1241                .map(|(index, (side, qty, px))| {
1242                    create_test_entry_fill(side, qty, px, &format!("T-{index}"), index as u64 + 10)
1243                })
1244                .collect(),
1245            ..Default::default()
1246        };
1247        let mut position_reports = vec![create_test_entry_position_report(
1248            PositionSide::Long,
1249            "7",
1250            venue_avg_px,
1251        )];
1252
1253        fill_position_avg_px_from_fills(
1254            &mut position_reports,
1255            &evidence,
1256            &create_test_avg_px_provider(),
1257        );
1258
1259        assert_eq!(position_reports[0].avg_px_open_precision, expected);
1260    }
1261
1262    #[rstest]
1263    fn test_fill_position_avg_px_from_fills_keeps_venue_average_for_other_commission_currency() {
1264        let mut fill = create_test_entry_fill(OrderSide::Buy, "7", "229.67", "T-1", 10);
1265        fill.commission = Money::from("1.00 EUR");
1266        let evidence = FillEvidence {
1267            reports: vec![fill],
1268            ..Default::default()
1269        };
1270
1271        let avg_px_open = rebuild_avg_px_open(
1272            create_test_entry_position_report(PositionSide::Long, "7", "229.81"),
1273            &evidence,
1274        );
1275
1276        assert_eq!(avg_px_open, Some(Decimal::from_str("229.81").unwrap()));
1277    }
1278
1279    #[rstest]
1280    // A small PAXOS crypto lot: IB's average cost includes the 0.20031 USD commission, while the
1281    // fill report carries it rounded to 0.20, which moves the expected average cost by 0.039,
1282    // several ticks, so only a tolerance sized to that rounding accepts the entry price
1283    #[case::commission_rounded_to_cents(
1284        vec![(OrderSide::Buy, "0.00795734", "2507.10")],
1285        "0.00795734",
1286        "2532.27",
1287        "2507.10"
1288    )]
1289    #[case::average_cost_disagrees(
1290        vec![(OrderSide::Buy, "0.00795734", "2507.10")],
1291        "0.00795734",
1292        "2540.00",
1293        "2540.00"
1294    )]
1295    // Closing 0.0099 of 0.01 ETH retains 1% of the opening commission, so the rounding allowance
1296    // shrinks with it to 0.51 per ETH instead of staying at 50.01, and an average cost 10 away
1297    // from the fills still keeps the venue average
1298    #[case::partial_close_agrees(
1299        vec![(OrderSide::Buy, "0.01", "2500.00"), (OrderSide::Sell, "0.0099", "2510.00")],
1300        "0.0001",
1301        "2520.00",
1302        "2500.00"
1303    )]
1304    #[case::partial_close_disagrees(
1305        vec![(OrderSide::Buy, "0.01", "2500.00"), (OrderSide::Sell, "0.0099", "2510.00")],
1306        "0.0001",
1307        "2530.00",
1308        "2530.00"
1309    )]
1310    fn test_fill_position_avg_px_from_fills_allows_commission_rounding(
1311        #[case] fills: Vec<(OrderSide, &str, &str)>,
1312        #[case] position_qty: &str,
1313        #[case] venue_avg_px: &str,
1314        #[case] expected: &str,
1315    ) {
1316        let instrument = CurrencyPair::builder()
1317            .instrument_id(InstrumentId::from("ETH/USD.PAXOS"))
1318            .raw_symbol(Symbol::from("ETH.USD"))
1319            .base_currency(Currency::from("ETH"))
1320            .quote_currency(Currency::USD())
1321            .price_precision(2)
1322            .size_precision(8)
1323            .price_increment(Price::from("0.01"))
1324            .size_increment(Quantity::from("0.00000001"))
1325            .ts_event(UnixNanos::default())
1326            .ts_init(UnixNanos::default())
1327            .build()
1328            .unwrap();
1329        let instrument_id = instrument.id;
1330        let provider = InteractiveBrokersInstrumentProvider::new(
1331            crate::config::InteractiveBrokersInstrumentProviderConfig::default(),
1332        )
1333        .unwrap();
1334        provider.insert_test_instrument(InstrumentAny::CurrencyPair(instrument), 495_759_171, 1);
1335        let reports = fills
1336            .into_iter()
1337            .enumerate()
1338            .map(|(index, (side, qty, px))| {
1339                FillReport::new(
1340                    AccountId::from("IB-DU001"),
1341                    instrument_id,
1342                    VenueOrderId::new(format!("PERM-{index}")),
1343                    TradeId::new(format!("T-{index}")),
1344                    side,
1345                    Quantity::from(qty),
1346                    Price::from(px),
1347                    Money::from("0.20 USD"),
1348                    LiquiditySide::Taker,
1349                    None,
1350                    None,
1351                    UnixNanos::from(index as u64 + 10),
1352                    UnixNanos::default(),
1353                    None,
1354                )
1355            })
1356            .collect();
1357        let evidence = FillEvidence {
1358            reports,
1359            ..Default::default()
1360        };
1361        let mut position_reports = vec![PositionStatusReport::new(
1362            AccountId::from("IB-DU001"),
1363            instrument_id,
1364            PositionSide::Long,
1365            Quantity::from(position_qty),
1366            UnixNanos::default(),
1367            UnixNanos::default(),
1368            None,
1369            None,
1370            Some(Decimal::from_str(venue_avg_px).unwrap()),
1371        )];
1372
1373        fill_position_avg_px_from_fills(&mut position_reports, &evidence, &provider);
1374
1375        assert_eq!(
1376            position_reports[0].avg_px_open,
1377            Some(Decimal::from_str(expected).unwrap())
1378        );
1379    }
1380
1381    #[rstest]
1382    // Long 1 before the window, then BUY 1 at 100 and a SELL 1 that failed to parse. Without
1383    // the SELL the replay infers a flat start and a lot opened at 100, which matches an average
1384    // cost of 101.00, so only the parse gap keeps the venue average
1385    #[case::instrument_missing(false, vec![equity_aapl().id], "101.00")]
1386    #[case::all_missing(true, vec![], "101.00")]
1387    #[case::other_instrument_missing(false, vec![InstrumentId::from("MSFT.NASDAQ")], "100.00")]
1388    fn test_fill_position_avg_px_from_fills_keeps_venue_average_for_missing_executions(
1389        #[case] missing_all: bool,
1390        #[case] missing_instruments: Vec<InstrumentId>,
1391        #[case] expected: &str,
1392    ) {
1393        let evidence = FillEvidence {
1394            reports: vec![create_test_entry_fill(
1395                OrderSide::Buy,
1396                "1",
1397                "100.00",
1398                "T-1",
1399                10,
1400            )],
1401            combo_leg_reports: Vec::new(),
1402            missing_all,
1403            missing_instruments: missing_instruments.into_iter().collect(),
1404        };
1405
1406        let avg_px_open = rebuild_avg_px_open(
1407            create_test_entry_position_report(PositionSide::Long, "1", "101.00"),
1408            &evidence,
1409        );
1410
1411        assert_eq!(avg_px_open, Some(Decimal::from_str(expected).unwrap()));
1412    }
1413
1414    #[rstest]
1415    // Fill reports arrive in commission order, so fills sharing a timestamp have no known
1416    // execution order. In each case one delivery order would reconstruct an entry price that
1417    // matches IB's average cost; with the tied group made ambiguous the venue average stands,
1418    // and a later fill from flat sets the entry again
1419    #[case::opposite_sides(
1420        PositionSide::Long,
1421        "2",
1422        vec![(OrderSide::Buy, "2", "110.00"), (OrderSide::Sell, "2", "120.00")],
1423        vec![(OrderSide::Buy, "1", "100.00")],
1424        "105.50",
1425        "105.50"
1426    )]
1427    #[case::same_side_flip(
1428        PositionSide::Long,
1429        "2",
1430        vec![(OrderSide::Buy, "1", "100.00"), (OrderSide::Buy, "2", "110.00")],
1431        vec![],
1432        "110.50",
1433        "110.50"
1434    )]
1435    #[case::same_side_from_flat(
1436        PositionSide::Long,
1437        "2",
1438        vec![(OrderSide::Buy, "1", "100.00"), (OrderSide::Buy, "1", "110.00")],
1439        vec![],
1440        "106.00",
1441        "105.00"
1442    )]
1443    #[case::reopened_after_ambiguous_group(
1444        PositionSide::Long,
1445        "1",
1446        vec![(OrderSide::Buy, "1", "100.00"), (OrderSide::Sell, "1", "105.00")],
1447        vec![(OrderSide::Buy, "1", "110.00")],
1448        "111.00",
1449        "110.00"
1450    )]
1451    fn test_fill_position_avg_px_from_fills_same_timestamp_fills_ignore_delivery_order(
1452        #[case] position_side: PositionSide,
1453        #[case] quantity: &str,
1454        #[case] tied: Vec<(OrderSide, &str, &str)>,
1455        #[case] later: Vec<(OrderSide, &str, &str)>,
1456        #[case] venue_avg_px: &str,
1457        #[case] expected: &str,
1458        #[values(false, true)] reversed: bool,
1459    ) {
1460        let mut reports: Vec<_> = tied
1461            .into_iter()
1462            .enumerate()
1463            .map(|(index, (side, qty, px))| {
1464                create_test_entry_fill(side, qty, px, &format!("T-{index}"), 10)
1465            })
1466            .collect();
1467
1468        if reversed {
1469            reports.reverse();
1470        }
1471
1472        reports.extend(
1473            later
1474                .into_iter()
1475                .enumerate()
1476                .map(|(index, (side, qty, px))| {
1477                    create_test_entry_fill(side, qty, px, &format!("L-{index}"), 20 + index as u64)
1478                }),
1479        );
1480        let evidence = FillEvidence {
1481            reports,
1482            ..Default::default()
1483        };
1484
1485        let avg_px_open = rebuild_avg_px_open(
1486            create_test_entry_position_report(position_side, quantity, venue_avg_px),
1487            &evidence,
1488        );
1489
1490        assert_eq!(avg_px_open, Some(Decimal::from_str(expected).unwrap()));
1491    }
1492
1493    #[rstest]
1494    #[case::with_combo_legs(true, "4.00")]
1495    #[case::without_combo_legs(false, "3.00")]
1496    fn test_fill_position_avg_px_from_fills_counts_combo_leg_fills(
1497        #[case] with_combo_legs: bool,
1498        #[case] expected: &str,
1499    ) {
1500        // Starting flat, SELL 2 at 5 and BUY 1 at 3 leave short 1, then a combo leg BUY 2 at 4
1501        // flips to long 1 at 4 with no commission in IB's average cost. Without the leg the
1502        // replay reads a pre-window long 2 and a lot opened at 3, whose 1.00 commission also
1503        // gives an average cost of 4.00, so only the leg fill gives the right entry
1504        let combo_leg_reports = if with_combo_legs {
1505            vec![create_test_entry_fill(
1506                OrderSide::Buy,
1507                "2",
1508                "4.00",
1509                "T-3",
1510                30,
1511            )]
1512        } else {
1513            Vec::new()
1514        };
1515        let evidence = FillEvidence {
1516            reports: vec![
1517                create_test_entry_fill(OrderSide::Sell, "2", "5.00", "T-1", 10),
1518                create_test_entry_fill(OrderSide::Buy, "1", "3.00", "T-2", 20),
1519            ],
1520            combo_leg_reports,
1521            ..Default::default()
1522        };
1523
1524        let avg_px_open = rebuild_avg_px_open(
1525            create_test_entry_position_report(PositionSide::Long, "1", "4.00"),
1526            &evidence,
1527        );
1528
1529        assert_eq!(avg_px_open, Some(Decimal::from_str(expected).unwrap()));
1530    }
1531
1532    #[rstest]
1533    fn test_fill_missing_avg_px_uses_fill_reports() {
1534        let instrument_id = InstrumentId::from("ESZ6.XCME");
1535        let account_id = AccountId::from("IB-DU001");
1536
1537        let order_report = |venue_order_id: &str, avg_px: Option<Decimal>| {
1538            let mut report = OrderStatusReport::new(
1539                account_id,
1540                instrument_id,
1541                None,
1542                VenueOrderId::new(venue_order_id),
1543                Some(OrderSide::Buy),
1544                OrderType::Market,
1545                TimeInForce::Day,
1546                NautilusOrderStatus::Filled,
1547                Quantity::from(3),
1548                Quantity::from(3),
1549                UnixNanos::default(),
1550                UnixNanos::default(),
1551                UnixNanos::default(),
1552                None,
1553            );
1554            report.avg_px = avg_px;
1555            report
1556        };
1557
1558        let fill = |venue_order_id: &str, trade_id: &str, qty: u64, px: &str| {
1559            FillReport::new(
1560                account_id,
1561                instrument_id,
1562                VenueOrderId::new(venue_order_id),
1563                TradeId::new(trade_id),
1564                OrderSide::Buy,
1565                Quantity::from(qty),
1566                Price::from(px),
1567                Money::from("0.00 USD"),
1568                LiquiditySide::Taker,
1569                None,
1570                None,
1571                UnixNanos::default(),
1572                UnixNanos::default(),
1573                None,
1574            )
1575        };
1576
1577        let mut reports = vec![
1578            order_report("PERM-1", None),
1579            order_report("PERM-2", Some(Decimal::from(7))),
1580            order_report("PERM-3", None),
1581        ];
1582        let fills = vec![
1583            fill("PERM-1", "T-1", 1, "2.55"),
1584            fill("PERM-1", "T-2", 2, "2.40"),
1585            fill("PERM-2", "T-3", 3, "9.00"),
1586        ];
1587
1588        fill_missing_avg_px(&mut reports, &fills);
1589
1590        assert_eq!(reports[0].avg_px, Some(Decimal::from_str("2.45").unwrap()));
1591        assert_eq!(reports[1].avg_px, Some(Decimal::from(7)));
1592        assert_eq!(reports[2].avg_px, None);
1593    }
1594
1595    #[rstest]
1596    #[case::combo(ibapi::contracts::SecurityType::Spread, true)]
1597    #[case::leg(ibapi::contracts::SecurityType::FuturesOption, false)]
1598    fn test_is_combo_execution(
1599        #[case] security_type: ibapi::contracts::SecurityType,
1600        #[case] expected: bool,
1601    ) {
1602        let exec_data = ibapi::orders::ExecutionData {
1603            contract: ibapi::contracts::Contract {
1604                security_type,
1605                ..Default::default()
1606            },
1607            ..Default::default()
1608        };
1609
1610        assert_eq!(is_combo_execution(&exec_data), expected);
1611    }
1612
1613    #[rstest]
1614    fn test_ibalgo_with_zero_limit_price_maps_to_market() {
1615        assert_eq!(map_ib_order_type("IBALGO", Some(0.0)), OrderType::Market);
1616    }
1617
1618    #[rstest]
1619    fn test_parse_execution_time_hyphenated_format() {
1620        let time_str = "20250225-15:15:00";
1621        let result = parse_execution_time(time_str);
1622        assert!(result.is_ok());
1623        let timestamp = result.unwrap();
1624        assert!(timestamp.as_i64() > 0);
1625    }
1626
1627    #[rstest]
1628    fn test_parse_execution_time_with_met_timezone() {
1629        // Regression for European paper accounts that IB stamps with `MET`.
1630        // MET (CET) in February observes standard time (UTC+1).
1631        let met = parse_execution_time("20230223 00:43:36 MET").unwrap();
1632        let utc = parse_execution_time("20230223 00:43:36 Universal").unwrap();
1633        // Local 00:43:36 MET == 2023-02-22 23:43:36 UTC, i.e. 1 hour before UTC.
1634        assert_eq!(
1635            met.as_i64(),
1636            utc.as_i64() - 3_600_000_000_000,
1637            "MET (CET) should be 1h ahead of UTC in February"
1638        );
1639        assert!(met.as_i64() > 0);
1640    }
1641
1642    #[rstest]
1643    fn test_parse_execution_time_applies_dst_for_regional_timezone() {
1644        // Same zone, two seasons: EST (UTC-5) in winter vs EDT (UTC-4) in summer.
1645        // Equal offsets would mean DST is NOT being applied - a real regression.
1646        let winter = parse_execution_time("20230223 00:43:36 America/New_York").unwrap();
1647        let summer = parse_execution_time("20230715 00:43:36 America/New_York").unwrap();
1648        let winter_utc = parse_execution_time("20230223 00:43:36 Universal").unwrap();
1649        let summer_utc = parse_execution_time("20230715 00:43:36 Universal").unwrap();
1650        assert_eq!(winter.as_i64(), winter_utc.as_i64() + 5 * 3_600_000_000_000); // EST
1651        assert_eq!(summer.as_i64(), summer_utc.as_i64() + 4 * 3_600_000_000_000); // EDT
1652    }
1653
1654    #[rstest]
1655    fn test_parse_execution_time_dst_fall_back_fold_resolves_to_earliest() {
1656        // CME US/Central account (bebop23's case): on 2023-11-05 fall-back night
1657        // 01:30 America/Chicago occurs twice. Resolve to earliest (CDT, 06:30 UTC),
1658        // don't drop the fill.
1659        let fold = parse_execution_time("20231105 01:30:00 America/Chicago").unwrap();
1660        assert_eq!(
1661            fold.as_i64(),
1662            parse_execution_time("20231105 06:30:00 Universal")
1663                .unwrap()
1664                .as_i64()
1665        );
1666        assert_ne!(
1667            fold.as_i64(),
1668            parse_execution_time("20231105 07:30:00 Universal")
1669                .unwrap()
1670                .as_i64()
1671        );
1672    }
1673
1674    #[rstest]
1675    fn test_parse_execution_time_dst_spring_forward_gap_errors() {
1676        // 02:30 America/Chicago never exists on 2023-03-12 spring-forward night.
1677        let gap = parse_execution_time("20230312 02:30:00 America/Chicago");
1678        assert!(gap.is_err());
1679    }
1680
1681    #[rstest]
1682    fn test_parse_execution_time_fixed_offset_zone_without_dst() {
1683        // Asia/Tokyo is JST (UTC+9) year-round - guards the no-DST path.
1684        let tokyo = parse_execution_time("20230223 00:43:36 Asia/Tokyo").unwrap();
1685        let utc = parse_execution_time("20230223 00:43:36 Universal").unwrap();
1686        assert_eq!(tokyo.as_i64(), utc.as_i64() - 9 * 3_600_000_000_000);
1687    }
1688
1689    #[rstest]
1690    fn test_parse_execution_time_with_unrecognized_timezone_errors() {
1691        let time_str = "20230223 00:43:36 Mars/Olympus";
1692        let result = parse_execution_time(time_str);
1693        assert!(result.is_err());
1694    }
1695
1696    #[rstest]
1697    fn test_parse_execution_time_utc() {
1698        let time_str = "20230223 00:43:36 Universal";
1699        let result = parse_execution_time(time_str);
1700        assert!(result.is_ok());
1701        let timestamp = result.unwrap();
1702        assert!(timestamp.as_i64() > 0);
1703    }
1704
1705    #[rstest]
1706    fn test_parse_execution_time_no_timezone_assumes_utc() {
1707        let time_str = "20230223 00:43:36";
1708        let result = parse_execution_time(time_str);
1709        assert!(result.is_ok());
1710        let timestamp = result.unwrap();
1711        assert!(timestamp.as_i64() > 0);
1712    }
1713
1714    #[rstest]
1715    fn test_parse_execution_time_invalid_format() {
1716        let time_str = "invalid format";
1717        let result = parse_execution_time(time_str);
1718        assert!(result.is_err());
1719    }
1720
1721    #[rstest]
1722    fn test_parse_execution_time_short_format() {
1723        let time_str = "20230223 00:43";
1724        let result = parse_execution_time(time_str);
1725        assert!(result.is_err());
1726    }
1727
1728    #[rstest]
1729    fn test_parse_order_status_to_report_submitted() {
1730        let instrument_provider = create_test_instrument_provider();
1731        let instrument_id = create_test_instrument_id();
1732        let account_id = AccountId::from("IB-001");
1733
1734        let order_status = OrderStatus {
1735            order_id: 12345,
1736            status: OrderStatusKind::Submitted,
1737            filled: 0.0,
1738            remaining: 100.0,
1739            average_fill_price: Some(0.0),
1740            perm_id: 0,
1741            parent_id: 0,
1742            last_fill_price: Some(0.0),
1743            client_id: 0,
1744            why_held: String::new(),
1745            market_cap_price: Some(0.0),
1746        };
1747
1748        let result = parse_order_status_to_report(
1749            &order_status,
1750            None,
1751            instrument_id,
1752            account_id,
1753            &instrument_provider,
1754            UnixNanos::new(0),
1755        );
1756
1757        // May fail if instrument not in provider, but that's expected
1758        if let Err(e) = result {
1759            let error_msg = e.to_string();
1760            assert!(
1761                error_msg.contains("not found") || error_msg.contains("instrument"),
1762                "Unexpected error: {error_msg}"
1763            );
1764        }
1765    }
1766
1767    #[rstest]
1768    fn test_parse_order_status_to_report_filled() {
1769        let instrument_provider = create_test_instrument_provider();
1770        let instrument_id = create_test_instrument_id();
1771        let account_id = AccountId::from("IB-001");
1772
1773        let order_status = OrderStatus {
1774            order_id: 12345,
1775            status: OrderStatusKind::Filled,
1776            filled: 100.0,
1777            remaining: 0.0,
1778            average_fill_price: Some(150.25),
1779            perm_id: 0,
1780            parent_id: 0,
1781            last_fill_price: Some(150.25),
1782            client_id: 0,
1783            why_held: String::new(),
1784            market_cap_price: Some(0.0),
1785        };
1786
1787        let result = parse_order_status_to_report(
1788            &order_status,
1789            None,
1790            instrument_id,
1791            account_id,
1792            &instrument_provider,
1793            UnixNanos::new(0),
1794        );
1795
1796        // May fail if instrument not in provider, but that's expected
1797        if let Err(e) = result {
1798            let error_msg = e.to_string();
1799            assert!(
1800                error_msg.contains("not found") || error_msg.contains("instrument"),
1801                "Unexpected error: {error_msg}"
1802            );
1803        }
1804    }
1805
1806    #[rstest]
1807    fn test_parse_order_status_to_report_spread_allows_negative_avg_fill_price() {
1808        let instrument_provider = create_test_instrument_provider();
1809
1810        let instrument_id = InstrumentId::new(
1811            Symbol::from("(1)SPY C400___((1))SPY C410"),
1812            Venue::from("SMART"),
1813        );
1814        let account_id = AccountId::from("IB-001");
1815
1816        let order_status = OrderStatus {
1817            order_id: 12345,
1818            status: OrderStatusKind::Filled,
1819            filled: 1.0,
1820            remaining: 0.0,
1821            average_fill_price: Some(-2.25),
1822            perm_id: 0,
1823            parent_id: 0,
1824            last_fill_price: Some(-2.25),
1825            client_id: 0,
1826            why_held: String::new(),
1827            market_cap_price: Some(0.0),
1828        };
1829
1830        let report = parse_order_status_to_report(
1831            &order_status,
1832            None,
1833            instrument_id,
1834            account_id,
1835            &instrument_provider,
1836            UnixNanos::new(0),
1837        )
1838        .unwrap();
1839
1840        assert_eq!(report.avg_px, Some(Decimal::from_str("-2.25").unwrap()));
1841    }
1842
1843    #[rstest]
1844    fn test_parse_order_status_to_report_inactive_maps_to_rejected() {
1845        let instrument_provider = create_test_instrument_provider();
1846        let instrument_id = create_test_instrument_id();
1847        let account_id = AccountId::from("IB-001");
1848
1849        let order_status = OrderStatus {
1850            order_id: 12345,
1851            status: OrderStatusKind::Inactive,
1852            filled: 0.0,
1853            remaining: 100.0,
1854            average_fill_price: Some(0.0),
1855            perm_id: 0,
1856            parent_id: 0,
1857            last_fill_price: Some(0.0),
1858            client_id: 0,
1859            why_held: String::new(),
1860            market_cap_price: Some(0.0),
1861        };
1862
1863        let report = parse_order_status_to_report(
1864            &order_status,
1865            None,
1866            instrument_id,
1867            account_id,
1868            &instrument_provider,
1869            UnixNanos::new(0),
1870        )
1871        .unwrap();
1872
1873        assert_eq!(report.order_status, NautilusOrderStatus::Rejected);
1874    }
1875
1876    #[rstest]
1877    fn test_parse_order_status_to_report_partial_fill_and_perm_fallback() {
1878        let instrument_provider = create_test_instrument_provider();
1879        let instrument_id = create_test_instrument_id();
1880        let account_id = AccountId::from("IB-001");
1881
1882        let order_status = OrderStatus {
1883            order_id: 0,
1884            status: OrderStatusKind::Submitted,
1885            filled: 3.0,
1886            remaining: 7.0,
1887            average_fill_price: Some(150.25),
1888            perm_id: 123_456,
1889            parent_id: 0,
1890            last_fill_price: Some(150.25),
1891            client_id: 0,
1892            why_held: String::new(),
1893            market_cap_price: Some(0.0),
1894        };
1895
1896        let order = Order {
1897            action: Action::Buy,
1898            total_quantity: 10.0,
1899            order_type: "LMT".to_string(),
1900            limit_price: Some(150.25),
1901            order_ref: "O-20260527-001:123".to_string(),
1902            ..Default::default()
1903        };
1904
1905        let report = parse_order_status_to_report(
1906            &order_status,
1907            Some(&order),
1908            instrument_id,
1909            account_id,
1910            &instrument_provider,
1911            UnixNanos::new(0),
1912        )
1913        .unwrap();
1914
1915        assert_eq!(report.order_status, NautilusOrderStatus::PartiallyFilled);
1916        assert_eq!(report.venue_order_id.to_string(), "PERM-123456");
1917        assert_eq!(
1918            report.client_order_id,
1919            Some(ClientOrderId::from("O-20260527-001"))
1920        );
1921    }
1922
1923    #[rstest]
1924    #[case::remaining_quantity(70.0, false)]
1925    #[case::original_quantity(0.0, true)]
1926    #[case::both_quantities(70.0, true)]
1927    fn test_parse_order_status_to_report_preserves_partial_cancel(
1928        #[values(OrderStatusKind::Cancelled, OrderStatusKind::ApiCancelled)]
1929        status: OrderStatusKind,
1930        #[case] remaining: f64,
1931        #[case] with_order: bool,
1932    ) {
1933        let order_status = OrderStatus {
1934            status,
1935            filled: 30.0,
1936            remaining,
1937            average_fill_price: Some(150.25),
1938            ..Default::default()
1939        };
1940
1941        let order = Order {
1942            total_quantity: 100.0,
1943            ..Default::default()
1944        };
1945
1946        let report = parse_order_status_to_report(
1947            &order_status,
1948            with_order.then_some(&order),
1949            create_test_instrument_id(),
1950            AccountId::from("IB-001"),
1951            &create_test_instrument_provider(),
1952            UnixNanos::default(),
1953        )
1954        .unwrap();
1955
1956        assert_eq!(report.order_status, NautilusOrderStatus::Canceled);
1957        assert_eq!(report.quantity, Quantity::from(100));
1958        assert_eq!(report.filled_qty, Quantity::from(30));
1959        assert_eq!(report.avg_px, Some(Decimal::from_str("150.25").unwrap()));
1960    }
1961
1962    #[rstest]
1963    #[case::submitted(OrderStatusKind::Submitted, 30.0, NautilusOrderStatus::PartiallyFilled)]
1964    #[case::pre_submitted(
1965        OrderStatusKind::PreSubmitted,
1966        30.0,
1967        NautilusOrderStatus::PartiallyFilled
1968    )]
1969    #[case::pending_cancel(
1970        OrderStatusKind::PendingCancel,
1971        30.0,
1972        NautilusOrderStatus::PartiallyFilled
1973    )]
1974    #[case::inactive(OrderStatusKind::Inactive, 30.0, NautilusOrderStatus::PartiallyFilled)]
1975    #[case::filled(OrderStatusKind::Filled, 100.0, NautilusOrderStatus::Filled)]
1976    #[case::cancelled_unfilled(OrderStatusKind::Cancelled, 0.0, NautilusOrderStatus::Canceled)]
1977    #[case::api_cancelled_unfilled(
1978        OrderStatusKind::ApiCancelled,
1979        0.0,
1980        NautilusOrderStatus::Canceled
1981    )]
1982    fn test_parse_order_status_to_report_fill_status(
1983        #[case] status: OrderStatusKind,
1984        #[case] filled: f64,
1985        #[case] expected_status: NautilusOrderStatus,
1986    ) {
1987        let order_status = OrderStatus {
1988            status,
1989            filled,
1990            remaining: 100.0 - filled,
1991            ..Default::default()
1992        };
1993
1994        let report = parse_order_status_to_report(
1995            &order_status,
1996            None,
1997            create_test_instrument_id(),
1998            AccountId::from("IB-001"),
1999            &create_test_instrument_provider(),
2000            UnixNanos::default(),
2001        )
2002        .unwrap();
2003
2004        assert_eq!(report.order_status, expected_status);
2005        assert_eq!(report.quantity, Quantity::from(100));
2006        assert_eq!(report.filled_qty, Quantity::new(filled, 0));
2007    }
2008
2009    #[rstest]
2010    fn test_parse_order_status_to_report_recovers_completed_order_quantity() {
2011        let instrument_provider = create_test_instrument_provider();
2012        let instrument_id = create_test_instrument_id();
2013
2014        let order_status = OrderStatus {
2015            status: OrderStatusKind::Filled,
2016            filled: 3.0,
2017            remaining: 0.0,
2018            ..Default::default()
2019        };
2020
2021        let order = Order {
2022            total_quantity: 0.0,
2023            filled_quantity: 3.0,
2024            ..Default::default()
2025        };
2026
2027        let report = parse_order_status_to_report(
2028            &order_status,
2029            Some(&order),
2030            instrument_id,
2031            AccountId::from("IB-001"),
2032            &instrument_provider,
2033            UnixNanos::new(0),
2034        )
2035        .unwrap();
2036
2037        assert_eq!(report.quantity, Quantity::from(3));
2038        assert_eq!(report.filled_qty, Quantity::from(3));
2039    }
2040
2041    #[rstest]
2042    fn test_parse_order_status_to_report_sets_stop_trigger_type() {
2043        let instrument_provider = create_test_instrument_provider();
2044        let instrument_id = create_test_instrument_id();
2045
2046        let order_status = OrderStatus {
2047            status: OrderStatusKind::Cancelled,
2048            remaining: 1.0,
2049            ..Default::default()
2050        };
2051
2052        let order = Order {
2053            total_quantity: 1.0,
2054            order_type: "STP".to_string(),
2055            aux_price: Some(100.0),
2056            trigger_method: ibapi::orders::conditions::TriggerMethod::Last,
2057            ..Default::default()
2058        };
2059
2060        let report = parse_order_status_to_report(
2061            &order_status,
2062            Some(&order),
2063            instrument_id,
2064            AccountId::from("IB-001"),
2065            &instrument_provider,
2066            UnixNanos::new(0),
2067        )
2068        .unwrap();
2069
2070        assert_eq!(report.order_type, OrderType::StopMarket);
2071        assert_eq!(report.trigger_price, Some(Price::new(100.0, 0)));
2072        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
2073    }
2074
2075    #[rstest]
2076    #[case(
2077        "GTD",
2078        "20260925 20:00:00 UTC",
2079        TimeInForce::Gtd,
2080        Some(1_790_366_400_000_000_000)
2081    )]
2082    #[case(
2083        "GTC",
2084        "20260925-20:00:00",
2085        TimeInForce::Gtd,
2086        Some(1_790_366_400_000_000_000)
2087    )]
2088    #[case("GTD", "not a date", TimeInForce::Gtc, None)]
2089    #[case("DAY", "", TimeInForce::Day, None)]
2090    fn test_parse_order_status_to_report_sets_gtd_expire_time(
2091        #[case] tif: &str,
2092        #[case] good_till_date: &str,
2093        #[case] expected_time_in_force: TimeInForce,
2094        #[case] expected_expire_time: Option<u64>,
2095    ) {
2096        let instrument_provider = create_test_instrument_provider();
2097        let instrument_id = create_test_instrument_id();
2098
2099        let order_status = OrderStatus {
2100            status: OrderStatusKind::Filled,
2101            filled: 1.0,
2102            ..Default::default()
2103        };
2104
2105        let order = Order {
2106            total_quantity: 1.0,
2107            order_type: "LMT".to_string(),
2108            limit_price: Some(101.0),
2109            tif: ibapi::orders::TimeInForce::from(tif),
2110            good_till_date: good_till_date.to_string(),
2111            ..Default::default()
2112        };
2113
2114        let report = parse_order_status_to_report(
2115            &order_status,
2116            Some(&order),
2117            instrument_id,
2118            AccountId::from("IB-001"),
2119            &instrument_provider,
2120            UnixNanos::new(0),
2121        )
2122        .unwrap();
2123
2124        assert_eq!(report.time_in_force, expected_time_in_force);
2125        assert_eq!(
2126            report.expire_time,
2127            expected_expire_time.map(UnixNanos::from)
2128        );
2129    }
2130
2131    #[rstest]
2132    #[case("MKT", Some(0.0), OrderType::Market, None)]
2133    #[case("STP", Some(0.0), OrderType::StopMarket, None)]
2134    #[case("LMT", Some(101.0), OrderType::Limit, Some(Price::new(101.0, 0)))]
2135    fn test_parse_order_status_to_report_sets_price_only_for_limit_types(
2136        #[case] ib_order_type: &str,
2137        #[case] limit_price: Option<f64>,
2138        #[case] expected_order_type: OrderType,
2139        #[case] expected_price: Option<Price>,
2140    ) {
2141        let instrument_provider = create_test_instrument_provider();
2142        let instrument_id = create_test_instrument_id();
2143
2144        let order_status = OrderStatus {
2145            status: OrderStatusKind::Filled,
2146            filled: 1.0,
2147            ..Default::default()
2148        };
2149
2150        let order = Order {
2151            total_quantity: 1.0,
2152            order_type: ib_order_type.to_string(),
2153            limit_price,
2154            aux_price: Some(100.0),
2155            ..Default::default()
2156        };
2157
2158        let report = parse_order_status_to_report(
2159            &order_status,
2160            Some(&order),
2161            instrument_id,
2162            AccountId::from("IB-001"),
2163            &instrument_provider,
2164            UnixNanos::new(0),
2165        )
2166        .unwrap();
2167
2168        assert_eq!(report.order_type, expected_order_type);
2169        assert_eq!(report.price, expected_price);
2170    }
2171
2172    #[rstest]
2173    fn test_ib_venue_order_id_prefers_perm_id_and_falls_back_to_order_id() {
2174        assert_eq!(ib_venue_order_id(123, 456).to_string(), "PERM-456");
2175        assert_eq!(ib_venue_order_id(123, 0).to_string(), "123");
2176    }
2177
2178    #[rstest]
2179    fn test_normalized_order_ref_strips_ib_suffix() {
2180        assert_eq!(normalized_order_ref("O-001:123"), Some("O-001"));
2181        assert_eq!(normalized_order_ref("O-001"), Some("O-001"));
2182        assert_eq!(normalized_order_ref(""), None);
2183    }
2184
2185    #[rstest]
2186    #[case(Liquidity::AddedLiquidity, LiquiditySide::Maker)]
2187    #[case(Liquidity::RemovedLiquidity, LiquiditySide::Taker)]
2188    #[case(Liquidity::None, LiquiditySide::NoLiquiditySide)]
2189    #[case(Liquidity::LiquidityRoutedOut, LiquiditySide::NoLiquiditySide)]
2190    #[case(Liquidity::Unknown(4), LiquiditySide::NoLiquiditySide)]
2191    fn test_execution_liquidity_side(
2192        #[case] liquidity: Liquidity,
2193        #[case] expected: LiquiditySide,
2194    ) {
2195        assert_eq!(execution_liquidity_side(&liquidity), expected);
2196    }
2197
2198    struct PricingExpectation {
2199        order_type: OrderType,
2200        price: Option<Price>,
2201        trigger_price: Option<Price>,
2202        limit_offset: Option<Decimal>,
2203        trailing_offset: Option<Decimal>,
2204        trailing_offset_type: Option<TrailingOffsetType>,
2205    }
2206
2207    #[rstest]
2208    #[case(
2209        "MKT",
2210        None,
2211        None,
2212        None,
2213        None,
2214        PricingExpectation {
2215            order_type: OrderType::Market,
2216            price: None,
2217            trigger_price: None,
2218            limit_offset: None,
2219            trailing_offset: None,
2220            trailing_offset_type: None,
2221        }
2222    )]
2223    #[case(
2224        "LMT",
2225        Some(185.0),
2226        None,
2227        None,
2228        None,
2229        PricingExpectation {
2230            order_type: OrderType::Limit,
2231            price: Some(Price::new(185.0, 0)),
2232            trigger_price: None,
2233            limit_offset: None,
2234            trailing_offset: None,
2235            trailing_offset_type: None,
2236        }
2237    )]
2238    #[case(
2239        "IBALGO",
2240        Some(185.0),
2241        None,
2242        None,
2243        None,
2244        PricingExpectation {
2245            order_type: OrderType::Limit,
2246            price: Some(Price::new(185.0, 0)),
2247            trigger_price: None,
2248            limit_offset: None,
2249            trailing_offset: None,
2250            trailing_offset_type: None,
2251        }
2252    )]
2253    #[case(
2254        "IBALGO",
2255        None,
2256        None,
2257        None,
2258        None,
2259        PricingExpectation {
2260            order_type: OrderType::Market,
2261            price: None,
2262            trigger_price: None,
2263            limit_offset: None,
2264            trailing_offset: None,
2265            trailing_offset_type: None,
2266        }
2267    )]
2268    #[case(
2269        "MIT",
2270        None,
2271        Some(180.0),
2272        None,
2273        None,
2274        PricingExpectation {
2275            order_type: OrderType::MarketIfTouched,
2276            price: None,
2277            trigger_price: Some(Price::new(180.0, 0)),
2278            limit_offset: None,
2279            trailing_offset: None,
2280            trailing_offset_type: None,
2281        }
2282    )]
2283    #[case(
2284        "LIT",
2285        Some(179.0),
2286        Some(180.0),
2287        None,
2288        None,
2289        PricingExpectation {
2290            order_type: OrderType::LimitIfTouched,
2291            price: Some(Price::new(179.0, 0)),
2292            trigger_price: Some(Price::new(180.0, 0)),
2293            limit_offset: None,
2294            trailing_offset: None,
2295            trailing_offset_type: None,
2296        }
2297    )]
2298    #[case(
2299        "STP",
2300        None,
2301        Some(180.0),
2302        None,
2303        None,
2304        PricingExpectation {
2305            order_type: OrderType::StopMarket,
2306            price: None,
2307            trigger_price: Some(Price::new(180.0, 0)),
2308            limit_offset: None,
2309            trailing_offset: None,
2310            trailing_offset_type: None,
2311        }
2312    )]
2313    #[case(
2314        "STP LMT",
2315        Some(179.0),
2316        Some(180.0),
2317        None,
2318        None,
2319        PricingExpectation {
2320            order_type: OrderType::StopLimit,
2321            price: Some(Price::new(179.0, 0)),
2322            trigger_price: Some(Price::new(180.0, 0)),
2323            limit_offset: None,
2324            trailing_offset: None,
2325            trailing_offset_type: None,
2326        }
2327    )]
2328    #[case(
2329        "TRAIL LIMIT",
2330        None,
2331        Some(2.5),
2332        Some(185.0),
2333        Some(0.25),
2334        PricingExpectation {
2335            order_type: OrderType::TrailingStopLimit,
2336            price: None,
2337            trigger_price: Some(Price::new(185.0, 0)),
2338            limit_offset: Some(Decimal::from_str("0.25").unwrap()),
2339            trailing_offset: Some(Decimal::from_str("2.5").unwrap()),
2340            trailing_offset_type: Some(TrailingOffsetType::Price),
2341        },
2342    )]
2343    fn test_parse_order_status_to_report_maps_pricing_fields_by_order_type(
2344        #[case] ib_order_type: &str,
2345        #[case] limit_price: Option<f64>,
2346        #[case] aux_price: Option<f64>,
2347        #[case] trail_stop_price: Option<f64>,
2348        #[case] limit_price_offset: Option<f64>,
2349        #[case] expected: PricingExpectation,
2350    ) {
2351        let instrument_provider = create_test_instrument_provider();
2352        let instrument_id = create_test_instrument_id();
2353        let account_id = AccountId::from("IB-001");
2354
2355        let order_status = OrderStatus {
2356            order_id: 12345,
2357            status: OrderStatusKind::Submitted,
2358            filled: 0.0,
2359            remaining: 5.0,
2360            average_fill_price: Some(0.0),
2361            perm_id: 0,
2362            parent_id: 0,
2363            last_fill_price: Some(0.0),
2364            client_id: 0,
2365            why_held: String::new(),
2366            market_cap_price: Some(0.0),
2367        };
2368
2369        let order = Order {
2370            action: Action::Buy,
2371            total_quantity: 5.0,
2372            order_type: ib_order_type.to_string(),
2373            limit_price,
2374            aux_price,
2375            trail_stop_price,
2376            limit_price_offset,
2377            tif: ibapi::orders::TimeInForce::GoodTillCanceled,
2378            ..Default::default()
2379        };
2380
2381        let report = parse_order_status_to_report(
2382            &order_status,
2383            Some(&order),
2384            instrument_id,
2385            account_id,
2386            &instrument_provider,
2387            UnixNanos::new(0),
2388        )
2389        .unwrap();
2390
2391        assert_eq!(report.order_type, expected.order_type);
2392        assert_eq!(report.price, expected.price);
2393        assert_eq!(report.trigger_price, expected.trigger_price);
2394        assert_eq!(report.limit_offset, expected.limit_offset);
2395        assert_eq!(report.trailing_offset, expected.trailing_offset);
2396        assert_eq!(report.trailing_offset_type, expected.trailing_offset_type);
2397    }
2398
2399    #[rstest]
2400    fn test_parse_order_status_to_report_maps_trailing_percent_to_basis_points() {
2401        let instrument_provider = create_test_instrument_provider();
2402        let instrument_id = create_test_instrument_id();
2403        let account_id = AccountId::from("IB-001");
2404
2405        let order_status = OrderStatus {
2406            order_id: 12345,
2407            status: OrderStatusKind::Submitted,
2408            filled: 0.0,
2409            remaining: 5.0,
2410            average_fill_price: Some(0.0),
2411            perm_id: 0,
2412            parent_id: 0,
2413            last_fill_price: Some(0.0),
2414            client_id: 0,
2415            why_held: String::new(),
2416            market_cap_price: Some(0.0),
2417        };
2418
2419        let order = Order {
2420            action: Action::Buy,
2421            total_quantity: 5.0,
2422            order_type: "TRAIL".to_string(),
2423            trail_stop_price: Some(185.0),
2424            trailing_percent: Some(2.5),
2425            tif: ibapi::orders::TimeInForce::GoodTillCanceled,
2426            ..Default::default()
2427        };
2428
2429        let report = parse_order_status_to_report(
2430            &order_status,
2431            Some(&order),
2432            instrument_id,
2433            account_id,
2434            &instrument_provider,
2435            UnixNanos::new(0),
2436        )
2437        .unwrap();
2438
2439        assert_eq!(report.order_type, OrderType::TrailingStopMarket);
2440        assert_eq!(report.trigger_price, Some(Price::new(185.0, 0)));
2441        assert_eq!(
2442            report.trailing_offset,
2443            Some(Decimal::from_str("250").unwrap())
2444        );
2445        assert_eq!(
2446            report.trailing_offset_type,
2447            Some(TrailingOffsetType::BasisPoints),
2448        );
2449        assert_eq!(report.limit_offset, None);
2450    }
2451
2452    #[rstest]
2453    fn test_parse_execution_to_fill_report_buy() {
2454        let instrument_provider = create_test_instrument_provider();
2455        let instrument_id = create_test_instrument_id();
2456        let account_id = AccountId::from("IB-001");
2457
2458        let execution = Execution {
2459            order_id: 12345,
2460            client_id: 0,
2461            execution_id: String::from("EXEC-001"),
2462            time: String::from("20230223 00:43:36 Universal"),
2463            account_number: String::new(),
2464            exchange: String::new(),
2465            side: ExecutionSide::Bought,
2466            shares: 100.0,
2467            price: 150.25,
2468            perm_id: 0,
2469            liquidation: 0,
2470            cumulative_quantity: 100.0,
2471            average_price: 150.25,
2472            order_reference: String::from("ORDER-REF-001"),
2473            ev_rule: String::new(),
2474            ev_multiplier: None,
2475            model_code: String::new(),
2476            last_liquidity: Liquidity::None,
2477            pending_price_revision: false,
2478            submitter: String::new(),
2479        };
2480
2481        let contract = Contract::default();
2482        let result = parse_execution_to_fill_report(
2483            &execution,
2484            &contract,
2485            1.0,
2486            "USD",
2487            instrument_id,
2488            account_id,
2489            &instrument_provider,
2490            UnixNanos::new(0),
2491            None, // avg_px
2492        );
2493
2494        // May fail if instrument not in provider, but that's expected
2495        match result {
2496            Err(e) => {
2497                let error_msg = e.to_string();
2498                assert!(
2499                    error_msg.contains("not found") || error_msg.contains("instrument"),
2500                    "Unexpected error: {error_msg}"
2501                );
2502            }
2503            Ok(fill) => {
2504                assert_eq!(fill.order_side, OrderSide::Buy);
2505                assert_eq!(fill.trade_id.to_string(), "EXEC-001");
2506            }
2507        }
2508    }
2509
2510    #[rstest]
2511    fn test_parse_execution_to_fill_report_clamps_only_pending_commission_sentinel() {
2512        let instrument_provider = create_test_instrument_provider();
2513        let instrument = equity_aapl();
2514        let instrument_id = instrument.id();
2515        instrument_provider.insert_test_instrument(InstrumentAny::from(instrument), 265598, 1);
2516        let account_id = AccountId::from("IB-001");
2517        let contract = Contract::default();
2518
2519        for (commission, expected) in [(-1.0, 0.0), (-0.25, -0.25)] {
2520            let execution = Execution {
2521                order_id: 12345,
2522                client_id: 0,
2523                execution_id: format!("EXEC-{commission}"),
2524                time: String::from("20230223 00:43:36 Universal"),
2525                account_number: String::new(),
2526                exchange: String::new(),
2527                side: ExecutionSide::Bought,
2528                shares: 100.0,
2529                price: 150.25,
2530                perm_id: 0,
2531                liquidation: 0,
2532                cumulative_quantity: 100.0,
2533                average_price: 150.25,
2534                order_reference: String::from("ORDER-REF-001"),
2535                ev_rule: String::new(),
2536                ev_multiplier: None,
2537                model_code: String::new(),
2538                last_liquidity: Liquidity::None,
2539                pending_price_revision: false,
2540                submitter: String::new(),
2541            };
2542
2543            let report = parse_execution_to_fill_report(
2544                &execution,
2545                &contract,
2546                commission,
2547                "USD",
2548                instrument_id,
2549                account_id,
2550                &instrument_provider,
2551                UnixNanos::new(0),
2552                None,
2553            )
2554            .unwrap();
2555
2556            assert_eq!(report.commission, Money::new(expected, Currency::USD()));
2557        }
2558    }
2559
2560    #[rstest]
2561    fn test_parse_execution_to_fill_report_sell() {
2562        let instrument_provider = create_test_instrument_provider();
2563        let instrument_id = create_test_instrument_id();
2564        let account_id = AccountId::from("IB-001");
2565
2566        let execution = Execution {
2567            order_id: 12345,
2568            client_id: 0,
2569            execution_id: String::from("EXEC-002"),
2570            time: String::from("20230223 00:43:36 Universal"),
2571            account_number: String::new(),
2572            exchange: String::new(),
2573            side: ExecutionSide::Sold,
2574            shares: 50.0,
2575            price: 151.0,
2576            perm_id: 0,
2577            liquidation: 0,
2578            cumulative_quantity: 50.0,
2579            average_price: 151.0,
2580            order_reference: String::new(),
2581            ev_rule: String::new(),
2582            ev_multiplier: None,
2583            model_code: String::new(),
2584            last_liquidity: Liquidity::None,
2585            pending_price_revision: false,
2586            submitter: String::new(),
2587        };
2588
2589        let contract = Contract::default();
2590        let result = parse_execution_to_fill_report(
2591            &execution,
2592            &contract,
2593            0.5,
2594            "USD",
2595            instrument_id,
2596            account_id,
2597            &instrument_provider,
2598            UnixNanos::new(0),
2599            None, // avg_px
2600        );
2601
2602        // May fail if instrument not in provider, but that's expected
2603        match result {
2604            Err(e) => {
2605                let error_msg = e.to_string();
2606                assert!(
2607                    error_msg.contains("not found") || error_msg.contains("instrument"),
2608                    "Unexpected error: {error_msg}"
2609                );
2610            }
2611            Ok(fill) => {
2612                assert_eq!(fill.order_side, OrderSide::Sell);
2613            }
2614        }
2615    }
2616
2617    fn contingency_report(
2618        client_order_id: Option<&str>,
2619        venue_order_id: &str,
2620    ) -> OrderStatusReport {
2621        OrderStatusReport::new(
2622            AccountId::from("IB-001"),
2623            create_test_instrument_id(),
2624            client_order_id.map(ClientOrderId::from),
2625            VenueOrderId::from(venue_order_id),
2626            OrderSide::Sell.into(),
2627            OrderType::StopMarket,
2628            TimeInForce::Gtc,
2629            NautilusOrderStatus::Accepted,
2630            Quantity::from(1),
2631            Quantity::from(0),
2632            UnixNanos::default(),
2633            UnixNanos::default(),
2634            UnixNanos::default(),
2635            None,
2636        )
2637    }
2638
2639    fn contingency_order(order_id: i32, perm_id: i64, parent_id: i32, oca: &str) -> Order {
2640        Order {
2641            order_id,
2642            perm_id,
2643            client_id: 7,
2644            parent_id,
2645            account: "DU123".to_string(),
2646            oca_group: oca.to_string(),
2647            oca_type: ibapi::orders::OcaType::ReduceWithBlock,
2648            ..Default::default()
2649        }
2650    }
2651
2652    #[rstest]
2653    fn test_link_order_contingencies_restores_bracket_and_oca_group() {
2654        let mut reports = vec![
2655            contingency_report(Some("O-ENTRY"), "PERM-10"),
2656            contingency_report(Some("O-STOP"), "PERM-11"),
2657            contingency_report(None, "PERM-12"),
2658            contingency_report(Some("O-ALONE"), "PERM-13"),
2659        ];
2660        let orders = vec![
2661            contingency_order(1, 10, 0, ""),
2662            contingency_order(2, 11, 1, "EXIT-1"),
2663            contingency_order(3, 12, 1, "EXIT-1"),
2664            contingency_order(4, 13, 99, ""),
2665        ];
2666
2667        link_order_contingencies(&mut reports, &orders);
2668
2669        let links = reports
2670            .iter()
2671            .map(|report| {
2672                (
2673                    report.contingency_type,
2674                    report.linked_order_ids.clone(),
2675                    report.parent_order_id,
2676                )
2677            })
2678            .collect::<Vec<_>>();
2679
2680        assert_eq!(
2681            links,
2682            vec![
2683                (
2684                    Some(ContingencyType::Oto),
2685                    Some(vec![
2686                        ClientOrderId::from("O-STOP"),
2687                        ClientOrderId::from("PERM-12")
2688                    ]),
2689                    None,
2690                ),
2691                (
2692                    Some(ContingencyType::Ouo),
2693                    Some(vec![ClientOrderId::from("PERM-12")]),
2694                    Some(ClientOrderId::from("O-ENTRY")),
2695                ),
2696                (
2697                    Some(ContingencyType::Ouo),
2698                    Some(vec![ClientOrderId::from("O-STOP")]),
2699                    Some(ClientOrderId::from("O-ENTRY")),
2700                ),
2701                (None, None, None),
2702            ]
2703        );
2704    }
2705
2706    #[rstest]
2707    #[case::cancel(ibapi::orders::OcaType::CancelWithBlock, Some(ContingencyType::Oco))]
2708    #[case::reduce_without_block(
2709        ibapi::orders::OcaType::ReduceWithoutBlock,
2710        Some(ContingencyType::Ouo)
2711    )]
2712    #[case::unset(ibapi::orders::OcaType::None, None)]
2713    fn test_link_order_contingencies_maps_oca_type(
2714        #[case] oca_type: ibapi::orders::OcaType,
2715        #[case] expected: Option<ContingencyType>,
2716    ) {
2717        let mut reports = vec![
2718            contingency_report(Some("O-A"), "PERM-20"),
2719            contingency_report(Some("O-B"), "PERM-21"),
2720        ];
2721        let mut orders = vec![
2722            contingency_order(1, 20, 0, "GROUP"),
2723            contingency_order(2, 21, 0, "GROUP"),
2724        ];
2725
2726        for order in &mut orders {
2727            order.oca_type = oca_type;
2728        }
2729
2730        link_order_contingencies(&mut reports, &orders);
2731
2732        assert_eq!(
2733            reports
2734                .iter()
2735                .map(|report| (report.contingency_type, report.linked_order_ids.clone()))
2736                .collect::<Vec<_>>(),
2737            vec![
2738                (expected, expected.map(|_| vec![ClientOrderId::from("O-B")])),
2739                (expected, expected.map(|_| vec![ClientOrderId::from("O-A")])),
2740            ]
2741        );
2742    }
2743
2744    #[rstest]
2745    #[case::iceberg(Some(2), Some(Quantity::from(2)))]
2746    #[case::full_size(Some(5), None)]
2747    #[case::unset(Some(0), None)]
2748    fn test_parse_order_status_to_report_sets_display_qty(
2749        #[case] display_size: Option<i32>,
2750        #[case] expected: Option<Quantity>,
2751    ) {
2752        let instrument_provider = create_test_instrument_provider();
2753
2754        let order = Order {
2755            total_quantity: 5.0,
2756            order_type: "LMT".to_string(),
2757            limit_price: Some(101.0),
2758            display_size,
2759            ..Default::default()
2760        };
2761
2762        let order_status = OrderStatus {
2763            status: OrderStatusKind::Submitted,
2764            remaining: 5.0,
2765            ..Default::default()
2766        };
2767
2768        let report = parse_order_status_to_report(
2769            &order_status,
2770            Some(&order),
2771            create_test_instrument_id(),
2772            AccountId::from("IB-001"),
2773            &instrument_provider,
2774            UnixNanos::new(0),
2775        )
2776        .unwrap();
2777
2778        assert_eq!(report.display_qty, expected);
2779    }
2780
2781    #[rstest]
2782    #[case::completed("20260924 12:02:04 UTC", 1_790_251_324_000_000_000)]
2783    #[case::open("", 7)]
2784    #[case::unparsable("20260924 12:02:04 Unknown/Timezone", 7)]
2785    fn test_parse_order_data_to_report_uses_completed_time(
2786        #[case] completed_time: &str,
2787        #[case] expected_ts_last: u64,
2788    ) {
2789        let instrument_provider = create_test_instrument_provider();
2790
2791        let mut data = OrderData {
2792            order_id: 1,
2793            order: Order {
2794                total_quantity: 1.0,
2795                order_type: "MKT".to_string(),
2796                ..Default::default()
2797            },
2798            ..Default::default()
2799        };
2800
2801        data.order_state.completed_time = completed_time.to_string();
2802
2803        let report = parse_order_data_to_report(
2804            &data,
2805            create_test_instrument_id(),
2806            AccountId::from("IB-001"),
2807            &instrument_provider,
2808            UnixNanos::new(7),
2809        )
2810        .unwrap();
2811
2812        assert_eq!(report.ts_last, UnixNanos::from(expected_ts_last));
2813    }
2814
2815    #[cfg(feature = "execution")]
2816    #[rstest]
2817    fn test_completed_partial_cancel_closes_reconciled_order(
2818        #[values(OrderStatusKind::Cancelled, OrderStatusKind::ApiCancelled)]
2819        status: OrderStatusKind,
2820        #[values(false, true)] cached_partial_fill: bool,
2821    ) {
2822        let instrument = InstrumentAny::Equity(equity_aapl());
2823        let account_id = AccountId::from("IB-DU001");
2824        let ts_init = UnixNanos::new(1_790_251_325_000_000_000);
2825
2826        let mut data = OrderData {
2827            order_id: -1,
2828            order: Order {
2829                action: Action::Buy,
2830                total_quantity: 100.0,
2831                filled_quantity: 30.0,
2832                perm_id: 123_456,
2833                order_type: "MKT".to_string(),
2834                ..Default::default()
2835            },
2836            ..Default::default()
2837        };
2838        data.order_state.status = status;
2839        data.order_state.completed_time = "20260924 12:02:04 UTC".to_string();
2840
2841        let report = parse_order_data_to_report(
2842            &data,
2843            instrument.id(),
2844            account_id,
2845            &create_test_avg_px_provider(),
2846            ts_init,
2847        )
2848        .unwrap();
2849        assert_eq!(report.venue_order_id, VenueOrderId::from("PERM-123456"));
2850        assert_eq!(report.quantity, Quantity::from(100));
2851        assert_eq!(report.filled_qty, Quantity::from(30));
2852        assert_eq!(report.ts_last, UnixNanos::new(1_790_251_324_000_000_000));
2853        assert_eq!(report.avg_px, None);
2854
2855        // Completed orders get their missing average price from executions at startup
2856        let fill = create_test_entry_fill(OrderSide::Buy, "30", "150.25", "123456", 1);
2857        let mut reports = [report];
2858        fill_missing_avg_px(&mut reports, &[fill]);
2859        let report = &reports[0];
2860
2861        let mut order = OrderTestBuilder::new(OrderType::Market)
2862            .instrument_id(instrument.id())
2863            .side(OrderSide::Buy)
2864            .quantity(Quantity::from(100))
2865            .build();
2866
2867        let events = if cached_partial_fill {
2868            let mut working_report = report.clone();
2869            working_report.order_status = NautilusOrderStatus::PartiallyFilled;
2870
2871            for event in generate_external_order_status_events(
2872                &order,
2873                &working_report,
2874                &account_id,
2875                &instrument,
2876                ts_init,
2877            ) {
2878                order.apply(event).unwrap();
2879            }
2880            assert_eq!(order.status(), NautilusOrderStatus::PartiallyFilled);
2881
2882            generate_reconciliation_order_events(&order, report, Some(&instrument), ts_init)
2883        } else {
2884            generate_external_order_status_events(&order, report, &account_id, &instrument, ts_init)
2885        };
2886
2887        assert!(matches!(events.last(), Some(OrderEventAny::Canceled(_))));
2888        for event in events {
2889            order.apply(event).unwrap();
2890        }
2891
2892        assert_eq!(order.status(), NautilusOrderStatus::Canceled);
2893        assert!(order.is_closed());
2894        assert!(!order.is_open());
2895        assert_eq!(order.quantity(), Quantity::from(100));
2896        assert_eq!(order.filled_qty(), Quantity::from(30));
2897        assert_eq!(order.avg_px(), Some(Decimal::from_str("150.25").unwrap()));
2898        assert!(
2899            generate_reconciliation_order_events(&order, report, Some(&instrument), ts_init)
2900                .is_empty()
2901        );
2902    }
2903
2904    // A 4-decimal instrument whose contract IB prices in a sub-unit 100 times the currency
2905    fn create_magnified_provider() -> (InteractiveBrokersInstrumentProvider, InstrumentId) {
2906        let provider = create_test_instrument_provider();
2907        let instrument = equity_aapl_itch();
2908        let instrument_id = instrument.id();
2909        provider.insert_test_instrument(InstrumentAny::from(instrument), 265_598, 100);
2910        (provider, instrument_id)
2911    }
2912
2913    fn create_test_order_status(average_fill_price: Option<f64>) -> OrderStatus {
2914        OrderStatus {
2915            order_id: 12345,
2916            status: OrderStatusKind::Submitted,
2917            filled: 3.0,
2918            remaining: 7.0,
2919            average_fill_price,
2920            perm_id: 0,
2921            parent_id: 0,
2922            last_fill_price: average_fill_price,
2923            client_id: 0,
2924            why_held: String::new(),
2925            market_cap_price: Some(0.0),
2926        }
2927    }
2928
2929    #[rstest]
2930    fn test_parse_execution_to_fill_report_divides_magnified_price() {
2931        let (provider, instrument_id) = create_magnified_provider();
2932
2933        let execution = Execution {
2934            order_id: 12345,
2935            client_id: 0,
2936            execution_id: String::from("EXEC-001"),
2937            time: String::from("20230223 00:43:36 Universal"),
2938            account_number: String::new(),
2939            exchange: String::new(),
2940            side: ExecutionSide::Bought,
2941            shares: 1.0,
2942            price: 425.25,
2943            perm_id: 0,
2944            liquidation: 0,
2945            cumulative_quantity: 1.0,
2946            average_price: 425.25,
2947            order_reference: String::from("ORDER-REF-001"),
2948            ev_rule: String::new(),
2949            ev_multiplier: None,
2950            model_code: String::new(),
2951            last_liquidity: Liquidity::None,
2952            pending_price_revision: false,
2953            submitter: String::new(),
2954        };
2955
2956        let fill = parse_execution_to_fill_report(
2957            &execution,
2958            &Contract::default(),
2959            1.0,
2960            "USD",
2961            instrument_id,
2962            AccountId::from("IB-001"),
2963            &provider,
2964            UnixNanos::new(0),
2965            None,
2966        )
2967        .unwrap();
2968
2969        assert_eq!(fill.last_px, Price::from("4.2525"));
2970    }
2971
2972    #[rstest]
2973    fn test_parse_order_status_to_report_divides_magnified_prices() {
2974        let (provider, instrument_id) = create_magnified_provider();
2975
2976        let order = Order {
2977            action: Action::Buy,
2978            total_quantity: 10.0,
2979            order_type: "STP LMT".to_string(),
2980            limit_price: Some(425.25),
2981            aux_price: Some(430.25),
2982            ..Default::default()
2983        };
2984
2985        let report = parse_order_status_to_report(
2986            &create_test_order_status(Some(425.5)),
2987            Some(&order),
2988            instrument_id,
2989            AccountId::from("IB-001"),
2990            &provider,
2991            UnixNanos::new(0),
2992        )
2993        .unwrap();
2994
2995        assert_eq!(report.price, Some(Price::from("4.2525")));
2996        assert_eq!(report.trigger_price, Some(Price::from("4.3025")));
2997        assert_eq!(report.avg_px, Some(Decimal::from_str("4.255").unwrap()));
2998    }
2999
3000    #[rstest]
3001    #[case(400.02, "4.0002")]
3002    #[case(486.75, "4.8675")]
3003    #[case(117.3, "1.173")]
3004    #[case(0.07, "0.0007")]
3005    fn test_parse_order_status_to_report_divides_magnified_avg_px_exactly(
3006        #[case] ib_avg_fill_price: f64,
3007        #[case] expected: &str,
3008    ) {
3009        let (provider, instrument_id) = create_magnified_provider();
3010
3011        let report = parse_order_status_to_report(
3012            &create_test_order_status(Some(ib_avg_fill_price)),
3013            None,
3014            instrument_id,
3015            AccountId::from("IB-001"),
3016            &provider,
3017            UnixNanos::new(0),
3018        )
3019        .unwrap();
3020
3021        assert_eq!(report.avg_px, Some(Decimal::from_str(expected).unwrap()));
3022    }
3023
3024    #[rstest]
3025    fn test_parse_order_status_to_report_divides_magnified_trailing_prices() {
3026        let (provider, instrument_id) = create_magnified_provider();
3027
3028        let order = Order {
3029            action: Action::Sell,
3030            total_quantity: 10.0,
3031            order_type: "TRAIL".to_string(),
3032            trail_stop_price: Some(481.25),
3033            aux_price: Some(5.25),
3034            ..Default::default()
3035        };
3036
3037        let report = parse_order_status_to_report(
3038            &create_test_order_status(Some(0.0)),
3039            Some(&order),
3040            instrument_id,
3041            AccountId::from("IB-001"),
3042            &provider,
3043            UnixNanos::new(0),
3044        )
3045        .unwrap();
3046
3047        assert_eq!(report.trigger_price, Some(Price::from("4.8125")));
3048        assert_eq!(
3049            report.trailing_offset,
3050            Some(Decimal::from_str("0.0525").unwrap())
3051        );
3052        assert_eq!(report.trailing_offset_type, Some(TrailingOffsetType::Price));
3053    }
3054}