Skip to main content

nautilus_kalshi/execution/
context.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
16use std::{
17    collections::{HashMap, HashSet},
18    sync::{Arc, Mutex},
19};
20
21use anyhow::Context;
22use nautilus_common::{
23    cache::{Cache, fifo::FifoCache},
24    messages::ExecutionReport,
25};
26use nautilus_core::{Params, UUID4, UnixNanos, time::get_atomic_clock_realtime};
27use nautilus_live::{ExecutionEventEmitter, execution::context::OrderContext};
28use nautilus_model::{
29    enums::{AccountType, OrderSide, OrderStatus, OrderType, PositionSide, TimeInForce},
30    events::{
31        AccountState, OrderAccepted, OrderCanceled, OrderDenied, OrderEventAny, OrderFilled,
32        OrderRejected, OrderSubmitted, OrderUpdated,
33    },
34    identifiers::{ClientOrderId, InstrumentId, StrategyId, TradeId, VenueOrderId},
35    instruments::BinaryOption,
36    orders::{LimitOrder, Order, OrderAny},
37    reports::{FillReport, OrderStatusReport, PositionStatusReport},
38    types::{AccountBalance, Currency, Price, Quantity},
39};
40use rust_decimal::Decimal;
41use serde::Deserialize;
42
43use super::{
44    account::{AccountLedger, ReservationId},
45    mutation::{Command, PendingMutation},
46    reports,
47    settlement::SettlementBarrier,
48    submit, timestamp,
49};
50use crate::{
51    common::enums::OrderType as VenueOrderType,
52    http::models::{
53        Field, FixedPoint, MarketPosition, Order as VenueOrder, OrderStatus as VenueStatus,
54    },
55    websocket::messages::KalshiWsMessage,
56};
57
58/// Execution state the private stream uses to turn venue evidence into order events.
59#[derive(Debug)]
60pub struct PrivateState {
61    pub(super) ledger: AccountLedger,
62    pub(super) barrier: Arc<Mutex<SettlementBarrier>>,
63    pub(super) orders: HashMap<ClientOrderId, PrivateOrder>,
64    pub(super) session: String,
65    pub(super) epoch: Option<(u64, u64)>,
66    pub(super) start: UnixNanos,
67    pub(super) submissions: HashSet<ClientOrderId>,
68    pub(super) batches: HashSet<UUID4>,
69    pub(super) mutations: HashMap<ClientOrderId, PendingMutation>,
70    pub(super) mutations_dispatched: HashSet<UUID4>,
71    bindings: HashMap<VenueOrderId, ClientOrderId>,
72    fills: FifoCache<TradeId, 100_000>,
73    pub(super) positions: HashMap<InstrumentId, Decimal>,
74    pub(super) external_leaves: HashMap<(InstrumentId, OrderSide), Decimal>,
75    positions_ts: HashMap<InstrumentId, UnixNanos>,
76    positions_initialized: bool,
77    notices_fills: HashMap<TradeId, FillNotice>,
78    covered_fills: HashMap<InstrumentId, UnixNanos>,
79    notices_orders: HashMap<VenueOrderId, OrderNotice>,
80    pub(super) notices_positions: HashMap<InstrumentId, PositionNotice>,
81}
82
83#[allow(
84    clippy::missing_panics_doc,
85    reason = "private state mutex poisoning is not expected"
86)]
87impl PrivateState {
88    /// Creates empty private execution state.
89    #[must_use]
90    #[allow(
91        clippy::new_without_default,
92        reason = "construction records a session id and clock time, so Default would not be stable"
93    )]
94    pub fn new() -> Self {
95        Self {
96            ledger: AccountLedger::new(),
97            barrier: Arc::new(Mutex::new(SettlementBarrier::default())),
98            orders: HashMap::new(),
99            session: UUID4::new().to_string(),
100            epoch: None,
101            start: get_atomic_clock_realtime().get_time_ns(),
102            submissions: HashSet::new(),
103            batches: HashSet::new(),
104            mutations: HashMap::new(),
105            mutations_dispatched: HashSet::new(),
106            bindings: HashMap::new(),
107            fills: FifoCache::new(),
108            positions: HashMap::new(),
109            external_leaves: HashMap::new(),
110            positions_ts: HashMap::new(),
111            positions_initialized: false,
112            notices_fills: HashMap::new(),
113            covered_fills: HashMap::new(),
114            notices_orders: HashMap::new(),
115            notices_positions: HashMap::new(),
116        }
117    }
118
119    pub(super) fn requires_rebase(&self, order: &OrderAny) -> bool {
120        !self.ledger.total_is_unknown()
121            && !order.trade_ids().is_empty()
122            && !self.orders.contains_key(&order.client_order_id())
123    }
124
125    pub(super) fn rebase(&mut self) {
126        self.ledger.rebase();
127        self.positions_initialized = false;
128        self.invalidate();
129    }
130
131    /// Records opening position evidence once.
132    ///
133    /// Later calls keep the first seed until an accounting rebase. Each restored order receives a
134    /// zero net when the seed omits its instrument.
135    ///
136    /// # Errors
137    ///
138    /// Returns an error if a supplied net overflows.
139    pub fn seed_positions(
140        &mut self,
141        positions: impl IntoIterator<Item = (InstrumentId, Decimal, UnixNanos)>,
142    ) -> anyhow::Result<()> {
143        if self.positions_initialized {
144            return Ok(());
145        }
146
147        let mut nets = HashMap::new();
148        let mut timestamps = HashMap::new();
149
150        for (id, qty, timestamp) in positions {
151            let net: &mut Decimal = nets.entry(id).or_insert(Decimal::ZERO);
152            *net = net
153                .checked_add(qty)
154                .context("cached account net overflow")?;
155            timestamps
156                .entry(id)
157                .and_modify(|ts: &mut UnixNanos| *ts = (*ts).max(timestamp))
158                .or_insert(timestamp);
159        }
160
161        for id in nets.keys() {
162            self.barrier
163                .lock()
164                .expect("settlement barrier lock")
165                .track(*id);
166        }
167
168        for context in self.orders.values() {
169            nets.entry(context.order.instrument_id())
170                .or_insert(Decimal::ZERO);
171        }
172
173        self.positions = nets;
174        self.positions_ts = timestamps;
175        self.positions_initialized = true;
176        Ok(())
177    }
178
179    /// Inserts or replaces one cached order when the incoming record is not older.
180    ///
181    /// A new cached order that already has fills rebases private cash when the ledger has a known
182    /// total.
183    pub fn restore(&mut self, order: OrderAny) {
184        if self.requires_rebase(&order) {
185            self.rebase();
186        }
187
188        let id = order.client_order_id();
189        let prior = self.orders.get(&id);
190        if prior.is_some_and(|prior| {
191            let cached_trades: HashSet<_> = order.trade_ids().into_iter().collect();
192            prior.order.ts_last() > order.ts_last()
193                || prior.order.venue_order_id().is_some() && order.venue_order_id().is_none()
194                || prior.order.is_closed() && !order.is_closed()
195                || prior
196                    .order
197                    .trade_ids()
198                    .into_iter()
199                    .any(|id| !cached_trades.contains(id))
200        }) {
201            return;
202        }
203
204        let source_ts = prior.map_or(order.ts_last(), |prior| {
205            prior.source_ts.max(order.ts_last())
206        });
207
208        let mut accounted = prior
209            .map(|prior| prior.accounted.clone())
210            .unwrap_or_default();
211
212        if self.ledger.total_is_unknown() {
213            for trade_id in order.trade_ids() {
214                self.fills.add(*trade_id);
215                accounted.insert(*trade_id);
216            }
217        }
218
219        self.barrier
220            .lock()
221            .expect("settlement barrier lock")
222            .track(order.instrument_id());
223        if prior.is_none() || !order.is_closed() {
224            self.start = self.start.min(order.ts_init());
225        }
226
227        self.invalidate();
228        self.orders.remove(&id);
229        let venue_id = order.venue_order_id();
230
231        let context = PrivateOrder {
232            order,
233            accounted,
234            source_ts,
235        };
236
237        if let Some(venue_id) = venue_id {
238            self.bindings.insert(venue_id, id);
239        }
240
241        self.orders.insert(id, context);
242    }
243
244    pub(super) fn submit(
245        &mut self,
246        order: &mut OrderAny,
247        hold: Decimal,
248        position_qty: Option<Decimal>,
249        emitter: &ExecutionEventEmitter,
250    ) -> anyhow::Result<()> {
251        let id = order.client_order_id();
252        anyhow::ensure!(
253            !self.orders.contains_key(&id),
254            "Kalshi order already tracked"
255        );
256        self.check_reduction(order, position_qty)?;
257        let now = get_atomic_clock_realtime().get_time_ns();
258        let event = OrderEventAny::Submitted(OrderSubmitted::new(
259            order.trader_id(),
260            order.strategy_id(),
261            order.instrument_id(),
262            id,
263            emitter.account_id(),
264            UUID4::new(),
265            now,
266            now,
267        ));
268        let mut next = order.clone();
269        next.apply(event.clone())?;
270        self.ledger.reserve(id, hold)?;
271        if let Err(e) = self
272            .publish_balance(emitter, now)
273            .and_then(|()| emitter.try_send_order_event(event))
274        {
275            self.ledger.release(id);
276
277            if let Err(e) = self.publish_balance(emitter, now) {
278                log::warn!("Kalshi admission balance rollback could not be routed: {e}");
279            }
280
281            return Err(e);
282        }
283
284        self.start = self.start.min(order.ts_init());
285        self.barrier
286            .lock()
287            .expect("settlement barrier lock")
288            .track(order.instrument_id());
289        self.orders.insert(
290            id,
291            PrivateOrder {
292                source_ts: next.ts_last(),
293                order: next.clone(),
294                accounted: HashSet::new(),
295            },
296        );
297
298        *order = next;
299        Ok(())
300    }
301
302    fn check_reduction(
303        &self,
304        order: &OrderAny,
305        position_qty: Option<Decimal>,
306    ) -> anyhow::Result<()> {
307        if !order.is_reduce_only() {
308            return self.check_position_flow(order);
309        }
310
311        let id = order.instrument_id();
312        let side = order.order_side();
313        let net = self.positions.get(&id).copied().unwrap_or(Decimal::ZERO);
314        anyhow::ensure!(
315            net > Decimal::ZERO && side == OrderSide::Sell
316                || net < Decimal::ZERO && side == OrderSide::Buy,
317            "Kalshi reduce-only side does not reduce the account net"
318        );
319        let mut available = net
320            .abs()
321            .checked_sub(
322                self.external_leaves
323                    .get(&(id, side))
324                    .copied()
325                    .unwrap_or(Decimal::ZERO),
326            )
327            .context("Kalshi reducible quantity overflow")?;
328
329        for context in self.orders.values() {
330            let pending = &context.order;
331            if !pending.is_closed() && pending.instrument_id() == id && pending.order_side() == side
332            {
333                available = available
334                    .checked_sub(pending.leaves_qty().as_decimal())
335                    .context("Kalshi reducible quantity overflow")?;
336            }
337        }
338
339        anyhow::ensure!(
340            order.quantity().as_decimal() <= available,
341            "Kalshi reduce-only quantity exceeds the unreserved account net"
342        );
343        self.check_position_flow(order)?;
344        let position_qty = position_qty
345            .context("Kalshi reduce-only requires a strategy-owned canonical position")?;
346        anyhow::ensure!(
347            position_qty > Decimal::ZERO && side == OrderSide::Sell
348                || position_qty < Decimal::ZERO && side == OrderSide::Buy,
349            "Kalshi reduce-only side does not reduce the canonical position"
350        );
351        anyhow::ensure!(
352            order.quantity().as_decimal() <= position_qty.abs(),
353            "Kalshi reduce-only quantity exceeds the canonical position"
354        );
355        Ok(())
356    }
357
358    fn check_position_flow(&self, order: &OrderAny) -> anyhow::Result<()> {
359        anyhow::ensure!(
360            !self.orders.values().any(|context| {
361                let pending = &context.order;
362                !pending.is_closed()
363                    && pending.instrument_id() == order.instrument_id()
364                    && pending.strategy_id() == order.strategy_id()
365                    && (order.is_reduce_only() || pending.is_reduce_only())
366            }),
367            "Kalshi reduce-only requires exclusive strategy-instrument order flow"
368        );
369
370        if order.is_reduce_only() {
371            let id = order.instrument_id();
372            let side = order.order_side();
373            anyhow::ensure!(
374                self.external_leaves
375                    .get(&(id, side))
376                    .is_none_or(Decimal::is_zero)
377                    && !self.orders.values().any(|context| {
378                        let pending = &context.order;
379                        !pending.is_closed()
380                            && pending.instrument_id() == id
381                            && pending.order_side() == side
382                            && pending.strategy_id().is_external()
383                    }),
384                "Kalshi reduce-only requires resolved external orders on its reducing side"
385            );
386        }
387
388        Ok(())
389    }
390
391    pub(super) fn deny_submission(
392        &mut self,
393        order: &mut OrderAny,
394        reason: &str,
395        emitter: &ExecutionEventEmitter,
396    ) -> anyhow::Result<()> {
397        let id = order.client_order_id();
398        if let Some(prior) = self.orders.get(&id)
399            && prior.order.status() != OrderStatus::Initialized
400        {
401            *order = prior.order.clone();
402            return Ok(());
403        }
404
405        let now = get_atomic_clock_realtime().get_time_ns();
406        let event = OrderEventAny::Denied(OrderDenied::new(
407            order.trader_id(),
408            order.strategy_id(),
409            order.instrument_id(),
410            id,
411            reason.into(),
412            UUID4::new(),
413            now,
414            now,
415        ));
416        order.apply(event.clone())?;
417
418        let prior = self.orders.insert(
419            id,
420            PrivateOrder {
421                source_ts: order.ts_last(),
422                order: order.clone(),
423                accounted: HashSet::new(),
424            },
425        );
426
427        // A restored initialized order can own a hold in the in-flight recovery
428        if prior.is_some() {
429            self.ledger.invalidate();
430        }
431
432        emitter.try_send_order_event(event)
433    }
434
435    pub(super) fn acknowledge(
436        &mut self,
437        id: ClientOrderId,
438        venue_id: VenueOrderId,
439        ts_event: UnixNanos,
440        emitter: &ExecutionEventEmitter,
441    ) -> anyhow::Result<()> {
442        anyhow::ensure!(
443            self.bindings
444                .get(&venue_id)
445                .is_none_or(|owner| *owner == id),
446            "Kalshi acknowledgement venue identity mismatch"
447        );
448        let context = self
449            .orders
450            .get_mut(&id)
451            .context("Kalshi submission context missing")?;
452        anyhow::ensure!(
453            context
454                .order
455                .venue_order_id()
456                .is_none_or(|known| known == venue_id),
457            "Kalshi acknowledgement order identity mismatch"
458        );
459
460        if context.order.venue_order_id().is_some() || context.order.is_closed() {
461            return Ok(());
462        }
463
464        let order = &context.order;
465        let now = get_atomic_clock_realtime().get_time_ns();
466        let event = OrderEventAny::Accepted(OrderAccepted::new(
467            order.trader_id(),
468            order.strategy_id(),
469            order.instrument_id(),
470            id,
471            venue_id,
472            emitter.account_id(),
473            UUID4::new(),
474            ts_event,
475            now,
476            false,
477        ));
478        let mut next = order.clone();
479        next.apply(event.clone())?;
480        emitter.try_send_order_event(event)?;
481        context.order = next;
482        self.bindings.insert(venue_id, id);
483        self.ledger.invalidate();
484        Ok(())
485    }
486
487    pub(super) fn resolve_mutation(
488        &mut self,
489        command: &Command,
490        order: &OrderAny,
491        reason: &str,
492        denied: bool,
493        emitter: &ExecutionEventEmitter,
494    ) -> anyhow::Result<()> {
495        let id = order.client_order_id();
496
497        if !self
498            .mutations
499            .get(&id)
500            .is_some_and(|pending| pending.command_id == command.id())
501        {
502            return Ok(());
503        }
504
505        let Some(context) = self.orders.get_mut(&id) else {
506            self.mutations.remove(&id);
507            return Ok(());
508        };
509
510        if !context.order.is_closed() {
511            let claimed = context.order.strategy_id().is_external()
512                && context.order.strategy_id() != order.strategy_id();
513            let event = if claimed {
514                command.outcome_at(order, context.order.ts_last(), reason, denied, emitter)
515            } else {
516                command.outcome(&context.order, reason, denied, emitter)
517            };
518
519            if !claimed {
520                let mut next = context.order.clone();
521                next.apply(event.clone())?;
522                context.order = next;
523            }
524
525            emitter.try_send_order_event(event)?;
526        }
527
528        self.mutations.remove(&id);
529        self.ledger.invalidate();
530        Ok(())
531    }
532
533    pub(super) fn reject_submission(
534        &mut self,
535        id: ClientOrderId,
536        reason: &str,
537        due_post_only: bool,
538        emitter: &ExecutionEventEmitter,
539    ) -> anyhow::Result<()> {
540        let context = self
541            .orders
542            .get_mut(&id)
543            .context("Kalshi submission context missing")?;
544        anyhow::ensure!(
545            context.order.venue_order_id().is_none() && !context.order.is_closed(),
546            "Kalshi submission already has venue evidence"
547        );
548        let order = &context.order;
549        let now = get_atomic_clock_realtime().get_time_ns();
550        let event = OrderEventAny::Rejected(OrderRejected::new(
551            order.trader_id(),
552            order.strategy_id(),
553            order.instrument_id(),
554            id,
555            emitter.account_id(),
556            reason.into(),
557            UUID4::new(),
558            now,
559            now,
560            false,
561            due_post_only,
562        ));
563        let mut next = order.clone();
564        next.apply(event.clone())?;
565        emitter.try_send_order_event(event)?;
566        context.order = next;
567        self.ledger.release(id);
568        self.publish_balance(emitter, now)
569    }
570
571    pub(super) fn publish_balance(
572        &self,
573        emitter: &ExecutionEventEmitter,
574        ts_event: UnixNanos,
575    ) -> anyhow::Result<()> {
576        let balance = self.ledger.balance()?;
577
578        let info = Params::new(
579            [(
580                "kalshi_session".into(),
581                serde_json::Value::String(self.session.clone()),
582            )]
583            .into(),
584        );
585
586        let account = AccountState::new(
587            emitter.account_id(),
588            AccountType::Cash,
589            vec![balance],
590            Vec::new(),
591            true,
592            UUID4::new(),
593            ts_event,
594            get_atomic_clock_realtime().get_time_ns(),
595            Some(Currency::USD()),
596        )
597        .with_info(Some(info));
598        emitter.try_send_account_state(account)
599    }
600
601    pub(super) fn invalidate(&mut self) {
602        self.session = UUID4::new().to_string();
603        self.epoch = None;
604        self.ledger.invalidate();
605        self.barrier
606            .lock()
607            .expect("settlement barrier lock")
608            .invalidate(&self.session);
609    }
610
611    pub(super) fn notice(&mut self, message: &KalshiWsMessage) -> anyhow::Result<()> {
612        self.invalidate();
613
614        match message {
615            KalshiWsMessage::Fill(data) => self.notice_fill(&data.msg),
616            KalshiWsMessage::UserOrder(data) => self.notice_order(&data.msg),
617            KalshiWsMessage::MarketPosition(data) => self.notice_position(&data.msg),
618            _ => Ok(()),
619        }
620    }
621
622    fn notice_fill(&mut self, value: &serde_json::Value) -> anyhow::Result<()> {
623        let raw = value
624            .get("trade_id")
625            .and_then(serde_json::Value::as_str)
626            .context("private fill notification lacks stable identity")?;
627        let id = TradeId::new_checked(raw)?;
628
629        if let Some(alias) = value.get("fill_id").and_then(serde_json::Value::as_str) {
630            anyhow::ensure!(
631                alias == raw,
632                "private fill notification identities disagree"
633            );
634        }
635
636        let instrument_id = value
637            .get("market_ticker")
638            .and_then(serde_json::Value::as_str)
639            .context("private fill notification lacks market identity")
640            .and_then(crate::common::parse::parse_instrument_id);
641
642        let start = value
643            .get("ts_ms")
644            .and_then(serde_json::Value::as_u64)
645            .and_then(|time| time.checked_mul(1_000_000))
646            .map(UnixNanos::from)
647            .or_else(|| {
648                value
649                    .get("ts")
650                    .and_then(serde_json::Value::as_u64)
651                    .and_then(|time| time.checked_mul(1_000_000_000))
652                    .map(UnixNanos::from)
653            })
654            .unwrap_or_default();
655
656        let notice = FillNotice {
657            instrument: instrument_id.as_ref().ok().copied(),
658            ts_event: start,
659        };
660
661        self.notices_fills.insert(id, notice);
662        self.start = self.start.min(start);
663        instrument_id?;
664        Ok(())
665    }
666
667    fn notice_order(&mut self, value: &serde_json::Value) -> anyhow::Result<()> {
668        let id = VenueOrderId::new_checked(
669            value
670                .get("order_id")
671                .and_then(serde_json::Value::as_str)
672                .context("private order notification lacks identity")?,
673        )?;
674
675        let updated = value
676            .get("last_updated_ts_ms")
677            .and_then(serde_json::Value::as_u64)
678            .map(|time| {
679                time.checked_mul(1_000_000)
680                    .context("private order notification timestamp overflow")
681            })
682            .transpose()?
683            .map(UnixNanos::from);
684
685        let notice = self.notices_orders.entry(id).or_insert(OrderNotice {
686            filled: Decimal::ZERO,
687            updated,
688        });
689
690        notice.updated = notice.updated.max(updated);
691        let filled: FixedPoint = serde_json::from_value(
692            value
693                .get("fill_count_fp")
694                .context("private order notification lacks filled count")?
695                .clone(),
696        )?;
697        anyhow::ensure!(
698            filled.0 >= Decimal::ZERO,
699            "negative private order notification count"
700        );
701        notice.filled = notice.filled.max(filled.0);
702
703        let has_new_fills = self
704            .bindings
705            .get(&id)
706            .and_then(|id| self.orders.get(id))
707            .is_some_and(|context| notice.filled > context.order.filled_qty().as_decimal());
708
709        if self.has_external_order(id) && !has_new_fills {
710            return Ok(());
711        }
712
713        let start = self
714            .bindings
715            .get(&id)
716            .and_then(|id| self.orders.get(id))
717            .map(|context| context.order.ts_init())
718            .or_else(|| {
719                value
720                    .get("created_ts_ms")
721                    .and_then(serde_json::Value::as_u64)
722                    .and_then(|time| time.checked_mul(1_000_000))
723                    .map(UnixNanos::from)
724            })
725            .unwrap_or_default();
726
727        self.start = self.start.min(start);
728        Ok(())
729    }
730
731    fn notice_position(&mut self, value: &serde_json::Value) -> anyhow::Result<()> {
732        let ticker = value
733            .get("market_ticker")
734            .and_then(serde_json::Value::as_str)
735            .context("private position notification lacks market identity")?;
736        let id = crate::common::parse::parse_instrument_id(ticker)?;
737
738        let notice = self.notices_positions.entry(id).or_insert(PositionNotice {
739            volume: Decimal::ZERO,
740            economics: None,
741        });
742
743        notice.economics = None;
744        let volume: FixedPoint = serde_json::from_value(
745            value
746                .get("volume_fp")
747                .context("private position notification lacks traded volume")?
748                .clone(),
749        )?;
750        anyhow::ensure!(
751            volume.0 >= Decimal::ZERO,
752            "negative private position traded volume"
753        );
754        notice.volume = notice.volume.max(volume.0);
755        notice.economics = Some(serde_json::from_value(value.clone())?);
756        Ok(())
757    }
758
759    pub(super) fn recovery_targets(&self) -> Vec<InstrumentId> {
760        self.positions
761            .iter()
762            .filter(|(_, net)| !net.is_zero())
763            .map(|(id, _)| *id)
764            .chain(self.notices_positions.keys().copied())
765            .collect()
766    }
767
768    pub(super) fn external_order_notices(&self) -> Vec<VenueOrderId> {
769        self.notices_orders
770            .keys()
771            .filter(|id| self.has_external_order(**id))
772            .copied()
773            .collect()
774    }
775
776    fn has_external_order(&self, id: VenueOrderId) -> bool {
777        self.ledger.has_external(id)
778            || self
779                .bindings
780                .get(&id)
781                .and_then(|id| self.orders.get(id))
782                .is_some_and(|context| context.order.strategy_id().is_external())
783    }
784
785    pub(super) fn check_notices(
786        &mut self,
787        snapshot: &super::KalshiExecutionSnapshot,
788        plans: &[OrderPlan],
789    ) -> anyhow::Result<()> {
790        let fills: HashMap<_, _> = snapshot
791            .fills
792            .iter()
793            .map(|fill| (fill.fill_id.as_str(), fill))
794            .collect();
795
796        for (id, notice) in &mut self.notices_fills {
797            let fill = fills
798                .get(id.as_str())
799                .context("REST recovery does not yet cover received fill identities")?;
800
801            if let Some(expected) = notice.instrument {
802                let actual = crate::common::parse::parse_instrument_id(&fill.ticker)?;
803                anyhow::ensure!(
804                    actual == expected,
805                    "REST recovery does not yet cover received fill identities"
806                );
807            }
808
809            notice.ts_event = timestamp(&fill.created_time)?;
810        }
811
812        let orders: HashMap<_, _> = snapshot
813            .orders
814            .iter()
815            .map(|order| (order.order_id.as_str(), order))
816            .collect();
817
818        for (id, notice) in &self.notices_orders {
819            let order = orders
820                .get(id.as_str())
821                .context("REST recovery lacks a notified order")?;
822            anyhow::ensure!(
823                order.fill_count_fp.0 >= notice.filled,
824                "REST order does not yet cover notified fills"
825            );
826
827            if let Some(updated) = notice.updated {
828                anyhow::ensure!(
829                    timestamp(&order.last_update_time)? >= updated,
830                    "REST order does not yet cover notified update time"
831                );
832            }
833        }
834
835        if self.notices_positions.is_empty() {
836            self.record_execution(plans);
837            return Ok(());
838        }
839
840        let orders: HashMap<_, _> = self
841            .orders
842            .values()
843            .map(|context| (context.order.client_order_id(), &context.order))
844            .chain(
845                plans
846                    .iter()
847                    .map(|plan| (plan.result.client_order_id(), &plan.result)),
848            )
849            .collect();
850
851        for (id, notice) in &self.notices_positions {
852            let economics = notice
853                .economics
854                .as_ref()
855                .context("private position notification remains malformed")?;
856            let position = snapshot
857                .positions
858                .iter()
859                .chain(&snapshot.positions_settled)
860                .find(|position| position.ticker == id.symbol.as_str())
861                .context("REST recovery lacks a notified position")?;
862            // WebSocket realized PnL includes fees; REST realized PnL excludes them
863            let net_pnl = position
864                .realized_pnl_dollars
865                .0
866                .checked_sub(position.fees_paid_dollars.0)
867                .context("private position PnL overflow")?;
868            anyhow::ensure!(
869                position.position_fp == economics.position_fp
870                    && net_pnl == economics.realized_pnl_dollars.0
871                    && position.fees_paid_dollars == economics.fees_paid_dollars,
872                "REST position does not yet cover notified economics"
873            );
874
875            // Only retained coverage is bounded by newer execution evidence
876            if self.has_fill_notice(*id) {
877                if self
878                    .notices_fills
879                    .values()
880                    .any(|notice| notice.instrument == Some(*id))
881                {
882                    continue;
883                }
884
885                if !self.covered_fills.contains_key(id) {
886                    continue;
887                }
888
889                let latest = self
890                    .covered_fills
891                    .get(id)
892                    .copied()
893                    .into_iter()
894                    .chain(
895                        plans
896                            .iter()
897                            .filter(|plan| plan.result.instrument_id() == *id)
898                            .flat_map(|plan| &plan.fresh)
899                            .map(|(_, fill)| fill.ts_event),
900                    )
901                    .chain(
902                        plans
903                            .iter()
904                            .filter(|plan| plan.result.instrument_id() == *id)
905                            .map(|plan| plan.source_ts),
906                    )
907                    .max();
908                let updated = timestamp(&Field::Value(position.last_updated_ts))?;
909
910                if latest.is_some_and(|latest| updated <= latest) {
911                    continue;
912                }
913
914                self.start = self
915                    .orders
916                    .values()
917                    .filter(|context| context.order.instrument_id() == *id)
918                    .fold(self.start, |start, context| {
919                        start.min(context.order.ts_init())
920                    });
921            }
922
923            let volume = orders
924                .values()
925                .filter(|order| order.instrument_id() == *id)
926                .try_fold(Decimal::ZERO, |total, order| {
927                    total
928                        .checked_add(order.filled_qty().as_decimal())
929                        .context("private traded volume overflow")
930                })?;
931
932            anyhow::ensure!(
933                volume >= notice.volume,
934                "REST recovery does not yet cover notified traded volume"
935            );
936        }
937
938        self.record_execution(plans);
939        Ok(())
940    }
941
942    fn record_execution(&mut self, plans: &[OrderPlan]) {
943        for plan in plans {
944            let instrument = plan.result.instrument_id();
945            for notice in self.notices_fills.values_mut() {
946                if notice.instrument == Some(instrument) {
947                    notice.ts_event = notice.ts_event.max(plan.source_ts);
948                }
949            }
950
951            if let Some(timestamp) = self.covered_fills.get_mut(&instrument) {
952                *timestamp = (*timestamp).max(plan.source_ts);
953            }
954        }
955    }
956
957    pub(super) fn has_fill_notice(&self, instrument_id: InstrumentId) -> bool {
958        self.covered_fills.contains_key(&instrument_id)
959            || self
960                .notices_fills
961                .values()
962                .any(|notice| notice.instrument == Some(instrument_id))
963    }
964
965    pub(super) fn clear_notices(&mut self) {
966        for notice in self.notices_fills.values() {
967            if let Some(instrument) = notice.instrument
968                && !self.notices_positions.contains_key(&instrument)
969            {
970                self.covered_fills
971                    .entry(instrument)
972                    .and_modify(|timestamp| *timestamp = (*timestamp).max(notice.ts_event))
973                    .or_insert(notice.ts_event);
974            }
975        }
976
977        for instrument in self.notices_positions.keys() {
978            self.covered_fills.remove(instrument);
979        }
980
981        self.notices_fills.clear();
982        self.notices_orders.clear();
983        self.notices_positions.clear();
984    }
985
986    pub(super) fn advance_recovery(&mut self, start: UnixNanos) {
987        let start = self
988            .orders
989            .values()
990            .filter(|context| {
991                !context.order.is_closed() && context.order.venue_order_id().is_none()
992            })
993            .fold(start, |start, context| start.min(context.order.ts_init()));
994
995        self.start = self
996            .barrier
997            .lock()
998            .expect("settlement barrier lock")
999            .recovery_start(start, self.start);
1000    }
1001
1002    pub(super) fn source_order(&self, value: &VenueOrder) -> anyhow::Result<Option<OrderAny>> {
1003        let venue_id = VenueOrderId::new_checked(&value.order_id)?;
1004        let wire_id = (!value.client_order_id.is_empty())
1005            .then(|| ClientOrderId::new_checked(&value.client_order_id))
1006            .transpose()?;
1007
1008        let by_venue = self
1009            .bindings
1010            .get(&venue_id)
1011            .and_then(|id| self.orders.get(id));
1012
1013        let by_client = wire_id.and_then(|id| self.orders.get(&id));
1014        anyhow::ensure!(
1015            by_venue
1016                .zip(by_client)
1017                .is_none_or(|(a, b)| a.order.client_order_id() == b.order.client_order_id()),
1018            "private order identities disagree"
1019        );
1020        let order = by_client.or(by_venue);
1021        if order.is_none() && wire_id.is_none() {
1022            let id = ClientOrderId::new_checked(&value.order_id)?;
1023            anyhow::ensure!(
1024                !self.orders.contains_key(&id),
1025                "recovered order identity conflicts with an existing order"
1026            );
1027        }
1028
1029        if let Some(order) = order {
1030            let rejected = order.order.status() == OrderStatus::Rejected;
1031
1032            let unsent = order.order.status() == OrderStatus::Denied
1033                || rejected
1034                    && order.order.events().into_iter().any(|event| {
1035                        matches!(
1036                            event,
1037                            OrderEventAny::Rejected(rejected) if rejected.reason.as_str() == submit::NOT_SENT_REASON
1038                        )
1039                    });
1040
1041            let recoverable_rejection =
1042                value.status == VenueStatus::Canceled && value.fill_count_fp.0.is_zero();
1043
1044            anyhow::ensure!(
1045                !unsent && (!rejected || recoverable_rejection),
1046                "venue evidence conflicts with an unsent Kalshi order"
1047            );
1048            anyhow::ensure!(
1049                order.order.venue_order_id().is_none_or(|id| id == venue_id)
1050                    && wire_id.is_none_or(|id| id == order.order.client_order_id()),
1051                "private venue order binding mismatch"
1052            );
1053        }
1054
1055        Ok(order.map(|context| context.order.clone()))
1056    }
1057
1058    /// Plans the order and fill events one venue order requires.
1059    ///
1060    /// Returns `Ok(None)` when the venue record is already covered. The plan is not emitted until
1061    /// [`Self::apply_plans`].
1062    ///
1063    /// Owned limit orders retain independently valid fills with an unmapped type or status.
1064    /// These plans keep recovery unresolved. Fills that require unconfirmed quantity wait for
1065    /// authoritative order terms.
1066    ///
1067    /// # Errors
1068    ///
1069    /// Returns an error if identity, counts, prices, or timestamps are inconsistent, an external
1070    /// order has an unmapped classification, or fills require unconfirmed order quantity.
1071    pub fn plan_order(
1072        &self,
1073        source: &VenueOrder,
1074        fills: &[FillReport],
1075        instrument: &BinaryOption,
1076        emitter: &ExecutionEventEmitter,
1077        ts_init: UnixNanos,
1078    ) -> anyhow::Result<Option<OrderPlan>> {
1079        let mut order = self
1080            .recovery_order(source, instrument, emitter, ts_init)?
1081            .context("external Kalshi order lacks recoverable quantity")?;
1082        let context = OrderContext::from(&order);
1083        let mapped =
1084            source.order_type == VenueOrderType::Limit && source.status != VenueStatus::Unknown;
1085
1086        if !mapped {
1087            log::warn!(
1088                "Observed unmapped Kalshi order classification, order_id={}, ticker={}, type={:?}, status={:?}",
1089                source.order_id,
1090                source.ticker,
1091                source.order_type,
1092                source.status
1093            );
1094            anyhow::ensure!(
1095                !order.strategy_id().is_external(),
1096                "unmapped external Kalshi order classification"
1097            );
1098        }
1099
1100        let id = context.identity.client_order_id;
1101        let venue_id = VenueOrderId::new_checked(&source.order_id)?;
1102        let ts_accepted = timestamp(&source.created_time)?;
1103        let ts_last = timestamp(&source.last_update_time)?;
1104        anyhow::ensure!(
1105            ts_last >= ts_accepted,
1106            "private order timestamps out of sequence"
1107        );
1108        anyhow::ensure!(
1109            context.identity.instrument_id == instrument.id
1110                && order
1111                    .account_id()
1112                    .is_none_or(|id| id == emitter.account_id())
1113                && (source.order_type == VenueOrderType::Limit
1114                    || matches!(source.order_type, VenueOrderType::Other(_)))
1115                && context.identity.order_type == OrderType::Limit
1116                && reports::direction(source.book_side, source.outcome_side)?
1117                    == context.identity.order_side,
1118            "private order identity or direction mismatch"
1119        );
1120        reports::complementary(source.yes_price_dollars, source.no_price_dollars)?;
1121        anyhow::ensure!(
1122            source.fill_count_fp.0 >= Decimal::ZERO && source.remaining_count_fp.0 >= Decimal::ZERO,
1123            "negative private order count"
1124        );
1125        anyhow::ensure!(
1126            source.status != VenueStatus::Executed
1127                || source.remaining_count_fp.0.is_zero() && source.fill_count_fp.0 > Decimal::ZERO,
1128            "invalid executed order counts"
1129        );
1130
1131        if self.order_is_stale(source, fills, &order, ts_last) {
1132            return Ok(None);
1133        }
1134
1135        self.check_settled_order(source, fills, &order, instrument.id)?;
1136
1137        let original = order.clone();
1138        let mut before = Vec::new();
1139        let mut fresh = Vec::new();
1140        let mut after = Vec::new();
1141
1142        if !order.is_closed() && order.venue_order_id().is_none() {
1143            let accepted = OrderAccepted::new(
1144                order.trader_id(),
1145                order.strategy_id(),
1146                instrument.id,
1147                id,
1148                venue_id,
1149                emitter.account_id(),
1150                UUID4::new(),
1151                ts_accepted,
1152                ts_init,
1153                false,
1154            );
1155
1156            let event = OrderEventAny::Accepted(accepted);
1157            order.apply(event.clone())?;
1158            before.push(event);
1159        }
1160
1161        if let Some((quantity, price)) =
1162            self.recovery_terms(&order, source, instrument, ts_last, mapped)?
1163        {
1164            let update = OrderUpdated::new(
1165                order.trader_id(),
1166                order.strategy_id(),
1167                instrument.id,
1168                id,
1169                quantity,
1170                UUID4::new(),
1171                ts_last,
1172                ts_init,
1173                true,
1174                Some(venue_id),
1175                Some(emitter.account_id()),
1176                Some(price),
1177                None,
1178                None,
1179                false,
1180            );
1181
1182            let event = OrderEventAny::Updated(update);
1183            order.apply(event.clone())?;
1184            before.push(event);
1185        }
1186
1187        let before_status = order.status();
1188        let before_filled = order.filled_qty();
1189
1190        for fill in fills {
1191            if self.fill_accounted(id, fill.trade_id) {
1192                continue;
1193            }
1194
1195            anyhow::ensure!(
1196                fill.instrument_id == instrument.id
1197                    && fill.account_id == emitter.account_id()
1198                    && fill.venue_order_id == venue_id
1199                    && fill.order_side == context.identity.order_side
1200                    && fill.commission.currency == Currency::USD()
1201                    && fill.commission.as_decimal() >= Decimal::ZERO
1202                    && fill.ts_event >= ts_accepted
1203                    && fill.ts_event <= ts_last,
1204                "private fill identity or fee mismatch"
1205            );
1206
1207            if order.trade_ids().contains(&&fill.trade_id) {
1208                fresh.push((None, fill.clone()));
1209                continue;
1210            }
1211
1212            let filled = OrderFilled::new(
1213                order.trader_id(),
1214                order.strategy_id(),
1215                instrument.id,
1216                id,
1217                venue_id,
1218                emitter.account_id(),
1219                fill.trade_id,
1220                context.identity.order_side,
1221                context.identity.order_type,
1222                fill.last_qty,
1223                fill.last_px,
1224                Currency::USD(),
1225                fill.liquidity_side,
1226                UUID4::new(),
1227                fill.ts_event,
1228                ts_init,
1229                false,
1230                None,
1231                Some(fill.commission),
1232                None,
1233            );
1234
1235            let event = OrderEventAny::Filled(filled);
1236            order.apply(event.clone())?;
1237            fresh.push((Some(event), fill.clone()));
1238        }
1239
1240        anyhow::ensure!(
1241            order.filled_qty().as_decimal() == source.fill_count_fp.0,
1242            "private order fill coverage is incomplete"
1243        );
1244
1245        if mapped
1246            && source.status == VenueStatus::Canceled
1247            && self.order_is_current(&order, source, ts_last)
1248        {
1249            let canceled = OrderCanceled::new(
1250                order.trader_id(),
1251                order.strategy_id(),
1252                instrument.id,
1253                id,
1254                UUID4::new(),
1255                ts_last,
1256                ts_init,
1257                false,
1258                Some(venue_id),
1259                Some(emitter.account_id()),
1260                None,
1261            );
1262
1263            let event = OrderEventAny::Canceled(canceled);
1264            order.apply(event.clone())?;
1265            after.push(event);
1266        }
1267
1268        let external = if order.strategy_id().is_external() {
1269            Some(
1270                reports::order(
1271                    source,
1272                    instrument,
1273                    emitter.account_id(),
1274                    Some(&order),
1275                    ts_init,
1276                )?
1277                .context("external Kalshi order metadata is incomplete")?,
1278            )
1279        } else {
1280            None
1281        };
1282
1283        let external_before = external
1284            .as_ref()
1285            .filter(|_| !before.is_empty())
1286            .map(|report| {
1287                let mut report = report.clone();
1288                report.order_status = before_status;
1289                report.filled_qty = before_filled;
1290                report
1291            });
1292
1293        Ok(Some(OrderPlan {
1294            original,
1295            result: order,
1296            venue_id,
1297            before,
1298            fresh,
1299            after,
1300            external,
1301            external_before,
1302            source_ts: ts_last,
1303            mapped,
1304        }))
1305    }
1306
1307    fn recovery_terms(
1308        &self,
1309        order: &OrderAny,
1310        source: &VenueOrder,
1311        instrument: &BinaryOption,
1312        ts_last: UnixNanos,
1313        mapped: bool,
1314    ) -> anyhow::Result<Option<(Quantity, Price)>> {
1315        reports::quantity(source.fill_count_fp, instrument.size_precision)?;
1316        reports::quantity(source.remaining_count_fp, instrument.size_precision)?;
1317        let qty = source
1318            .fill_count_fp
1319            .0
1320            .checked_add(source.remaining_count_fp.0)
1321            .context("private order count overflow")?;
1322        let price =
1323            crate::data::parse::price(source.yes_price_dollars, instrument.price_precision)?;
1324
1325        let (qty, price) = if mapped {
1326            (qty, price)
1327        } else {
1328            let known_qty = order.quantity().as_decimal();
1329
1330            let increase_pending = order.has_pending_update_command()
1331                || self
1332                    .mutations
1333                    .get(&order.client_order_id())
1334                    .is_some_and(|pending| {
1335                        pending.dispatched
1336                            && pending.terms.is_some_and(|(qty, _)| qty > order.quantity())
1337                    });
1338
1339            anyhow::ensure!(
1340                source.remaining_count_fp.0 > Decimal::ZERO
1341                    || source.fill_count_fp.0 <= known_qty
1342                        && !(increase_pending && source.fill_count_fp.0 == known_qty),
1343                "Kalshi fills require authoritative order quantity"
1344            );
1345
1346            let qty = if source.remaining_count_fp.0 > Decimal::ZERO {
1347                qty.max(known_qty)
1348            } else {
1349                known_qty
1350            };
1351
1352            anyhow::ensure!(
1353                qty == known_qty
1354                    || !order.has_pending_update_command()
1355                        && !order.has_pending_cancel_command()
1356                        && !self.mutations.contains_key(&order.client_order_id()),
1357                "Kalshi fills require authoritative order quantity"
1358            );
1359
1360            (qty, order.price().context("owned limit order lacks price")?)
1361        };
1362
1363        if (mapped && source.status == VenueStatus::Canceled)
1364            || !self.order_is_current(order, source, ts_last)
1365            || order.quantity().as_decimal() == qty && order.price() == Some(price)
1366        {
1367            return Ok(None);
1368        }
1369
1370        let quantity = Quantity::from_decimal_dp(qty, instrument.size_precision)?;
1371        Ok(Some((quantity, price)))
1372    }
1373
1374    pub(super) fn recovery_order(
1375        &self,
1376        source: &VenueOrder,
1377        instrument: &BinaryOption,
1378        emitter: &ExecutionEventEmitter,
1379        ts_init: UnixNanos,
1380    ) -> anyhow::Result<Option<OrderAny>> {
1381        if let Some(order) = self.source_order(source)? {
1382            return Ok(Some(order));
1383        }
1384
1385        // Resting totals are authoritative from their filled and remaining counts
1386        if source.fill_count_fp.0.is_zero() && source.status != VenueStatus::Resting {
1387            return Ok(None);
1388        }
1389
1390        let Some(report) = reports::order(source, instrument, emitter.account_id(), None, ts_init)?
1391        else {
1392            return Ok(None);
1393        };
1394
1395        let client_order_id = report
1396            .client_order_id
1397            .unwrap_or_else(|| ClientOrderId::from(report.venue_order_id.as_str()));
1398
1399        let order_ts_init = if source.fill_count_fp.0.is_zero() {
1400            ts_init
1401        } else {
1402            report.ts_accepted
1403        };
1404
1405        let order = LimitOrder::new_checked(
1406            emitter.trader_id(),
1407            StrategyId::external(),
1408            instrument.id,
1409            client_order_id,
1410            report.order_side.context("recovered order lacks side")?,
1411            report.quantity,
1412            report.price.context("recovered order lacks price")?,
1413            report.time_in_force,
1414            report.expire_time,
1415            report.post_only,
1416            report.reduce_only,
1417            false,
1418            None,
1419            None,
1420            None,
1421            None,
1422            None,
1423            None,
1424            None,
1425            None,
1426            None,
1427            None,
1428            None,
1429            UUID4::new(),
1430            order_ts_init,
1431        )?;
1432        Ok(Some(OrderAny::Limit(order)))
1433    }
1434
1435    fn check_settled_order(
1436        &self,
1437        source: &VenueOrder,
1438        fills: &[FillReport],
1439        order: &OrderAny,
1440        instrument_id: InstrumentId,
1441    ) -> anyhow::Result<()> {
1442        let id = order.client_order_id();
1443
1444        if self
1445            .barrier
1446            .lock()
1447            .expect("settlement barrier lock")
1448            .sealed(instrument_id)
1449            && (source.fill_count_fp.0 > order.filled_qty().as_decimal()
1450                || fills
1451                    .iter()
1452                    .any(|fill| !self.fill_accounted(id, fill.trade_id)))
1453        {
1454            self.barrier
1455                .lock()
1456                .expect("settlement barrier lock")
1457                .block();
1458            anyhow::bail!("unapplied execution evidence after settlement");
1459        }
1460
1461        Ok(())
1462    }
1463
1464    pub(super) fn report_covered(
1465        &self,
1466        id: ClientOrderId,
1467        trade: Option<TradeId>,
1468        filled: Decimal,
1469    ) -> bool {
1470        self.orders.get(&id).is_some_and(|context| {
1471            context.order.filled_qty().as_decimal() >= filled
1472                && trade.is_none_or(|trade| context.accounted.contains(&trade))
1473        })
1474    }
1475
1476    pub(super) fn admit_reports(
1477        &mut self,
1478        cache: &Cache,
1479        orders: &[OrderStatusReport],
1480        fills: &[FillReport],
1481    ) -> anyhow::Result<()> {
1482        let mut barrier = self.barrier.lock().expect("settlement barrier lock");
1483        let mut changed = false;
1484
1485        for report in orders {
1486            let cached = report.client_order_id.and_then(|id| cache.order_ref(&id));
1487            let received = cached
1488                .as_ref()
1489                .is_some_and(|order| order.filled_qty() >= report.filled_qty);
1490            let covered = report
1491                .client_order_id
1492                .is_some_and(|id| self.report_covered(id, None, report.filled_qty.as_decimal()));
1493
1494            if !received
1495                && (cache.instrument_close(&report.instrument_id).is_some()
1496                    || barrier.sealed(report.instrument_id) && !covered)
1497            {
1498                barrier.block();
1499                anyhow::bail!("unapplied order report after settlement");
1500            }
1501
1502            if !received {
1503                self.start = self.start.min(report.ts_accepted);
1504                barrier.admit_order(report);
1505                changed = true;
1506            }
1507        }
1508
1509        for report in fills {
1510            if self.admit_fill_report(cache, &mut barrier, report)? {
1511                self.start = self.start.min(report.ts_event);
1512                changed = true;
1513            }
1514        }
1515
1516        if changed {
1517            self.session = UUID4::new().to_string();
1518            self.ledger.invalidate();
1519            barrier.invalidate(&self.session);
1520        }
1521
1522        Ok(())
1523    }
1524
1525    fn admit_fill_report(
1526        &self,
1527        cache: &Cache,
1528        barrier: &mut SettlementBarrier,
1529        report: &FillReport,
1530    ) -> anyhow::Result<bool> {
1531        let id = report
1532            .client_order_id
1533            .or_else(|| cache.client_order_id(&report.venue_order_id).copied());
1534        let received = id
1535            .and_then(|id| cache.order_ref(&id))
1536            .is_some_and(|order| order.trade_ids().contains(&&report.trade_id));
1537        let covered =
1538            id.is_some_and(|id| self.report_covered(id, Some(report.trade_id), Decimal::ZERO));
1539
1540        if !received
1541            && (cache.instrument_close(&report.instrument_id).is_some()
1542                || barrier.sealed(report.instrument_id) && !covered)
1543        {
1544            barrier.block();
1545            anyhow::bail!("unapplied fill report after settlement");
1546        }
1547
1548        if !received {
1549            barrier.admit_fill(report);
1550        }
1551
1552        Ok(!received)
1553    }
1554
1555    fn order_is_stale(
1556        &self,
1557        source: &VenueOrder,
1558        fills: &[FillReport],
1559        order: &OrderAny,
1560        ts_last: UnixNanos,
1561    ) -> bool {
1562        if terminal_progress(order, source) {
1563            return false;
1564        }
1565
1566        let id = order.client_order_id();
1567
1568        let Some(context) = self.orders.get(&id) else {
1569            return false;
1570        };
1571
1572        let source_ts = context.source_ts.max(order.ts_last());
1573
1574        ts_last < source_ts
1575            && source.fill_count_fp.0 <= order.filled_qty().as_decimal()
1576            && fills
1577                .iter()
1578                .all(|fill| self.fill_accounted(id, fill.trade_id))
1579    }
1580
1581    fn order_is_current(&self, order: &OrderAny, source: &VenueOrder, ts_last: UnixNanos) -> bool {
1582        let source_ts = self
1583            .orders
1584            .get(&order.client_order_id())
1585            .map_or(order.ts_last(), |context| {
1586                context.source_ts.max(order.ts_last())
1587            });
1588
1589        !order.is_closed() && (ts_last >= source_ts || terminal_progress(order, source))
1590    }
1591
1592    fn fill_accounted(&self, id: ClientOrderId, trade_id: TradeId) -> bool {
1593        self.fills.contains(&trade_id)
1594            || self
1595                .orders
1596                .get(&id)
1597                .is_some_and(|context| context.accounted.contains(&trade_id))
1598    }
1599
1600    pub(super) fn openings(
1601        &self,
1602        plans: &[OrderPlan],
1603        positions: &[MarketPosition],
1604        settlements: &[Settlement],
1605    ) -> anyhow::Result<HashMap<InstrumentId, Decimal>> {
1606        let mut openings = self.positions.clone();
1607        let mut deltas = HashMap::new();
1608
1609        for (_, fill) in plans.iter().flat_map(|plan| &plan.fresh) {
1610            let signed = if fill.order_side == OrderSide::Buy {
1611                fill.last_qty.as_decimal()
1612            } else {
1613                -fill.last_qty.as_decimal()
1614            };
1615
1616            let delta: &mut Decimal = deltas.entry(fill.instrument_id).or_insert(Decimal::ZERO);
1617            *delta = delta
1618                .checked_add(signed)
1619                .context("initial position delta overflow")?;
1620        }
1621
1622        for position in positions {
1623            let id = crate::common::parse::parse_instrument_id(&position.ticker)?;
1624            let delta = deltas.remove(&id).unwrap_or(Decimal::ZERO);
1625            openings.insert(id, self.opening(id, position.position_fp.0, delta)?);
1626        }
1627
1628        for settlement in settlements {
1629            let id = &settlement.instrument_id;
1630            let delta = deltas.remove(id).unwrap_or(Decimal::ZERO);
1631            if let Some(net) = settlement.net {
1632                openings.insert(*id, self.opening(*id, net, delta)?);
1633            } else {
1634                anyhow::ensure!(
1635                    openings.contains_key(id),
1636                    "settlement lacks cached opening authority"
1637                );
1638            }
1639        }
1640
1641        anyhow::ensure!(deltas.is_empty(), "fills lack explicit position coverage");
1642        Ok(openings)
1643    }
1644
1645    fn opening(&self, id: InstrumentId, net: Decimal, delta: Decimal) -> anyhow::Result<Decimal> {
1646        let opening = net
1647            .checked_sub(delta)
1648            .context("initial position overflow")?;
1649
1650        let prior = self.positions.get(&id);
1651        if !prior.map_or(opening.is_zero(), |prior| *prior == opening) {
1652            if prior.is_none() || !self.positions_ts.contains_key(&id) {
1653                return Err(RecoveryContextError::Position.into());
1654            }
1655
1656            anyhow::bail!("position cycle lacks cached opening authority");
1657        }
1658
1659        Ok(opening)
1660    }
1661
1662    pub(super) fn check_amendments(&self, plans: &[OrderPlan]) -> anyhow::Result<()> {
1663        anyhow::ensure!(
1664            plans.iter().all(|plan| plan.mapped),
1665            "Kalshi order classification remains unmapped"
1666        );
1667        anyhow::ensure!(
1668            self.mutations.iter().all(|(id, pending)| {
1669                !pending.dispatched
1670                    || plans.iter().any(|plan| {
1671                        plan.result.client_order_id() == *id
1672                            && pending.covered(&plan.result, plan.source_ts)
1673                    })
1674            }),
1675            "Kalshi change lacks definitive order evidence"
1676        );
1677        anyhow::ensure!(
1678            self.orders.values().all(|context| {
1679                context.order.status() != OrderStatus::PendingUpdate
1680                    || plans.iter().any(|plan| {
1681                        plan.original.client_order_id() == context.order.client_order_id()
1682                            && plan.result.status() != OrderStatus::PendingUpdate
1683                    })
1684            }),
1685            "uncertain amendment lacks authoritative terms"
1686        );
1687        Ok(())
1688    }
1689
1690    pub(super) fn check_settlements(
1691        &self,
1692        plans: &[OrderPlan],
1693        settlements: &[Settlement],
1694    ) -> anyhow::Result<()> {
1695        for settlement in settlements {
1696            let id = settlement.instrument_id;
1697            anyhow::ensure!(
1698                plans
1699                    .iter()
1700                    .filter(|plan| plan.result.instrument_id() == id)
1701                    .all(|plan| plan.mapped),
1702                "settlement has unmapped order evidence"
1703            );
1704            anyhow::ensure!(
1705                self.orders.values().all(|context| {
1706                    context.order.is_closed()
1707                        || context.order.instrument_id() != id
1708                        || plans.iter().any(|plan| {
1709                            plan.original.client_order_id() == context.order.client_order_id()
1710                                && plan.result.is_closed()
1711                        })
1712                }),
1713                "settlement has unresolved orders"
1714            );
1715            self.barrier
1716                .lock()
1717                .expect("settlement barrier lock")
1718                .check_signature(id, settlement.value, settlement.ts_event)?;
1719        }
1720
1721        Ok(())
1722    }
1723
1724    pub(super) fn preview(
1725        &self,
1726        plans: &[OrderPlan],
1727        positions: &HashMap<InstrumentId, Decimal>,
1728        settlements: &[Settlement],
1729        total: Decimal,
1730        holds: &mut HashMap<ReservationId, Decimal>,
1731    ) -> anyhow::Result<(AccountBalance, HashMap<InstrumentId, Decimal>)> {
1732        let mut ledger = self.ledger.clone();
1733        let mut positions = positions.clone();
1734        let mut timestamps = self.positions_ts.clone();
1735
1736        let mut retained: HashMap<_, _> = plans
1737            .iter()
1738            .filter(|plan| !plan.mapped)
1739            .filter_map(|plan| {
1740                let id = plan.original.client_order_id();
1741                self.ledger.reservation(id).map(|hold| (id, hold))
1742            })
1743            .collect();
1744
1745        for (id, pending) in &self.mutations {
1746            let covered = plans.iter().any(|plan| {
1747                plan.mapped
1748                    && plan.result.client_order_id() == *id
1749                    && pending.covered(&plan.result, plan.source_ts)
1750            });
1751
1752            if pending.dispatched
1753                && pending.terms.is_some()
1754                && !covered
1755                && let Some(hold) = self.ledger.reservation(*id)
1756            {
1757                retained.insert(*id, hold);
1758            }
1759        }
1760
1761        for (index, _, fill) in ordered_fills(plans) {
1762            let change = apply_fill(&mut ledger, &mut positions, fill.instrument_id, &fill)?;
1763            if let Some(hold) = retained.get_mut(&plans[index].original.client_order_id()) {
1764                *hold = (*hold + change.min(Decimal::ZERO)).max(Decimal::ZERO);
1765            }
1766
1767            timestamps
1768                .entry(fill.instrument_id)
1769                .and_modify(|ts| *ts = (*ts).max(fill.ts_event))
1770                .or_insert(fill.ts_event);
1771        }
1772
1773        for (id, retained) in retained {
1774            let hold = holds.entry(ReservationId::Client(id)).or_default();
1775            *hold = (*hold).max(retained);
1776        }
1777
1778        for Settlement {
1779            instrument_id: id,
1780            value,
1781            ts_event: timestamp,
1782            ..
1783        } in settlements
1784        {
1785            anyhow::ensure!(
1786                timestamps.get(id).is_none_or(|last| *last <= *timestamp),
1787                "settlement precedes collected execution evidence"
1788            );
1789            apply_settlement(&mut ledger, &mut positions, *id, *value)?;
1790        }
1791
1792        let ticket = ledger.begin_refresh();
1793        let balance = ledger.apply_refresh(ticket, total, holds.clone())?;
1794        Ok((balance, positions))
1795    }
1796
1797    /// Emits planned order events and applies their fills to private cash and position state.
1798    ///
1799    /// # Errors
1800    ///
1801    /// Returns an error if an event receiver is closed or a fill lacks opening position evidence.
1802    pub fn apply_plans(
1803        &mut self,
1804        plans: Vec<OrderPlan>,
1805        emitter: &ExecutionEventEmitter,
1806    ) -> anyhow::Result<()> {
1807        let fills = ordered_fills(&plans);
1808
1809        let mut ledger = self.ledger.clone();
1810        let mut positions = self.positions.clone();
1811        for (_, _, fill) in &fills {
1812            apply_fill(&mut ledger, &mut positions, fill.instrument_id, fill)?;
1813        }
1814
1815        for plan in &plans {
1816            self.begin_plan(plan, emitter)?;
1817        }
1818
1819        for (index, event, report) in fills {
1820            let plan = &plans[index];
1821            let id = plan.original.client_order_id();
1822            if let Some(event) = event {
1823                if plan.external.is_some() {
1824                    emitter.try_send_execution_report(ExecutionReport::Fill(Box::new(
1825                        report.clone(),
1826                    )))?;
1827                } else {
1828                    emitter.try_send_order_event(event.clone())?;
1829                }
1830
1831                self.orders
1832                    .get_mut(&id)
1833                    .expect("plan owns context")
1834                    .order
1835                    .apply(event)?;
1836            }
1837
1838            apply_fill(
1839                &mut self.ledger,
1840                &mut self.positions,
1841                report.instrument_id,
1842                &report,
1843            )?;
1844            self.orders
1845                .get_mut(&id)
1846                .expect("plan owns context")
1847                .accounted
1848                .insert(report.trade_id);
1849            self.positions_ts
1850                .entry(report.instrument_id)
1851                .and_modify(|ts| *ts = (*ts).max(report.ts_event))
1852                .or_insert(report.ts_event);
1853            self.fills.add(report.trade_id);
1854        }
1855
1856        for plan in plans {
1857            self.finish_plan(plan, emitter)?;
1858        }
1859
1860        Ok(())
1861    }
1862
1863    fn begin_plan(
1864        &mut self,
1865        plan: &OrderPlan,
1866        emitter: &ExecutionEventEmitter,
1867    ) -> anyhow::Result<()> {
1868        let id = plan.original.client_order_id();
1869        if plan.has_events() {
1870            self.barrier
1871                .lock()
1872                .expect("settlement barrier lock")
1873                .receipt(&plan.result);
1874        }
1875
1876        self.bindings.insert(plan.venue_id, id);
1877        let accounted = self
1878            .orders
1879            .get(&id)
1880            .map(|context| context.accounted.clone())
1881            .unwrap_or_default();
1882        let source_ts = self
1883            .orders
1884            .get(&id)
1885            .map_or(plan.source_ts, |context| context.source_ts);
1886        self.orders.insert(
1887            id,
1888            PrivateOrder {
1889                order: plan.original.clone(),
1890                accounted,
1891                source_ts,
1892            },
1893        );
1894
1895        if let Some(report) = &plan.external_before {
1896            emitter.try_send_execution_report(ExecutionReport::OrderWithFills(
1897                Box::new(report.clone()),
1898                Vec::new(),
1899            ))?;
1900        }
1901
1902        for event in &plan.before {
1903            if plan.external.is_none() {
1904                emitter.try_send_order_event(event.clone())?;
1905            }
1906
1907            self.orders
1908                .get_mut(&id)
1909                .expect("plan owns context")
1910                .order
1911                .apply(event.clone())?;
1912        }
1913
1914        Ok(())
1915    }
1916
1917    fn finish_plan(
1918        &mut self,
1919        plan: OrderPlan,
1920        emitter: &ExecutionEventEmitter,
1921    ) -> anyhow::Result<()> {
1922        let id = plan.original.client_order_id();
1923        if plan.mapped
1924            && self.mutations.get(&id).is_some_and(|pending| {
1925                pending.dispatched && pending.covered(&plan.result, plan.source_ts)
1926            })
1927        {
1928            self.mutations.remove(&id);
1929        }
1930
1931        if let Some(report) = plan.external {
1932            emitter.try_send_execution_report(ExecutionReport::OrderWithFills(
1933                Box::new(report),
1934                Vec::new(),
1935            ))?;
1936
1937            for event in plan.after {
1938                self.orders
1939                    .get_mut(&id)
1940                    .expect("plan owns context")
1941                    .order
1942                    .apply(event)?;
1943            }
1944        } else {
1945            for event in plan.after {
1946                emitter.try_send_order_event(event.clone())?;
1947                self.orders
1948                    .get_mut(&id)
1949                    .expect("plan owns context")
1950                    .order
1951                    .apply(event)?;
1952            }
1953        }
1954
1955        let context = self.orders.get_mut(&id).expect("plan owns context");
1956        if plan.mapped {
1957            context.source_ts = context.source_ts.max(plan.source_ts);
1958        }
1959
1960        if plan.mapped && plan.result.is_closed() {
1961            self.ledger.release(id);
1962        }
1963
1964        Ok(())
1965    }
1966
1967    pub(super) fn apply_position(
1968        &mut self,
1969        report: PositionStatusReport,
1970        emitter: &ExecutionEventEmitter,
1971    ) -> anyhow::Result<()> {
1972        let id = report.instrument_id;
1973        let timestamp = report.ts_last;
1974        emitter.try_send_execution_report(ExecutionReport::Position(Box::new(report)))?;
1975        self.positions_ts
1976            .entry(id)
1977            .and_modify(|last| *last = (*last).max(timestamp))
1978            .or_insert(timestamp);
1979        Ok(())
1980    }
1981
1982    pub(super) fn settle(
1983        &mut self,
1984        instrument: &BinaryOption,
1985        value: Decimal,
1986        ts_event: UnixNanos,
1987        ts_init: UnixNanos,
1988        emitter: &ExecutionEventEmitter,
1989    ) -> anyhow::Result<()> {
1990        anyhow::ensure!(
1991            value >= Decimal::ZERO && value <= Decimal::ONE,
1992            "invalid settlement value"
1993        );
1994        anyhow::ensure!(
1995            self.positions_ts
1996                .get(&instrument.id)
1997                .is_none_or(|last| *last <= ts_event),
1998            "settlement precedes collected execution evidence"
1999        );
2000        anyhow::ensure!(
2001            self.orders.values().all(|context| context.order.is_closed()
2002                || context.order.instrument_id() != instrument.id),
2003            "settlement has unresolved orders"
2004        );
2005        let exposure = self
2006            .positions
2007            .get(&instrument.id)
2008            .copied()
2009            .unwrap_or(Decimal::ZERO);
2010        self.barrier
2011            .lock()
2012            .expect("settlement barrier lock")
2013            .prepare(instrument.id, value, ts_event, exposure)?;
2014        let mut ledger = self.ledger.clone();
2015        let mut positions = self.positions.clone();
2016        if !apply_settlement(&mut ledger, &mut positions, instrument.id, value)? {
2017            return Ok(());
2018        }
2019
2020        let report = PositionStatusReport::new(
2021            emitter.account_id(),
2022            instrument.id,
2023            PositionSide::Flat,
2024            Quantity::zero(instrument.size_precision),
2025            ts_event,
2026            ts_init,
2027            None,
2028            None,
2029            None,
2030        );
2031
2032        emitter.try_send_execution_report(ExecutionReport::Position(Box::new(report)))?;
2033        self.ledger = ledger;
2034        self.positions = positions;
2035        self.positions_ts.insert(instrument.id, ts_event);
2036        Ok(())
2037    }
2038}
2039
2040fn terminal_progress(order: &OrderAny, source: &VenueOrder) -> bool {
2041    !order.is_closed()
2042        && matches!(order.time_in_force(), TimeInForce::Ioc | TimeInForce::Fok)
2043        && source.client_order_id == order.client_order_id().as_str()
2044        && matches!(source.status, VenueStatus::Canceled | VenueStatus::Executed)
2045        && source.fill_count_fp.0 >= order.filled_qty().as_decimal()
2046}
2047
2048#[derive(Debug, Clone, Copy)]
2049struct FillNotice {
2050    instrument: Option<InstrumentId>,
2051    ts_event: UnixNanos,
2052}
2053
2054#[derive(Debug)]
2055struct OrderNotice {
2056    filled: Decimal,
2057    updated: Option<UnixNanos>,
2058}
2059
2060#[derive(Debug)]
2061pub(super) struct PositionNotice {
2062    volume: Decimal,
2063    economics: Option<PositionEconomics>,
2064}
2065
2066#[derive(Debug, thiserror::Error)]
2067pub(super) enum RecoveryContextError {
2068    #[error(
2069        "KALSHI_ORDER_CONTEXT_REQUIRED: filled quantity lacks command metadata; restore persisted orders"
2070    )]
2071    Order,
2072    #[error(
2073        "KALSHI_OPENING_CONTEXT_REQUIRED: position cycle lacks cached opening authority; restore complete cached orders and positions"
2074    )]
2075    Position,
2076}
2077
2078#[derive(Debug, Deserialize)]
2079struct PositionEconomics {
2080    position_fp: FixedPoint,
2081    realized_pnl_dollars: FixedPoint,
2082    fees_paid_dollars: FixedPoint,
2083}
2084
2085pub(super) struct Settlement {
2086    pub(super) instrument_id: InstrumentId,
2087    pub(super) value: Decimal,
2088    pub(super) ts_event: UnixNanos,
2089    pub(super) net: Option<Decimal>,
2090}
2091
2092#[derive(Debug, Clone)]
2093pub(super) struct PrivateOrder {
2094    pub(super) order: OrderAny,
2095    accounted: HashSet<TradeId>,
2096    source_ts: UnixNanos,
2097}
2098
2099/// Planned order events for one venue order, before they are emitted.
2100#[derive(Debug)]
2101pub struct OrderPlan {
2102    original: OrderAny,
2103    result: OrderAny,
2104    venue_id: VenueOrderId,
2105    before: Vec<OrderEventAny>,
2106    fresh: Vec<(Option<OrderEventAny>, FillReport)>,
2107    after: Vec<OrderEventAny>,
2108    external: Option<OrderStatusReport>,
2109    external_before: Option<OrderStatusReport>,
2110    source_ts: UnixNanos,
2111    pub(super) mapped: bool,
2112}
2113
2114impl OrderPlan {
2115    pub(super) fn hold_terms(&self) -> (Decimal, Decimal) {
2116        (
2117            self.result.leaves_qty().as_decimal(),
2118            self.result
2119                .price()
2120                .expect("planned order is a limit order")
2121                .as_decimal(),
2122        )
2123    }
2124
2125    pub(super) fn is_open(&self) -> bool {
2126        !self.result.is_closed()
2127    }
2128
2129    pub(super) fn has_events(&self) -> bool {
2130        !self.before.is_empty() || !self.fresh.is_empty() || !self.after.is_empty()
2131    }
2132}
2133
2134fn ordered_fills(plans: &[OrderPlan]) -> Vec<(usize, Option<OrderEventAny>, FillReport)> {
2135    let mut fills = Vec::new();
2136
2137    for (index, plan) in plans.iter().enumerate() {
2138        for (event, report) in &plan.fresh {
2139            fills.push((index, event.clone(), report.clone()));
2140        }
2141    }
2142
2143    fills.sort_by(|a, b| {
2144        a.2.ts_event
2145            .cmp(&b.2.ts_event)
2146            .then_with(|| a.2.trade_id.cmp(&b.2.trade_id))
2147    });
2148
2149    fills
2150}
2151
2152fn apply_settlement(
2153    ledger: &mut AccountLedger,
2154    positions: &mut HashMap<InstrumentId, Decimal>,
2155    id: InstrumentId,
2156    value: Decimal,
2157) -> anyhow::Result<bool> {
2158    anyhow::ensure!(
2159        value >= Decimal::ZERO && value <= Decimal::ONE,
2160        "invalid settlement value"
2161    );
2162    let net = positions
2163        .get(&id)
2164        .copied()
2165        .context("settlement lacks opening exposure")?;
2166
2167    if net.is_zero() {
2168        return Ok(false);
2169    }
2170
2171    let payout = if net > Decimal::ZERO {
2172        net.checked_mul(value)
2173    } else {
2174        (-net).checked_mul(Decimal::ONE - value)
2175    }
2176    .context("settlement payout overflow")?;
2177
2178    ledger.note_cash_change(payout)?;
2179    positions.insert(id, Decimal::ZERO);
2180    Ok(true)
2181}
2182
2183fn apply_fill(
2184    ledger: &mut AccountLedger,
2185    positions: &mut HashMap<InstrumentId, Decimal>,
2186    instrument_id: InstrumentId,
2187    fill: &FillReport,
2188) -> anyhow::Result<Decimal> {
2189    let net = positions
2190        .get(&instrument_id)
2191        .copied()
2192        .context("fill lacks opening position authority")?;
2193
2194    let signed = if fill.order_side == OrderSide::Buy {
2195        fill.last_qty.as_decimal()
2196    } else {
2197        -fill.last_qty.as_decimal()
2198    };
2199
2200    let next = net
2201        .checked_add(signed)
2202        .context("private position overflow")?;
2203    let change = fill
2204        .last_px
2205        .as_decimal()
2206        .checked_mul(-signed)
2207        .and_then(|value| value.checked_add(next.min(Decimal::ZERO)))
2208        .and_then(|value| value.checked_sub(net.min(Decimal::ZERO)))
2209        .and_then(|value| value.checked_sub(fill.commission.as_decimal()))
2210        .context("private fill cash overflow")?;
2211    ledger.note_cash_change(change)?;
2212    positions.insert(instrument_id, next);
2213    Ok(change)
2214}
2215
2216#[cfg(test)]
2217mod tests {
2218    use nautilus_common::messages::{DataEvent, ExecutionEvent, execution::CancelOrder};
2219    use nautilus_model::{
2220        data::{Data, InstrumentClose},
2221        enums::{
2222            AccountType, InstrumentCloseType, LiquiditySide, OrderStatus, OrderType, TimeInForce,
2223        },
2224        events::{OrderModifyDenied, OrderPendingCancel, OrderPendingUpdate, OrderSubmitted},
2225        identifiers::{AccountId, StrategyId},
2226        orders::builder::OrderTestBuilder,
2227        types::{Money, Price},
2228    };
2229    use rstest::rstest;
2230    use serde_json::Value;
2231
2232    use super::*;
2233    use crate::http::{
2234        models::{BookSide, Event, Field, Fill, FixedPoint, Market, OutcomeSide},
2235        parse::parse_instrument,
2236    };
2237
2238    fn instrument() -> BinaryOption {
2239        let f: Value =
2240            serde_json::from_str(include_str!("../../test_data/instruments.json")).unwrap();
2241        let market: Market =
2242            serde_json::from_value(f["definitions"]["live"]["market"].clone()).unwrap();
2243        let event: Event =
2244            serde_json::from_value(f["definitions"]["live"]["event"].clone()).unwrap();
2245        parse_instrument(&market, &event, UnixNanos::from(1)).unwrap()
2246    }
2247
2248    fn source(instrument: &BinaryOption, side: OrderSide) -> VenueOrder {
2249        let f: Value =
2250            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
2251        let mut source: VenueOrder = serde_json::from_value(f["order"]["order"].clone()).unwrap();
2252        source.ticker = instrument.id.symbol.to_string();
2253
2254        source.book_side = if side == OrderSide::Buy {
2255            BookSide::Bid
2256        } else {
2257            BookSide::Ask
2258        };
2259
2260        source.outcome_side = if side == OrderSide::Buy {
2261            OutcomeSide::Yes
2262        } else {
2263            OutcomeSide::No
2264        };
2265
2266        source.yes_price_dollars = FixedPoint(Decimal::new(6001, 4));
2267        source.no_price_dollars = FixedPoint(Decimal::new(3999, 4));
2268        source.fill_count_fp = FixedPoint(Decimal::new(75, 2));
2269        source.remaining_count_fp = FixedPoint(Decimal::new(125, 2));
2270        source.initial_count_fp = FixedPoint(Decimal::from(2));
2271        source.expiration_time = Field::Null;
2272        source
2273    }
2274
2275    fn report(source: &VenueOrder, instrument: &BinaryOption, account_id: AccountId) -> FillReport {
2276        let f: Value =
2277            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
2278        let mut fill: Fill = serde_json::from_value(f["fills"]["fills"][0].clone()).unwrap();
2279        fill.order_id = source.order_id.clone();
2280        fill.ticker = source.ticker.clone();
2281        fill.market_ticker = source.ticker.clone();
2282        fill.book_side = source.book_side;
2283        fill.outcome_side = source.outcome_side;
2284        fill.yes_price_dollars = source.yes_price_dollars;
2285        fill.no_price_dollars = source.no_price_dollars;
2286        fill.count_fp = source.fill_count_fp;
2287        reports::fill(&fill, instrument, account_id, source, UnixNanos::from(543)).unwrap()
2288    }
2289
2290    fn submitted(instrument: &BinaryOption, side: OrderSide, client_id: &str) -> OrderAny {
2291        let mut order = OrderTestBuilder::new(OrderType::Limit)
2292            .instrument_id(instrument.id)
2293            .client_order_id(ClientOrderId::from(client_id))
2294            .side(side)
2295            .quantity(Quantity::from("2.00"))
2296            .price(Price::from("0.600000"))
2297            .time_in_force(TimeInForce::Gtc)
2298            .build();
2299
2300        let submitted = OrderSubmitted::new(
2301            order.trader_id(),
2302            order.strategy_id(),
2303            instrument.id,
2304            order.client_order_id(),
2305            AccountId::from("KALSHI-007"),
2306            UUID4::new(),
2307            UnixNanos::from(1),
2308            UnixNanos::from(2),
2309        );
2310
2311        order.apply(OrderEventAny::Submitted(submitted)).unwrap();
2312        order
2313    }
2314
2315    fn state(order: OrderAny, instrument: &BinaryOption) -> PrivateState {
2316        let mut state = PrivateState::new();
2317        state.restore(order);
2318        state.positions.insert(instrument.id, Decimal::ZERO);
2319        let ticket = state.ledger.begin_refresh();
2320        state
2321            .ledger
2322            .apply_refresh(ticket, Decimal::new(1000001, 4), HashMap::new())
2323            .unwrap();
2324        state
2325    }
2326
2327    fn emitter() -> (
2328        ExecutionEventEmitter,
2329        tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent>,
2330    ) {
2331        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
2332
2333        let mut emitter = ExecutionEventEmitter::new(
2334            get_atomic_clock_realtime(),
2335            "TRADER-001".into(),
2336            AccountId::from("KALSHI-007"),
2337            AccountType::Cash,
2338            Some(Currency::USD()),
2339        );
2340
2341        emitter.set_sender(sender);
2342        (emitter, receiver)
2343    }
2344
2345    #[rstest]
2346    #[case::new(false)]
2347    #[case::restored(true)]
2348    fn unsent_denial_fences_only_tracked_orders_and_rejects_conflicting_venue_identity(
2349        #[case] restored: bool,
2350    ) {
2351        let instrument = instrument();
2352        let mut order = OrderTestBuilder::new(OrderType::Limit)
2353            .instrument_id(instrument.id)
2354            .client_order_id("client-a".into())
2355            .quantity(Quantity::from("1.25"))
2356            .price(Price::from("0.600000"))
2357            .time_in_force(TimeInForce::Gtc)
2358            .build();
2359        let mut state = PrivateState::new();
2360        if restored {
2361            state.restore(order.clone());
2362        }
2363
2364        let ticket = state.ledger.begin_refresh();
2365        state
2366            .ledger
2367            .apply_refresh(
2368                ticket,
2369                Decimal::ONE,
2370                HashMap::from([(ReservationId::Venue("external".into()), Decimal::new(25, 2))]),
2371            )
2372            .unwrap();
2373        let balance = state.ledger.balance().unwrap();
2374        let ticket = state.ledger.begin_refresh();
2375        let (emitter, mut output) = emitter();
2376        state
2377            .deny_submission(&mut order, "local validation", &emitter)
2378            .unwrap();
2379        assert_eq!(order.status(), OrderStatus::Denied);
2380
2381        if restored {
2382            assert_eq!(
2383                state.ledger.check_refresh(ticket).unwrap_err().to_string(),
2384                "stale Kalshi account refresh"
2385            );
2386        } else {
2387            state.ledger.check_refresh(ticket).unwrap();
2388        }
2389
2390        assert_eq!(
2391            state
2392                .source_order(&source(&instrument, OrderSide::Buy))
2393                .unwrap_err()
2394                .to_string(),
2395            "venue evidence conflicts with an unsent Kalshi order"
2396        );
2397        assert_eq!(state.ledger.balance().unwrap(), balance);
2398        assert!(matches!(
2399            output.try_recv().unwrap(),
2400            ExecutionEvent::Order(OrderEventAny::Denied(_))
2401        ));
2402        assert!(output.try_recv().is_err());
2403    }
2404
2405    #[rstest]
2406    fn venue_rejection_does_not_conflict_with_recovered_order() {
2407        let instrument = instrument();
2408        let order = submitted(&instrument, OrderSide::Buy, "client-a");
2409        let id = order.client_order_id();
2410        let mut state = state(order, &instrument);
2411        let (emitter, mut output) = emitter();
2412        state
2413            .reject_submission(id, "Post-only order would cross", true, &emitter)
2414            .unwrap();
2415        let mut source = source(&instrument, OrderSide::Buy);
2416        source.status = VenueStatus::Canceled;
2417        source.fill_count_fp = FixedPoint(Decimal::ZERO);
2418        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
2419
2420        let recovered = state.source_order(&source).unwrap().unwrap();
2421
2422        assert_eq!(recovered.status(), OrderStatus::Rejected);
2423        assert!(matches!(
2424            output.try_recv().unwrap(),
2425            ExecutionEvent::Order(OrderEventAny::Rejected(event)) if event.due_post_only
2426        ));
2427    }
2428
2429    #[rstest]
2430    #[case(VenueStatus::Resting, Decimal::ZERO, Decimal::new(1, 2))]
2431    #[case(VenueStatus::Canceled, Decimal::new(75, 2), Decimal::ZERO)]
2432    #[case(VenueStatus::Executed, Decimal::new(75, 2), Decimal::ZERO)]
2433    fn venue_rejection_rejects_live_or_filled_order(
2434        #[case] status: VenueStatus,
2435        #[case] filled: Decimal,
2436        #[case] remaining: Decimal,
2437    ) {
2438        let instrument = instrument();
2439        let order = submitted(&instrument, OrderSide::Buy, "client-a");
2440        let id = order.client_order_id();
2441        let mut state = state(order, &instrument);
2442        let (emitter, _output) = emitter();
2443        state
2444            .reject_submission(id, "Post-only order would cross", true, &emitter)
2445            .unwrap();
2446        let mut source = source(&instrument, OrderSide::Buy);
2447        source.status = status;
2448        source.fill_count_fp = FixedPoint(filled);
2449        source.remaining_count_fp = FixedPoint(remaining);
2450
2451        let error = state.source_order(&source).unwrap_err();
2452
2453        assert_eq!(
2454            error.to_string(),
2455            "venue evidence conflicts with an unsent Kalshi order"
2456        );
2457    }
2458
2459    #[rstest]
2460    fn not_sent_rejection_fences_conflicting_venue_identity() {
2461        let instrument = instrument();
2462        let order = submitted(&instrument, OrderSide::Buy, "client-a");
2463        let id = order.client_order_id();
2464        let mut state = state(order, &instrument);
2465        let (emitter, _output) = emitter();
2466        state
2467            .reject_submission(id, submit::NOT_SENT_REASON, false, &emitter)
2468            .unwrap();
2469        let rejected = state.orders[&id].order.clone();
2470
2471        let event = OrderModifyDenied::new(
2472            rejected.trader_id(),
2473            rejected.strategy_id(),
2474            rejected.instrument_id(),
2475            rejected.client_order_id(),
2476            "closed order".into(),
2477            UUID4::new(),
2478            UnixNanos::from(rejected.ts_last().as_u64() + 1),
2479            UnixNanos::from(rejected.ts_last().as_u64() + 2),
2480            rejected.venue_order_id(),
2481            Some(emitter.account_id()),
2482        );
2483
2484        let mut rejected = rejected;
2485        rejected.apply(OrderEventAny::ModifyDenied(event)).unwrap();
2486        state.restore(rejected);
2487        assert!(matches!(
2488            state.orders[&id].order.last_event(),
2489            OrderEventAny::ModifyDenied(_)
2490        ));
2491        let mut source = source(&instrument, OrderSide::Buy);
2492        source.status = VenueStatus::Canceled;
2493        source.fill_count_fp = FixedPoint(Decimal::ZERO);
2494        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
2495
2496        let error = state.source_order(&source).unwrap_err();
2497
2498        assert_eq!(
2499            error.to_string(),
2500            "venue evidence conflicts with an unsent Kalshi order"
2501        );
2502    }
2503
2504    #[rstest]
2505    fn admission_denial_cannot_replace_an_owned_submission() {
2506        let instrument = instrument();
2507        let submitted = submitted(&instrument, OrderSide::Buy, "client-a");
2508        let mut state = state(submitted.clone(), &instrument);
2509        let mut local = OrderTestBuilder::new(OrderType::Limit)
2510            .instrument_id(instrument.id)
2511            .client_order_id("client-a".into())
2512            .quantity(Quantity::from("1.25"))
2513            .price(Price::from("0.600000"))
2514            .time_in_force(TimeInForce::Gtc)
2515            .build();
2516        let (emitter, mut output) = emitter();
2517        state
2518            .deny_submission(&mut local, "late local validation", &emitter)
2519            .unwrap();
2520        assert_eq!(local.status(), OrderStatus::Submitted);
2521        assert_eq!(state.orders[&local.client_order_id()].order, submitted);
2522        assert!(output.try_recv().is_err());
2523    }
2524
2525    #[rstest]
2526    fn submission_ack_fences_refresh_and_cannot_replace_venue_evidence() {
2527        let instrument = instrument();
2528        let order = submitted(&instrument, OrderSide::Buy, "ack-client");
2529        let id = order.client_order_id();
2530        let mut state = state(order, &instrument);
2531        let (emitter, mut output) = emitter();
2532        state.ledger.reserve(id, Decimal::new(62, 2)).unwrap();
2533        let held = state.ledger.balance().unwrap();
2534        let stale = state.ledger.begin_refresh();
2535        let venue_id = VenueOrderId::from("ack-venue");
2536        state
2537            .acknowledge(id, venue_id, UnixNanos::from(3), &emitter)
2538            .unwrap();
2539        let accepted = output.try_recv().unwrap();
2540        assert!(matches!(
2541            accepted,
2542            ExecutionEvent::Order(OrderEventAny::Accepted(_))
2543        ));
2544        assert_eq!(
2545            state.ledger.check_refresh(stale).unwrap_err().to_string(),
2546            "stale Kalshi account refresh"
2547        );
2548        state
2549            .acknowledge(id, venue_id, UnixNanos::from(4), &emitter)
2550            .unwrap();
2551        assert_eq!(
2552            state
2553                .acknowledge(
2554                    id,
2555                    VenueOrderId::from("other-venue"),
2556                    UnixNanos::from(5),
2557                    &emitter
2558                )
2559                .unwrap_err()
2560                .to_string(),
2561            "Kalshi acknowledgement order identity mismatch"
2562        );
2563        assert_eq!(
2564            state
2565                .reject_submission(id, "late failure", false, &emitter)
2566                .unwrap_err()
2567                .to_string(),
2568            "Kalshi submission already has venue evidence"
2569        );
2570        assert!(output.try_recv().is_err());
2571        assert_eq!(state.orders[&id].order.status(), OrderStatus::Accepted);
2572        assert_eq!(state.orders[&id].order.venue_order_id(), Some(venue_id));
2573        assert_eq!(state.ledger.balance().unwrap(), held);
2574    }
2575
2576    #[rstest]
2577    #[case(OrderSide::Buy, "99.550024", "0.75")]
2578    #[case(OrderSide::Sell, "99.700174", "-0.75")]
2579    fn partial_fill_accepts_and_updates_before_filling_once(
2580        #[case] side: OrderSide,
2581        #[case] cash: &str,
2582        #[case] net: &str,
2583    ) {
2584        let instrument = instrument();
2585        let source = source(&instrument, side);
2586        let order = submitted(&instrument, side, "client-a");
2587        let mut state = state(order.clone(), &instrument);
2588        let (emitter, mut output) = emitter();
2589        let report = report(&source, &instrument, emitter.account_id());
2590        let plan = state
2591            .plan_order(
2592                &source,
2593                std::slice::from_ref(&report),
2594                &instrument,
2595                &emitter,
2596                UnixNanos::from(543),
2597            )
2598            .unwrap()
2599            .unwrap();
2600        assert_eq!(
2601            state.orders[&report.client_order_id.unwrap()]
2602                .order
2603                .venue_order_id(),
2604            None
2605        );
2606        state.apply_plans(vec![plan], &emitter).unwrap();
2607        let accepted = output.try_recv().unwrap();
2608        let updated = output.try_recv().unwrap();
2609        let filled = output.try_recv().unwrap();
2610
2611        let ExecutionEvent::Order(OrderEventAny::Accepted(accepted)) = accepted else {
2612            panic!("expected acceptance");
2613        };
2614
2615        let ExecutionEvent::Order(OrderEventAny::Updated(updated)) = updated else {
2616            panic!("expected update");
2617        };
2618
2619        let ExecutionEvent::Order(OrderEventAny::Filled(filled)) = filled else {
2620            panic!("expected fill");
2621        };
2622
2623        assert_eq!(
2624            accepted,
2625            OrderAccepted::new(
2626                order.trader_id(),
2627                order.strategy_id(),
2628                instrument.id,
2629                order.client_order_id(),
2630                report.venue_order_id,
2631                emitter.account_id(),
2632                accepted.event_id,
2633                timestamp(&source.created_time).unwrap(),
2634                UnixNanos::from(543),
2635                false
2636            )
2637        );
2638        assert_eq!(
2639            updated,
2640            OrderUpdated::new(
2641                order.trader_id(),
2642                order.strategy_id(),
2643                instrument.id,
2644                order.client_order_id(),
2645                Quantity::from("2.00"),
2646                updated.event_id,
2647                timestamp(&source.last_update_time).unwrap(),
2648                UnixNanos::from(543),
2649                true,
2650                Some(report.venue_order_id),
2651                Some(emitter.account_id()),
2652                Some(Price::from("0.600100")),
2653                None,
2654                None,
2655                false
2656            )
2657        );
2658        assert_eq!(
2659            filled,
2660            OrderFilled::new(
2661                order.trader_id(),
2662                order.strategy_id(),
2663                instrument.id,
2664                order.client_order_id(),
2665                report.venue_order_id,
2666                emitter.account_id(),
2667                report.trade_id,
2668                side,
2669                OrderType::Limit,
2670                Quantity::from("0.75"),
2671                Price::from("0.600100"),
2672                Currency::USD(),
2673                LiquiditySide::Taker,
2674                filled.event_id,
2675                report.ts_event,
2676                UnixNanos::from(543),
2677                false,
2678                None,
2679                Some(report.commission),
2680                None
2681            )
2682        );
2683        let plan = state
2684            .plan_order(
2685                &source,
2686                std::slice::from_ref(&report),
2687                &instrument,
2688                &emitter,
2689                UnixNanos::from(544),
2690            )
2691            .unwrap()
2692            .unwrap();
2693        state.apply_plans(vec![plan], &emitter).unwrap();
2694        assert!(output.try_recv().is_err());
2695        assert_eq!(
2696            state.positions[&instrument.id],
2697            net.parse::<Decimal>().unwrap()
2698        );
2699        let ticket = state.ledger.begin_refresh();
2700        let balance = state
2701            .ledger
2702            .apply_refresh(ticket, cash.parse().unwrap(), HashMap::new())
2703            .unwrap();
2704        assert_eq!(balance.total.as_decimal(), cash.parse::<Decimal>().unwrap());
2705        assert_eq!(
2706            state.orders[&report.client_order_id.unwrap()]
2707                .order
2708                .filled_qty(),
2709            Quantity::from("0.75")
2710        );
2711    }
2712
2713    #[rstest]
2714    #[case(false, "99.550024", "0.75")]
2715    #[case(true, "98.799899", "2.00")]
2716    fn cached_fill_is_accounted_without_routing_twice_and_survives_replay_eviction(
2717        #[case] terminal: bool,
2718        #[case] cash: &str,
2719        #[case] net: &str,
2720    ) {
2721        let cash: Decimal = cash.parse().unwrap();
2722        let net: Decimal = net.parse().unwrap();
2723        let instrument = instrument();
2724        let mut source = source(&instrument, OrderSide::Buy);
2725        if terminal {
2726            source.status = VenueStatus::Executed;
2727            source.fill_count_fp = FixedPoint(Decimal::from(2));
2728            source.remaining_count_fp = FixedPoint(Decimal::ZERO);
2729        }
2730
2731        let mut state = state(
2732            submitted(&instrument, OrderSide::Buy, "client-a"),
2733            &instrument,
2734        );
2735        let (emitter, output) = emitter();
2736        let fill = report(&source, &instrument, emitter.account_id());
2737        let plan = state
2738            .plan_order(
2739                &source,
2740                std::slice::from_ref(&fill),
2741                &instrument,
2742                &emitter,
2743                UnixNanos::from(543),
2744            )
2745            .unwrap()
2746            .unwrap();
2747        state.restore(plan.result);
2748        let plan = state
2749            .plan_order(
2750                &source,
2751                std::slice::from_ref(&fill),
2752                &instrument,
2753                &emitter,
2754                UnixNanos::from(544),
2755            )
2756            .unwrap()
2757            .unwrap();
2758        state.apply_plans(vec![plan], &emitter).unwrap();
2759        for i in 0..100_001 {
2760            state.fills.add(TradeId::new(format!("other-{i}")));
2761        }
2762
2763        state.invalidate();
2764        let plan = state
2765            .plan_order(
2766                &source,
2767                std::slice::from_ref(&fill),
2768                &instrument,
2769                &emitter,
2770                UnixNanos::from(545),
2771            )
2772            .unwrap()
2773            .unwrap();
2774        state.apply_plans(vec![plan], &emitter).unwrap();
2775        let ticket = state.ledger.begin_refresh();
2776        let balance = state
2777            .ledger
2778            .apply_refresh(ticket, cash, HashMap::new())
2779            .unwrap();
2780        assert_eq!(output.len(), 0);
2781        assert!(!state.fills.contains(&fill.trade_id));
2782        assert_eq!(state.positions[&instrument.id], net);
2783        assert_eq!(balance.total.as_decimal(), cash);
2784        assert_eq!(
2785            state.orders[&ClientOrderId::from("client-a")]
2786                .order
2787                .is_closed(),
2788            terminal
2789        );
2790    }
2791
2792    #[rstest]
2793    #[case("0.75", "1", "100.7501")]
2794    #[case("-0.75", "0", "100.7501")]
2795    #[case("0.75", "0.42", "100.3151")]
2796    #[case("-0.75", "0.42", "100.4351")]
2797    fn settlement_uses_exact_payout_and_timestamp_without_inventing_a_fill(
2798        #[case] net: &str,
2799        #[case] value: &str,
2800        #[case] cash: &str,
2801    ) {
2802        let instrument = instrument();
2803        let mut state = PrivateState::new();
2804        let ticket = state.ledger.begin_refresh();
2805        state
2806            .ledger
2807            .apply_refresh(ticket, "100.0001".parse().unwrap(), HashMap::new())
2808            .unwrap();
2809        state.positions.insert(instrument.id, net.parse().unwrap());
2810        state
2811            .positions_ts
2812            .insert(instrument.id, UnixNanos::from(123));
2813        let (emitter, mut output) = emitter();
2814        let value = value.parse().unwrap();
2815        assert_eq!(
2816            state
2817                .settle(
2818                    &instrument,
2819                    value,
2820                    UnixNanos::from(122),
2821                    UnixNanos::from(456),
2822                    &emitter
2823                )
2824                .unwrap_err()
2825                .to_string(),
2826            "settlement precedes collected execution evidence"
2827        );
2828        state
2829            .settle(
2830                &instrument,
2831                value,
2832                UnixNanos::from(124),
2833                UnixNanos::from(456),
2834                &emitter,
2835            )
2836            .unwrap();
2837        state
2838            .settle(
2839                &instrument,
2840                value,
2841                UnixNanos::from(124),
2842                UnixNanos::from(457),
2843                &emitter,
2844            )
2845            .unwrap();
2846
2847        let ExecutionEvent::Report(ExecutionReport::Position(actual)) = output.try_recv().unwrap()
2848        else {
2849            panic!("expected settlement position report");
2850        };
2851
2852        let expected = PositionStatusReport::new(
2853            emitter.account_id(),
2854            instrument.id,
2855            PositionSide::Flat,
2856            Quantity::zero(instrument.size_precision),
2857            UnixNanos::from(124),
2858            UnixNanos::from(456),
2859            Some(actual.report_id),
2860            None,
2861            None,
2862        );
2863
2864        assert_eq!(*actual, expected);
2865        assert_eq!(output.len(), 0);
2866        assert_eq!(state.positions[&instrument.id], Decimal::ZERO);
2867        assert_eq!(state.positions_ts[&instrument.id], UnixNanos::from(124));
2868        let ticket = state.ledger.begin_refresh();
2869        let cash: Decimal = cash.parse().unwrap();
2870        let balance = state
2871            .ledger
2872            .apply_refresh(ticket, cash, HashMap::new())
2873            .unwrap();
2874        assert_eq!(balance.total.as_decimal(), cash);
2875    }
2876
2877    #[rstest]
2878    fn invalid_fee_or_identity_remains_replayable_and_failed_routing_does_not_advance_context() {
2879        let instrument = instrument();
2880        let source = source(&instrument, OrderSide::Buy);
2881        let mut state = state(
2882            submitted(&instrument, OrderSide::Buy, "client-a"),
2883            &instrument,
2884        );
2885        let (emitter, output) = emitter();
2886        let valid = report(&source, &instrument, emitter.account_id());
2887        let mut invalid = valid.clone();
2888        invalid.commission =
2889            Money::from_decimal_exact(Decimal::new(-1, 6), Currency::USD()).unwrap();
2890        assert!(
2891            state
2892                .plan_order(
2893                    &source,
2894                    &[invalid],
2895                    &instrument,
2896                    &emitter,
2897                    UnixNanos::from(543)
2898                )
2899                .is_err()
2900        );
2901        let mut invalid = valid.clone();
2902        invalid.venue_order_id = VenueOrderId::from("wrong-order");
2903        assert!(
2904            state
2905                .plan_order(
2906                    &source,
2907                    &[invalid],
2908                    &instrument,
2909                    &emitter,
2910                    UnixNanos::from(543)
2911                )
2912                .is_err()
2913        );
2914        assert!(!state.fills.contains(&valid.trade_id));
2915        drop(output);
2916        let plan = state
2917            .plan_order(
2918                &source,
2919                std::slice::from_ref(&valid),
2920                &instrument,
2921                &emitter,
2922                UnixNanos::from(543),
2923            )
2924            .unwrap()
2925            .unwrap();
2926        assert!(state.apply_plans(vec![plan], &emitter).is_err());
2927        assert_eq!(
2928            state.orders[&valid.client_order_id.unwrap()].order.status(),
2929            OrderStatus::Submitted
2930        );
2931        assert!(!state.fills.contains(&valid.trade_id));
2932        let (emitter, mut output) = self::emitter();
2933        let plan = state
2934            .plan_order(
2935                &source,
2936                std::slice::from_ref(&valid),
2937                &instrument,
2938                &emitter,
2939                UnixNanos::from(544),
2940            )
2941            .unwrap()
2942            .unwrap();
2943        state.apply_plans(vec![plan], &emitter).unwrap();
2944        assert_eq!(output.len(), 3);
2945        assert!(output.try_recv().is_ok());
2946        assert!(state.fills.contains(&valid.trade_id));
2947    }
2948
2949    #[rstest]
2950    fn malformed_terminal_counts_and_unknown_outcomes_do_not_release_or_reject() {
2951        let instrument = instrument();
2952        let mut source = source(&instrument, OrderSide::Buy);
2953        let state = state(
2954            submitted(&instrument, OrderSide::Buy, "client-a"),
2955            &instrument,
2956        );
2957        let (emitter, output) = emitter();
2958        let valid = report(&source, &instrument, emitter.account_id());
2959        source.status = VenueStatus::Executed;
2960        assert_eq!(
2961            state
2962                .plan_order(
2963                    &source,
2964                    std::slice::from_ref(&valid),
2965                    &instrument,
2966                    &emitter,
2967                    UnixNanos::from(543)
2968                )
2969                .err()
2970                .unwrap()
2971                .to_string(),
2972            "invalid executed order counts"
2973        );
2974        source.status = VenueStatus::Unknown;
2975        let plan = state
2976            .plan_order(
2977                &source,
2978                &[valid],
2979                &instrument,
2980                &emitter,
2981                UnixNanos::from(543),
2982            )
2983            .unwrap()
2984            .unwrap();
2985        assert!(!plan.mapped);
2986        assert!(state.check_amendments(&[plan]).is_err());
2987        assert_eq!(
2988            state.orders[&ClientOrderId::from("client-a")]
2989                .order
2990                .status(),
2991            OrderStatus::Submitted
2992        );
2993        assert_eq!(output.len(), 0);
2994    }
2995
2996    #[rstest]
2997    #[case::buy_open(OrderSide::Buy, "0", "99.550024", "1.549924", "0.75")]
2998    #[case::sell_open(OrderSide::Sell, "0", "99.700174", "1.700074", "-0.75")]
2999    #[case::sell_reduce(OrderSide::Sell, "1", "100.450174", "2", "0.25")]
3000    #[case::buy_reduce(OrderSide::Buy, "-1", "100.300024", "2", "-0.25")]
3001    fn unresolved_reservation_consumes_only_cash_debits(
3002        #[case] side: OrderSide,
3003        #[case] opening: &str,
3004        #[case] total: &str,
3005        #[case] retained: &str,
3006        #[case] position: &str,
3007        #[values(false, true)] mapped: bool,
3008    ) {
3009        let instrument = instrument();
3010        let order = submitted(&instrument, side, "client-a");
3011        let id = order.client_order_id();
3012        let mut state = state(order, &instrument);
3013        state
3014            .positions
3015            .insert(instrument.id, opening.parse().unwrap());
3016        state.ledger.reserve(id, Decimal::ONE).unwrap();
3017        state
3018            .ledger
3019            .reserve_amendment(id, Decimal::from(2), Decimal::from(2), Decimal::ONE)
3020            .unwrap();
3021        let command_id = UUID4::new();
3022        state.mutations.insert(
3023            id,
3024            PendingMutation {
3025                command_id,
3026                started: UnixNanos::from(2),
3027                dispatched: true,
3028                acknowledgement: None,
3029                terms: Some((Quantity::from("3.00"), Price::from("0.600000"))),
3030            },
3031        );
3032
3033        let mut source = source(&instrument, side);
3034
3035        source.status = if mapped {
3036            VenueStatus::Resting
3037        } else {
3038            VenueStatus::Unknown
3039        };
3040
3041        let (emitter, mut output) = emitter();
3042        let mut fill = report(&source, &instrument, emitter.account_id());
3043        fill.commission = Money::from_decimal_exact(Decimal::new(1, 6), Currency::USD()).unwrap();
3044        let mut holds = HashMap::from([(ReservationId::Client(id), Decimal::new(1, 2))]);
3045
3046        for replay in 0..2 {
3047            let plan = state
3048                .plan_order(
3049                    &source,
3050                    std::slice::from_ref(&fill),
3051                    &instrument,
3052                    &emitter,
3053                    UnixNanos::from(543),
3054                )
3055                .unwrap()
3056                .unwrap();
3057            assert_eq!(
3058                state
3059                    .check_settlements(
3060                        std::slice::from_ref(&plan),
3061                        &[Settlement {
3062                            instrument_id: instrument.id,
3063                            value: Decimal::ONE,
3064                            ts_event: UnixNanos::from(544),
3065                            net: None
3066                        }]
3067                    )
3068                    .unwrap_err()
3069                    .to_string(),
3070                if mapped {
3071                    "settlement has unresolved orders"
3072                } else {
3073                    "settlement has unmapped order evidence"
3074                }
3075            );
3076            let (balance, positions) = state
3077                .preview(
3078                    std::slice::from_ref(&plan),
3079                    &state.positions,
3080                    &[],
3081                    total.parse().unwrap(),
3082                    &mut holds,
3083                )
3084                .unwrap();
3085            assert_eq!(
3086                positions[&instrument.id],
3087                position.parse::<Decimal>().unwrap()
3088            );
3089            assert_eq!(
3090                balance.total.as_decimal(),
3091                total.parse::<Decimal>().unwrap()
3092            );
3093            assert_eq!(
3094                balance.locked.as_decimal(),
3095                retained.parse::<Decimal>().unwrap()
3096            );
3097            assert_eq!(
3098                balance.free.as_decimal(),
3099                total.parse::<Decimal>().unwrap() - retained.parse::<Decimal>().unwrap()
3100            );
3101            assert_eq!(balance.currency, Currency::USD());
3102            state.apply_plans(vec![plan], &emitter).unwrap();
3103            let ticket = state.ledger.begin_refresh();
3104            state
3105                .ledger
3106                .apply_refresh(ticket, total.parse().unwrap(), holds.clone())
3107                .unwrap();
3108            assert_eq!(
3109                state.positions[&instrument.id],
3110                position.parse::<Decimal>().unwrap()
3111            );
3112            assert_eq!(state.ledger.balance().unwrap(), balance);
3113            assert_eq!(
3114                state.ledger.reservation(id),
3115                Some(retained.parse().unwrap())
3116            );
3117            assert_eq!(state.mutations[&id].command_id, command_id);
3118            assert_eq!(
3119                output.len(),
3120                if replay == 0 {
3121                    if mapped { 3 } else { 2 }
3122                } else {
3123                    0
3124                }
3125            );
3126
3127            while output.try_recv().is_ok() {}
3128        }
3129    }
3130
3131    #[rstest]
3132    fn unmapped_quantity_change_waits_without_resolving_commands(
3133        #[values(false, true)] amendment: bool,
3134        #[values(false, true)] fresh_claim: bool,
3135        #[values(0, 1)] filled: u32,
3136    ) {
3137        let instrument = instrument();
3138        let mut order = submitted(&instrument, OrderSide::Buy, "client-a");
3139        let id = order.client_order_id();
3140        let mut source = source(&instrument, OrderSide::Buy);
3141        order
3142            .apply(OrderEventAny::Accepted(OrderAccepted::new(
3143                order.trader_id(),
3144                order.strategy_id(),
3145                instrument.id,
3146                id,
3147                VenueOrderId::from(source.order_id.as_str()),
3148                order.account_id().unwrap(),
3149                UUID4::new(),
3150                UnixNanos::from(2),
3151                UnixNanos::from(2),
3152                false,
3153            )))
3154            .unwrap();
3155        let command_id = UUID4::new();
3156
3157        if amendment {
3158            let mut pending = OrderPendingUpdate::new(
3159                order.trader_id(),
3160                order.strategy_id(),
3161                instrument.id,
3162                id,
3163                order.account_id(),
3164                UUID4::new(),
3165                UnixNanos::from(3),
3166                UnixNanos::from(3),
3167                false,
3168                order.venue_order_id(),
3169            );
3170
3171            pending.causation_id = Some(command_id);
3172            order.apply(OrderEventAny::PendingUpdate(pending)).unwrap();
3173        } else {
3174            let mut pending = OrderPendingCancel::new(
3175                order.trader_id(),
3176                order.strategy_id(),
3177                instrument.id,
3178                id,
3179                order.account_id(),
3180                UUID4::new(),
3181                UnixNanos::from(3),
3182                UnixNanos::from(3),
3183                false,
3184                order.venue_order_id(),
3185            );
3186
3187            pending.causation_id = Some(command_id);
3188            order.apply(OrderEventAny::PendingCancel(pending)).unwrap();
3189        }
3190
3191        let mut state = state(order.clone(), &instrument);
3192        if fresh_claim {
3193            state.mutations.insert(
3194                id,
3195                PendingMutation {
3196                    command_id,
3197                    started: UnixNanos::from(3),
3198                    dispatched: true,
3199                    acknowledgement: None,
3200                    terms: amendment.then_some((Quantity::from("3.00"), Price::from("0.700000"))),
3201                },
3202            );
3203        }
3204
3205        let (emitter, mut output) = emitter();
3206        source.status = VenueStatus::Unknown;
3207        source.fill_count_fp = FixedPoint(Decimal::from(filled));
3208        source.remaining_count_fp = FixedPoint(Decimal::from(3 - filled));
3209
3210        let fills = if filled == 0 {
3211            vec![]
3212        } else {
3213            vec![report(&source, &instrument, emitter.account_id())]
3214        };
3215
3216        let before = state.ledger.balance().unwrap();
3217        assert_eq!(
3218            state
3219                .plan_order(&source, &fills, &instrument, &emitter, UnixNanos::from(543))
3220                .unwrap_err()
3221                .to_string(),
3222            "Kalshi fills require authoritative order quantity"
3223        );
3224        assert_eq!(state.orders[&id].order, order);
3225        assert_eq!(
3226            state.orders[&id].order.has_pending_update_command(),
3227            amendment
3228        );
3229        assert_eq!(
3230            state.orders[&id].order.has_pending_cancel_command(),
3231            !amendment
3232        );
3233        assert_eq!(state.ledger.balance().unwrap(), before);
3234        assert_eq!(state.positions[&instrument.id], Decimal::ZERO);
3235        assert_eq!(
3236            state.mutations.get(&id).map(|pending| pending.command_id),
3237            fresh_claim.then_some(command_id)
3238        );
3239        assert!(output.try_recv().is_err());
3240    }
3241
3242    #[rstest]
3243    fn unknown_quantity_boundary_waits_for_authoritative_terms(
3244        #[values(false, true)] restored: bool,
3245    ) {
3246        let instrument = instrument();
3247        let mut order = submitted(&instrument, OrderSide::Buy, "client-a");
3248        let id = order.client_order_id();
3249        let command_id = UUID4::new();
3250
3251        if restored {
3252            let venue = source(&instrument, OrderSide::Buy);
3253            order
3254                .apply(OrderEventAny::Accepted(OrderAccepted::new(
3255                    order.trader_id(),
3256                    order.strategy_id(),
3257                    instrument.id,
3258                    id,
3259                    VenueOrderId::from(venue.order_id.as_str()),
3260                    order.account_id().unwrap(),
3261                    UUID4::new(),
3262                    UnixNanos::from(2),
3263                    UnixNanos::from(2),
3264                    false,
3265                )))
3266                .unwrap();
3267
3268            let mut pending = OrderPendingUpdate::new(
3269                order.trader_id(),
3270                order.strategy_id(),
3271                instrument.id,
3272                id,
3273                order.account_id(),
3274                UUID4::new(),
3275                UnixNanos::from(2),
3276                UnixNanos::from(2),
3277                false,
3278                order.venue_order_id(),
3279            );
3280
3281            pending.causation_id = Some(command_id);
3282            order.apply(OrderEventAny::PendingUpdate(pending)).unwrap();
3283        }
3284
3285        let mut state = state(order.clone(), &instrument);
3286        let (emitter, mut output) = emitter();
3287
3288        if !restored {
3289            state.mutations.insert(
3290                id,
3291                PendingMutation {
3292                    command_id,
3293                    started: UnixNanos::from(2),
3294                    dispatched: true,
3295                    acknowledgement: None,
3296                    terms: Some((Quantity::from("3.00"), Price::from("0.600000"))),
3297                },
3298            );
3299        }
3300
3301        let mut source = source(&instrument, OrderSide::Buy);
3302        source.status = VenueStatus::Unknown;
3303        source.fill_count_fp = FixedPoint(Decimal::from(2));
3304        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
3305        let fill = report(&source, &instrument, emitter.account_id());
3306        let before = state.ledger.balance().unwrap();
3307        assert_eq!(
3308            state
3309                .plan_order(
3310                    &source,
3311                    std::slice::from_ref(&fill),
3312                    &instrument,
3313                    &emitter,
3314                    UnixNanos::from(543)
3315                )
3316                .unwrap_err()
3317                .to_string(),
3318            "Kalshi fills require authoritative order quantity"
3319        );
3320        assert_eq!(state.orders[&id].order, order);
3321        assert_eq!(state.positions[&instrument.id], Decimal::ZERO);
3322        assert_eq!(state.ledger.balance().unwrap(), before);
3323
3324        if restored {
3325            assert!(!state.mutations.contains_key(&id));
3326        } else {
3327            assert_eq!(state.mutations[&id].command_id, command_id);
3328        }
3329
3330        assert!(output.try_recv().is_err());
3331        source.status = VenueStatus::Resting;
3332        source.remaining_count_fp = FixedPoint(Decimal::ONE);
3333        let plan = state
3334            .plan_order(
3335                &source,
3336                &[fill],
3337                &instrument,
3338                &emitter,
3339                UnixNanos::from(544),
3340            )
3341            .unwrap()
3342            .unwrap();
3343        state.apply_plans(vec![plan], &emitter).unwrap();
3344        let current = &state.orders[&id].order;
3345        assert_eq!(current.quantity(), Quantity::from("3.00"));
3346        assert_eq!(current.filled_qty(), Quantity::from("2.00"));
3347        assert_eq!(current.leaves_qty(), Quantity::from("1.00"));
3348        assert_eq!(current.status(), OrderStatus::PartiallyFilled);
3349        assert_eq!(state.positions[&instrument.id], Decimal::from(2));
3350
3351        if restored {
3352            assert!(!state.mutations.contains_key(&id));
3353        } else {
3354            assert_eq!(state.mutations[&id].command_id, command_id);
3355        }
3356
3357        assert_eq!(output.len(), if restored { 2 } else { 3 });
3358    }
3359
3360    #[rstest]
3361    fn active_ownership_survives_replay_eviction_and_reconnect() {
3362        let instrument = instrument();
3363        let order = submitted(&instrument, OrderSide::Buy, "client-a");
3364        let id = order.client_order_id();
3365        let mut state = state(order, &instrument);
3366        let source = source(&instrument, OrderSide::Buy);
3367        let retained = TradeId::from("retained-fill");
3368        state.fills.add(retained);
3369        for i in 0..100_001 {
3370            state.fills.add(TradeId::new(format!("other-{i}")));
3371        }
3372
3373        state.invalidate();
3374        assert!(!state.fills.contains(&retained));
3375        assert_eq!(
3376            state
3377                .source_order(&source)
3378                .unwrap()
3379                .unwrap()
3380                .client_order_id(),
3381            id
3382        );
3383        assert_eq!(state.orders[&id].order.status(), OrderStatus::Submitted);
3384    }
3385
3386    #[rstest]
3387    #[case(false)]
3388    #[case(true)]
3389    fn reconnect_replays_cash_in_fill_time_order_across_orders(#[case] tied: bool) {
3390        let instrument = instrument();
3391        let close = submitted(&instrument, OrderSide::Sell, "client-z");
3392        let reopen = submitted(&instrument, OrderSide::Buy, "client-a");
3393        let mut state = state(close, &instrument);
3394        state.restore(reopen);
3395        state.positions.insert(instrument.id, Decimal::ONE);
3396        let ticket = state.ledger.begin_refresh();
3397        state
3398            .ledger
3399            .apply_refresh(ticket, Decimal::new(1, 4), HashMap::new())
3400            .unwrap();
3401        let (emitter, mut output) = emitter();
3402        let mut closing = source(&instrument, OrderSide::Sell);
3403        closing.order_id = "z-close".into();
3404        closing.client_order_id = "client-z".into();
3405        let mut opening = source(&instrument, OrderSide::Buy);
3406        opening.order_id = "a-open".into();
3407        let mut close_fill = report(&closing, &instrument, emitter.account_id());
3408        close_fill.trade_id = TradeId::from("fill-z-close");
3409        let mut open_fill = report(&opening, &instrument, emitter.account_id());
3410        open_fill.trade_id = TradeId::from("fill-a-open");
3411        open_fill.ts_event = UnixNanos::from(close_fill.ts_event.as_u64() + u64::from(!tied));
3412        let opening = state
3413            .plan_order(
3414                &opening,
3415                &[open_fill],
3416                &instrument,
3417                &emitter,
3418                UnixNanos::from(543),
3419            )
3420            .unwrap()
3421            .unwrap();
3422        let closing = state
3423            .plan_order(
3424                &closing,
3425                &[close_fill],
3426                &instrument,
3427                &emitter,
3428                UnixNanos::from(543),
3429            )
3430            .unwrap()
3431            .unwrap();
3432        state.apply_plans(vec![opening, closing], &emitter).unwrap();
3433        let mut actual = Vec::new();
3434
3435        while let Ok(event) = output.try_recv() {
3436            if let ExecutionEvent::Order(OrderEventAny::Filled(event)) = event {
3437                actual.push(event.trade_id);
3438            }
3439        }
3440
3441        assert_eq!(
3442            actual,
3443            if tied {
3444                vec![TradeId::from("fill-a-open"), TradeId::from("fill-z-close")]
3445            } else {
3446                vec![TradeId::from("fill-z-close"), TradeId::from("fill-a-open")]
3447            }
3448        );
3449        assert_eq!(state.positions[&instrument.id], Decimal::ONE);
3450        let ticket = state.ledger.begin_refresh();
3451        let balance = state
3452            .ledger
3453            .apply_refresh(ticket, Decimal::new(98, 6), HashMap::new())
3454            .unwrap();
3455        assert_eq!(balance.total.as_decimal(), Decimal::new(98, 6));
3456    }
3457
3458    #[rstest]
3459    fn full_fill_and_stale_terminal_replay_preserve_the_completed_order_and_cash() {
3460        let instrument = instrument();
3461        let mut source = source(&instrument, OrderSide::Buy);
3462        source.status = VenueStatus::Executed;
3463        source.fill_count_fp = FixedPoint(Decimal::from(2));
3464        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
3465        let mut state = state(
3466            submitted(&instrument, OrderSide::Buy, "client-a"),
3467            &instrument,
3468        );
3469        let (emitter, mut output) = emitter();
3470        let mut fill = report(&source, &instrument, emitter.account_id());
3471        fill.ts_event = UnixNanos::from(fill.ts_event.as_u64() + 1);
3472        let plan = state
3473            .plan_order(
3474                &source,
3475                std::slice::from_ref(&fill),
3476                &instrument,
3477                &emitter,
3478                UnixNanos::from(543),
3479            )
3480            .unwrap()
3481            .unwrap();
3482        state.apply_plans(vec![plan], &emitter).unwrap();
3483        assert_eq!(output.len(), 3);
3484
3485        while output.try_recv().is_ok() {}
3486        let mut stale = source.clone();
3487        stale.status = VenueStatus::Canceled;
3488        stale.fill_count_fp = FixedPoint(Decimal::ZERO);
3489        stale.last_update_time = source.created_time.clone();
3490        assert!(
3491            state
3492                .plan_order(&stale, &[], &instrument, &emitter, UnixNanos::from(544))
3493                .unwrap()
3494                .is_none()
3495        );
3496        let plan = state
3497            .plan_order(
3498                &source,
3499                std::slice::from_ref(&fill),
3500                &instrument,
3501                &emitter,
3502                UnixNanos::from(545),
3503            )
3504            .unwrap()
3505            .unwrap();
3506        state.apply_plans(vec![plan], &emitter).unwrap();
3507        state
3508            .acknowledge(
3509                ClientOrderId::from("client-a"),
3510                VenueOrderId::new_checked(&source.order_id).unwrap(),
3511                UnixNanos::from(546),
3512                &emitter,
3513            )
3514            .unwrap();
3515        assert!(output.try_recv().is_err());
3516        assert!(
3517            state.orders[&ClientOrderId::from("client-a")]
3518                .order
3519                .is_closed()
3520        );
3521        assert_eq!(
3522            state
3523                .orders
3524                .get(&ClientOrderId::from("client-a"))
3525                .unwrap()
3526                .order
3527                .status(),
3528            OrderStatus::Filled
3529        );
3530        assert_eq!(state.positions[&instrument.id], Decimal::from(2));
3531        let ticket = state.ledger.begin_refresh();
3532        let balance = state
3533            .ledger
3534            .apply_refresh(ticket, "98.799899".parse().unwrap(), HashMap::new())
3535            .unwrap();
3536        assert_eq!(balance.total.as_decimal(), "98.799899".parse().unwrap());
3537    }
3538
3539    #[rstest]
3540    #[case(true)]
3541    #[case(false)]
3542    fn external_cached_metadata_routes_reports_and_applies_account_evidence_once(
3543        #[case] acknowledged: bool,
3544    ) {
3545        let instrument = instrument();
3546        let source = source(&instrument, OrderSide::Buy);
3547        let mut order = OrderTestBuilder::new(OrderType::Limit)
3548            .instrument_id(instrument.id)
3549            .client_order_id(ClientOrderId::from("client-a"))
3550            .strategy_id(StrategyId::external())
3551            .side(OrderSide::Buy)
3552            .quantity(Quantity::from("2.00"))
3553            .price(Price::from("0.600100"))
3554            .time_in_force(TimeInForce::Gtc)
3555            .build();
3556
3557        let accepted = OrderAccepted::new(
3558            order.trader_id(),
3559            order.strategy_id(),
3560            instrument.id,
3561            order.client_order_id(),
3562            VenueOrderId::from("order-a"),
3563            AccountId::from("KALSHI-007"),
3564            UUID4::new(),
3565            timestamp(&source.created_time).unwrap(),
3566            UnixNanos::from(9),
3567            false,
3568        );
3569
3570        if acknowledged {
3571            order.apply(OrderEventAny::Accepted(accepted)).unwrap();
3572        }
3573
3574        let mut state = state(order, &instrument);
3575        let (emitter, mut output) = emitter();
3576        let fill = report(&source, &instrument, emitter.account_id());
3577        let plan = state
3578            .plan_order(
3579                &source,
3580                std::slice::from_ref(&fill),
3581                &instrument,
3582                &emitter,
3583                UnixNanos::from(543),
3584            )
3585            .unwrap()
3586            .unwrap();
3587        state.apply_plans(vec![plan], &emitter).unwrap();
3588
3589        if !acknowledged {
3590            let ExecutionEvent::Report(ExecutionReport::OrderWithFills(before, fills)) =
3591                output.try_recv().unwrap()
3592            else {
3593                panic!("expected external acceptance report before fill");
3594            };
3595
3596            assert_eq!(before.order_status, OrderStatus::Accepted);
3597            assert_eq!(before.filled_qty, Quantity::from("0.00"));
3598            assert_eq!(before.quantity, Quantity::from("2.00"));
3599            assert_eq!(before.price, Some(fill.last_px));
3600            assert_eq!(before.client_order_id, fill.client_order_id);
3601            assert_eq!(before.venue_order_id, fill.venue_order_id);
3602            assert_eq!(fills, Vec::new());
3603        }
3604
3605        let ExecutionEvent::Report(ExecutionReport::Fill(actual)) = output.try_recv().unwrap()
3606        else {
3607            panic!("expected external fill report");
3608        };
3609
3610        assert_eq!(*actual, fill);
3611
3612        let ExecutionEvent::Report(ExecutionReport::OrderWithFills(order, fills)) =
3613            output.try_recv().unwrap()
3614        else {
3615            panic!("expected external snapshot report");
3616        };
3617
3618        assert_eq!(order.order_status, OrderStatus::PartiallyFilled);
3619        assert_eq!(order.filled_qty, Quantity::from("0.75"));
3620        assert_eq!(order.quantity, Quantity::from("2.00"));
3621        assert_eq!(order.client_order_id, Some(ClientOrderId::from("client-a")));
3622        assert_eq!(order.price, Some(fill.last_px));
3623        assert_eq!(fills, Vec::new());
3624        assert!(output.try_recv().is_err());
3625        let plan = state
3626            .plan_order(
3627                &source,
3628                &[fill],
3629                &instrument,
3630                &emitter,
3631                UnixNanos::from(544),
3632            )
3633            .unwrap()
3634            .unwrap();
3635        state.apply_plans(vec![plan], &emitter).unwrap();
3636        assert_eq!(output.len(), 1);
3637        assert_eq!(state.positions[&instrument.id], "0.75".parse().unwrap());
3638        let ticket = state.ledger.begin_refresh();
3639        let balance = state
3640            .ledger
3641            .apply_refresh(ticket, "99.550024".parse().unwrap(), HashMap::new())
3642            .unwrap();
3643        assert_eq!(balance.total.as_decimal(), "99.550024".parse().unwrap());
3644    }
3645
3646    #[rstest]
3647    #[case::buy(false, true, OrderSide::Buy, "99.550024", "0.75")]
3648    #[case::partial(false, false, OrderSide::Buy, "99.550024", "0.75")]
3649    #[case::sell_without_client_id(true, true, OrderSide::Sell, "99.700174", "-0.75")]
3650    fn unknown_external_recovery_preserves_core_economics_and_owned_context(
3651        #[case] empty_id: bool,
3652        #[case] terminal: bool,
3653        #[case] side: OrderSide,
3654        #[case] cash: &str,
3655        #[case] net: &str,
3656    ) {
3657        use nautilus_live::testing::ExecutionHarness;
3658        use nautilus_model::{accounts::AccountAny, events::AccountState};
3659
3660        let instrument = instrument();
3661        let (emitter, mut output) = emitter();
3662
3663        let harness = ExecutionHarness::new(
3664            emitter.trader_id(),
3665            "KALSHI".into(),
3666            emitter.account_id(),
3667            instrument.clone().into(),
3668        );
3669
3670        let account = AccountState::new(
3671            emitter.account_id(),
3672            AccountType::Cash,
3673            Vec::new(),
3674            Vec::new(),
3675            true,
3676            UUID4::new(),
3677            UnixNanos::from(1),
3678            UnixNanos::from(1),
3679            Some(Currency::USD()),
3680        );
3681
3682        harness
3683            .cache()
3684            .borrow_mut()
3685            .add_account(AccountAny::from(account))
3686            .unwrap();
3687        let owned = submitted(&instrument, side, "owned-order");
3688        harness
3689            .cache()
3690            .borrow_mut()
3691            .add_order(owned.clone(), None, Some(harness.client_id()), false)
3692            .unwrap();
3693        let mut state = state(owned.clone(), &instrument);
3694        let mut owned_source = source(&instrument, side);
3695        owned_source.client_order_id = "owned-order".into();
3696        owned_source.order_id = "owned-venue-order".into();
3697        assert_eq!(
3698            state
3699                .recovery_order(&owned_source, &instrument, &emitter, UnixNanos::from(543))
3700                .unwrap(),
3701            Some(owned.clone())
3702        );
3703
3704        let mut source = source(&instrument, side);
3705        if terminal {
3706            source.status = VenueStatus::Executed;
3707            source.remaining_count_fp = FixedPoint(Decimal::ZERO);
3708        }
3709
3710        if empty_id {
3711            source.client_order_id.clear();
3712        }
3713
3714        let id = ClientOrderId::from(if empty_id { "order-a" } else { "client-a" });
3715        let mut fill = report(&source, &instrument, emitter.account_id());
3716        fill.client_order_id = Some(id);
3717
3718        for iteration in 0..2 {
3719            let plan = state
3720                .plan_order(
3721                    &source,
3722                    std::slice::from_ref(&fill),
3723                    &instrument,
3724                    &emitter,
3725                    UnixNanos::from(543 + iteration),
3726                )
3727                .unwrap()
3728                .unwrap();
3729            state.apply_plans(vec![plan], &emitter).unwrap();
3730            let mut fill_reports = 0;
3731
3732            while let Ok(event) = output.try_recv() {
3733                let ExecutionEvent::Report(report) = event else {
3734                    panic!("external recovery emitted owned order event")
3735                };
3736
3737                if let ExecutionReport::Fill(actual) = &report {
3738                    assert_eq!(actual.as_ref(), &fill);
3739                    fill_reports += 1;
3740                }
3741
3742                harness
3743                    .exec_engine()
3744                    .borrow_mut()
3745                    .reconcile_execution_report(&report);
3746            }
3747
3748            assert_eq!(fill_reports, usize::from(iteration == 0));
3749        }
3750
3751        let cache = harness.cache().borrow();
3752        let external = cache.order(&id).unwrap();
3753        assert_eq!(external.strategy_id(), StrategyId::external());
3754        assert_eq!(
3755            external.status(),
3756            if terminal {
3757                OrderStatus::Filled
3758            } else {
3759                OrderStatus::PartiallyFilled
3760            }
3761        );
3762        assert_eq!(
3763            external.quantity(),
3764            Quantity::from(if terminal { "0.75" } else { "2.00" })
3765        );
3766        assert_eq!(external.filled_qty(), Quantity::from("0.75"));
3767        assert_eq!(external.trade_ids(), vec![&fill.trade_id]);
3768        assert_eq!(external.time_in_force(), TimeInForce::Gtc);
3769        assert!(!external.is_post_only());
3770        assert!(!external.is_reduce_only());
3771        assert_eq!(
3772            cache.order(&owned.client_order_id()).unwrap().cloned(),
3773            owned
3774        );
3775        let positions = cache.positions_open(
3776            None,
3777            Some(&instrument.id),
3778            None,
3779            Some(&emitter.account_id()),
3780            None,
3781        );
3782        assert_eq!(positions.len(), 1);
3783        assert_eq!(positions[0].signed_decimal_qty(), net.parse().unwrap());
3784        assert_eq!(positions[0].commissions(), vec![fill.commission]);
3785        assert_eq!(
3786            positions[0].trade_ids,
3787            [fill.trade_id].into_iter().collect()
3788        );
3789        assert_eq!(state.positions[&instrument.id], net.parse().unwrap());
3790        let ticket = state.ledger.begin_refresh();
3791        let balance = state
3792            .ledger
3793            .apply_refresh(ticket, cash.parse().unwrap(), HashMap::new())
3794            .unwrap();
3795        assert_eq!(balance.total.as_decimal(), cash.parse().unwrap());
3796    }
3797
3798    #[rstest]
3799    fn external_local_identity_cannot_replace_an_owned_order() {
3800        let instrument = instrument();
3801        let owned = submitted(&instrument, OrderSide::Buy, "order-a");
3802        let state = state(owned.clone(), &instrument);
3803        let (emitter, mut output) = emitter();
3804        let mut source = source(&instrument, OrderSide::Buy);
3805        source.client_order_id.clear();
3806        let error = state
3807            .recovery_order(&source, &instrument, &emitter, UnixNanos::from(543))
3808            .unwrap_err();
3809        assert_eq!(
3810            error.to_string(),
3811            "recovered order identity conflicts with an existing order"
3812        );
3813        assert_eq!(state.orders[&owned.client_order_id()].order, owned);
3814        assert!(output.try_recv().is_err());
3815    }
3816
3817    #[rstest]
3818    #[case(OrderStatus::Accepted, false, "100.0001", "0")]
3819    #[case(OrderStatus::Accepted, true, "100.0001", "0")]
3820    #[case(OrderStatus::Canceled, false, "100.0001", "0")]
3821    #[case(OrderStatus::Canceled, true, "100.0001", "0")]
3822    #[case(OrderStatus::PartiallyFilled, false, "99.550024", "0.75")]
3823    #[case(OrderStatus::PartiallyFilled, true, "99.550024", "0.75")]
3824    fn restore_preserves_execution_progress_when_timestamps_tie(
3825        #[case] progressed_status: OrderStatus,
3826        #[case] cached_ahead: bool,
3827        #[case] cash: &str,
3828        #[case] net: &str,
3829    ) {
3830        let instrument = instrument();
3831        let mut source = source(&instrument, OrderSide::Buy);
3832        let mut state = state(
3833            submitted(&instrument, OrderSide::Buy, "client-a"),
3834            &instrument,
3835        );
3836        let id = ClientOrderId::from("client-a");
3837        let ts_event = state.orders[&id].order.ts_last();
3838        let timestamp = jiff::Timestamp::from_nanosecond(i128::from(ts_event.as_u64())).unwrap();
3839        source.created_time = Field::Value(timestamp);
3840        source.last_update_time = Field::Value(timestamp);
3841        if progressed_status != OrderStatus::PartiallyFilled {
3842            source.fill_count_fp = FixedPoint(Decimal::ZERO);
3843            source.remaining_count_fp = FixedPoint(Decimal::from(2));
3844        }
3845
3846        if progressed_status == OrderStatus::Canceled {
3847            source.status = VenueStatus::Canceled;
3848        }
3849
3850        let (emitter, mut output) = emitter();
3851
3852        if progressed_status != OrderStatus::Accepted {
3853            state
3854                .acknowledge(id, source.order_id.as_str().into(), ts_event, &emitter)
3855                .unwrap();
3856        }
3857
3858        let lagging = state.orders[&id].order.clone();
3859
3860        let fills = if progressed_status == OrderStatus::PartiallyFilled {
3861            let mut fill = report(&source, &instrument, emitter.account_id());
3862            fill.ts_event = ts_event;
3863            vec![fill]
3864        } else {
3865            Vec::new()
3866        };
3867
3868        let plan = state
3869            .plan_order(&source, &fills, &instrument, &emitter, UnixNanos::from(543))
3870            .unwrap()
3871            .unwrap();
3872        let progressed = plan.result.clone();
3873        assert_eq!(lagging.ts_last(), progressed.ts_last());
3874
3875        if cached_ahead {
3876            state.restore(progressed.clone());
3877        } else {
3878            state.apply_plans(vec![plan], &emitter).unwrap();
3879            state.restore(lagging);
3880        }
3881
3882        assert_eq!(state.orders[&id].order, progressed);
3883
3884        while output.try_recv().is_ok() {}
3885        let plan = state
3886            .plan_order(&source, &fills, &instrument, &emitter, UnixNanos::from(544))
3887            .unwrap()
3888            .unwrap();
3889        state.apply_plans(vec![plan], &emitter).unwrap();
3890        let ticket = state.ledger.begin_refresh();
3891        let balance = state
3892            .ledger
3893            .apply_refresh(ticket, cash.parse().unwrap(), HashMap::new())
3894            .unwrap();
3895        assert_eq!(state.orders[&id].order.status(), progressed_status);
3896        assert_eq!(
3897            state.positions[&instrument.id],
3898            net.parse::<Decimal>().unwrap()
3899        );
3900        assert_eq!(balance.total.as_decimal(), cash.parse::<Decimal>().unwrap());
3901        assert_eq!(output.len(), 0);
3902    }
3903
3904    #[rstest]
3905    fn new_cached_completed_accounting_rebases_without_applying_cached_fill_again() {
3906        let instrument = instrument();
3907        let mut source = source(&instrument, OrderSide::Buy);
3908        source.status = VenueStatus::Executed;
3909        source.fill_count_fp = FixedPoint(Decimal::from(2));
3910        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
3911        let mut state = state(
3912            submitted(&instrument, OrderSide::Buy, "client-a"),
3913            &instrument,
3914        );
3915        let (emitter, mut output) = emitter();
3916        let fill = report(&source, &instrument, emitter.account_id());
3917        let plan = state
3918            .plan_order(
3919                &source,
3920                std::slice::from_ref(&fill),
3921                &instrument,
3922                &emitter,
3923                UnixNanos::from(543),
3924            )
3925            .unwrap()
3926            .unwrap();
3927        let cached = plan.result.clone();
3928        state.apply_plans(vec![plan], &emitter).unwrap();
3929
3930        while output.try_recv().is_ok() {}
3931        let ticket = state.ledger.begin_refresh();
3932        let total: Decimal = "98.799899".parse().unwrap();
3933        state
3934            .ledger
3935            .apply_refresh(ticket, total, HashMap::new())
3936            .unwrap();
3937        state.orders.clear();
3938        state.bindings.clear();
3939        state.fills.clear();
3940        state.restore(cached);
3941        let plan = state
3942            .plan_order(
3943                &source,
3944                &[fill],
3945                &instrument,
3946                &emitter,
3947                UnixNanos::from(544),
3948            )
3949            .unwrap()
3950            .unwrap();
3951        state.apply_plans(vec![plan], &emitter).unwrap();
3952        assert_eq!(state.positions[&instrument.id], Decimal::from(2));
3953        assert_eq!(output.len(), 0);
3954        let ticket = state.ledger.begin_refresh();
3955        assert_eq!(
3956            state
3957                .ledger
3958                .apply_refresh(ticket, total, HashMap::new())
3959                .unwrap()
3960                .total
3961                .as_decimal(),
3962            total
3963        );
3964    }
3965
3966    #[rstest]
3967    fn cached_positions_seed_once_until_an_accounting_rebase() {
3968        let instrument = instrument();
3969        let mut state = PrivateState::new();
3970        let cached = vec![
3971            (instrument.id, Decimal::new(275, 2), UnixNanos::from(123)),
3972            (instrument.id, Decimal::new(-75, 2), UnixNanos::from(125)),
3973        ];
3974        state.seed_positions(cached.clone()).unwrap();
3975        state.seed_positions(cached).unwrap();
3976        assert!(state.ledger.total_is_unknown());
3977        assert_eq!(
3978            state.positions,
3979            HashMap::from([(instrument.id, Decimal::from(2))])
3980        );
3981        assert_eq!(
3982            state.positions_ts,
3983            HashMap::from([(instrument.id, UnixNanos::from(125))])
3984        );
3985        state.rebase();
3986        state
3987            .seed_positions([(instrument.id, Decimal::new(75, 2), UnixNanos::from(126))])
3988            .unwrap();
3989        assert_eq!(
3990            state.positions,
3991            HashMap::from([(instrument.id, Decimal::new(75, 2))])
3992        );
3993        assert_eq!(
3994            state.positions_ts,
3995            HashMap::from([(instrument.id, UnixNanos::from(126))])
3996        );
3997    }
3998
3999    #[rstest]
4000    fn failed_initial_settlement_preview_keeps_the_opening_net_and_is_retryable() {
4001        let instrument = instrument();
4002        let mut state = PrivateState::new();
4003        state
4004            .seed_positions([(instrument.id, Decimal::new(75, 2), UnixNanos::from(123))])
4005            .unwrap();
4006
4007        let settlements = [Settlement {
4008            instrument_id: instrument.id,
4009            value: Decimal::ONE,
4010            ts_event: UnixNanos::from(124),
4011            net: None,
4012        }];
4013
4014        let openings = state.openings(&[], &[], &settlements).unwrap();
4015        let mut holds = HashMap::from([(
4016            ReservationId::Client(ClientOrderId::from("pending")),
4017            Decimal::from(2),
4018        )]);
4019        assert_eq!(
4020            state
4021                .preview(&[], &openings, &settlements, Decimal::ONE, &mut holds)
4022                .unwrap_err()
4023                .to_string(),
4024            "insufficient Kalshi cash for admission holds"
4025        );
4026        assert!(state.ledger.total_is_unknown());
4027        assert_eq!(state.positions, openings);
4028        assert_eq!(state.positions_ts[&instrument.id], UnixNanos::from(123));
4029        let (balance, projected) = state
4030            .preview(
4031                &[],
4032                &openings,
4033                &settlements,
4034                Decimal::ONE,
4035                &mut HashMap::new(),
4036            )
4037            .unwrap();
4038        assert_eq!(projected[&instrument.id], Decimal::ZERO);
4039        assert_eq!(balance.total.as_decimal(), Decimal::ONE);
4040        assert_eq!(balance.free.as_decimal(), Decimal::ONE);
4041        assert_eq!(balance.locked.as_decimal(), Decimal::ZERO);
4042        assert!(state.ledger.total_is_unknown());
4043        assert_eq!(state.positions, openings);
4044    }
4045
4046    #[rstest]
4047    fn late_fill_after_cancellation_uses_the_retained_owned_context() {
4048        let instrument = instrument();
4049        let mut source = source(&instrument, OrderSide::Buy);
4050        source.status = VenueStatus::Canceled;
4051        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
4052        let mut state = state(
4053            submitted(&instrument, OrderSide::Buy, "client-a"),
4054            &instrument,
4055        );
4056        let (emitter, mut output) = emitter();
4057        let first = report(&source, &instrument, emitter.account_id());
4058        let plan = state
4059            .plan_order(
4060                &source,
4061                std::slice::from_ref(&first),
4062                &instrument,
4063                &emitter,
4064                UnixNanos::from(543),
4065            )
4066            .unwrap()
4067            .unwrap();
4068        state.apply_plans(vec![plan], &emitter).unwrap();
4069
4070        while output.try_recv().is_ok() {}
4071        let stale = source.clone();
4072        source.status = VenueStatus::Executed;
4073        source.fill_count_fp = FixedPoint(Decimal::from(2));
4074        source.last_update_time = Field::Value("2026-10-16T08:08:08.800000008Z".parse().unwrap());
4075        let mut late = first.clone();
4076        late.trade_id = TradeId::from("late-fill");
4077        late.last_qty = Quantity::from("1.25");
4078        late.ts_event = UnixNanos::from(first.ts_event.as_u64() + 1);
4079        let plan = state
4080            .plan_order(
4081                &source,
4082                &[first, late.clone()],
4083                &instrument,
4084                &emitter,
4085                UnixNanos::from(544),
4086            )
4087            .unwrap()
4088            .unwrap();
4089        state.apply_plans(vec![plan], &emitter).unwrap();
4090        assert!(
4091            matches!(output.try_recv().unwrap(), ExecutionEvent::Order(OrderEventAny::Filled(event)) if event.trade_id == late.trade_id && event.last_qty == late.last_qty && event.client_order_id == ClientOrderId::from("client-a"))
4092        );
4093        assert_eq!(output.len(), 0);
4094        assert_eq!(
4095            state
4096                .orders
4097                .get(&ClientOrderId::from("client-a"))
4098                .unwrap()
4099                .order
4100                .status(),
4101            OrderStatus::Filled
4102        );
4103        assert_eq!(state.positions[&instrument.id], Decimal::from(2));
4104        assert!(
4105            state
4106                .plan_order(&stale, &[], &instrument, &emitter, UnixNanos::from(545))
4107                .unwrap()
4108                .is_none()
4109        );
4110    }
4111
4112    #[rstest]
4113    #[case(true)]
4114    #[case(false)]
4115    fn uncertain_amendment_or_cancellation_is_retained_until_authoritative_terminal_evidence(
4116        #[case] amendment: bool,
4117    ) {
4118        let instrument = instrument();
4119        let mut source = source(&instrument, OrderSide::Buy);
4120        source.fill_count_fp = FixedPoint(Decimal::ZERO);
4121        source.remaining_count_fp = FixedPoint(Decimal::from(2));
4122        let mut state = state(
4123            submitted(&instrument, OrderSide::Buy, "client-a"),
4124            &instrument,
4125        );
4126        let (emitter, mut output) = emitter();
4127        let plan = state
4128            .plan_order(&source, &[], &instrument, &emitter, UnixNanos::from(543))
4129            .unwrap()
4130            .unwrap();
4131        state.apply_plans(vec![plan], &emitter).unwrap();
4132
4133        while output.try_recv().is_ok() {}
4134        let mut order = state.orders[&ClientOrderId::from("client-a")].order.clone();
4135
4136        let pending = if amendment {
4137            OrderEventAny::PendingUpdate(OrderPendingUpdate::new(
4138                order.trader_id(),
4139                order.strategy_id(),
4140                instrument.id,
4141                order.client_order_id(),
4142                order.account_id(),
4143                UUID4::new(),
4144                UnixNanos::from(timestamp(&source.last_update_time).unwrap().as_u64() + 1),
4145                UnixNanos::from(544),
4146                false,
4147                order.venue_order_id(),
4148            ))
4149        } else {
4150            OrderEventAny::PendingCancel(OrderPendingCancel::new(
4151                order.trader_id(),
4152                order.strategy_id(),
4153                instrument.id,
4154                order.client_order_id(),
4155                order.account_id(),
4156                UUID4::new(),
4157                UnixNanos::from(timestamp(&source.last_update_time).unwrap().as_u64() + 1),
4158                UnixNanos::from(544),
4159                false,
4160                order.venue_order_id(),
4161            ))
4162        };
4163
4164        order.apply(pending).unwrap();
4165        let status = order.status();
4166        state.restore(order);
4167        assert!(
4168            state
4169                .plan_order(&source, &[], &instrument, &emitter, UnixNanos::from(545))
4170                .unwrap()
4171                .is_none()
4172        );
4173        assert_eq!(
4174            state.orders[&ClientOrderId::from("client-a")]
4175                .order
4176                .status(),
4177            status
4178        );
4179
4180        if amendment {
4181            assert_eq!(
4182                state.check_amendments(&[]).unwrap_err().to_string(),
4183                "uncertain amendment lacks authoritative terms"
4184            );
4185        } else {
4186            state.check_amendments(&[]).unwrap();
4187        }
4188
4189        assert_eq!(output.len(), 0);
4190        source.status = VenueStatus::Canceled;
4191        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
4192        source.last_update_time = Field::Value("2026-10-16T08:08:08.800000008Z".parse().unwrap());
4193        let plan = state
4194            .plan_order(&source, &[], &instrument, &emitter, UnixNanos::from(546))
4195            .unwrap()
4196            .unwrap();
4197        state.check_amendments(std::slice::from_ref(&plan)).unwrap();
4198        state.apply_plans(vec![plan], &emitter).unwrap();
4199        assert!(
4200            matches!(output.try_recv().unwrap(), ExecutionEvent::Order(OrderEventAny::Canceled(event)) if event.client_order_id == ClientOrderId::from("client-a") && event.ts_event == timestamp(&source.last_update_time).unwrap())
4201        );
4202        assert_eq!(output.len(), 0);
4203        assert_eq!(
4204            state
4205                .orders
4206                .get(&ClientOrderId::from("client-a"))
4207                .unwrap()
4208                .order
4209                .status(),
4210            OrderStatus::Canceled
4211        );
4212        assert_eq!(state.positions[&instrument.id], Decimal::ZERO);
4213        let ticket = state.ledger.begin_refresh();
4214        let cash: Decimal = "100.0001".parse().unwrap();
4215        assert_eq!(
4216            state
4217                .ledger
4218                .apply_refresh(ticket, cash, HashMap::new())
4219                .unwrap()
4220                .total
4221                .as_decimal(),
4222            cash
4223        );
4224    }
4225
4226    #[rstest]
4227    fn successfully_routed_position_evidence_prevents_an_older_settlement() {
4228        let instrument = instrument();
4229        let mut state = state(
4230            submitted(&instrument, OrderSide::Buy, "client-a"),
4231            &instrument,
4232        );
4233        state.positions.insert(instrument.id, Decimal::new(75, 2));
4234        state
4235            .positions_ts
4236            .insert(instrument.id, UnixNanos::from(100));
4237        let (closed, output) = emitter();
4238
4239        let report = PositionStatusReport::new(
4240            closed.account_id(),
4241            instrument.id,
4242            PositionSide::Long,
4243            Quantity::from("0.75"),
4244            UnixNanos::from(200),
4245            UnixNanos::from(210),
4246            None,
4247            None,
4248            None,
4249        );
4250
4251        drop(output);
4252        assert!(state.apply_position(report.clone(), &closed).is_err());
4253        assert_eq!(state.positions_ts[&instrument.id], UnixNanos::from(100));
4254        let (emitter, mut output) = emitter();
4255        state.apply_position(report.clone(), &emitter).unwrap();
4256
4257        let ExecutionEvent::Report(ExecutionReport::Position(actual)) = output.try_recv().unwrap()
4258        else {
4259            panic!("expected current position report");
4260        };
4261
4262        assert_eq!(*actual, report);
4263        assert_eq!(state.positions_ts[&instrument.id], UnixNanos::from(200));
4264        assert_eq!(
4265            state
4266                .preview(
4267                    &[],
4268                    &state.positions,
4269                    &[Settlement {
4270                        instrument_id: instrument.id,
4271                        value: Decimal::ONE,
4272                        ts_event: UnixNanos::from(150),
4273                        net: None
4274                    }],
4275                    "100.0001".parse().unwrap(),
4276                    &mut HashMap::new()
4277                )
4278                .unwrap_err()
4279                .to_string(),
4280            "settlement precedes collected execution evidence"
4281        );
4282        assert_eq!(
4283            state
4284                .settle(
4285                    &instrument,
4286                    Decimal::ONE,
4287                    UnixNanos::from(150),
4288                    UnixNanos::from(211),
4289                    &emitter
4290                )
4291                .unwrap_err()
4292                .to_string(),
4293            "settlement precedes collected execution evidence"
4294        );
4295        assert_eq!(state.positions[&instrument.id], Decimal::new(75, 2));
4296        assert_eq!(output.len(), 0);
4297    }
4298
4299    #[rstest]
4300    fn authoritative_reduction_to_already_filled_quantity_closes_without_another_fill() {
4301        let instrument = instrument();
4302        let mut source = source(&instrument, OrderSide::Buy);
4303        let mut state = state(
4304            submitted(&instrument, OrderSide::Buy, "client-a"),
4305            &instrument,
4306        );
4307        let (emitter, mut output) = emitter();
4308        let fill = report(&source, &instrument, emitter.account_id());
4309        let plan = state
4310            .plan_order(
4311                &source,
4312                std::slice::from_ref(&fill),
4313                &instrument,
4314                &emitter,
4315                UnixNanos::from(543),
4316            )
4317            .unwrap()
4318            .unwrap();
4319        state.apply_plans(vec![plan], &emitter).unwrap();
4320
4321        while output.try_recv().is_ok() {}
4322        let id = ClientOrderId::from("client-a");
4323        let total: Decimal = "99.550024".parse().unwrap();
4324        let ticket = state.ledger.begin_refresh();
4325        state
4326            .ledger
4327            .apply_refresh(
4328                ticket,
4329                total,
4330                HashMap::from([(ReservationId::Client(id), Decimal::new(5, 1))]),
4331            )
4332            .unwrap();
4333        source.status = VenueStatus::Executed;
4334        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
4335        source.last_update_time = Field::Value("2026-10-16T08:08:08.800000008Z".parse().unwrap());
4336        let plan = state
4337            .plan_order(
4338                &source,
4339                &[fill],
4340                &instrument,
4341                &emitter,
4342                UnixNanos::from(544),
4343            )
4344            .unwrap()
4345            .unwrap();
4346        state.apply_plans(vec![plan], &emitter).unwrap();
4347        assert!(
4348            matches!(output.try_recv().unwrap(), ExecutionEvent::Order(OrderEventAny::Updated(event)) if event.quantity == Quantity::from("0.75") && event.reconciliation)
4349        );
4350        assert_eq!(output.len(), 0);
4351        assert!(state.orders[&id].order.is_closed());
4352        assert_eq!(
4353            state.orders.get(&id).unwrap().order.status(),
4354            OrderStatus::Filled
4355        );
4356        assert_eq!(
4357            state.orders.get(&id).unwrap().order.filled_qty(),
4358            Quantity::from("0.75")
4359        );
4360        assert_eq!(state.positions[&instrument.id], Decimal::new(75, 2));
4361        let ticket = state.ledger.begin_refresh();
4362        let balance = state
4363            .ledger
4364            .apply_refresh(ticket, total, HashMap::new())
4365            .unwrap();
4366        assert_eq!(balance.total.as_decimal(), total);
4367        assert_eq!(balance.locked.as_decimal(), Decimal::ZERO);
4368        assert_eq!(balance.free.as_decimal(), total);
4369    }
4370
4371    #[rstest]
4372    fn position_notice_counts_new_and_retained_plans_once() {
4373        let instrument = instrument();
4374        let owned = submitted(&instrument, OrderSide::Buy, "buy");
4375        let mut state = state(owned, &instrument);
4376        let (emitter, _output) = emitter();
4377        let mut plans = Vec::new();
4378
4379        for (side, id) in [(OrderSide::Buy, "buy"), (OrderSide::Sell, "sell")] {
4380            let mut source = source(&instrument, side);
4381            source.client_order_id = id.into();
4382            source.order_id = format!("venue-{id}");
4383            source.status = VenueStatus::Executed;
4384            source.remaining_count_fp = FixedPoint(Decimal::ZERO);
4385            let mut fill = report(&source, &instrument, emitter.account_id());
4386            fill.trade_id = TradeId::from(id);
4387            fill.commission = Money::from("0 USD");
4388
4389            if id == "buy" {
4390                let plan = state
4391                    .plan_order(
4392                        &source,
4393                        std::slice::from_ref(&fill),
4394                        &instrument,
4395                        &emitter,
4396                        UnixNanos::from(543),
4397                    )
4398                    .unwrap()
4399                    .unwrap();
4400                state.apply_plans(vec![plan], &emitter).unwrap();
4401            }
4402
4403            plans.push(
4404                state
4405                    .plan_order(
4406                        &source,
4407                        &[fill],
4408                        &instrument,
4409                        &emitter,
4410                        UnixNanos::from(543),
4411                    )
4412                    .unwrap()
4413                    .unwrap(),
4414            );
4415        }
4416
4417        let fixtures: Value =
4418            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
4419        let mut position: MarketPosition =
4420            serde_json::from_value(fixtures["positions"]["market_positions"][0].clone()).unwrap();
4421        position.ticker = instrument.id.symbol.to_string();
4422        position.position_fp = FixedPoint(Decimal::ZERO);
4423        position.realized_pnl_dollars = FixedPoint(Decimal::ZERO);
4424        position.fees_paid_dollars = FixedPoint(Decimal::ZERO);
4425        state.notices_positions.insert(
4426            instrument.id,
4427            PositionNotice {
4428                volume: Decimal::new(150, 2),
4429                economics: Some(PositionEconomics {
4430                    position_fp: position.position_fp,
4431                    realized_pnl_dollars: position.realized_pnl_dollars,
4432                    fees_paid_dollars: position.fees_paid_dollars,
4433                }),
4434            },
4435        );
4436
4437        let snapshot = super::super::KalshiExecutionSnapshot {
4438            orders: Vec::new(),
4439            fills: Vec::new(),
4440            positions: vec![position],
4441            positions_settled: Vec::new(),
4442            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
4443            lookback_start: Some(state.start),
4444            ts_init: UnixNanos::from(543),
4445        };
4446
4447        assert_eq!(
4448            state
4449                .check_notices(&snapshot, &plans[..1])
4450                .unwrap_err()
4451                .to_string(),
4452            "REST recovery does not yet cover notified traded volume"
4453        );
4454        state.check_notices(&snapshot, &plans).unwrap();
4455        assert_eq!(state.orders.len(), 1);
4456        state
4457            .notices_positions
4458            .get_mut(&instrument.id)
4459            .unwrap()
4460            .volume = Decimal::new(225, 2);
4461        assert_eq!(
4462            state
4463                .check_notices(&snapshot, &plans)
4464                .unwrap_err()
4465                .to_string(),
4466            "REST recovery does not yet cover notified traded volume"
4467        );
4468        state
4469            .notices_positions
4470            .get_mut(&instrument.id)
4471            .unwrap()
4472            .volume = Decimal::new(150, 2);
4473        state.apply_plans(plans, &emitter).unwrap();
4474        state.check_notices(&snapshot, &[]).unwrap();
4475        state
4476            .notices_positions
4477            .get_mut(&instrument.id)
4478            .unwrap()
4479            .volume = Decimal::new(225, 2);
4480        assert_eq!(
4481            state.check_notices(&snapshot, &[]).unwrap_err().to_string(),
4482            "REST recovery does not yet cover notified traded volume"
4483        );
4484    }
4485
4486    #[rstest]
4487    fn fill_notice_requires_market_identity() {
4488        let mut state = PrivateState::new();
4489        let notice =
4490            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
4491                .unwrap()["fill_without_market"]
4492                .clone();
4493        let notice = serde_json::from_value(notice).unwrap();
4494
4495        let error = state.notice(&notice).unwrap_err();
4496
4497        assert_eq!(
4498            error.to_string(),
4499            "private fill notification lacks market identity"
4500        );
4501        assert_eq!(state.notices_fills.len(), 1);
4502        assert!(
4503            state.notices_fills[&TradeId::from("current-fill")]
4504                .instrument
4505                .is_none(),
4506            "malformed fill must retain identity without an instrument bypass"
4507        );
4508        assert_eq!(state.start, UnixNanos::from(1_792_112_523_000_000_000));
4509        let fixtures: Value =
4510            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
4511
4512        let snapshot = super::super::KalshiExecutionSnapshot {
4513            orders: Vec::new(),
4514            fills: Vec::new(),
4515            positions: Vec::new(),
4516            positions_settled: Vec::new(),
4517            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
4518            lookback_start: Some(state.start),
4519            ts_init: UnixNanos::from(u64::MAX - 1000),
4520        };
4521
4522        assert_eq!(
4523            state.check_notices(&snapshot, &[]).unwrap_err().to_string(),
4524            "REST recovery does not yet cover received fill identities"
4525        );
4526    }
4527
4528    #[rstest]
4529    fn explicit_fill_notice_covers_position_with_older_traded_volume() {
4530        let instrument = instrument();
4531        let owned = submitted(&instrument, OrderSide::Buy, "current");
4532        let mut state = state(owned, &instrument);
4533        let (emitter, _output) = emitter();
4534        let mut source = source(&instrument, OrderSide::Buy);
4535        source.client_order_id = "current".into();
4536        source.order_id = "venue-current".into();
4537        source.status = VenueStatus::Executed;
4538        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
4539        let fixtures: Value =
4540            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
4541        let mut fill: Fill = serde_json::from_value(fixtures["fills"]["fills"][0].clone()).unwrap();
4542        fill.fill_id = "current-fill".into();
4543        fill.trade_id = "current-fill".into();
4544        fill.order_id = source.order_id.clone();
4545        fill.ticker = source.ticker.clone();
4546        fill.market_ticker = source.ticker.clone();
4547        fill.book_side = source.book_side;
4548        fill.outcome_side = source.outcome_side;
4549        fill.count_fp = source.fill_count_fp;
4550        fill.yes_price_dollars = source.yes_price_dollars;
4551        fill.no_price_dollars = source.no_price_dollars;
4552        fill.fee_cost = FixedPoint(Decimal::ZERO);
4553        let report = reports::fill(
4554            &fill,
4555            &instrument,
4556            emitter.account_id(),
4557            &source,
4558            UnixNanos::from(543),
4559        )
4560        .unwrap();
4561        let plan = state
4562            .plan_order(
4563                &source,
4564                &[report],
4565                &instrument,
4566                &emitter,
4567                UnixNanos::from(543),
4568            )
4569            .unwrap()
4570            .unwrap();
4571
4572        let mut fill_notice =
4573            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
4574                .unwrap()["fill"]
4575                .clone();
4576        fill_notice["msg"]["trade_id"] = serde_json::json!(fill.fill_id);
4577        fill_notice["msg"]["market_ticker"] = serde_json::json!(fill.ticker);
4578        let fill_notice = serde_json::from_value(fill_notice).unwrap();
4579        state.notice(&fill_notice).unwrap();
4580        let mut position: MarketPosition =
4581            serde_json::from_value(fixtures["positions"]["market_positions"][0].clone()).unwrap();
4582        position.ticker = instrument.id.symbol.to_string();
4583        position.position_fp = FixedPoint(Decimal::new(75, 2));
4584        position.realized_pnl_dollars = FixedPoint(Decimal::ZERO);
4585        position.fees_paid_dollars = FixedPoint(Decimal::ZERO);
4586
4587        let mut position_notice =
4588            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
4589                .unwrap()["position_pending"]
4590                .clone();
4591        position_notice["msg"]["market_ticker"] = serde_json::json!(position.ticker);
4592        let position_notice = serde_json::from_value(position_notice).unwrap();
4593        state.notice(&position_notice).unwrap();
4594
4595        let mut snapshot = super::super::KalshiExecutionSnapshot {
4596            orders: vec![source],
4597            fills: vec![fill],
4598            positions: vec![position],
4599            positions_settled: Vec::new(),
4600            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
4601            lookback_start: Some(state.start),
4602            ts_init: UnixNanos::from(543),
4603        };
4604
4605        let plans = vec![plan];
4606        state.check_notices(&snapshot, &plans).unwrap();
4607
4608        let mut future =
4609            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
4610                .unwrap()["fill_future"]
4611                .clone();
4612        future["msg"]["market_ticker"] = serde_json::json!(instrument.id.symbol.as_str());
4613        let future = serde_json::from_value(future).unwrap();
4614        state.notice(&future).unwrap();
4615        state.check_notices(&snapshot, &plans).unwrap();
4616        assert_eq!(
4617            state.notices_fills[&TradeId::from("current-fill")].ts_event,
4618            plans[0].source_ts
4619        );
4620
4621        snapshot.positions[0].position_fp = FixedPoint(Decimal::ZERO);
4622        assert_eq!(
4623            state
4624                .check_notices(&snapshot, &plans)
4625                .unwrap_err()
4626                .to_string(),
4627            "REST position does not yet cover notified economics"
4628        );
4629
4630        snapshot.positions[0].position_fp = FixedPoint(Decimal::new(75, 2));
4631        let other = InstrumentId::from("OTHER.KALSHI");
4632        let mut other_position = snapshot.positions[0].clone();
4633        other_position.ticker = other.symbol.to_string();
4634        state.notices_positions.insert(
4635            other,
4636            PositionNotice {
4637                volume: Decimal::ONE,
4638                economics: Some(PositionEconomics {
4639                    position_fp: other_position.position_fp,
4640                    realized_pnl_dollars: other_position.realized_pnl_dollars,
4641                    fees_paid_dollars: other_position.fees_paid_dollars,
4642                }),
4643            },
4644        );
4645
4646        snapshot.positions.push(other_position);
4647        assert_eq!(
4648            state
4649                .check_notices(&snapshot, &plans)
4650                .unwrap_err()
4651                .to_string(),
4652            "REST recovery does not yet cover notified traded volume"
4653        );
4654
4655        let mut mismatched =
4656            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
4657                .unwrap()["fill"]
4658                .clone();
4659        mismatched["msg"]["market_ticker"] = serde_json::json!(other.symbol.as_str());
4660        let mismatched = serde_json::from_value(mismatched).unwrap();
4661        state.notice(&mismatched).unwrap();
4662        assert_eq!(
4663            state
4664                .check_notices(&snapshot, &plans)
4665                .unwrap_err()
4666                .to_string(),
4667            "REST recovery does not yet cover received fill identities"
4668        );
4669
4670        state.notice(&fill_notice).unwrap();
4671        state.notices_positions.clear();
4672        state.clear_notices();
4673        state.notice(&fill_notice).unwrap();
4674        let position_updated = snapshot.positions[0].last_updated_ts;
4675        snapshot.positions[0].last_updated_ts = "2100-01-01T00:00:00Z".parse().unwrap();
4676
4677        let (position_fp, realized_pnl, fees_paid) = (
4678            snapshot.positions[0].position_fp,
4679            snapshot.positions[0].realized_pnl_dollars,
4680            snapshot.positions[0].fees_paid_dollars,
4681        );
4682
4683        let position_economics = || PositionEconomics {
4684            position_fp,
4685            realized_pnl_dollars: realized_pnl,
4686            fees_paid_dollars: fees_paid,
4687        };
4688
4689        state.notices_positions.clear();
4690        state.notices_positions.insert(
4691            instrument.id,
4692            PositionNotice {
4693                volume: Decimal::new(300, 2),
4694                economics: Some(position_economics()),
4695            },
4696        );
4697
4698        state.check_notices(&snapshot, &plans).unwrap();
4699        state.clear_notices();
4700        state.notice(&fill_notice).unwrap();
4701        state.notices_positions.clear();
4702        state.clear_notices();
4703        assert!(state.has_fill_notice(instrument.id));
4704        assert_eq!(
4705            state.covered_fills[&instrument.id],
4706            UnixNanos::from(1_792_112_523_000_000_000)
4707        );
4708        state.notices_positions.insert(
4709            instrument.id,
4710            PositionNotice {
4711                volume: Decimal::new(300, 2),
4712                economics: Some(position_economics()),
4713            },
4714        );
4715
4716        assert_eq!(
4717            state
4718                .check_notices(&snapshot, &plans)
4719                .unwrap_err()
4720                .to_string(),
4721            "REST recovery does not yet cover notified traded volume"
4722        );
4723
4724        snapshot.positions[0].last_updated_ts = position_updated;
4725        state.check_notices(&snapshot, &plans).unwrap();
4726        state.clear_notices();
4727        assert!(!state.has_fill_notice(instrument.id));
4728
4729        state.notices_positions.insert(
4730            instrument.id,
4731            PositionNotice {
4732                volume: Decimal::new(300, 2),
4733                economics: Some(position_economics()),
4734            },
4735        );
4736
4737        assert_eq!(
4738            state
4739                .check_notices(&snapshot, &plans)
4740                .unwrap_err()
4741                .to_string(),
4742            "REST recovery does not yet cover notified traded volume"
4743        );
4744    }
4745
4746    #[rstest]
4747    fn final_close_waits_for_each_offsetting_fill_in_the_canonical_cache() {
4748        use nautilus_common::{cache::Cache, live::sender::EventSender};
4749        use nautilus_model::{
4750            accounts::AccountAny, data::InstrumentClose, enums::InstrumentCloseType,
4751            events::AccountState,
4752        };
4753
4754        use super::super::settlement::{Registration, publish_close};
4755
4756        let instrument = instrument();
4757        let buy = submitted(&instrument, OrderSide::Buy, "buy");
4758        let sell = submitted(&instrument, OrderSide::Sell, "sell");
4759        let mut cache = Cache::default();
4760        cache.add_order(buy.clone(), None, None, false).unwrap();
4761        cache.add_order(sell.clone(), None, None, false).unwrap();
4762        let mut state = state(buy, &instrument);
4763        state.restore(sell);
4764        let (emitter, mut output) = emitter();
4765        let (sender, mut closes) = tokio::sync::mpsc::unbounded_channel();
4766        let sender: EventSender<_> = sender.into();
4767        let _registration = Registration::new(sender.clone(), &state.barrier);
4768
4769        let mut plans = Vec::new();
4770
4771        for (side, id, venue) in [
4772            (OrderSide::Buy, "buy", "venue-buy"),
4773            (OrderSide::Sell, "sell", "venue-sell"),
4774        ] {
4775            let mut source = source(&instrument, side);
4776            source.client_order_id = id.into();
4777            source.order_id = venue.into();
4778            source.status = VenueStatus::Canceled;
4779            source.remaining_count_fp = FixedPoint(Decimal::ZERO);
4780            let mut fill = report(&source, &instrument, emitter.account_id());
4781            fill.trade_id = TradeId::from(id);
4782            fill.commission = Money::from("0 USD");
4783            plans.push(
4784                state
4785                    .plan_order(
4786                        &source,
4787                        &[fill],
4788                        &instrument,
4789                        &emitter,
4790                        UnixNanos::from(543),
4791                    )
4792                    .unwrap()
4793                    .unwrap(),
4794            );
4795        }
4796
4797        let mut notice =
4798            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
4799                .unwrap()["position_flat"]
4800                .clone();
4801        notice["msg"]["market_ticker"] = serde_json::json!(instrument.id.symbol.as_str());
4802        let notice = serde_json::from_value(notice).unwrap();
4803        state.notice(&notice).unwrap();
4804        let fixtures: Value =
4805            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
4806        let mut position: MarketPosition =
4807            serde_json::from_value(fixtures["positions"]["market_positions"][0].clone()).unwrap();
4808        position.ticker = instrument.id.symbol.to_string();
4809        position.position_fp = FixedPoint(Decimal::ZERO);
4810        position.realized_pnl_dollars = FixedPoint(Decimal::ZERO);
4811        position.fees_paid_dollars = FixedPoint(Decimal::ZERO);
4812
4813        let snapshot = super::super::KalshiExecutionSnapshot {
4814            orders: Vec::new(),
4815            fills: Vec::new(),
4816            positions: vec![position],
4817            positions_settled: Vec::new(),
4818            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
4819            lookback_start: Some(state.start),
4820            ts_init: UnixNanos::from(u64::MAX - 1000),
4821        };
4822
4823        assert_eq!(
4824            state.check_notices(&snapshot, &[]).unwrap_err().to_string(),
4825            "REST recovery does not yet cover notified traded volume"
4826        );
4827        state.check_notices(&snapshot, &plans).unwrap();
4828        state.apply_plans(plans, &emitter).unwrap();
4829        state.check_notices(&snapshot, &[]).unwrap();
4830        state.clear_notices();
4831        assert_eq!(state.positions[&instrument.id], Decimal::ZERO);
4832        assert!(
4833            state
4834                .orders
4835                .values()
4836                .all(|context| context.order.is_closed())
4837        );
4838        let ts_event = UnixNanos::from(u64::MAX - 1000);
4839        state
4840            .settle(&instrument, Decimal::ONE, ts_event, ts_event, &emitter)
4841            .unwrap();
4842
4843        let close = InstrumentClose::new(
4844            instrument.id,
4845            Price::from("1.000000"),
4846            InstrumentCloseType::ContractExpired,
4847            ts_event,
4848            ts_event,
4849        );
4850
4851        let mut account = AccountState::new(
4852            emitter.account_id(),
4853            AccountType::Cash,
4854            Vec::new(),
4855            Vec::new(),
4856            true,
4857            UUID4::new(),
4858            ts_event,
4859            ts_event,
4860            Some(Currency::USD()),
4861        );
4862
4863        account.info = Some(nautilus_core::Params::new(
4864            [(
4865                "kalshi_session".into(),
4866                Value::String(state.session.clone()),
4867            )]
4868            .into(),
4869        ));
4870        cache.add_account(AccountAny::from(account)).unwrap();
4871
4872        state
4873            .barrier
4874            .lock()
4875            .unwrap()
4876            .observe(&cache, emitter.account_id());
4877        assert!(!publish_close(&sender, close).unwrap());
4878
4879        while let Ok(ExecutionEvent::Order(event)) = output.try_recv() {
4880            cache.update_order(&event).unwrap();
4881            state
4882                .barrier
4883                .lock()
4884                .unwrap()
4885                .observe(&cache, emitter.account_id());
4886
4887            if event.client_order_id().as_str() == "buy" {
4888                assert!(!publish_close(&sender, close).unwrap());
4889            }
4890        }
4891
4892        state
4893            .barrier
4894            .lock()
4895            .unwrap()
4896            .observe(&cache, emitter.account_id());
4897        assert!(publish_close(&sender, close).unwrap());
4898        assert!(
4899            matches!(closes.try_recv().unwrap(), DataEvent::Data(Data::InstrumentClose(actual)) if actual == close)
4900        );
4901        assert!(closes.try_recv().is_err());
4902        assert_eq!(
4903            cache
4904                .order_ref(&ClientOrderId::from("buy"))
4905                .unwrap()
4906                .trade_ids(),
4907            vec![&TradeId::from("buy")]
4908        );
4909        assert_eq!(
4910            cache
4911                .order_ref(&ClientOrderId::from("sell"))
4912                .unwrap()
4913                .trade_ids(),
4914            vec![&TradeId::from("sell")]
4915        );
4916
4917        state.invalidate();
4918        assert!(!publish_close(&sender, close).unwrap());
4919        assert!(state.barrier.lock().unwrap().sealed(instrument.id));
4920        assert!(
4921            state
4922                .barrier
4923                .lock()
4924                .unwrap()
4925                .prepare(instrument.id, Decimal::ZERO, ts_event, Decimal::ZERO)
4926                .is_err()
4927        );
4928        assert!(state.barrier.lock().unwrap().is_blocked());
4929    }
4930
4931    #[rstest]
4932    fn settled_context_rejects_unapplied_fill_replays_and_report_admission() {
4933        use nautilus_common::cache::Cache;
4934        let instrument = instrument();
4935        let mut source = source(&instrument, OrderSide::Buy);
4936        source.status = VenueStatus::Canceled;
4937        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
4938        let order = submitted(&instrument, OrderSide::Buy, "client-a");
4939        let mut state = state(order.clone(), &instrument);
4940        let (emitter, mut output) = emitter();
4941        let mut fill = report(&source, &instrument, emitter.account_id());
4942        let plan = state
4943            .plan_order(
4944                &source,
4945                std::slice::from_ref(&fill),
4946                &instrument,
4947                &emitter,
4948                UnixNanos::from(543),
4949            )
4950            .unwrap()
4951            .unwrap();
4952        state.apply_plans(vec![plan], &emitter).unwrap();
4953        let mut cache = Cache::default();
4954        cache.add_order(order, None, None, false).unwrap();
4955        while let Ok(ExecutionEvent::Order(event)) = output.try_recv() {
4956            cache.update_order(&event).unwrap();
4957        }
4958
4959        let timestamp = UnixNanos::from(u64::MAX - 1000);
4960        state
4961            .settle(&instrument, Decimal::ONE, timestamp, timestamp, &emitter)
4962            .unwrap();
4963        let total = state
4964            .ledger
4965            .clone()
4966            .apply_refresh(
4967                state.ledger.begin_refresh(),
4968                "100.300024".parse().unwrap(),
4969                HashMap::new(),
4970            )
4971            .unwrap()
4972            .total;
4973        let prior_trade = fill.trade_id;
4974        fill.trade_id = TradeId::from("late-unapplied");
4975        fill.last_qty = Quantity::from("0.25");
4976        source.fill_count_fp = FixedPoint(Decimal::ONE);
4977        assert_eq!(
4978            state
4979                .plan_order(
4980                    &source,
4981                    std::slice::from_ref(&fill),
4982                    &instrument,
4983                    &emitter,
4984                    timestamp
4985                )
4986                .err()
4987                .unwrap()
4988                .to_string(),
4989            "unapplied execution evidence after settlement"
4990        );
4991        assert!(!state.fill_accounted(ClientOrderId::from("client-a"), fill.trade_id));
4992        assert!(state.fill_accounted(ClientOrderId::from("client-a"), prior_trade));
4993        assert_eq!(state.positions[&instrument.id], Decimal::ZERO);
4994        assert!(state.admit_reports(&cache, &[], &[fill]).is_err());
4995        assert!(state.barrier.lock().unwrap().is_blocked());
4996        assert_eq!(total.as_decimal(), "100.300024".parse::<Decimal>().unwrap());
4997    }
4998
4999    #[rstest]
5000    #[case::absent(false)]
5001    #[case::restored_order_only(true)]
5002    fn missing_opening_evidence_is_fatal_even_when_order_restore_seeds_zero(
5003        #[case] restored_order: bool,
5004    ) {
5005        let instrument = instrument();
5006        let mut state = PrivateState::new();
5007        if restored_order {
5008            state.restore(submitted(&instrument, OrderSide::Buy, "client-a"));
5009        }
5010
5011        state.seed_positions([]).unwrap();
5012
5013        let error = state
5014            .opening(instrument.id, Decimal::ONE, Decimal::ZERO)
5015            .unwrap_err();
5016        assert!(matches!(
5017            error.downcast_ref::<RecoveryContextError>(),
5018            Some(RecoveryContextError::Position)
5019        ));
5020        assert_eq!(
5021            state.positions.get(&instrument.id),
5022            restored_order.then_some(&Decimal::ZERO)
5023        );
5024    }
5025
5026    #[rstest]
5027    fn retained_opening_mismatch_remains_retryable() {
5028        let instrument = instrument();
5029        let mut state = PrivateState::new();
5030        state
5031            .seed_positions([(instrument.id, Decimal::ONE, UnixNanos::from(123))])
5032            .unwrap();
5033
5034        let error = state
5035            .opening(instrument.id, Decimal::TWO, Decimal::ZERO)
5036            .unwrap_err();
5037        assert!(error.downcast_ref::<RecoveryContextError>().is_none());
5038        assert_eq!(
5039            error.to_string(),
5040            "position cycle lacks cached opening authority"
5041        );
5042        assert_eq!(state.positions[&instrument.id], Decimal::ONE);
5043        assert_eq!(state.positions_ts[&instrument.id], UnixNanos::from(123));
5044    }
5045
5046    #[rstest]
5047    fn restored_unfilled_orders_seed_a_flat_cycle_and_settlement_requires_resolution() {
5048        let instrument = instrument();
5049        let mut state = PrivateState::new();
5050        state.restore(submitted(&instrument, OrderSide::Buy, "client-a"));
5051        state.seed_positions([]).unwrap();
5052        assert_eq!(state.positions[&instrument.id], Decimal::ZERO);
5053
5054        let settlement = Settlement {
5055            instrument_id: instrument.id,
5056            value: Decimal::ONE,
5057            ts_event: UnixNanos::from(u64::MAX - 1000),
5058            net: None,
5059        };
5060
5061        assert_eq!(
5062            state
5063                .check_settlements(&[], &[settlement])
5064                .unwrap_err()
5065                .to_string(),
5066            "settlement has unresolved orders"
5067        );
5068    }
5069
5070    #[rstest]
5071    #[case(false)]
5072    #[case(true)]
5073    fn final_report_admission_fences_a_close_and_rejects_a_close_that_won_the_race(
5074        #[case] cached_close: bool,
5075    ) {
5076        use nautilus_common::cache::Cache;
5077        let instrument = instrument();
5078        let source = source(&instrument, OrderSide::Buy);
5079        let order = submitted(&instrument, OrderSide::Buy, "client-a");
5080        let mut cache = Cache::default();
5081        cache.add_order(order.clone(), None, None, false).unwrap();
5082        let mut state = state(order, &instrument);
5083        let (emitter, _) = emitter();
5084        let fill = report(&source, &instrument, emitter.account_id());
5085        let session = state.session.clone();
5086        let ticket = state.ledger.begin_refresh();
5087        state
5088            .admit_reports(&cache, &[], std::slice::from_ref(&fill))
5089            .unwrap();
5090        assert_ne!(state.session, session);
5091        assert!(state.ledger.check_refresh(ticket).is_err());
5092        assert!(!state.fill_accounted(ClientOrderId::from("client-a"), fill.trade_id));
5093
5094        if cached_close {
5095            cache
5096                .add_instrument_close(InstrumentClose::new(
5097                    instrument.id,
5098                    Price::from("1.000000"),
5099                    InstrumentCloseType::ContractExpired,
5100                    UnixNanos::from(u64::MAX - 1000),
5101                    UnixNanos::from(u64::MAX - 999),
5102                ))
5103                .unwrap();
5104        } else {
5105            state
5106                .barrier
5107                .lock()
5108                .unwrap()
5109                .prepare(
5110                    instrument.id,
5111                    Decimal::ONE,
5112                    UnixNanos::from(u64::MAX - 1000),
5113                    Decimal::ZERO,
5114                )
5115                .unwrap();
5116        }
5117
5118        assert_eq!(
5119            state
5120                .admit_reports(&cache, &[], std::slice::from_ref(&fill))
5121                .unwrap_err()
5122                .to_string(),
5123            "unapplied fill report after settlement"
5124        );
5125        assert!(!state.fill_accounted(ClientOrderId::from("client-a"), fill.trade_id));
5126        assert!(state.barrier.lock().unwrap().is_blocked());
5127    }
5128
5129    #[rstest]
5130    fn terminal_ownership_survives_more_than_ten_thousand_unobserved_completions() {
5131        let instrument = instrument();
5132        let mut state = PrivateState::new();
5133        state.positions.insert(instrument.id, Decimal::ZERO);
5134        let ticket = state.ledger.begin_refresh();
5135        state
5136            .ledger
5137            .apply_refresh(ticket, Decimal::from(100_000), HashMap::new())
5138            .unwrap();
5139        let (emitter, _output) = emitter();
5140        let original = submitted(&instrument, OrderSide::Buy, "client-a");
5141        let mut first = source(&instrument, OrderSide::Buy);
5142        first.status = VenueStatus::Executed;
5143        first.fill_count_fp = FixedPoint(Decimal::from(2));
5144        first.remaining_count_fp = FixedPoint(Decimal::ZERO);
5145        for index in 0..10_001 {
5146            let mut current = first.clone();
5147
5148            let id = if index == 0 {
5149                "client-a".to_string()
5150            } else {
5151                format!("completed-{index}")
5152            };
5153
5154            current.client_order_id = id.clone();
5155
5156            current.order_id = if index == 0 {
5157                first.order_id.clone()
5158            } else {
5159                format!("venue-{index}")
5160            };
5161
5162            state.restore(submitted(&instrument, OrderSide::Buy, &id));
5163            let mut fill = report(&current, &instrument, emitter.account_id());
5164            fill.trade_id = TradeId::new(format!("completed-fill-{index}"));
5165            let plan = state
5166                .plan_order(
5167                    &current,
5168                    &[fill],
5169                    &instrument,
5170                    &emitter,
5171                    UnixNanos::from(543),
5172                )
5173                .unwrap()
5174                .unwrap();
5175            state.apply_plans(vec![plan], &emitter).unwrap();
5176        }
5177
5178        state.restore(original);
5179        let retained = state.source_order(&first).unwrap().unwrap();
5180        assert_eq!(retained.client_order_id(), ClientOrderId::from("client-a"));
5181        assert_eq!(retained.status(), OrderStatus::Filled);
5182        assert_eq!(retained.filled_qty(), Quantity::from("2.00"));
5183        assert_eq!(
5184            retained.trade_ids(),
5185            vec![&TradeId::from("completed-fill-0")]
5186        );
5187        assert_eq!(state.positions[&instrument.id], Decimal::from(20_002));
5188        let ticket = state.ledger.begin_refresh();
5189        let balance = state
5190            .ledger
5191            .apply_refresh(ticket, "87996.789799".parse().unwrap(), HashMap::new())
5192            .unwrap();
5193        assert_eq!(balance.total.as_decimal(), "87996.789799".parse().unwrap());
5194    }
5195
5196    #[rstest]
5197    fn recovery_window_waits_for_canonical_receipts_and_reopens_for_old_notices() {
5198        use nautilus_common::cache::Cache;
5199
5200        let instrument = instrument();
5201        let source = source(&instrument, OrderSide::Buy);
5202        let original = submitted(&instrument, OrderSide::Buy, "client-a");
5203        let mut state = state(original.clone(), &instrument);
5204        let (emitter, mut output) = emitter();
5205        let fill = report(&source, &instrument, emitter.account_id());
5206        let plan = state
5207            .plan_order(
5208                &source,
5209                std::slice::from_ref(&fill),
5210                &instrument,
5211                &emitter,
5212                UnixNanos::from(543),
5213            )
5214            .unwrap()
5215            .unwrap();
5216        state.apply_plans(vec![plan], &emitter).unwrap();
5217        let next = UnixNanos::from(u64::MAX - 1000);
5218        state.advance_recovery(next);
5219        assert_eq!(state.start, original.ts_init());
5220        let mut cache = Cache::default();
5221        cache
5222            .add_order(original.clone(), None, None, false)
5223            .unwrap();
5224        state
5225            .barrier
5226            .lock()
5227            .unwrap()
5228            .observe(&cache, emitter.account_id());
5229        state.advance_recovery(next);
5230        assert_eq!(state.start, original.ts_init());
5231
5232        while let Ok(event) = output.try_recv() {
5233            let ExecutionEvent::Order(event) = event else {
5234                panic!("expected order event");
5235            };
5236
5237            cache.update_order(&event).unwrap();
5238        }
5239
5240        state
5241            .barrier
5242            .lock()
5243            .unwrap()
5244            .observe(&cache, emitter.account_id());
5245        state.advance_recovery(next);
5246        assert_eq!(
5247            state.start, next,
5248            "an observed resting GTC order must not pin broad history"
5249        );
5250
5251        if let Some(plan) = state
5252            .plan_order(
5253                &source,
5254                std::slice::from_ref(&fill),
5255                &instrument,
5256                &emitter,
5257                UnixNanos::from(544),
5258            )
5259            .unwrap()
5260        {
5261            state.apply_plans(vec![plan], &emitter).unwrap();
5262        }
5263
5264        assert!(output.try_recv().is_err());
5265        state.advance_recovery(next);
5266        assert_eq!(
5267            state.start, next,
5268            "a no-op replay must not recreate a receipt"
5269        );
5270        let mut notice =
5271            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
5272                .unwrap()["order_partial_payload"]
5273                .clone();
5274        notice["order_id"] = serde_json::json!(source.order_id);
5275        state.notice_order(&notice).unwrap();
5276        assert_eq!(
5277            state.start,
5278            original.ts_init(),
5279            "a replayed notice must reopen order coverage even without another fill"
5280        );
5281        let fixtures: Value =
5282            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
5283
5284        let snapshot = super::super::KalshiExecutionSnapshot {
5285            orders: vec![source],
5286            fills: Vec::new(),
5287            positions: Vec::new(),
5288            positions_settled: Vec::new(),
5289            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
5290            lookback_start: Some(state.start),
5291            ts_init: next,
5292        };
5293
5294        state.check_notices(&snapshot, &[]).unwrap();
5295    }
5296
5297    #[rstest]
5298    #[case(0, "REST recovery lacks a notified order")]
5299    #[case(1, "REST order does not yet cover notified fills")]
5300    #[case(2, "REST order does not yet cover notified update time")]
5301    #[case(3, "")]
5302    fn received_order_evidence_waits_for_rest_identity_quantity_and_time(
5303        #[case] evidence: u8,
5304        #[case] error: &str,
5305    ) {
5306        let instrument = instrument();
5307        let mut source = source(&instrument, OrderSide::Buy);
5308        let mut state = state(
5309            submitted(&instrument, OrderSide::Buy, "client-a"),
5310            &instrument,
5311        );
5312        let updated = timestamp(&source.last_update_time).unwrap();
5313        let mut notice =
5314            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
5315                .unwrap()["order_updated_payload"]
5316                .clone();
5317        notice["order_id"] = serde_json::json!(source.order_id);
5318        notice["last_updated_ts_ms"] = serde_json::json!(updated.as_u64() / 1_000_000 + 1);
5319        state.notice_order(&notice).unwrap();
5320
5321        if evidence == 1 {
5322            source.fill_count_fp = FixedPoint(Decimal::ZERO);
5323        }
5324
5325        if evidence == 3 {
5326            let time =
5327                jiff::Timestamp::from_nanosecond(i128::from(updated.as_u64()) + 1_000_000).unwrap();
5328            source.last_update_time = Field::Value(time);
5329        }
5330
5331        let fixtures: Value =
5332            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
5333
5334        let snapshot = super::super::KalshiExecutionSnapshot {
5335            orders: if evidence == 0 {
5336                Vec::new()
5337            } else {
5338                vec![source]
5339            },
5340            fills: Vec::new(),
5341            positions: Vec::new(),
5342            positions_settled: Vec::new(),
5343            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
5344            lookback_start: Some(state.start),
5345            ts_init: updated,
5346        };
5347
5348        let result = state.check_notices(&snapshot, &[]);
5349        if error.is_empty() {
5350            result.unwrap();
5351        } else {
5352            assert_eq!(result.unwrap_err().to_string(), error);
5353        }
5354    }
5355
5356    #[rstest]
5357    #[case::external(true)]
5358    #[case::same_text_client(false)]
5359    fn held_external_order_notices_preserve_the_fill_window(#[case] external: bool) {
5360        let mut state = PrivateState::new();
5361        state.start = UnixNanos::from(20_000_000_000);
5362        let id = VenueOrderId::from("old-order");
5363        let reservation = if external {
5364            ReservationId::Venue(id)
5365        } else {
5366            ReservationId::Client(ClientOrderId::from(id.as_str()))
5367        };
5368
5369        let ticket = state.ledger.begin_refresh();
5370        state
5371            .ledger
5372            .apply_refresh(
5373                ticket,
5374                Decimal::ONE,
5375                HashMap::from([(reservation, Decimal::new(1, 1))]),
5376            )
5377            .unwrap();
5378        let mut notice =
5379            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
5380                .unwrap()["order_created_payload"]
5381                .clone();
5382        notice["order_id"] = serde_json::json!(id.as_str());
5383        state.notice_order(&notice).unwrap();
5384        assert_eq!(
5385            state.start,
5386            UnixNanos::from(if external {
5387                20_000_000_000
5388            } else {
5389                1_000_000_000
5390            })
5391        );
5392        assert_eq!(
5393            state.external_order_notices(),
5394            if external { vec![id] } else { Vec::new() }
5395        );
5396    }
5397
5398    #[rstest]
5399    #[case(false, true)]
5400    #[case(true, true)]
5401    #[case(true, false)]
5402    fn admitted_historical_reports_reopen_coverage_until_canonical_consumption(
5403        #[case] include_order: bool,
5404        #[case] include_fill: bool,
5405    ) {
5406        use nautilus_common::cache::Cache;
5407
5408        let instrument = instrument();
5409        let source = source(&instrument, OrderSide::Buy);
5410        let (emitter, mut output) = emitter();
5411        let mut original = submitted(&instrument, OrderSide::Buy, "client-a");
5412        let accepted = timestamp(&source.created_time).unwrap();
5413
5414        let event = OrderAccepted::new(
5415            original.trader_id(),
5416            original.strategy_id(),
5417            instrument.id,
5418            original.client_order_id(),
5419            source.order_id.as_str().into(),
5420            emitter.account_id(),
5421            UUID4::new(),
5422            accepted,
5423            accepted,
5424            false,
5425        );
5426
5427        original.apply(OrderEventAny::Accepted(event)).unwrap();
5428        let mut cache = Cache::default();
5429        cache
5430            .add_order(original.clone(), None, None, false)
5431            .unwrap();
5432        let mut state = state(original.clone(), &instrument);
5433        let next = UnixNanos::from(u64::MAX - 1000);
5434        state.start = next;
5435        let fill = report(&source, &instrument, emitter.account_id());
5436
5437        let orders = if include_order {
5438            vec![
5439                reports::order(
5440                    &source,
5441                    &instrument,
5442                    emitter.account_id(),
5443                    Some(&original),
5444                    next,
5445                )
5446                .unwrap()
5447                .unwrap(),
5448            ]
5449        } else {
5450            Vec::new()
5451        };
5452
5453        state
5454            .admit_reports(
5455                &cache,
5456                &orders,
5457                if include_fill {
5458                    std::slice::from_ref(&fill)
5459                } else {
5460                    &[]
5461                },
5462            )
5463            .unwrap();
5464
5465        assert_eq!(state.start, accepted.min(fill.ts_event));
5466        assert!(!state.fill_accounted(original.client_order_id(), fill.trade_id));
5467        assert_eq!(state.positions[&instrument.id], Decimal::ZERO);
5468        state.advance_recovery(next);
5469        assert_eq!(state.start, accepted.min(fill.ts_event));
5470        state
5471            .barrier
5472            .lock()
5473            .unwrap()
5474            .observe(&cache, emitter.account_id());
5475        state.advance_recovery(next);
5476        assert_eq!(state.start, accepted.min(fill.ts_event));
5477        let plan = state
5478            .plan_order(
5479                &source,
5480                std::slice::from_ref(&fill),
5481                &instrument,
5482                &emitter,
5483                next,
5484            )
5485            .unwrap()
5486            .unwrap();
5487        state.apply_plans(vec![plan], &emitter).unwrap();
5488
5489        while let Ok(event) = output.try_recv() {
5490            let ExecutionEvent::Order(event) = event else {
5491                panic!("expected order event");
5492            };
5493
5494            cache.update_order(&event).unwrap();
5495        }
5496
5497        state
5498            .barrier
5499            .lock()
5500            .unwrap()
5501            .observe(&cache, emitter.account_id());
5502        state.advance_recovery(next);
5503        assert_eq!(state.start, next);
5504        assert_eq!(state.positions[&instrument.id], Decimal::new(75, 2));
5505        assert!(state.fill_accounted(original.client_order_id(), fill.trade_id));
5506        let expected = Decimal::from_str_exact("99.550024").unwrap();
5507        let ticket = state.ledger.begin_refresh();
5508        let balance = state
5509            .ledger
5510            .apply_refresh(ticket, expected, HashMap::new())
5511            .unwrap();
5512        assert_eq!(balance.total.as_decimal(), expected);
5513    }
5514
5515    #[rstest]
5516    #[case("missing", false)]
5517    #[case("net", false)]
5518    #[case("pnl", false)]
5519    #[case("fees", false)]
5520    #[case("covered", false)]
5521    #[case("covered", true)]
5522    fn position_notifications_require_matching_rest_economics(
5523        #[case] evidence: &str,
5524        #[case] settled: bool,
5525    ) {
5526        let instrument = instrument();
5527        let mut state = state(
5528            submitted(&instrument, OrderSide::Buy, "client-a"),
5529            &instrument,
5530        );
5531        let fixtures: Value =
5532            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
5533        let mut position: MarketPosition =
5534            serde_json::from_value(fixtures["positions"]["market_positions"][0].clone()).unwrap();
5535        position.ticker = instrument.id.symbol.to_string();
5536        position.position_fp = FixedPoint(Decimal::new(75, 2));
5537        position.realized_pnl_dollars = FixedPoint(Decimal::new(-37, 4));
5538        position.fees_paid_dollars = FixedPoint(Decimal::new(23, 4));
5539
5540        let mut notice =
5541            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
5542                .unwrap()["position_economics"]
5543                .clone();
5544        notice["msg"]["market_ticker"] = serde_json::json!(position.ticker);
5545        let notice = serde_json::from_value(notice).unwrap();
5546        state.advance_recovery(UnixNanos::from(u64::MAX - 1000));
5547        state.notice(&notice).unwrap();
5548        state.invalidate();
5549        assert_eq!(state.start, UnixNanos::from(0));
5550
5551        match evidence {
5552            "net" => position.position_fp = FixedPoint(Decimal::ZERO),
5553            "pnl" => position.realized_pnl_dollars = FixedPoint(Decimal::ZERO),
5554            "fees" => position.fees_paid_dollars = FixedPoint(Decimal::ZERO),
5555            _ => {}
5556        }
5557
5558        let positions = if evidence == "missing" {
5559            Vec::new()
5560        } else {
5561            vec![position]
5562        };
5563
5564        let snapshot = super::super::KalshiExecutionSnapshot {
5565            orders: Vec::new(),
5566            fills: Vec::new(),
5567            positions: if settled {
5568                Vec::new()
5569            } else {
5570                positions.clone()
5571            },
5572            positions_settled: if settled { positions } else { Vec::new() },
5573            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
5574            lookback_start: Some(state.start),
5575            ts_init: UnixNanos::from(u64::MAX - 1000),
5576        };
5577
5578        let result = state.check_notices(&snapshot, &[]);
5579        if evidence == "covered" {
5580            result.unwrap();
5581        } else {
5582            assert!(
5583                result.is_err(),
5584                "stale {evidence} evidence covered a position notification"
5585            );
5586        }
5587
5588        state.clear_notices();
5589        state.check_notices(&snapshot, &[]).unwrap();
5590    }
5591
5592    #[rstest]
5593    fn position_only_notice_keeps_a_flat_final_close_withheld() {
5594        use nautilus_common::{cache::Cache, live::sender::EventSender};
5595        use nautilus_model::{
5596            accounts::AccountAny, data::InstrumentClose, enums::InstrumentCloseType,
5597            events::AccountState,
5598        };
5599
5600        use super::super::settlement::{Registration, publish_close};
5601        let instrument = instrument();
5602        let original = submitted(&instrument, OrderSide::Buy, "client-a");
5603        let mut state = state(original.clone(), &instrument);
5604        let (emitter, mut output) = emitter();
5605        let mut source = source(&instrument, OrderSide::Buy);
5606        source.status = VenueStatus::Canceled;
5607        source.fill_count_fp = FixedPoint(Decimal::ZERO);
5608        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
5609        let plan = state
5610            .plan_order(&source, &[], &instrument, &emitter, UnixNanos::from(543))
5611            .unwrap()
5612            .unwrap();
5613        state.apply_plans(vec![plan], &emitter).unwrap();
5614        let mut cache = Cache::default();
5615        cache.add_order(original, None, None, false).unwrap();
5616        while let Ok(ExecutionEvent::Order(event)) = output.try_recv() {
5617            cache.update_order(&event).unwrap();
5618        }
5619
5620        assert!(
5621            state.orders[&ClientOrderId::from("client-a")]
5622                .order
5623                .is_closed()
5624        );
5625        state
5626            .barrier
5627            .lock()
5628            .unwrap()
5629            .observe(&cache, emitter.account_id());
5630        let (sender, mut closes) = tokio::sync::mpsc::unbounded_channel();
5631        let sender: EventSender<_> = sender.into();
5632        let _registration = Registration::new(sender.clone(), &state.barrier);
5633        let next = UnixNanos::from(u64::MAX - 1000);
5634        state.advance_recovery(next);
5635        assert_eq!(state.start, next);
5636
5637        let mut notice =
5638            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
5639                .unwrap()["position_economics"]
5640                .clone();
5641        notice["msg"]["market_ticker"] = serde_json::json!(instrument.id.symbol.as_str());
5642        let notice = serde_json::from_value(notice).unwrap();
5643        state.notice(&notice).unwrap();
5644        let fixtures: Value =
5645            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
5646
5647        let snapshot = super::super::KalshiExecutionSnapshot {
5648            orders: vec![source],
5649            fills: Vec::new(),
5650            positions: Vec::new(),
5651            positions_settled: Vec::new(),
5652            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
5653            lookback_start: Some(state.start),
5654            ts_init: next,
5655        };
5656
5657        assert_eq!(
5658            state.check_notices(&snapshot, &[]).unwrap_err().to_string(),
5659            "REST recovery lacks a notified position"
5660        );
5661        assert_eq!(state.start, next);
5662
5663        let close = InstrumentClose::new(
5664            instrument.id,
5665            Price::from("1.000000"),
5666            InstrumentCloseType::ContractExpired,
5667            next,
5668            next,
5669        );
5670
5671        let account = AccountState::new(
5672            emitter.account_id(),
5673            AccountType::Cash,
5674            Vec::new(),
5675            Vec::new(),
5676            true,
5677            UUID4::new(),
5678            next,
5679            next,
5680            Some(Currency::USD()),
5681        );
5682
5683        cache.add_account(AccountAny::from(account)).unwrap();
5684        state
5685            .barrier
5686            .lock()
5687            .unwrap()
5688            .observe(&cache, emitter.account_id());
5689        assert!(!publish_close(&sender, close).unwrap());
5690        assert!(closes.try_recv().is_err());
5691    }
5692
5693    #[rstest]
5694    fn malformed_position_economics_remain_pending_until_valid_replay() {
5695        let instrument = instrument();
5696        let mut state = state(
5697            submitted(&instrument, OrderSide::Buy, "client-a"),
5698            &instrument,
5699        );
5700        let fixtures: Value =
5701            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
5702        let mut position: MarketPosition =
5703            serde_json::from_value(fixtures["positions"]["market_positions"][0].clone()).unwrap();
5704        position.ticker = instrument.id.symbol.to_string();
5705        position.position_fp = FixedPoint(Decimal::ZERO);
5706        position.realized_pnl_dollars = FixedPoint(Decimal::new(-42000, 6));
5707        position.fees_paid_dollars = FixedPoint(Decimal::new(1700, 6));
5708
5709        let mut message =
5710            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
5711                .unwrap()["position_malformed_fees"]
5712                .clone();
5713        message["msg"]["market_ticker"] = serde_json::json!(position.ticker);
5714        message["msg"]["position_fp"] = serde_json::json!(position.position_fp);
5715        message["msg"]["realized_pnl_dollars"] = serde_json::json!(FixedPoint(
5716            position.realized_pnl_dollars.0 - position.fees_paid_dollars.0
5717        ));
5718
5719        assert!(
5720            state
5721                .notice(&serde_json::from_value(message.clone()).unwrap())
5722                .is_err()
5723        );
5724        state.invalidate();
5725
5726        let mut snapshot = super::super::KalshiExecutionSnapshot {
5727            orders: Vec::new(),
5728            fills: Vec::new(),
5729            positions: vec![position.clone()],
5730            positions_settled: Vec::new(),
5731            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
5732            lookback_start: Some(state.start),
5733            ts_init: UnixNanos::from(u64::MAX - 1000),
5734        };
5735
5736        assert_eq!(
5737            state.check_notices(&snapshot, &[]).unwrap_err().to_string(),
5738            "private position notification remains malformed"
5739        );
5740        assert_eq!(state.recovery_targets(), vec![instrument.id]);
5741        message["msg"]["fees_paid_dollars"] =
5742            serde_json::to_value(position.fees_paid_dollars).unwrap();
5743        state
5744            .notice(&serde_json::from_value(message.clone()).unwrap())
5745            .unwrap();
5746        state.check_notices(&snapshot, &[]).unwrap();
5747        message["msg"]["position_fp"] = "-0.37".into();
5748        state
5749            .notice(&serde_json::from_value(message).unwrap())
5750            .unwrap();
5751        assert_eq!(
5752            state.check_notices(&snapshot, &[]).unwrap_err().to_string(),
5753            "REST position does not yet cover notified economics"
5754        );
5755        snapshot.positions[0].position_fp = FixedPoint(Decimal::new(-37, 2));
5756        state.check_notices(&snapshot, &[]).unwrap();
5757        state.clear_notices();
5758        assert!(state.recovery_targets().is_empty());
5759    }
5760
5761    #[rstest]
5762    #[case(false)]
5763    #[case(true)]
5764    fn position_volume_requirement_survives_older_and_malformed_notices(#[case] malformed: bool) {
5765        let instrument = instrument();
5766        let mut state = state(
5767            submitted(&instrument, OrderSide::Buy, "client-a"),
5768            &instrument,
5769        );
5770        let (emitter, _output) = emitter();
5771        let mut source = source(&instrument, OrderSide::Buy);
5772        source.fill_count_fp = FixedPoint(Decimal::new(150, 2));
5773        source.remaining_count_fp = FixedPoint(Decimal::new(50, 2));
5774        let mut fill = report(&source, &instrument, emitter.account_id());
5775        fill.commission = Money::from("0 USD");
5776        let plan = state
5777            .plan_order(
5778                &source,
5779                &[fill],
5780                &instrument,
5781                &emitter,
5782                UnixNanos::from(543),
5783            )
5784            .unwrap()
5785            .unwrap();
5786        state.apply_plans(vec![plan], &emitter).unwrap();
5787        let fixtures: Value =
5788            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
5789        let mut position: MarketPosition =
5790            serde_json::from_value(fixtures["positions"]["market_positions"][0].clone()).unwrap();
5791        position.ticker = instrument.id.symbol.to_string();
5792        position.position_fp = FixedPoint(Decimal::new(150, 2));
5793        position.realized_pnl_dollars = FixedPoint(Decimal::ZERO);
5794        position.fees_paid_dollars = FixedPoint(Decimal::ZERO);
5795
5796        let mut message =
5797            serde_json::from_str::<Value>(include_str!("../../test_data/websocket_messages.json"))
5798                .unwrap()["position_volume"]
5799                .clone();
5800        message["msg"]["market_ticker"] = serde_json::json!(position.ticker);
5801        message["msg"]["fees_paid_dollars"] =
5802            serde_json::json!(if malformed { "malformed" } else { "0.000000" });
5803
5804        let result = state.notice(&serde_json::from_value(message.clone()).unwrap());
5805        assert_eq!(result.is_err(), malformed);
5806        state.invalidate();
5807        message["msg"]["volume_fp"] = "1.50".into();
5808        message["msg"]["fees_paid_dollars"] = "0.000000".into();
5809        state
5810            .notice(&serde_json::from_value(message).unwrap())
5811            .unwrap();
5812
5813        let snapshot = super::super::KalshiExecutionSnapshot {
5814            orders: Vec::new(),
5815            fills: Vec::new(),
5816            positions: vec![position],
5817            positions_settled: Vec::new(),
5818            cutoff: serde_json::from_value(fixtures["cutoff"].clone()).unwrap(),
5819            lookback_start: Some(state.start),
5820            ts_init: UnixNanos::from(u64::MAX - 1000),
5821        };
5822
5823        assert_eq!(
5824            state.check_notices(&snapshot, &[]).unwrap_err().to_string(),
5825            "REST recovery does not yet cover notified traded volume"
5826        );
5827    }
5828
5829    #[rstest]
5830    #[case("2.50", OrderSide::Sell, "1.25", "0", true)]
5831    #[case("-2.50", OrderSide::Buy, "1.25", "0", true)]
5832    #[case("2.50", OrderSide::Buy, "1.25", "0", false)]
5833    #[case("-2.50", OrderSide::Sell, "1.25", "0", false)]
5834    #[case("0", OrderSide::Sell, "1.25", "0", false)]
5835    #[case("2.50", OrderSide::Sell, "2.51", "0", false)]
5836    #[case("2.50", OrderSide::Sell, "1.25", "1.25", false)]
5837    #[case("2.50", OrderSide::Sell, "1.26", "1.25", false)]
5838    fn reduction_uses_account_net_and_external_remaining_quantity(
5839        #[case] net: &str,
5840        #[case] side: OrderSide,
5841        #[case] qty: &str,
5842        #[case] external: &str,
5843        #[case] admitted: bool,
5844    ) {
5845        let instrument = instrument();
5846        let mut state = PrivateState::new();
5847        state.positions.insert(instrument.id, net.parse().unwrap());
5848        state
5849            .external_leaves
5850            .insert((instrument.id, side), external.parse().unwrap());
5851        let other = InstrumentId::from("OTHER.KALSHI");
5852        state
5853            .external_leaves
5854            .insert((other, side), Decimal::from(100));
5855        let order = OrderTestBuilder::new(OrderType::Limit)
5856            .instrument_id(instrument.id)
5857            .strategy_id("REDUCE-002".into())
5858            .side(side)
5859            .quantity(Quantity::from(qty))
5860            .price(Price::from("0.600000"))
5861            .time_in_force(TimeInForce::Ioc)
5862            .reduce_only(true)
5863            .build();
5864        assert_eq!(
5865            state
5866                .check_reduction(&order, Some(net.parse().unwrap()))
5867                .is_ok(),
5868            admitted
5869        );
5870    }
5871
5872    #[rstest]
5873    #[case(OrderSide::Sell, "2.50")]
5874    #[case(OrderSide::Buy, "-2.50")]
5875    fn concurrent_reductions_retain_quantity_until_definitive_rejection(
5876        #[case] side: OrderSide,
5877        #[case] net: &str,
5878        #[values(false, true)] same_strategy: bool,
5879    ) {
5880        let instrument = instrument();
5881        let position_qty: Decimal = net.parse().unwrap();
5882        let mut state = PrivateState::new();
5883        state.positions.insert(instrument.id, net.parse().unwrap());
5884        let ticket = state.ledger.begin_refresh();
5885        state
5886            .ledger
5887            .apply_refresh(ticket, Decimal::from(10), HashMap::new())
5888            .unwrap();
5889        let state = Arc::new(Mutex::new(state));
5890        let barrier = Arc::new(std::sync::Barrier::new(3));
5891        let (emitter, mut output) = emitter();
5892
5893        #[allow(
5894            clippy::needless_collect,
5895            reason = "both workers must start before the admission barrier"
5896        )]
5897        let threads: Vec<_> = (0..2)
5898            .map(|i| {
5899                let state = Arc::clone(&state);
5900                let barrier = Arc::clone(&barrier);
5901                let emitter = emitter.clone();
5902
5903                let mut order = OrderTestBuilder::new(OrderType::Limit)
5904                    .instrument_id(instrument.id)
5905                    .strategy_id(if same_strategy {
5906                        "REDUCE-001".into()
5907                    } else {
5908                        format!("REDUCE-00{i}").into()
5909                    })
5910                    .client_order_id(format!("reduction-{i}").into())
5911                    .quantity(Quantity::from("1.50"))
5912                    .price(Price::from("0.600000"))
5913                    .side(side)
5914                    .time_in_force(TimeInForce::Ioc)
5915                    .reduce_only(true)
5916                    .build();
5917
5918                std::thread::spawn(move || {
5919                    barrier.wait();
5920                    let result = state.lock().unwrap().submit(
5921                        &mut order,
5922                        Decimal::ONE,
5923                        Some(position_qty),
5924                        &emitter,
5925                    );
5926                    (order, result.is_ok())
5927                })
5928            })
5929            .collect();
5930
5931        barrier.wait();
5932        let outcomes: Vec<_> = threads
5933            .into_iter()
5934            .map(|thread| thread.join().unwrap())
5935            .collect();
5936        let mut state = state.lock().unwrap();
5937        let successful = outcomes
5938            .iter()
5939            .find(|(_, success)| *success)
5940            .unwrap()
5941            .0
5942            .clone();
5943        let mut denied = outcomes
5944            .iter()
5945            .find(|(_, success)| !*success)
5946            .unwrap()
5947            .0
5948            .clone();
5949        assert_eq!(outcomes.iter().filter(|(_, success)| *success).count(), 1);
5950        assert_eq!(state.orders.len(), 1);
5951        assert_eq!(
5952            state.ledger.balance().unwrap().locked.as_decimal(),
5953            Decimal::ONE
5954        );
5955        assert_eq!(denied.status(), OrderStatus::Initialized);
5956        assert!(state.check_reduction(&denied, Some(position_qty)).is_err());
5957        state
5958            .reject_submission(
5959                successful.client_order_id(),
5960                "definitive venue rejection",
5961                false,
5962                &emitter,
5963            )
5964            .unwrap();
5965        state
5966            .submit(&mut denied, Decimal::ONE, Some(position_qty), &emitter)
5967            .unwrap();
5968        assert_eq!(
5969            state.ledger.balance().unwrap().locked.as_decimal(),
5970            Decimal::ONE
5971        );
5972        assert_eq!(
5973            state.positions[&instrument.id],
5974            net.parse::<Decimal>().unwrap()
5975        );
5976        let mut events = Vec::new();
5977
5978        while let Ok(event) = output.try_recv() {
5979            if let ExecutionEvent::Order(event) = event {
5980                events.push(event);
5981            }
5982        }
5983
5984        assert_eq!(
5985            events
5986                .iter()
5987                .filter(|event| matches!(event, OrderEventAny::Submitted(_)))
5988                .count(),
5989            2
5990        );
5991        assert_eq!(
5992            events
5993                .iter()
5994                .filter(|event| matches!(event, OrderEventAny::Rejected(_)))
5995                .count(),
5996            1
5997        );
5998    }
5999
6000    #[rstest]
6001    fn immediate_terminal_evidence_precedes_local_submission_and_ack(
6002        #[values(false, true)] ack_first: bool,
6003        #[values(TimeInForce::Ioc, TimeInForce::Fok)] tif: TimeInForce,
6004    ) {
6005        let instrument = instrument();
6006        let mut order = OrderTestBuilder::new(OrderType::Limit)
6007            .instrument_id(instrument.id)
6008            .client_order_id("client-a".into())
6009            .quantity(Quantity::from("2.00"))
6010            .price(Price::from("0.600100"))
6011            .time_in_force(tif)
6012            .build();
6013        let mut state = PrivateState::new();
6014        let ticket = state.ledger.begin_refresh();
6015        state
6016            .ledger
6017            .apply_refresh(ticket, Decimal::from(10), HashMap::new())
6018            .unwrap();
6019        let (emitter, mut output) = emitter();
6020        state
6021            .submit(&mut order, Decimal::ONE, None, &emitter)
6022            .unwrap();
6023        let mut source = source(&instrument, OrderSide::Buy);
6024        source.status = VenueStatus::Canceled;
6025        source.fill_count_fp = FixedPoint(Decimal::ZERO);
6026        source.remaining_count_fp = FixedPoint(Decimal::ZERO);
6027        let before_submit =
6028            jiff::Timestamp::from_nanosecond(i128::from(order.ts_last().as_u64() - 2_000_000_000))
6029                .unwrap();
6030        source.created_time = Field::Value(before_submit);
6031        source.last_update_time = Field::Value(before_submit);
6032        let venue_id = VenueOrderId::from(source.order_id.as_str());
6033
6034        if ack_first {
6035            state
6036                .acknowledge(
6037                    order.client_order_id(),
6038                    venue_id,
6039                    UnixNanos::from(order.ts_last().as_u64() + 1_000_000_000),
6040                    &emitter,
6041                )
6042                .unwrap();
6043        }
6044
6045        let plan = state
6046            .plan_order(&source, &[], &instrument, &emitter, order.ts_last())
6047            .unwrap();
6048        assert!(
6049            plan.is_some(),
6050            "terminal venue evidence was discarded as stale"
6051        );
6052        state.apply_plans(vec![plan.unwrap()], &emitter).unwrap();
6053        state
6054            .acknowledge(order.client_order_id(), venue_id, order.ts_last(), &emitter)
6055            .unwrap();
6056        assert_eq!(
6057            state.orders[&order.client_order_id()].order.status(),
6058            OrderStatus::Canceled
6059        );
6060        assert_eq!(
6061            state.ledger.balance().unwrap().locked.as_decimal(),
6062            Decimal::ZERO
6063        );
6064        let mut events = Vec::new();
6065
6066        while let Ok(event) = output.try_recv() {
6067            if let ExecutionEvent::Order(event) = event {
6068                events.push(event);
6069            }
6070        }
6071
6072        assert_eq!(events.len(), 3);
6073
6074        let OrderEventAny::Canceled(canceled) = &events[2] else {
6075            panic!("expected Canceled")
6076        };
6077
6078        assert_eq!(
6079            canceled.ts_event,
6080            timestamp(&source.last_update_time).unwrap()
6081        );
6082    }
6083
6084    #[rstest]
6085    #[case(
6086        None,
6087        "Kalshi reduce-only requires a strategy-owned canonical position"
6088    )]
6089    #[case(
6090        Some("-2.00"),
6091        "Kalshi reduce-only side does not reduce the canonical position"
6092    )]
6093    #[case(
6094        Some("1.00"),
6095        "Kalshi reduce-only quantity exceeds the canonical position"
6096    )]
6097    fn canonical_reduction_capacity_is_independent_of_account_capacity(
6098        #[case] canonical: Option<&str>,
6099        #[case] reason: &str,
6100    ) {
6101        let instrument = instrument();
6102        let mut state = PrivateState::new();
6103        state.positions.insert(instrument.id, Decimal::from(5));
6104        let order = OrderTestBuilder::new(OrderType::Limit)
6105            .instrument_id(instrument.id)
6106            .side(OrderSide::Sell)
6107            .quantity(Quantity::from("1.25"))
6108            .price(Price::from("0.600000"))
6109            .time_in_force(TimeInForce::Ioc)
6110            .reduce_only(true)
6111            .build();
6112        let error = state
6113            .check_reduction(&order, canonical.map(|qty| qty.parse().unwrap()))
6114            .unwrap_err();
6115        assert_eq!(error.to_string(), reason);
6116    }
6117
6118    #[rstest]
6119    #[case(false)]
6120    #[case(true)]
6121    fn externally_claimable_orders_cannot_consume_canonical_reduction_capacity(
6122        #[case] tracked: bool,
6123    ) {
6124        let instrument = instrument();
6125        let mut state = PrivateState::new();
6126        state.positions.insert(instrument.id, Decimal::from(5));
6127
6128        if tracked {
6129            let pending = OrderTestBuilder::new(OrderType::Limit)
6130                .instrument_id(instrument.id)
6131                .client_order_id("external-pending".into())
6132                .strategy_id(StrategyId::external())
6133                .side(OrderSide::Sell)
6134                .quantity(Quantity::from("1.00"))
6135                .price(Price::from("0.600000"))
6136                .build();
6137            state.restore(pending);
6138        } else {
6139            state
6140                .external_leaves
6141                .insert((instrument.id, OrderSide::Sell), Decimal::ONE);
6142        }
6143
6144        let order = OrderTestBuilder::new(OrderType::Limit)
6145            .instrument_id(instrument.id)
6146            .strategy_id("OWNER-001".into())
6147            .side(OrderSide::Sell)
6148            .quantity(Quantity::from("1.25"))
6149            .price(Price::from("0.600000"))
6150            .time_in_force(TimeInForce::Ioc)
6151            .reduce_only(true)
6152            .build();
6153        let error = state
6154            .check_reduction(&order, Some(Decimal::from(2)))
6155            .unwrap_err();
6156        assert_eq!(
6157            error.to_string(),
6158            "Kalshi reduce-only requires resolved external orders on its reducing side"
6159        );
6160    }
6161
6162    #[rstest]
6163    #[case(false, true)]
6164    #[case(true, false)]
6165    fn unresolved_strategy_order_excludes_competing_reduction_flow(
6166        #[case] pending_reduce: bool,
6167        #[case] next_reduce: bool,
6168    ) {
6169        let instrument = instrument();
6170        let mut state = PrivateState::new();
6171        state.positions.insert(instrument.id, Decimal::from(5));
6172        let pending = OrderTestBuilder::new(OrderType::Limit)
6173            .instrument_id(instrument.id)
6174            .client_order_id("flow-pending".into())
6175            .quantity(Quantity::from("0.25"))
6176            .price(Price::from("0.600000"))
6177            .side(OrderSide::Sell)
6178            .time_in_force(TimeInForce::Ioc)
6179            .reduce_only(pending_reduce)
6180            .build();
6181        let next = OrderTestBuilder::new(OrderType::Limit)
6182            .instrument_id(instrument.id)
6183            .client_order_id("flow-next".into())
6184            .quantity(Quantity::from("0.25"))
6185            .price(Price::from("0.600000"))
6186            .side(OrderSide::Buy)
6187            .time_in_force(TimeInForce::Ioc)
6188            .reduce_only(next_reduce)
6189            .build();
6190        state.restore(pending);
6191        assert_eq!(
6192            state.check_position_flow(&next).unwrap_err().to_string(),
6193            "Kalshi reduce-only requires exclusive strategy-instrument order flow"
6194        );
6195    }
6196
6197    #[rstest]
6198    fn late_mutation_rejection_preserves_the_current_command() {
6199        let definition = instrument();
6200        let order = submitted(&definition, OrderSide::Buy, "change-correlation");
6201        let mut private = state(order.clone(), &definition);
6202        let (emitter, mut output) = emitter();
6203        private
6204            .acknowledge(
6205                order.client_order_id(),
6206                "venue-a".into(),
6207                UnixNanos::from(3),
6208                &emitter,
6209            )
6210            .unwrap();
6211        output.try_recv().unwrap();
6212        let current = private.orders[&order.client_order_id()].order.clone();
6213
6214        let old = CancelOrder::new(
6215            order.trader_id(),
6216            None,
6217            order.strategy_id(),
6218            order.instrument_id(),
6219            order.client_order_id(),
6220            current.venue_order_id(),
6221            UUID4::new(),
6222            UnixNanos::from(4),
6223            None,
6224            None,
6225        );
6226
6227        let mut next = old.clone();
6228        next.command_id = UUID4::new();
6229        private.mutations.insert(
6230            order.client_order_id(),
6231            PendingMutation {
6232                command_id: next.command_id,
6233                started: UnixNanos::from(5),
6234                dispatched: true,
6235                acknowledgement: None,
6236                terms: None,
6237            },
6238        );
6239
6240        private
6241            .resolve_mutation(
6242                &Command::Cancel(old),
6243                &current,
6244                "Old failure",
6245                false,
6246                &emitter,
6247            )
6248            .unwrap();
6249        assert!(output.try_recv().is_err());
6250        assert_eq!(private.orders[&order.client_order_id()].order, current);
6251        assert_eq!(
6252            private.mutations[&order.client_order_id()].command_id,
6253            next.command_id
6254        );
6255        private
6256            .resolve_mutation(
6257                &Command::Cancel(next.clone()),
6258                &current,
6259                "Invalid parameters",
6260                false,
6261                &emitter,
6262            )
6263            .unwrap();
6264
6265        let ExecutionEvent::Order(OrderEventAny::CancelRejected(event)) =
6266            output.try_recv().unwrap()
6267        else {
6268            panic!("expected cancel rejection")
6269        };
6270
6271        assert_eq!(event.causation_id, Some(next.command_id));
6272        assert_eq!(event.trader_id, current.trader_id());
6273        assert_eq!(event.strategy_id, current.strategy_id());
6274        assert_eq!(event.instrument_id, current.instrument_id());
6275        assert_eq!(event.client_order_id, current.client_order_id());
6276        assert_eq!(event.venue_order_id, current.venue_order_id());
6277        assert_eq!(event.account_id, Some(emitter.account_id()));
6278        assert_eq!(event.reason.as_str(), "Invalid parameters");
6279        assert_eq!(
6280            private.orders[&order.client_order_id()].order.status(),
6281            OrderStatus::Accepted
6282        );
6283        assert!(!private.mutations.contains_key(&order.client_order_id()));
6284    }
6285
6286    #[rstest]
6287    fn mutation_outcome_preserves_venue_freshness(#[values(false, true)] denied: bool) {
6288        let definition = instrument();
6289        let order = submitted(&definition, OrderSide::Buy, "change-freshness");
6290        let mut private = state(order.clone(), &definition);
6291        let (emitter, mut output) = emitter();
6292        let id = order.client_order_id();
6293        private.ledger.reserve(id, Decimal::new(12, 1)).unwrap();
6294        private
6295            .acknowledge(id, "venue-a".into(), UnixNanos::from(3), &emitter)
6296            .unwrap();
6297        output.try_recv().unwrap();
6298        let accepted = private.orders[&id].order.clone();
6299
6300        let command_id = UUID4::new();
6301
6302        let mut pending = OrderPendingCancel::new(
6303            order.trader_id(),
6304            order.strategy_id(),
6305            definition.id,
6306            id,
6307            Some(emitter.account_id()),
6308            UUID4::new(),
6309            UnixNanos::from(20),
6310            UnixNanos::from(20),
6311            false,
6312            accepted.venue_order_id(),
6313        );
6314
6315        pending.causation_id = Some(command_id);
6316        private
6317            .orders
6318            .get_mut(&id)
6319            .unwrap()
6320            .order
6321            .apply(OrderEventAny::PendingCancel(pending))
6322            .unwrap();
6323        let command = Command::Cancel(CancelOrder::new(
6324            order.trader_id(),
6325            None,
6326            order.strategy_id(),
6327            definition.id,
6328            id,
6329            accepted.venue_order_id(),
6330            command_id,
6331            UnixNanos::from(20),
6332            None,
6333            None,
6334        ));
6335        private.mutations.insert(
6336            id,
6337            PendingMutation {
6338                command_id: command.id(),
6339                started: UnixNanos::from(20),
6340                dispatched: false,
6341                acknowledgement: None,
6342                terms: None,
6343            },
6344        );
6345
6346        private
6347            .resolve_mutation(&command, &accepted, "Not ready", denied, &emitter)
6348            .unwrap();
6349
6350        let ExecutionEvent::Order(event) = output.try_recv().unwrap() else {
6351            panic!("expected rejection")
6352        };
6353
6354        let mut cached = accepted;
6355        cached.apply(event.clone()).unwrap();
6356        private.restore(cached);
6357        let mut venue = source(&definition, OrderSide::Buy);
6358        venue.order_id = "venue-a".into();
6359        venue.client_order_id = id.to_string();
6360        venue.status = VenueStatus::Canceled;
6361        venue.fill_count_fp = FixedPoint(Decimal::ZERO);
6362        venue.remaining_count_fp = FixedPoint(Decimal::ZERO);
6363        venue.yes_price_dollars = FixedPoint(Decimal::new(6, 1));
6364        venue.no_price_dollars = FixedPoint(Decimal::new(4, 1));
6365        venue.created_time = Field::Value(jiff::Timestamp::from_nanosecond(2).unwrap());
6366        venue.last_update_time = Field::Value(jiff::Timestamp::from_nanosecond(4).unwrap());
6367        let plan = private
6368            .plan_order(&venue, &[], &definition, &emitter, UnixNanos::from(30))
6369            .unwrap();
6370        assert_eq!(event.ts_event(), UnixNanos::from(3));
6371        assert_eq!(private.orders[&id].order.ts_last(), UnixNanos::from(3));
6372        assert!(
6373            plan.is_some(),
6374            "venue cancellation was discarded after rejection"
6375        );
6376        private.apply_plans(vec![plan.unwrap()], &emitter).unwrap();
6377        assert_eq!(private.orders[&id].order.status(), OrderStatus::Canceled);
6378        assert_eq!(
6379            private.ledger.balance().unwrap().locked.as_decimal(),
6380            Decimal::ZERO
6381        );
6382    }
6383}