exchange-hours 1.2.2

Exchange trading hours, session boundaries, and calendar-aware bar boundaries. UTC in, UTC out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
// SPDX-License-Identifier: MIT-0

//! Caller-supplied trade-date overrides and their calendar adapter.

mod candles;
mod static_policy;
mod week;

pub use static_policy::{DayOverride, StaticDayPolicy, StaticDayPolicyError};

use chrono::{DateTime, NaiveDate, Utc};
use chrono_tz::Tz;

use super::exceptions::{DateException, ExceptionScopeError, SessionExceptionSource};
use super::exchange_calendar::SessionWindow;
use super::query::gate::Identified;
use super::query::{QueryContext, sessions, status};
use super::schedules::holidays::{Holiday, HolidayCoverage};
use super::{
    CalendarQueryError, CalendarSource, Exchange, ExchangeCalendar, MarketHours, MarketHoursKey,
    SessionKind, SessionState,
};

/// Day-level schedule overrides supplied by a caller.
///
/// Dates are venue-local **trade dates**, normally the local date of the
/// trading session's final close. For an ordinary wrapped Globex session,
/// closing Monday therefore removes the session that opened Sunday evening.
/// A sourced family convention can assign trading to the next open business
/// date instead: CME cryptocurrency weekend trading remains open and rolls to
/// Tuesday when Monday is closed. Implementations must be deterministic and
/// should perform no I/O or clock reads. The crate's own per-family holiday
/// tables are the innermost layer below this overlay, which only ever tightens
/// what they answer. A profile without a final daily close has no trade date,
/// so its queries ignore this overlay rather than inventing one.
/// Callers with hard-coded records can use [`StaticDayPolicy`] instead of
/// implementing this trait themselves. This boundary API cannot replace or
/// split arbitrary intraday phases; a special day with different internal
/// topology goes through [`SessionExceptionSource`], which this overlay then
/// clips exactly as it clips a normal week.
pub trait DayPolicy: Send + Sync {
    /// Returns whether the market does not trade on `trade_date`.
    ///
    /// This normally removes that complete trading day. An identified family
    /// with a sourced following-business-day convention may instead reassign
    /// its continuous trading to the next date for which this returns `false`.
    fn is_closed(&self, trade_date: NaiveDate) -> bool;

    /// Moves the trade date's final close to venue-local seconds since midnight.
    ///
    /// Later phases are removed. `None` keeps the normal close. Values greater
    /// than `86_400` are invalid and make that trade date unavailable.
    fn early_close_ssm(&self, trade_date: NaiveDate) -> Option<u32>;

    /// Delays the trade date's first open to venue-local seconds since midnight.
    ///
    /// `None` keeps the normal open. For a wrapped trading day, a value at or
    /// after the normal first-open wall clock is interpreted on the preceding
    /// opening date; smaller values are interpreted on the trade date. Values
    /// at or above `86_400` are invalid and make that trade date unavailable.
    fn late_open_ssm(&self, _trade_date: NaiveDate) -> Option<u32> {
        None
    }

    /// Returns whether this policy holds any record that can land on a trade
    /// date in the inclusive window `first..=last`.
    ///
    /// This is the coverage question the query engine's gate asks before it
    /// derives a trading day: the overlay can only change an occurrence's
    /// answer by holding a record for a trade date that occurrence could be
    /// assigned to, so a policy answering `false` for the whole window lets
    /// the query finish at the bare calendar's cost. The default answer is
    /// `true` — *possibly*, which keeps the derivation — so an implementation
    /// that does not track its own span behaves exactly as it did before this
    /// method existed, and every existing implementation stays
    /// source-compatible.
    ///
    /// Returning `false` for a window that in fact holds a record is a
    /// soundness bug in the implementation, not a tunable: the engine will
    /// skip the derivation and serve the unmodified normal week for an
    /// occurrence the record should have moved. [`StaticDayPolicy`] answers
    /// from one binary search over its validated, sorted records.
    fn may_affect(&self, first: NaiveDate, last: NaiveDate) -> bool {
        let _ = (first, last);
        true
    }
}

