1use std::{
19 collections::{HashMap, HashSet},
20 future::Future,
21};
22
23use nautilus_core::{
24 UnixNanos,
25 datetime::{NANOSECONDS_IN_SECOND, try_datetime_to_unix_nanos},
26 time::get_atomic_clock_realtime,
27};
28use nautilus_model::{identifiers::InstrumentId, instruments::BinaryOption, orders::OrderAny};
29
30use crate::{
31 common::enums::{OrderStatusFilter, PositionSettlementStatus},
32 http::{
33 client::KalshiHttpClient,
34 error::KalshiHttpError,
35 models::{Field, Fill, HistoricalCutoff, MarketPosition, Order, OrderStatus},
36 parse::Pagination,
37 query::{FillsQuery, HistoricalPositionsQuery, HistoryQuery, OrdersQuery, PositionsQuery},
38 },
39};
40
41const RECOVERY_MAX_PAGES: u32 = 100;
42
43#[derive(Debug)]
48pub struct KalshiExecutionSnapshot {
49 pub orders: Vec<Order>,
52 pub fills: Vec<Fill>,
54 pub positions: Vec<MarketPosition>,
56 pub positions_settled: Vec<MarketPosition>,
58 pub cutoff: HistoricalCutoff,
60 pub lookback_start: Option<UnixNanos>,
62 pub ts_init: UnixNanos,
64}
65
66pub async fn collect_snapshot(
78 http: &KalshiHttpClient,
79 exchange_index: u32,
80 lookback_start: Option<UnixNanos>,
81 max_pages: u32,
82) -> Result<KalshiExecutionSnapshot, KalshiHttpError> {
83 let ts_init = get_atomic_clock_realtime().get_time_ns();
84 collect_snapshot_at(http, exchange_index, lookback_start, max_pages, ts_init).await
85}
86
87pub(super) async fn collect_snapshot_at(
88 http: &KalshiHttpClient,
89 exchange_index: u32,
90 lookback_start: Option<UnixNanos>,
91 max_pages: u32,
92 ts_init: UnixNanos,
93) -> Result<KalshiExecutionSnapshot, KalshiHttpError> {
94 if max_pages == 0 || lookback_start.is_some_and(|start| start > ts_init) {
95 return Err(KalshiHttpError::Validation(
96 "invalid execution snapshot window or page budget",
97 ));
98 }
99
100 let cutoff = http.get_historical_cutoff().await?;
101
102 if !matches!(cutoff.market_positions_last_updated_ts, Field::Value(_)) {
103 return Err(KalshiHttpError::Parse(
104 "missing position history coverage".into(),
105 ));
106 }
107
108 let orders = collect_orders(http, exchange_index, None, max_pages).await?;
109
110 let retained_fills = collect_fills(
111 http,
112 &FillsQuery {
113 exchange_index,
114 ..Default::default()
115 },
116 lookback_start,
117 ts_init,
118 &cutoff,
119 max_pages,
120 )
121 .await?;
122
123 let retained_orders = retain_orders(orders, &retained_fills, lookback_start, &[])?;
124
125 let (positions, positions_settled) =
126 collect_positions(http, exchange_index, None, max_pages).await?;
127 Ok(KalshiExecutionSnapshot {
128 orders: retained_orders,
129 fills: retained_fills,
130 positions,
131 positions_settled,
132 cutoff,
133 lookback_start,
134 ts_init,
135 })
136}
137
138fn retain_orders(
139 orders: HashMap<String, Order>,
140 fills: &[Fill],
141 lookback_start: Option<UnixNanos>,
142 owned: &[OrderAny],
143) -> Result<Vec<Order>, KalshiHttpError> {
144 use nautilus_model::orders::Order as _;
145
146 let venue_ids: Vec<_> = owned
147 .iter()
148 .filter_map(|order| order.venue_order_id())
149 .collect();
150 let mut required_orders: HashSet<_> = venue_ids.iter().map(|id| id.as_str()).collect();
151
152 for fill in fills {
153 let Some(order) = orders.get(&fill.order_id) else {
154 return Err(KalshiHttpError::Parse(
155 "fill has no authoritative order evidence".into(),
156 ));
157 };
158
159 if order.ticker != fill.ticker || fill.ticker != fill.market_ticker {
160 return Err(KalshiHttpError::Parse(
161 "fill and order market identities differ".into(),
162 ));
163 }
164
165 required_orders.insert(fill.order_id.as_str());
166 }
167
168 let mut retained_orders = Vec::new();
169
170 for order in orders.into_values() {
171 let retain = order.status == OrderStatus::Resting
172 || required_orders.contains(order.order_id.as_str());
173 if retain || lookback_start.is_none() {
174 retained_orders.push(order);
175 continue;
176 }
177
178 let timestamp = timestamp(&order.last_update_time)?;
179 if lookback_start.is_some_and(|start| timestamp >= start) {
180 retained_orders.push(order);
181 }
182 }
183
184 retained_orders.sort_by(|a, b| a.order_id.cmp(&b.order_id));
185 Ok(retained_orders)
186}
187
188pub(super) async fn collect_recovery_snapshot(
189 http: &KalshiHttpClient,
190 exchange_index: u32,
191 start: UnixNanos,
192 tracked: &[InstrumentId],
193 owned: &[OrderAny],
194) -> Result<KalshiExecutionSnapshot, KalshiHttpError> {
195 use nautilus_model::orders::Order as _;
196
197 let max_pages = RECOVERY_MAX_PAGES;
198 let ts_init = get_atomic_clock_realtime().get_time_ns();
199 let cutoff = http.get_historical_cutoff().await?;
200
201 if !matches!(cutoff.market_positions_last_updated_ts, Field::Value(_)) {
202 return Err(KalshiHttpError::Parse(
203 "missing position history coverage".into(),
204 ));
205 }
206
207 let mut orders =
208 collect_orders_window(http, exchange_index, None, Some(start), max_pages).await?;
209
210 let resting = collect_orders_live(
211 http,
212 &OrdersQuery {
213 status: Some(OrderStatusFilter::Resting),
214 exchange_index,
215 ..Default::default()
216 },
217 max_pages,
218 )
219 .await?;
220
221 for order in resting.into_values() {
222 merge(&mut orders, order.order_id.clone(), order)?;
223 }
224
225 let mut fills = collect_fills(
226 http,
227 &FillsQuery {
228 exchange_index,
229 ..Default::default()
230 },
231 Some(start),
232 ts_init,
233 &cutoff,
234 max_pages,
235 )
236 .await?;
237
238 for context in owned {
239 if let Some(id) = context.venue_order_id() {
240 recover_order(
241 http,
242 exchange_index,
243 id.as_str(),
244 context.instrument_id().symbol.as_str(),
245 max_pages,
246 &mut orders,
247 )
248 .await?;
249 }
250 }
251
252 for fill in &fills {
253 recover_order(
254 http,
255 exchange_index,
256 &fill.order_id,
257 &fill.ticker,
258 max_pages,
259 &mut orders,
260 )
261 .await?;
262 }
263
264 recover_order_fills(
265 http,
266 exchange_index,
267 &orders,
268 owned,
269 &cutoff,
270 ts_init,
271 &mut fills,
272 )
273 .await?;
274 let orders = retain_orders(orders, &fills, Some(start), owned)?;
275 let positions = collect_positions_current(http, exchange_index, None, max_pages).await?;
276 let mut targets: HashSet<_> = tracked.iter().map(|id| id.symbol.to_string()).collect();
277 targets.extend(fills.iter().map(|fill| fill.ticker.clone()));
278 for position in &positions {
279 targets.remove(&position.ticker);
280 }
281
282 let mut positions_settled = Vec::new();
283 for ticker in targets {
284 positions_settled.extend(
285 collect_positions_settled(http, exchange_index, Some(&ticker), max_pages).await?,
286 );
287 }
288
289 positions_settled.sort_by(|a, b| a.ticker.cmp(&b.ticker));
290 Ok(KalshiExecutionSnapshot {
291 orders,
292 fills,
293 positions,
294 positions_settled,
295 cutoff,
296 lookback_start: Some(start),
297 ts_init,
298 })
299}
300
301async fn recover_order(
302 http: &KalshiHttpClient,
303 exchange_index: u32,
304 id: &str,
305 ticker: &str,
306 max_pages: u32,
307 orders: &mut HashMap<String, Order>,
308) -> Result<(), KalshiHttpError> {
309 if orders.contains_key(id) {
310 return Ok(());
311 }
312
313 match http.get_order(id).await {
314 Ok(response) => {
315 validate_order_scope(&response.order, exchange_index, false)?;
316 merge(orders, response.order.order_id.clone(), response.order)?;
317 }
318 Err(
319 KalshiHttpError::Status(404)
320 | KalshiHttpError::Http { status: 404, .. }
321 | KalshiHttpError::Venue { status: 404, .. },
322 ) => {
323 for order in collect_orders(http, exchange_index, Some(ticker), max_pages)
324 .await?
325 .into_values()
326 {
327 merge(orders, order.order_id.clone(), order)?;
328 }
329 }
330 Err(e) => return Err(e),
331 }
332
333 Ok(())
334}
335
336async fn recover_order_fills(
337 http: &KalshiHttpClient,
338 exchange_index: u32,
339 orders: &HashMap<String, Order>,
340 owned: &[OrderAny],
341 cutoff: &HistoricalCutoff,
342 ts_init: UnixNanos,
343 fills: &mut Vec<Fill>,
344) -> Result<(), KalshiHttpError> {
345 use nautilus_model::orders::Order as _;
346 let mut retained: HashMap<_, _> = fills
347 .drain(..)
348 .map(|fill| (fill.fill_id.clone(), fill))
349 .collect();
350
351 for context in owned {
352 let Some(id) = context.venue_order_id() else {
353 continue;
354 };
355
356 let Some(order) = orders.get(id.as_str()) else {
357 continue;
358 };
359
360 if order.fill_count_fp.0 <= context.filled_qty().as_decimal() {
361 continue;
362 }
363
364 let query = FillsQuery {
365 ticker: Some(order.ticker.clone()),
366 order_id: Some(order.order_id.clone()),
367 exchange_index,
368 ..Default::default()
369 };
370
371 for fill in collect_fills(
372 http,
373 &query,
374 Some(context.ts_init()),
375 ts_init,
376 cutoff,
377 RECOVERY_MAX_PAGES,
378 )
379 .await?
380 {
381 if fill.order_id == order.order_id {
382 merge(&mut retained, fill.fill_id.clone(), fill)?;
383 }
384 }
385 }
386
387 *fills = retained.into_values().collect();
388 fills.sort_by(|a, b| a.fill_id.cmp(&b.fill_id));
389 Ok(())
390}
391
392pub(super) async fn collect_orders(
393 http: &KalshiHttpClient,
394 exchange_index: u32,
395 ticker: Option<&str>,
396 max_pages: u32,
397) -> Result<HashMap<String, Order>, KalshiHttpError> {
398 collect_orders_window(http, exchange_index, ticker, None, max_pages).await
399}
400
401async fn collect_orders_window(
402 http: &KalshiHttpClient,
403 exchange_index: u32,
404 ticker: Option<&str>,
405 start: Option<UnixNanos>,
406 max_pages: u32,
407) -> Result<HashMap<String, Order>, KalshiHttpError> {
408 let min_ts =
409 start.map(|start| (start.as_u64() / NANOSECONDS_IN_SECOND).saturating_sub(1) as i64);
410
411 let mut orders = collect_orders_live(
412 http,
413 &OrdersQuery {
414 ticker: ticker.map(String::from),
415 min_ts,
416 exchange_index,
417 ..Default::default()
418 },
419 max_pages,
420 )
421 .await?;
422
423 let mut archived_orders = HashMap::new();
424 collect_pages(
425 max_pages,
426 &mut archived_orders,
427 |order: &Order| order.order_id.clone(),
428 |cursor| async move {
429 let page = http
430 .get_historical_orders(&HistoryQuery {
431 ticker: ticker.map(String::from),
432 min_ts,
433 cursor,
434 limit: Some(1000),
435 subaccount: 0,
436 ..Default::default()
437 })
438 .await?;
439
440 let empty = page.orders.is_empty();
441 Ok((page.orders, page.cursor, empty))
442 },
443 )
444 .await?;
445
446 for order in archived_orders.into_values() {
447 if validate_order_scope(&order, exchange_index, true)? {
448 merge(&mut orders, order.order_id.clone(), order)?;
449 }
450 }
451
452 Ok(orders)
453}
454
455async fn collect_orders_live(
456 http: &KalshiHttpClient,
457 query: &OrdersQuery,
458 max_pages: u32,
459) -> Result<HashMap<String, Order>, KalshiHttpError> {
460 let mut orders = HashMap::new();
461 collect_pages(
462 max_pages,
463 &mut orders,
464 |order: &Order| order.order_id.clone(),
465 |cursor| async move {
466 let page = http
467 .get_orders(&OrdersQuery {
468 cursor,
469 limit: Some(1000),
470 ..query.clone()
471 })
472 .await?;
473
474 let empty = page.orders.is_empty();
475 Ok((page.orders, page.cursor, empty))
476 },
477 )
478 .await?;
479
480 for order in orders.values() {
481 validate_order_scope(order, query.exchange_index, false)?;
482 }
483
484 Ok(orders)
485}
486
487pub(super) async fn collect_fills(
488 http: &KalshiHttpClient,
489 query: &FillsQuery,
490 lookback_start: Option<UnixNanos>,
491 ts_init: UnixNanos,
492 cutoff: &HistoricalCutoff,
493 max_pages: u32,
494) -> Result<Vec<Fill>, KalshiHttpError> {
495 let exchange_index = query.exchange_index;
496 let start = lookback_start.map(|value| (value.as_u64() / NANOSECONDS_IN_SECOND) as i64);
497 let end = (ts_init.as_u64() / NANOSECONDS_IN_SECOND + 1) as i64;
498 let mut fills = HashMap::new();
499 let live_start = Some(
500 start
501 .unwrap_or(0)
502 .max(cutoff.trades_created_ts.as_second())
503 .saturating_sub(1)
504 .max(0),
505 );
506 collect_pages(
507 max_pages,
508 &mut fills,
509 |fill: &Fill| format!("{}:{}", fill.exchange_index, fill.fill_id),
510 |cursor| async move {
511 let page = http
512 .get_fills(&FillsQuery {
513 ticker: query.ticker.clone(),
514 order_id: query.order_id.clone(),
515 cursor,
516 limit: Some(1000),
517 min_ts: live_start,
518 max_ts: Some(end),
519 subaccount: 0,
520 exchange_index,
521 })
522 .await?;
523
524 let empty = page.fills.is_empty();
525 Ok((page.fills, page.cursor, empty))
526 },
527 )
528 .await?;
529
530 for fill in fills.values() {
531 validate_fill_scope(fill, exchange_index, false)?;
532 }
533
534 let mut archived_fills = HashMap::new();
535 collect_pages(
536 max_pages,
537 &mut archived_fills,
538 |fill: &Fill| format!("{}:{}", fill.exchange_index, fill.fill_id),
539 |cursor| async move {
540 let page = http
541 .get_historical_fills(&HistoryQuery {
542 ticker: query.ticker.clone(),
543 cursor,
544 limit: Some(1000),
545 min_ts: start.map(|start| start.saturating_sub(1).max(0)),
546 max_ts: Some(end),
547 subaccount: 0,
548 })
549 .await?;
550
551 let empty = page.fills.is_empty();
552 Ok((page.fills, page.cursor, empty))
553 },
554 )
555 .await?;
556
557 for fill in archived_fills.into_values() {
558 if validate_fill_scope(&fill, exchange_index, true)? {
559 let key = format!("{}:{}", fill.exchange_index, fill.fill_id);
560 merge(&mut fills, key, fill)?;
561 }
562 }
563
564 let mut retained_fills = Vec::new();
565
566 for fill in fills.into_values() {
567 let timestamp = timestamp(&fill.created_time)?;
568 if lookback_start.is_none_or(|start| timestamp >= start) && timestamp <= ts_init {
569 retained_fills.push((timestamp, fill));
570 }
571 }
572
573 retained_fills.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.fill_id.cmp(&b.1.fill_id)));
574 let retained_fills: Vec<_> = retained_fills.into_iter().map(|(_, fill)| fill).collect();
575 Ok(retained_fills)
576}
577
578pub(super) async fn collect_positions_current(
579 http: &KalshiHttpClient,
580 exchange_index: u32,
581 ticker: Option<&str>,
582 max_pages: u32,
583) -> Result<Vec<MarketPosition>, KalshiHttpError> {
584 let mut positions = HashMap::new();
585 collect_pages(
586 max_pages,
587 &mut positions,
588 |position: &MarketPosition| position.ticker.clone(),
589 |cursor| async move {
590 let page = http
591 .get_positions(&PositionsQuery {
592 ticker: ticker.map(String::from),
593 cursor,
594 limit: Some(1000),
595 subaccount: 0,
596 exchange_index,
597 ..Default::default()
598 })
599 .await?;
600
601 let empty = page.market_positions.is_empty() && page.event_positions.is_empty();
602 Ok((page.market_positions, page.cursor, empty))
603 },
604 )
605 .await?;
606
607 if positions
608 .values()
609 .any(|p| i64::from(p.exchange_index) != i64::from(exchange_index))
610 {
611 return Err(KalshiHttpError::Parse(
612 "current position shard mismatch".into(),
613 ));
614 }
615
616 let mut positions: Vec<_> = positions.into_values().collect();
617 positions.sort_by(|a, b| a.ticker.cmp(&b.ticker));
618 Ok(positions)
619}
620
621async fn collect_positions(
622 http: &KalshiHttpClient,
623 exchange_index: u32,
624 ticker: Option<&str>,
625 max_pages: u32,
626) -> Result<(Vec<MarketPosition>, Vec<MarketPosition>), KalshiHttpError> {
627 let positions = collect_positions_current(http, exchange_index, ticker, max_pages).await?;
628 let positions_settled =
629 collect_positions_settled(http, exchange_index, ticker, max_pages).await?;
630 Ok((positions, positions_settled))
631}
632
633async fn collect_positions_settled(
634 http: &KalshiHttpClient,
635 exchange_index: u32,
636 ticker: Option<&str>,
637 max_pages: u32,
638) -> Result<Vec<MarketPosition>, KalshiHttpError> {
639 let mut positions_settled = HashMap::new();
640 collect_pages(
641 max_pages,
642 &mut positions_settled,
643 |position: &MarketPosition| format!("{}:{}", position.exchange_index, position.ticker),
644 |cursor| async move {
645 let page = http
646 .get_positions(&PositionsQuery {
647 ticker: ticker.map(String::from),
648 cursor,
649 limit: Some(1000),
650 settlement_status: Some(PositionSettlementStatus::Settled),
651 subaccount: 0,
652 exchange_index,
653 ..Default::default()
654 })
655 .await?;
656
657 let empty = page.market_positions.is_empty() && page.event_positions.is_empty();
658 Ok((page.market_positions, page.cursor, empty))
659 },
660 )
661 .await?;
662
663 if positions_settled
664 .values()
665 .any(|p| i64::from(p.exchange_index) != i64::from(exchange_index))
666 {
667 return Err(KalshiHttpError::Parse(
668 "settled position shard mismatch".into(),
669 ));
670 }
671
672 collect_pages(
673 max_pages,
674 &mut positions_settled,
675 |position: &MarketPosition| format!("{}:{}", position.exchange_index, position.ticker),
676 |cursor| async move {
677 let page = http
678 .get_historical_positions(&HistoricalPositionsQuery {
679 ticker: ticker.map(String::from),
680 cursor,
681 limit: Some(1000),
682 subaccount: 0,
683 ..Default::default()
684 })
685 .await?;
686
687 let empty = page.market_positions.is_empty() && page.event_positions.is_empty();
688 Ok((page.market_positions, page.cursor, empty))
689 },
690 )
691 .await?;
692
693 let mut positions_settled: Vec<_> = positions_settled
694 .into_values()
695 .filter(|p| i64::from(p.exchange_index) == i64::from(exchange_index))
696 .collect();
697 positions_settled.sort_by(|a, b| a.ticker.cmp(&b.ticker));
698 Ok(positions_settled)
699}
700
701async fn collect_pages<T, F, Fut>(
702 max_pages: u32,
703 records: &mut HashMap<String, T>,
704 identity: fn(&T) -> String,
705 mut fetch: F,
706) -> Result<(), KalshiHttpError>
707where
708 T: PartialEq,
709 F: FnMut(Option<String>) -> Fut,
710 Fut: Future<Output = Result<(Vec<T>, Field<String>, bool), KalshiHttpError>>,
711{
712 let mut cursor = None;
713 let mut pagination = Pagination::new(None);
714
715 for _ in 0..max_pages {
716 let (page, next, empty) = fetch(cursor).await?;
717 for record in page {
718 let key = identity(&record);
719 if key.is_empty() {
720 return Err(KalshiHttpError::Parse(
721 "missing execution record identity".into(),
722 ));
723 }
724
725 merge(records, key, record)?;
726 }
727
728 cursor = pagination.advance(next, empty)?;
729 if cursor.is_none() {
730 return Ok(());
731 }
732 }
733
734 Err(KalshiHttpError::Pagination(
735 "execution snapshot page budget exhausted",
736 ))
737}
738
739fn merge<T: PartialEq>(
740 records: &mut HashMap<String, T>,
741 key: String,
742 record: T,
743) -> Result<(), KalshiHttpError> {
744 if let Some(existing) = records.get(&key) {
745 if *existing != record {
746 return Err(KalshiHttpError::Parse(
747 "conflicting execution record".into(),
748 ));
749 }
750 } else {
751 records.insert(key, record);
752 }
753
754 Ok(())
755}
756
757pub(super) fn validate_order_scope(
758 order: &Order,
759 exchange_index: u32,
760 archived: bool,
761) -> Result<bool, KalshiHttpError> {
762 if matches!(order.subaccount_number, Field::Value(value) if value != 0) {
763 return Err(KalshiHttpError::Parse(
764 "order primary-account mismatch".into(),
765 ));
766 }
767
768 let Field::Value(shard) = order.exchange_index else {
769 return Err(KalshiHttpError::Parse(
770 "missing order shard identity".into(),
771 ));
772 };
773
774 if i64::from(shard) == i64::from(exchange_index) {
775 Ok(true)
776 } else if archived {
777 Ok(false)
778 } else {
779 Err(KalshiHttpError::Parse("live order shard mismatch".into()))
780 }
781}
782
783fn validate_fill_scope(
784 fill: &Fill,
785 exchange_index: u32,
786 archived: bool,
787) -> Result<bool, KalshiHttpError> {
788 if fill.fill_id.is_empty() || fill.order_id.is_empty() || fill.trade_id.is_empty() {
789 return Err(KalshiHttpError::Parse("missing fill identity".into()));
790 }
791
792 if matches!(fill.subaccount_number, Field::Value(value) if value != 0) {
793 return Err(KalshiHttpError::Parse(
794 "fill primary-account mismatch".into(),
795 ));
796 }
797
798 if i64::from(fill.exchange_index) == i64::from(exchange_index) {
799 Ok(true)
800 } else if archived {
801 Ok(false)
802 } else {
803 Err(KalshiHttpError::Parse("live fill shard mismatch".into()))
804 }
805}
806
807pub(super) fn timestamp(value: &Field<jiff::Timestamp>) -> Result<UnixNanos, KalshiHttpError> {
808 let Field::Value(value) = value else {
809 return Err(KalshiHttpError::Parse("missing execution timestamp".into()));
810 };
811
812 let timestamp = try_datetime_to_unix_nanos(*value)
813 .map_err(|_| KalshiHttpError::Parse("invalid execution timestamp".into()))?;
814
815 if timestamp == UnixNanos::default() {
816 return Err(KalshiHttpError::Parse("invalid execution timestamp".into()));
817 }
818
819 Ok(timestamp)
820}
821
822pub(super) async fn load_definition(
823 http: &KalshiHttpClient,
824 ticker: &str,
825 ts_init: UnixNanos,
826) -> anyhow::Result<BinaryOption> {
827 let market = crate::providers::KalshiInstrumentProvider::load_market(http, ticker).await?;
828 anyhow::ensure!(
829 market.ticker == ticker,
830 "requested market identity mismatch"
831 );
832
833 let event = http
834 .get_event(
835 &market.event_ticker,
836 &crate::http::query::EventQuery {
837 exclude_markets: Some(true),
838 ..Default::default()
839 },
840 )
841 .await?
842 .event;
843
844 let series = http.get_series(&event.series_ticker).await?.series;
845 crate::providers::KalshiInstrumentProvider::parse(&market, &event, &series, ts_init)
846}
847
848pub(super) fn validate_definition(
849 instrument: &BinaryOption,
850 exchange_index: u32,
851) -> anyhow::Result<()> {
852 let shard = instrument
853 .info
854 .as_ref()
855 .and_then(|info| info.get("market"))
856 .and_then(|market| market.get("exchange_index"))
857 .and_then(serde_json::Value::as_u64);
858 anyhow::ensure!(
859 shard == Some(u64::from(exchange_index)),
860 "report instrument shard mismatch"
861 );
862 Ok(())
863}