Skip to main content

nautilus_kalshi/execution/
snapshot.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Collects scoped REST execution snapshots and recovery evidence.
17
18use 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::{
38            AccountQuery, FillsQuery, HistoricalPositionsQuery, HistoryQuery, OrdersQuery,
39            PositionsQuery,
40        },
41    },
42};
43
44const RECOVERY_MAX_PAGES: u32 = 100;
45
46/// Complete REST source collection for one subaccount and shard.
47///
48/// Records retain the venue's values and omissions. Separate requests are not an atomic account
49/// snapshot. Settled positions are historical evidence, not current exposure or synthetic fills.
50/// For nonzero subaccounts, orders and fills require explicit matching subaccount identity.
51#[derive(Debug)]
52pub struct KalshiExecutionSnapshot {
53    /// Orders retained for the shard, including resting orders, orders inside the lookback,
54    /// and orders linked to retained fills.
55    pub orders: Vec<Order>,
56    /// Fills for the shard within the optional lookback and no later than `ts_init`.
57    pub fills: Vec<Fill>,
58    /// Current positions for the shard from the live positions endpoint.
59    pub positions: Vec<MarketPosition>,
60    /// Settled-position evidence for the shard from live and historical sources, not current exposure.
61    pub positions_settled: Vec<MarketPosition>,
62    /// Venue cutoffs used to route live and historical collection.
63    pub cutoff: HistoricalCutoff,
64    /// Inclusive start of the order and fill lookback, or `None` for unbounded history.
65    pub lookback_start: Option<UnixNanos>,
66    /// Timestamp captured before any source requests and preserved unchanged.
67    pub ts_init: UnixNanos,
68}
69
70/// Collects execution evidence without inventing missing command metadata.
71///
72/// Open orders and current positions have no history bound. Closed orders include every collected
73/// fill's order, including orders updated before the requested window. Live reads precede archive
74/// reads to cover forward handoffs. Each source must exhaust pagination; conflicts fail collection.
75/// The original initialization timestamp precedes all requests and survives collection unchanged.
76///
77/// # Errors
78///
79/// Returns an error if bounds or timestamps are invalid, pagination is incomplete, records conflict
80/// or lack scope, fills lack order evidence, or any source fails.
81pub async fn collect_snapshot(
82    http: &KalshiHttpClient,
83    account: &AccountQuery,
84    lookback_start: Option<UnixNanos>,
85    max_pages: u32,
86) -> Result<KalshiExecutionSnapshot, KalshiHttpError> {
87    let ts_init = get_atomic_clock_realtime().get_time_ns();
88    collect_snapshot_at(http, account, lookback_start, max_pages, ts_init).await
89}
90
91pub(super) async fn collect_snapshot_at(
92    http: &KalshiHttpClient,
93    account: &AccountQuery,
94    lookback_start: Option<UnixNanos>,
95    max_pages: u32,
96    ts_init: UnixNanos,
97) -> Result<KalshiExecutionSnapshot, KalshiHttpError> {
98    if max_pages == 0 || lookback_start.is_some_and(|start| start > ts_init) {
99        return Err(KalshiHttpError::Validation(
100            "invalid execution snapshot window or page budget",
101        ));
102    }
103
104    let cutoff = http.get_historical_cutoff().await?;
105
106    if !matches!(cutoff.market_positions_last_updated_ts, Field::Value(_)) {
107        return Err(KalshiHttpError::Parse(
108            "missing position history coverage".into(),
109        ));
110    }
111
112    let orders = collect_orders(http, account, None, max_pages).await?;
113
114    let retained_fills = collect_fills(
115        http,
116        &FillsQuery {
117            exchange_index: account.exchange_index,
118            subaccount: account.subaccount,
119            ..Default::default()
120        },
121        lookback_start,
122        ts_init,
123        &cutoff,
124        max_pages,
125    )
126    .await?;
127
128    let retained_orders = retain_orders(orders, &retained_fills, lookback_start, &[])?;
129
130    let (positions, positions_settled) = collect_positions(http, account, None, max_pages).await?;
131    Ok(KalshiExecutionSnapshot {
132        orders: retained_orders,
133        fills: retained_fills,
134        positions,
135        positions_settled,
136        cutoff,
137        lookback_start,
138        ts_init,
139    })
140}
141
142fn retain_orders(
143    orders: HashMap<String, Order>,
144    fills: &[Fill],
145    lookback_start: Option<UnixNanos>,
146    owned: &[OrderAny],
147) -> Result<Vec<Order>, KalshiHttpError> {
148    use nautilus_model::orders::Order as _;
149
150    let venue_ids: Vec<_> = owned
151        .iter()
152        .filter_map(|order| order.venue_order_id())
153        .collect();
154    let mut required_orders: HashSet<_> = venue_ids.iter().map(|id| id.as_str()).collect();
155
156    for fill in fills {
157        let Some(order) = orders.get(&fill.order_id) else {
158            return Err(KalshiHttpError::Parse(
159                "fill has no authoritative order evidence".into(),
160            ));
161        };
162
163        if order.ticker != fill.ticker || fill.ticker != fill.market_ticker {
164            return Err(KalshiHttpError::Parse(
165                "fill and order market identities differ".into(),
166            ));
167        }
168
169        required_orders.insert(fill.order_id.as_str());
170    }
171
172    let mut retained_orders = Vec::new();
173
174    for order in orders.into_values() {
175        let retain = order.status == OrderStatus::Resting
176            || required_orders.contains(order.order_id.as_str());
177        if retain || lookback_start.is_none() {
178            retained_orders.push(order);
179            continue;
180        }
181
182        let timestamp = timestamp(&order.last_update_time)?;
183        if lookback_start.is_some_and(|start| timestamp >= start) {
184            retained_orders.push(order);
185        }
186    }
187
188    retained_orders.sort_by(|a, b| a.order_id.cmp(&b.order_id));
189    Ok(retained_orders)
190}
191
192pub(super) async fn collect_recovery_snapshot(
193    http: &KalshiHttpClient,
194    account: &AccountQuery,
195    start: UnixNanos,
196    tracked: &[InstrumentId],
197    owned: &[OrderAny],
198) -> Result<KalshiExecutionSnapshot, KalshiHttpError> {
199    use nautilus_model::orders::Order as _;
200
201    let max_pages = RECOVERY_MAX_PAGES;
202    let ts_init = get_atomic_clock_realtime().get_time_ns();
203    let cutoff = http.get_historical_cutoff().await?;
204
205    if !matches!(cutoff.market_positions_last_updated_ts, Field::Value(_)) {
206        return Err(KalshiHttpError::Parse(
207            "missing position history coverage".into(),
208        ));
209    }
210
211    let mut orders = collect_orders_window(http, account, None, Some(start), max_pages).await?;
212
213    let resting = collect_orders_live(
214        http,
215        &OrdersQuery {
216            status: Some(OrderStatusFilter::Resting),
217            exchange_index: account.exchange_index,
218            subaccount: account.subaccount,
219            ..Default::default()
220        },
221        max_pages,
222    )
223    .await?;
224
225    for order in resting.into_values() {
226        merge(&mut orders, order.order_id.clone(), order)?;
227    }
228
229    let mut fills = collect_fills(
230        http,
231        &FillsQuery {
232            exchange_index: account.exchange_index,
233            subaccount: account.subaccount,
234            ..Default::default()
235        },
236        Some(start),
237        ts_init,
238        &cutoff,
239        max_pages,
240    )
241    .await?;
242
243    for context in owned {
244        if let Some(id) = context.venue_order_id() {
245            recover_order(
246                http,
247                account,
248                id.as_str(),
249                context.instrument_id().symbol.as_str(),
250                max_pages,
251                &mut orders,
252            )
253            .await?;
254        }
255    }
256
257    for fill in &fills {
258        recover_order(
259            http,
260            account,
261            &fill.order_id,
262            &fill.ticker,
263            max_pages,
264            &mut orders,
265        )
266        .await?;
267    }
268
269    recover_order_fills(http, account, &orders, owned, &cutoff, ts_init, &mut fills).await?;
270    let orders = retain_orders(orders, &fills, Some(start), owned)?;
271    let positions = collect_positions_current(http, account, None, max_pages).await?;
272    let mut targets: HashSet<_> = tracked.iter().map(|id| id.symbol.to_string()).collect();
273    targets.extend(fills.iter().map(|fill| fill.ticker.clone()));
274    for position in &positions {
275        targets.remove(&position.ticker);
276    }
277
278    let mut positions_settled = Vec::new();
279    for ticker in targets {
280        positions_settled
281            .extend(collect_positions_settled(http, account, Some(&ticker), max_pages).await?);
282    }
283
284    positions_settled.sort_by(|a, b| a.ticker.cmp(&b.ticker));
285    Ok(KalshiExecutionSnapshot {
286        orders,
287        fills,
288        positions,
289        positions_settled,
290        cutoff,
291        lookback_start: Some(start),
292        ts_init,
293    })
294}
295
296async fn recover_order(
297    http: &KalshiHttpClient,
298    account: &AccountQuery,
299    id: &str,
300    ticker: &str,
301    max_pages: u32,
302    orders: &mut HashMap<String, Order>,
303) -> Result<(), KalshiHttpError> {
304    if orders.contains_key(id) {
305        return Ok(());
306    }
307
308    match http.get_order(id).await {
309        Ok(response) => {
310            validate_order_scope(&response.order, account, false)?;
311            merge(orders, response.order.order_id.clone(), response.order)?;
312        }
313        Err(
314            KalshiHttpError::Status(404)
315            | KalshiHttpError::Http { status: 404, .. }
316            | KalshiHttpError::Venue { status: 404, .. },
317        ) => {
318            for order in collect_orders(http, account, Some(ticker), max_pages)
319                .await?
320                .into_values()
321            {
322                merge(orders, order.order_id.clone(), order)?;
323            }
324        }
325        Err(e) => return Err(e),
326    }
327
328    Ok(())
329}
330
331async fn recover_order_fills(
332    http: &KalshiHttpClient,
333    account: &AccountQuery,
334    orders: &HashMap<String, Order>,
335    owned: &[OrderAny],
336    cutoff: &HistoricalCutoff,
337    ts_init: UnixNanos,
338    fills: &mut Vec<Fill>,
339) -> Result<(), KalshiHttpError> {
340    use nautilus_model::orders::Order as _;
341    let mut retained: HashMap<_, _> = fills
342        .drain(..)
343        .map(|fill| (fill.fill_id.clone(), fill))
344        .collect();
345
346    for context in owned {
347        let Some(id) = context.venue_order_id() else {
348            continue;
349        };
350
351        let Some(order) = orders.get(id.as_str()) else {
352            continue;
353        };
354
355        if order.fill_count_fp.0 <= context.filled_qty().as_decimal() {
356            continue;
357        }
358
359        let query = FillsQuery {
360            ticker: Some(order.ticker.clone()),
361            order_id: Some(order.order_id.clone()),
362            exchange_index: account.exchange_index,
363            subaccount: account.subaccount,
364            ..Default::default()
365        };
366
367        for fill in collect_fills(
368            http,
369            &query,
370            Some(context.ts_init()),
371            ts_init,
372            cutoff,
373            RECOVERY_MAX_PAGES,
374        )
375        .await?
376        {
377            if fill.order_id == order.order_id {
378                merge(&mut retained, fill.fill_id.clone(), fill)?;
379            }
380        }
381    }
382
383    *fills = retained.into_values().collect();
384    fills.sort_by(|a, b| a.fill_id.cmp(&b.fill_id));
385    Ok(())
386}
387
388pub(super) async fn collect_orders(
389    http: &KalshiHttpClient,
390    account: &AccountQuery,
391    ticker: Option<&str>,
392    max_pages: u32,
393) -> Result<HashMap<String, Order>, KalshiHttpError> {
394    collect_orders_window(http, account, ticker, None, max_pages).await
395}
396
397async fn collect_orders_window(
398    http: &KalshiHttpClient,
399    account: &AccountQuery,
400    ticker: Option<&str>,
401    start: Option<UnixNanos>,
402    max_pages: u32,
403) -> Result<HashMap<String, Order>, KalshiHttpError> {
404    let min_ts =
405        start.map(|start| (start.as_u64() / NANOSECONDS_IN_SECOND).saturating_sub(1) as i64);
406
407    let mut orders = collect_orders_live(
408        http,
409        &OrdersQuery {
410            ticker: ticker.map(String::from),
411            min_ts,
412            exchange_index: account.exchange_index,
413            subaccount: account.subaccount,
414            ..Default::default()
415        },
416        max_pages,
417    )
418    .await?;
419
420    let mut archived_orders = HashMap::new();
421    collect_pages(
422        max_pages,
423        &mut archived_orders,
424        |order: &Order| order.order_id.clone(),
425        |cursor| async move {
426            let page = http
427                .get_historical_orders(&HistoryQuery {
428                    ticker: ticker.map(String::from),
429                    min_ts,
430                    cursor,
431                    limit: Some(1000),
432                    subaccount: account.subaccount,
433                    ..Default::default()
434                })
435                .await?;
436
437            let empty = page.orders.is_empty();
438            Ok((page.orders, page.cursor, empty))
439        },
440    )
441    .await?;
442
443    for order in archived_orders.into_values() {
444        if validate_order_scope(&order, account, true)? {
445            merge(&mut orders, order.order_id.clone(), order)?;
446        }
447    }
448
449    Ok(orders)
450}
451
452async fn collect_orders_live(
453    http: &KalshiHttpClient,
454    query: &OrdersQuery,
455    max_pages: u32,
456) -> Result<HashMap<String, Order>, KalshiHttpError> {
457    let mut orders = HashMap::new();
458    collect_pages(
459        max_pages,
460        &mut orders,
461        |order: &Order| order.order_id.clone(),
462        |cursor| async move {
463            let page = http
464                .get_orders(&OrdersQuery {
465                    cursor,
466                    limit: Some(1000),
467                    ..query.clone()
468                })
469                .await?;
470
471            let empty = page.orders.is_empty();
472            Ok((page.orders, page.cursor, empty))
473        },
474    )
475    .await?;
476
477    for order in orders.values() {
478        validate_order_scope(
479            order,
480            &AccountQuery {
481                subaccount: query.subaccount,
482                exchange_index: query.exchange_index,
483            },
484            false,
485        )?;
486    }
487
488    Ok(orders)
489}
490
491pub(super) async fn collect_fills(
492    http: &KalshiHttpClient,
493    query: &FillsQuery,
494    lookback_start: Option<UnixNanos>,
495    ts_init: UnixNanos,
496    cutoff: &HistoricalCutoff,
497    max_pages: u32,
498) -> Result<Vec<Fill>, KalshiHttpError> {
499    let account = AccountQuery {
500        subaccount: query.subaccount,
501        exchange_index: query.exchange_index,
502    };
503
504    let exchange_index = query.exchange_index;
505    let start = lookback_start.map(|value| (value.as_u64() / NANOSECONDS_IN_SECOND) as i64);
506    let end = (ts_init.as_u64() / NANOSECONDS_IN_SECOND + 1) as i64;
507    let mut fills = HashMap::new();
508    let live_start = Some(
509        start
510            .unwrap_or(0)
511            .max(cutoff.trades_created_ts.as_second())
512            .saturating_sub(1)
513            .max(0),
514    );
515    collect_pages(
516        max_pages,
517        &mut fills,
518        |fill: &Fill| format!("{}:{}", fill.exchange_index, fill.fill_id),
519        |cursor| async move {
520            let page = http
521                .get_fills(&FillsQuery {
522                    ticker: query.ticker.clone(),
523                    order_id: query.order_id.clone(),
524                    cursor,
525                    limit: Some(1000),
526                    min_ts: live_start,
527                    max_ts: Some(end),
528                    subaccount: account.subaccount,
529                    exchange_index,
530                })
531                .await?;
532
533            let empty = page.fills.is_empty();
534            Ok((page.fills, page.cursor, empty))
535        },
536    )
537    .await?;
538
539    for fill in fills.values() {
540        validate_fill_scope(fill, &account, false)?;
541    }
542
543    let mut archived_fills = HashMap::new();
544    collect_pages(
545        max_pages,
546        &mut archived_fills,
547        |fill: &Fill| format!("{}:{}", fill.exchange_index, fill.fill_id),
548        |cursor| async move {
549            let page = http
550                .get_historical_fills(&HistoryQuery {
551                    ticker: query.ticker.clone(),
552                    cursor,
553                    limit: Some(1000),
554                    min_ts: start.map(|start| start.saturating_sub(1).max(0)),
555                    max_ts: Some(end),
556                    subaccount: account.subaccount,
557                })
558                .await?;
559
560            let empty = page.fills.is_empty();
561            Ok((page.fills, page.cursor, empty))
562        },
563    )
564    .await?;
565
566    for fill in archived_fills.into_values() {
567        if validate_fill_scope(&fill, &account, true)? {
568            let key = format!("{}:{}", fill.exchange_index, fill.fill_id);
569            merge(&mut fills, key, fill)?;
570        }
571    }
572
573    let mut retained_fills = Vec::new();
574
575    for fill in fills.into_values() {
576        let timestamp = timestamp(&fill.created_time)?;
577        if lookback_start.is_none_or(|start| timestamp >= start) && timestamp <= ts_init {
578            retained_fills.push((timestamp, fill));
579        }
580    }
581
582    retained_fills.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.fill_id.cmp(&b.1.fill_id)));
583    let retained_fills: Vec<_> = retained_fills.into_iter().map(|(_, fill)| fill).collect();
584    Ok(retained_fills)
585}
586
587pub(super) async fn collect_positions_current(
588    http: &KalshiHttpClient,
589    account: &AccountQuery,
590    ticker: Option<&str>,
591    max_pages: u32,
592) -> Result<Vec<MarketPosition>, KalshiHttpError> {
593    let mut positions = HashMap::new();
594    collect_pages(
595        max_pages,
596        &mut positions,
597        |position: &MarketPosition| position.ticker.clone(),
598        |cursor| async move {
599            let page = http
600                .get_positions(&PositionsQuery {
601                    ticker: ticker.map(String::from),
602                    cursor,
603                    limit: Some(1000),
604                    subaccount: account.subaccount,
605                    exchange_index: account.exchange_index,
606                    ..Default::default()
607                })
608                .await?;
609
610            let empty = page.market_positions.is_empty() && page.event_positions.is_empty();
611            Ok((page.market_positions, page.cursor, empty))
612        },
613    )
614    .await?;
615
616    if positions
617        .values()
618        .any(|p| i64::from(p.exchange_index) != i64::from(account.exchange_index))
619    {
620        return Err(KalshiHttpError::Parse(
621            "current position shard mismatch".into(),
622        ));
623    }
624
625    let mut positions: Vec<_> = positions.into_values().collect();
626    positions.sort_by(|a, b| a.ticker.cmp(&b.ticker));
627    Ok(positions)
628}
629
630async fn collect_positions(
631    http: &KalshiHttpClient,
632    account: &AccountQuery,
633    ticker: Option<&str>,
634    max_pages: u32,
635) -> Result<(Vec<MarketPosition>, Vec<MarketPosition>), KalshiHttpError> {
636    let positions = collect_positions_current(http, account, ticker, max_pages).await?;
637    let positions_settled = collect_positions_settled(http, account, ticker, max_pages).await?;
638    Ok((positions, positions_settled))
639}
640
641async fn collect_positions_settled(
642    http: &KalshiHttpClient,
643    account: &AccountQuery,
644    ticker: Option<&str>,
645    max_pages: u32,
646) -> Result<Vec<MarketPosition>, KalshiHttpError> {
647    let mut positions_settled = HashMap::new();
648    collect_pages(
649        max_pages,
650        &mut positions_settled,
651        |position: &MarketPosition| format!("{}:{}", position.exchange_index, position.ticker),
652        |cursor| async move {
653            let page = http
654                .get_positions(&PositionsQuery {
655                    ticker: ticker.map(String::from),
656                    cursor,
657                    limit: Some(1000),
658                    settlement_status: Some(PositionSettlementStatus::Settled),
659                    subaccount: account.subaccount,
660                    exchange_index: account.exchange_index,
661                    ..Default::default()
662                })
663                .await?;
664
665            let empty = page.market_positions.is_empty() && page.event_positions.is_empty();
666            Ok((page.market_positions, page.cursor, empty))
667        },
668    )
669    .await?;
670
671    if positions_settled
672        .values()
673        .any(|p| i64::from(p.exchange_index) != i64::from(account.exchange_index))
674    {
675        return Err(KalshiHttpError::Parse(
676            "settled position shard mismatch".into(),
677        ));
678    }
679
680    collect_pages(
681        max_pages,
682        &mut positions_settled,
683        |position: &MarketPosition| format!("{}:{}", position.exchange_index, position.ticker),
684        |cursor| async move {
685            let page = http
686                .get_historical_positions(&HistoricalPositionsQuery {
687                    ticker: ticker.map(String::from),
688                    cursor,
689                    limit: Some(1000),
690                    subaccount: account.subaccount,
691                    ..Default::default()
692                })
693                .await?;
694
695            let empty = page.market_positions.is_empty() && page.event_positions.is_empty();
696            Ok((page.market_positions, page.cursor, empty))
697        },
698    )
699    .await?;
700
701    let mut positions_settled: Vec<_> = positions_settled
702        .into_values()
703        .filter(|p| i64::from(p.exchange_index) == i64::from(account.exchange_index))
704        .collect();
705    positions_settled.sort_by(|a, b| a.ticker.cmp(&b.ticker));
706    Ok(positions_settled)
707}
708
709async fn collect_pages<T, F, Fut>(
710    max_pages: u32,
711    records: &mut HashMap<String, T>,
712    identity: fn(&T) -> String,
713    mut fetch: F,
714) -> Result<(), KalshiHttpError>
715where
716    T: PartialEq,
717    F: FnMut(Option<String>) -> Fut,
718    Fut: Future<Output = Result<(Vec<T>, Field<String>, bool), KalshiHttpError>>,
719{
720    let mut cursor = None;
721    let mut pagination = Pagination::new(None);
722
723    for _ in 0..max_pages {
724        let (page, next, empty) = fetch(cursor).await?;
725        for record in page {
726            let key = identity(&record);
727            if key.is_empty() {
728                return Err(KalshiHttpError::Parse(
729                    "missing execution record identity".into(),
730                ));
731            }
732
733            merge(records, key, record)?;
734        }
735
736        cursor = pagination.advance(next, empty)?;
737        if cursor.is_none() {
738            return Ok(());
739        }
740    }
741
742    Err(KalshiHttpError::Pagination(
743        "execution snapshot page budget exhausted",
744    ))
745}
746
747fn merge<T: PartialEq>(
748    records: &mut HashMap<String, T>,
749    key: String,
750    record: T,
751) -> Result<(), KalshiHttpError> {
752    if let Some(existing) = records.get(&key) {
753        if *existing != record {
754            return Err(KalshiHttpError::Parse(
755                "conflicting execution record".into(),
756            ));
757        }
758    } else {
759        records.insert(key, record);
760    }
761
762    Ok(())
763}
764
765pub(super) fn validate_order_scope(
766    order: &Order,
767    account: &AccountQuery,
768    archived: bool,
769) -> Result<bool, KalshiHttpError> {
770    if matches!(order.subaccount_number, Field::Value(value) if i64::from(value) != i64::from(account.subaccount))
771    {
772        return Err(KalshiHttpError::Parse("order subaccount mismatch".into()));
773    }
774
775    if account.subaccount != 0 && !matches!(order.subaccount_number, Field::Value(_)) {
776        return Err(KalshiHttpError::Parse(
777            "missing order subaccount identity".into(),
778        ));
779    }
780
781    let Field::Value(shard) = order.exchange_index else {
782        return Err(KalshiHttpError::Parse(
783            "missing order shard identity".into(),
784        ));
785    };
786
787    if i64::from(shard) == i64::from(account.exchange_index) {
788        Ok(true)
789    } else if archived {
790        Ok(false)
791    } else {
792        Err(KalshiHttpError::Parse("live order shard mismatch".into()))
793    }
794}
795
796fn validate_fill_scope(
797    fill: &Fill,
798    account: &AccountQuery,
799    archived: bool,
800) -> Result<bool, KalshiHttpError> {
801    if fill.fill_id.is_empty() || fill.order_id.is_empty() || fill.trade_id.is_empty() {
802        return Err(KalshiHttpError::Parse("missing fill identity".into()));
803    }
804
805    if matches!(fill.subaccount_number, Field::Value(value) if i64::from(value) != i64::from(account.subaccount))
806    {
807        return Err(KalshiHttpError::Parse("fill subaccount mismatch".into()));
808    }
809
810    if account.subaccount != 0 && !matches!(fill.subaccount_number, Field::Value(_)) {
811        return Err(KalshiHttpError::Parse(
812            "missing fill subaccount identity".into(),
813        ));
814    }
815
816    if i64::from(fill.exchange_index) == i64::from(account.exchange_index) {
817        Ok(true)
818    } else if archived {
819        Ok(false)
820    } else {
821        Err(KalshiHttpError::Parse("live fill shard mismatch".into()))
822    }
823}
824
825pub(super) fn timestamp(value: &Field<jiff::Timestamp>) -> Result<UnixNanos, KalshiHttpError> {
826    let Field::Value(value) = value else {
827        return Err(KalshiHttpError::Parse("missing execution timestamp".into()));
828    };
829
830    let timestamp = try_datetime_to_unix_nanos(*value)
831        .map_err(|_| KalshiHttpError::Parse("invalid execution timestamp".into()))?;
832
833    if timestamp == UnixNanos::default() {
834        return Err(KalshiHttpError::Parse("invalid execution timestamp".into()));
835    }
836
837    Ok(timestamp)
838}
839
840pub(super) async fn load_definition(
841    http: &KalshiHttpClient,
842    ticker: &str,
843    ts_init: UnixNanos,
844) -> anyhow::Result<BinaryOption> {
845    let market = crate::providers::KalshiInstrumentProvider::load_market(http, ticker).await?;
846    anyhow::ensure!(
847        market.ticker == ticker,
848        "requested market identity mismatch"
849    );
850
851    let event = http
852        .get_event(
853            &market.event_ticker,
854            &crate::http::query::EventQuery {
855                exclude_markets: Some(true),
856                ..Default::default()
857            },
858        )
859        .await?
860        .event;
861
862    let series = http.get_series(&event.series_ticker).await?.series;
863    crate::providers::KalshiInstrumentProvider::parse(&market, &event, &series, ts_init)
864}
865
866pub(super) fn validate_definition(
867    instrument: &BinaryOption,
868    exchange_index: u32,
869) -> anyhow::Result<()> {
870    let shard = instrument
871        .info
872        .as_ref()
873        .and_then(|info| info.get("market"))
874        .and_then(|market| market.get("exchange_index"))
875        .and_then(serde_json::Value::as_u64);
876    anyhow::ensure!(
877        shard == Some(u64::from(exchange_index)),
878        "report instrument shard mismatch"
879    );
880    Ok(())
881}
882
883#[cfg(test)]
884mod tests {
885    use rstest::rstest;
886
887    use super::*;
888
889    #[rstest]
890    #[case(Field::Value(7), None)]
891    #[case(Field::Value(0), Some("subaccount mismatch"))]
892    #[case(Field::Value(-1), Some("subaccount mismatch"))]
893    #[case(Field::Missing, Some("missing"))]
894    #[case(Field::Null, Some("missing"))]
895    fn numbered_records_require_matching_account(
896        #[case] identity: Field<i32>,
897        #[case] error: Option<&str>,
898    ) {
899        let f: serde_json::Value =
900            serde_json::from_str(include_str!("../../test_data/rest_responses.json")).unwrap();
901        let mut order: Order = serde_json::from_value(f["order"]["order"].clone()).unwrap();
902        let mut fill: Fill = serde_json::from_value(f["fills"]["fills"][0].clone()).unwrap();
903        order.subaccount_number = identity.clone();
904        fill.subaccount_number = identity;
905
906        let account = AccountQuery {
907            subaccount: 7,
908            exchange_index: 3,
909        };
910
911        for (kind, result) in [
912            ("order", validate_order_scope(&order, &account, false)),
913            ("fill", validate_fill_scope(&fill, &account, false)),
914        ] {
915            match error {
916                None => assert!(result.unwrap()),
917                Some("missing") => assert_eq!(
918                    result.unwrap_err().to_string(),
919                    format!("parse error: missing {kind} subaccount identity")
920                ),
921                Some(_) => assert_eq!(
922                    result.unwrap_err().to_string(),
923                    format!("parse error: {kind} subaccount mismatch")
924                ),
925            }
926        }
927    }
928}