/// A policy that leaves every normal-week session unchanged.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoPolicy;

impl DayPolicy for NoPolicy {
    fn is_closed(&self, _trade_date: NaiveDate) -> bool {
        false
    }

    fn early_close_ssm(&self, _trade_date: NaiveDate) -> Option<u32> {
        None
    }

    /// No record anywhere: the policy can never affect an answer, so the
    /// engine's gate may always skip its derivation.
    fn may_affect(&self, _first: NaiveDate, _last: NaiveDate) -> bool {
        false
    }
}

impl core::fmt::Debug for PolicyCalendar<'_> {
    /// Reports the identity and which overlays are attached.
    ///
    /// Neither overlay is a `Debug` value — both are caller-supplied trait
    /// objects — so this states their presence rather than their contents.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("PolicyCalendar")
            .field("source", &self.calendar.source())
            .field("day_policy", &self.policy.is_some())
            .field("session_exceptions", &self.exceptions.is_some())
            .finish()
    }
}

/// A date-aware calendar with the caller's own day overlays applied.
///
/// Two independent overlays can be attached, and both are optional. A
/// [`DayPolicy`] clips a trading day's outer boundaries; a
/// [`SessionExceptionSource`] replaces a trade date outright with a complete
/// ordered block set. Precedence is fixed and one-directional: the exception
/// layer resolves the trading day, then the policy overlays it exactly as it
/// overlays a normal week. Two replacement layers never compose — attaching a
/// provider replaces any provider already attached.
///
/// The wrapper borrows both overlays and remains allocation-free itself. Work
/// or allocation performed inside the caller's callbacks is outside the
/// calendar's performance guarantees. [`Self::hours_at`] deliberately returns
/// the unmodified sourced profile; the overlays apply to queries, not tables.
#[derive(Clone, Copy)]
pub struct PolicyCalendar<'a> {
    calendar: ExchangeCalendar,
    policy: Option<&'a dyn DayPolicy>,
    exceptions: Option<&'a dyn SessionExceptionSource>,
}

impl<'a> PolicyCalendar<'a> {
    pub(super) const fn new(
        calendar: ExchangeCalendar,
        policy: Option<&'a dyn DayPolicy>,
        exceptions: Option<&'a dyn SessionExceptionSource>,
    ) -> Self {
        Self {
            calendar,
            policy,
            exceptions,
        }
    }

