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