    fn context(self) -> QueryContext<'a, Identified> {
        QueryContext::overlay(self.calendar, self.policy, self.exceptions)
    }

    /// Returns whether a [`DayPolicy`] is attached.
    #[must_use]
    pub const fn has_day_policy(self) -> bool {
        self.policy.is_some()
    }

    /// Returns whether a [`SessionExceptionSource`] is attached.
    #[must_use]
    pub const fn has_session_exceptions(self) -> bool {
        self.exceptions.is_some()
    }

    /// Applies caller-supplied trade-date boundary overrides to every query.
    ///
    /// Replaces any policy already attached.
    #[must_use]
    pub const fn with_day_policy(self, policy: &'a dyn DayPolicy) -> Self {
        Self::new(self.calendar, Some(policy), self.exceptions)
    }

    /// Applies a caller-supplied replacement-session provider to every query.
    ///
    /// Replaces any provider already attached: two replacement layers never
    /// compose.
    ///
    /// # Errors
    ///
    /// Returns [`ExceptionScopeError`] when `exceptions` is scoped to a
    /// different [`CalendarSource`] than this calendar represents.
    pub fn with_session_exceptions(
        self,
        exceptions: &'a dyn SessionExceptionSource,
    ) -> Result<Self, ExceptionScopeError> {
        let provider = exceptions.source();
        if provider == self.calendar.source() {
            Ok(Self::new(self.calendar, self.policy, Some(exceptions)))
        } else {
            Err(ExceptionScopeError {
                calendar: self.calendar.source(),
                provider,
            })
        }
    }

    /// Returns what the attached provider knows about `trade_date`.
    ///
    /// Returns `None` when no provider is attached. This is the only way to
    /// tell an audited-and-normal date from one the provider never covered:
    /// runtime queries necessarily serve the normal week for both.
    #[must_use]
    pub fn session_exception_on(self, trade_date: NaiveDate) -> Option<DateException<'a>> {
        self.exceptions
            .map(|provider| provider.exception_on(trade_date))
    }

    /// Returns the underlying date-aware calendar.
    #[must_use]
    pub const fn calendar(self) -> ExchangeCalendar {
        self.calendar
    }

    /// Detaches the identity's built-in holiday table, keeping both overlays.
    ///
    /// See [`ExchangeCalendar::without_holidays`].
    #[must_use]
    pub const fn without_holidays(self) -> Self {
        Self::new(
            self.calendar.without_holidays(),
            self.policy,
            self.exceptions,
        )
    }

    /// Returns the **built-in** holiday row for venue-local `trade_date`.
    ///
    /// This reports the crate's own table only, never the composed answer: the
    /// caller's own layers are introspected through
    /// [`Self::session_exception_on`] and through the [`DayPolicy`] the caller
    /// already holds. See [`ExchangeCalendar::holiday_on`] for what `None`
    /// means.
    #[must_use]
    pub fn holiday_on(self, trade_date: NaiveDate) -> Option<Holiday> {
        self.calendar.holiday_on(trade_date)
    }

    /// Returns the **built-in** table's audited trade-date window, or `None`
    /// when this identity has no table.
    ///
    /// This is the crate's own coverage claim; a caller's exception provider
    /// publishes its own through
    /// [`SessionExceptionSource::coverage`].
    #[must_use]
    pub fn holiday_coverage(self) -> Option<HolidayCoverage> {
        self.calendar.holiday_coverage()
    }

    /// Returns the schedule identity represented by this calendar.
    #[must_use]
    pub const fn source(self) -> CalendarSource {
        self.calendar.source()
    }

    /// Returns the represented exchange, or `None` for a product-family calendar.
    #[must_use]
    pub const fn exchange(self) -> Option<Exchange> {
        self.calendar.exchange()
    }

    /// Returns the represented family key, or `None` for an exchange calendar.
    #[must_use]
    pub const fn market_hours_key(self) -> Option<MarketHoursKey> {
        self.calendar.market_hours_key()
    }

    /// Resolves the unmodified fixed profile in force at `instant`.
    #[must_use]
    pub fn hours_at(self, instant: DateTime<Utc>) -> MarketHours {
        self.calendar.hours_at(instant)
    }

    /// Returns the schedule's invariant IANA time zone.
    #[must_use]
    pub fn tz(self) -> Tz {
        self.calendar.tz()
    }

    /// Returns whether any effective regular or extended session is open.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_open(self, instant: DateTime<Utc>) -> Result<bool, CalendarQueryError> {
        self.is_open_with(instant, SessionKind::Both)
    }

    /// Returns whether the effective selected session kind is open.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_open_with(
        self,
        instant: DateTime<Utc>,
        kind: SessionKind,
    ) -> Result<bool, CalendarQueryError> {
        status::is_open_with(&self.context(), instant, kind)
    }

    /// Returns whether an effective regular session is open.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_open_regular(self, instant: DateTime<Utc>) -> Result<bool, CalendarQueryError> {
        self.is_open_with(instant, SessionKind::Regular)
    }

    /// Returns whether an effective extended session is open.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_open_extended(self, instant: DateTime<Utc>) -> Result<bool, CalendarQueryError> {
        self.is_open_with(instant, SessionKind::Extended)
    }

    /// Returns whether orders may be entered, amended or cancelled at `instant`.
    ///
    /// True during effective order-entry-only phases and during any effective
    /// tradeable session. A closed trade date removes the queue that feeds it;
    /// a replaced trade date serves only the order-entry blocks the caller
    /// supplied for it.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_accepting_orders(self, instant: DateTime<Utc>) -> Result<bool, CalendarQueryError> {
        status::is_accepting_orders(&self.context(), instant)
    }

    /// Returns whether `instant` falls in an effective order-entry-only phase.
    ///
    /// Mutually exclusive with [`Self::is_open`].
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_order_entry_only(self, instant: DateTime<Utc>) -> Result<bool, CalendarQueryError> {
        status::is_order_entry_only(&self.context(), instant)
    }

    /// Returns the containing or next effective session bounds.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    ///
    /// This scan does **not** return
    /// [`CalendarQueryError::SearchExhausted`]: exhausting its own 14-day horizon
    /// is reported as `Ok(None)`, because the horizon is the query's documented
    /// bound rather than a day it failed to establish. Only the period walks
    /// (`candle_end`, `candle_start` and `trade_date`) report `SearchExhausted`,
    /// where a close must be found for the answer to exist.
    pub fn session_bounds(
        self,
        instant: DateTime<Utc>,
    ) -> Result<Option<SessionWindow>, CalendarQueryError> {
        self.session_bounds_with(instant, SessionKind::Both)
    }

    /// Returns the containing or next effective bounds for `kind`.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    ///
    /// This scan does **not** return
    /// [`CalendarQueryError::SearchExhausted`]: exhausting its own 14-day horizon
    /// is reported as `Ok(None)`, because the horizon is the query's documented
    /// bound rather than a day it failed to establish. Only the period walks
    /// (`candle_end`, `candle_start` and `trade_date`) report `SearchExhausted`,
    /// where a close must be found for the answer to exist.
    pub fn session_bounds_with(
        self,
        instant: DateTime<Utc>,
        kind: SessionKind,
    ) -> Result<Option<SessionWindow>, CalendarQueryError> {
        sessions::session_bounds_with(&self.context(), instant, kind)
    }

    /// Returns the first effective regular/extended session after `instant`.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    ///
    /// This scan does **not** return
    /// [`CalendarQueryError::SearchExhausted`]: exhausting its own 14-day horizon
    /// is reported as `Ok(None)`, because the horizon is the query's documented
    /// bound rather than a day it failed to establish. Only the period walks
    /// (`candle_end`, `candle_start` and `trade_date`) report `SearchExhausted`,
    /// where a close must be found for the answer to exist.
    pub fn next_session_after(
        self,
        instant: DateTime<Utc>,
    ) -> Result<Option<SessionWindow>, CalendarQueryError> {
        self.next_session_after_with(instant, SessionKind::Both)
    }

    /// Returns the first effective session of `kind` after `instant`.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    ///
    /// This scan does **not** return
    /// [`CalendarQueryError::SearchExhausted`]: exhausting its own 14-day horizon
    /// is reported as `Ok(None)`, because the horizon is the query's documented
    /// bound rather than a day it failed to establish. Only the period walks
    /// (`candle_end`, `candle_start` and `trade_date`) report `SearchExhausted`,
    /// where a close must be found for the answer to exist.
    pub fn next_session_after_with(
        self,
        instant: DateTime<Utc>,
        kind: SessionKind,
    ) -> Result<Option<SessionWindow>, CalendarQueryError> {
        sessions::next_session_after_with(&self.context(), instant, kind)
    }

    /// Returns only the next effective regular-or-extended session open.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn next_session_open_after(
        self,
        instant: DateTime<Utc>,
    ) -> Result<Option<DateTime<Utc>>, CalendarQueryError> {
        Ok(self.next_session_after(instant)?.map(|(open, _close)| open))
    }

    /// Returns whether `instant` is in a documented short maintenance gap.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_maintenance(self, instant: DateTime<Utc>) -> Result<bool, CalendarQueryError> {
        status::is_maintenance(&self.context(), instant)
    }

    /// Returns the effective policy-aware state at `instant`.
    ///
    /// Maintenance normally separates trade dates within the four-hour bound;
    /// a continuously traded-week profile can retain an operator-designated
    /// short maintenance gap inside one trade date.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn session_state(self, instant: DateTime<Utc>) -> Result<SessionState, CalendarQueryError> {
        status::session_state(&self.context(), instant)
    }

    /// Returns the effective local trade date containing `instant`.
    ///
    /// An identified following-business-day schedule skips policy-closed dates;
    /// CME cryptocurrency weekend trading therefore returns Tuesday when its
    /// usual Monday trade date is closed.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn trade_date(
        self,
        instant: DateTime<Utc>,
    ) -> Result<Option<NaiveDate>, CalendarQueryError> {
        status::trade_date(&self.context(), instant)
    }

    /// Returns whether no effective session of `kind` is assigned to `day`.
    ///
    /// Profiles without a trade-date concept return `true` because no session
    /// can be assigned to the requested trade date. Use the civil-day queries
    /// when asking whether trading intersects a calendar date instead.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_closed_trade_date(
        self,
        day: NaiveDate,
        kind: SessionKind,
    ) -> Result<bool, CalendarQueryError> {
        status::is_closed_trade_date(&self.context(), day, kind)
    }

    /// Returns whether no effective session intersects `day` in `calendar_tz`.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_closed_all_day_in_calendar(
        self,
        day: NaiveDate,
        calendar_tz: Tz,
        kind: SessionKind,
    ) -> Result<bool, CalendarQueryError> {
        status::is_closed_all_day_in_calendar(&self.context(), day, calendar_tz, kind)
    }

    /// Returns whether no effective session intersects venue-local `day`.
    ///
    /// This remains a calendar-date overlap query. Closing Monday's trade date
    /// does not make Monday wholly closed when Tuesday's session opens Monday
    /// evening; use [`Self::is_closed_trade_date`] for that question.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_closed_all_day_on(
        self,
        day: NaiveDate,
        kind: SessionKind,
    ) -> Result<bool, CalendarQueryError> {
        self.is_closed_all_day_in_calendar(day, self.tz(), kind)
    }

    /// Returns whether no effective session intersects the selected calendar day.
    ///
    /// # Errors
    ///
    /// Returns [`CalendarQueryError::BeforeSupportFloor`] when the venue-local
    /// day this query is addressed to precedes
    /// [`SUPPORT_FLOOR`](crate::SUPPORT_FLOOR),
    /// [`CalendarQueryError::OutsideCoveredRange`] when the identity has no
    /// sourced answer for a day the query depends on,
    /// [`CalendarQueryError::UnresolvedGap`] when that day is one the identity
    /// withholds as `Unsourced`, and
    /// [`CalendarQueryError::SearchExhausted`] when a bounded forward search
    /// runs out of window on a day it cannot establish. An error is never
    /// reported as `false`, `None`, or a default schedule (LAW-COVERAGE).
    pub fn is_closed_all_day_at(
        self,
        instant: DateTime<Utc>,
        calendar_tz: Tz,
        kind: SessionKind,
    ) -> Result<bool, CalendarQueryError> {
        status::is_closed_all_day_at(&self.context(), instant, calendar_tz, kind)
    }
}

impl ExchangeCalendar {
    /// Applies caller-supplied trade-date boundary overrides to every query.
    #[must_use]
    pub const fn with_day_policy(self, policy: &dyn DayPolicy) -> PolicyCalendar<'_> {
        PolicyCalendar::new(self, Some(policy), None)
    }

    /// Applies a caller-supplied replacement-session provider to every query.
    ///
    /// The provider replaces whole trade dates with complete ordered block
    /// sets, which scalar [`DayPolicy`] boundaries cannot express. Attach a
    /// policy as well with
    /// [`PolicyCalendar::with_day_policy`](PolicyCalendar::with_day_policy);
    /// the policy then overlays the replacement exactly as it overlays a
    /// normal week.
    ///
    /// # Errors
    ///
    /// Returns [`ExceptionScopeError`] when `exceptions` is scoped to a
    /// different [`CalendarSource`] than this calendar represents. One venue's
    /// holiday topology is never evidence about another's, so the mismatch is
    /// refused rather than applied.
    pub fn with_session_exceptions(
        self,
        exceptions: &dyn SessionExceptionSource,
    ) -> Result<PolicyCalendar<'_>, ExceptionScopeError> {
        let provider = exceptions.source();
        if provider == self.source() {
            Ok(PolicyCalendar::new(self, None, Some(exceptions)))
        } else {
            Err(ExceptionScopeError {
                calendar: self.source(),
                provider,
            })
        }
    }
}