exchange_hours/calendar/exceptions.rs
1// SPDX-License-Identifier: MIT-0
2
3//! Caller-owned exception sessions: complete replacement trading days.
4//!
5//! [`DayPolicy`](super::DayPolicy) clips a normal-week trading day's outer
6//! boundaries. Some published special days cannot be reduced to those scalars:
7//! a trade date that pauses and reopens, one whose regular session ends while
8//! extended trading continues, or one whose blocks span several civil dates.
9//! This layer replaces such a trade date outright with an ordered set of
10//! [`ExceptionBlock`] values.
11//!
12//! The crate ships **no** exception data. A caller supplies a
13//! [`SessionExceptionSource`] — usually the validated, allocation-free
14//! [`StaticSessionExceptions`] table — and attaches it with
15//! [`ExchangeCalendar::with_session_exceptions`](super::ExchangeCalendar::with_session_exceptions).
16//!
17//! Four states are distinguished per venue-local trade date, so a date outside
18//! the audited window can never be mistaken for one audited and found normal:
19//! [`DateException::KnownNormal`], [`DateException::Closed`],
20//! [`DateException::ReplaceSessions`], and [`DateException::OutOfCoverage`].
21//!
22//! Precedence is fixed: the exception layer resolves the trading day, then the
23//! caller's [`DayPolicy`](super::DayPolicy) overlays it exactly as it overlays
24//! a normal week. Two replacement layers never compose — attaching a provider
25//! replaces any provider already attached.
26
27mod static_table;
28mod validation;
29
30pub use static_table::{
31 SessionExceptionRecord, StaticSessionExceptions, StaticSessionExceptionsError,
32};
33
34pub(crate) use validation::{BlockViolation, first_block_violation};
35
36use chrono::NaiveDate;
37
38use super::exchange_calendar::CalendarSource;
39
40/// Which of a profile's rule sets a replacement block belongs to.
41///
42/// The three variants mirror [`MarketHours`](super::MarketHours)'s `regular`,
43/// `extended`, and `order_entry` sets, so a replaced trade date can restate a
44/// complete trading day rather than only its tradeable part.
45#[non_exhaustive]
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47pub enum ExceptionBlockKind {
48 /// A primary/RTH session; a trade can print.
49 Regular,
50 /// An electronic, overnight, or auction session; a trade can print.
51 Extended,
52 /// An order-entry-only phase in which no trade can match.
53 OrderEntry,
54}
55
56/// One block of a replacement trading day.
57///
58/// A block is stated exactly like a [`SessionRule`](super::SessionRule): venue-
59/// local seconds since midnight, end-exclusive close, and `open_ssm >=
60/// close_ssm` meaning the block wraps into the next local day. Opens resolve to
61/// the earliest valid instant across a DST fold and closes to the latest, the
62/// same asymmetric bias normal profiles use.
63///
64/// `open_day_offset` places the block's **opening** local day relative to the
65/// trade date the record is keyed by, so a Globex-style day that opens the
66/// previous evening uses `-1`. Like a `SessionRule`, one block spans at most
67/// one local midnight; continuous trading across more days is stated as
68/// adjacent blocks, and whether those read back as one session follows the
69/// calendar identity's normal adjacency convention.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub struct ExceptionBlock {
72 kind: ExceptionBlockKind,
73 open_day_offset: i8,
74 open_ssm: u32,
75 close_ssm: u32,
76}
77
78impl ExceptionBlock {
79 /// The earliest opening day a block may declare, relative to its trade date.
80 ///
81 /// Seven days back covers every published arrangement this crate has seen,
82 /// including a weekend block carried to the following open business date,
83 /// and bounds the engine's per-day replacement scan.
84 pub const MIN_DAY_OFFSET: i8 = -7;
85
86 /// The latest opening day a block may declare, relative to its trade date.
87 ///
88 /// A trade date is named by the local date of its final close, so no block
89 /// opens after it.
90 pub const MAX_DAY_OFFSET: i8 = 0;
91
92 /// Builds a tradeable regular block.
93 #[must_use]
94 pub const fn regular(open_day_offset: i8, open_ssm: u32, close_ssm: u32) -> Self {
95 Self {
96 kind: ExceptionBlockKind::Regular,
97 open_day_offset,
98 open_ssm,
99 close_ssm,
100 }
101 }
102
103 /// Builds a tradeable extended block.
104 #[must_use]
105 pub const fn extended(open_day_offset: i8, open_ssm: u32, close_ssm: u32) -> Self {
106 Self {
107 kind: ExceptionBlockKind::Extended,
108 open_day_offset,
109 open_ssm,
110 close_ssm,
111 }
112 }
113
114 /// Builds an order-entry-only block in which no trade can match.
115 #[must_use]
116 pub const fn order_entry(open_day_offset: i8, open_ssm: u32, close_ssm: u32) -> Self {
117 Self {
118 kind: ExceptionBlockKind::OrderEntry,
119 open_day_offset,
120 open_ssm,
121 close_ssm,
122 }
123 }
124
125 /// Returns which rule set this block belongs to.
126 #[must_use]
127 pub const fn kind(self) -> ExceptionBlockKind {
128 self.kind
129 }
130
131 /// Returns the opening local day relative to the record's trade date.
132 #[must_use]
133 pub const fn open_day_offset(self) -> i8 {
134 self.open_day_offset
135 }
136
137 /// Returns the open time in venue-local seconds since midnight.
138 #[must_use]
139 pub const fn open_ssm(self) -> u32 {
140 self.open_ssm
141 }
142
143 /// Returns the end-exclusive close in venue-local seconds since midnight.
144 #[must_use]
145 pub const fn close_ssm(self) -> u32 {
146 self.close_ssm
147 }
148
149 /// Returns whether this block closes on the local day after it opens.
150 ///
151 /// Equal endpoints wrap, matching [`SessionRule`](super::SessionRule): they
152 /// encode one complete local-day span rather than an empty interval.
153 #[must_use]
154 pub const fn wraps_to_next_day(self) -> bool {
155 self.open_ssm >= self.close_ssm
156 }
157}
158
159/// What a provider knows about one venue-local trade date.
160///
161/// The [`Self::OutOfCoverage`] state exists so a date the provider never
162/// audited cannot silently read as an ordinary weekday. Runtime queries treat
163/// it exactly like [`Self::KnownNormal`] — there is nothing else a
164/// deterministic engine can do with an unknown date — so a caller that must not
165/// trade on unaudited dates has to check
166/// [`PolicyCalendar::session_exception_on`](super::PolicyCalendar::session_exception_on)
167/// or the provider's own coverage window itself.
168#[non_exhaustive]
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum DateException<'a> {
171 /// The date was audited and carries no exception; the normal week applies.
172 KnownNormal,
173 /// No session belongs to this trade date.
174 Closed,
175 /// The complete ordered set of blocks that replaces this trade date.
176 ///
177 /// The slice is ordered by opening day and then by open time, and it is
178 /// never empty: a trade date with no blocks is [`Self::Closed`].
179 ///
180 /// The order is **non-decreasing**, not strictly increasing. Two blocks may
181 /// state the same opening instant when they belong to different kinds — an
182 /// order-entry phase and a tradeable session that both begin at the same
183 /// wall clock, for instance — so a repeated `(open_day_offset, open_ssm)`
184 /// pair is a valid arrangement rather than a duplicate to reject. Blocks
185 /// that agree on both are distinguished by their kind, and every scan
186 /// selects by kind first.
187 ///
188 /// **A record replaces every normal-week occurrence its blocks meet, not
189 /// only the ones belonging to its own trade date.** A block keyed to the
190 /// evening its trade date begins states an opening at a wall clock the
191 /// *following* trade date's ordinary occurrence also opens at, and the block
192 /// governs that instant: a query there answers from the block and reports
193 /// the record's trade date, which is what keeps the session reported and the
194 /// trade date reported the same session. A block set that covers the trading
195 /// day it replaces — which is what "complete" means here — meets no other
196 /// occurrence in the first place.
197 ///
198 /// **A fragment is reported as a closure.** Because the met occurrence is
199 /// not reported at all, a set that covers *part* of the normal week it meets
200 /// makes the rest of that occurrence read as closed: with a two-hour block
201 /// opening at the venue's evening boundary, `is_open` turns false for the
202 /// remaining hours of a session the record never mentions and `trade_date`
203 /// returns `None` across them. State the complete trading day, as an
204 /// operator publishes it, rather than a fragment of one.
205 ReplaceSessions(&'a [ExceptionBlock]),
206 /// The provider has no authoritative answer for this date.
207 OutOfCoverage,
208}
209
210/// The inclusive venue-local trade-date window a provider claims to have audited.
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
212pub struct ExceptionCoverage {
213 first: NaiveDate,
214 last: NaiveDate,
215}
216
217impl ExceptionCoverage {
218 /// Builds a coverage window, or `None` when `last` precedes `first`.
219 #[must_use]
220 pub fn new(first: NaiveDate, last: NaiveDate) -> Option<Self> {
221 (first <= last).then_some(Self { first, last })
222 }
223
224 /// Returns the first audited trade date.
225 #[must_use]
226 pub const fn first(self) -> NaiveDate {
227 self.first
228 }
229
230 /// Returns the last audited trade date.
231 #[must_use]
232 pub const fn last(self) -> NaiveDate {
233 self.last
234 }
235
236 /// Returns whether `trade_date` falls inside the audited window.
237 #[must_use]
238 pub fn contains(self, trade_date: NaiveDate) -> bool {
239 self.first <= trade_date && trade_date <= self.last
240 }
241}
242
243/// A caller-owned provider of replacement trading days.
244///
245/// Implementations must be deterministic and perform no I/O or clock reads.
246/// Callers with hard-coded records should use [`StaticSessionExceptions`]
247/// rather than implementing this trait themselves.
248///
249/// A provider is scoped to exactly one [`CalendarSource`]: attaching it to a
250/// calendar with a different identity is rejected, because one venue's holiday
251/// topology is never evidence about another's.
252pub trait SessionExceptionSource: Send + Sync {
253 /// Returns the single schedule identity these records describe.
254 fn source(&self) -> CalendarSource;
255
256 /// Returns the audited trade-date window, or `None` when nothing is audited.
257 ///
258 /// Every date outside this window must return
259 /// [`DateException::OutOfCoverage`] from [`Self::exception_on`].
260 fn coverage(&self) -> Option<ExceptionCoverage>;
261
262 /// Returns what this provider knows about `trade_date`.
263 ///
264 /// Dates inside [`Self::coverage`] with no recorded exception return
265 /// [`DateException::KnownNormal`].
266 fn exception_on(&self, trade_date: NaiveDate) -> DateException<'_>;
267
268 /// Returns whether this provider holds any record keyed inside the
269 /// inclusive window `first..=last`.
270 ///
271 /// This is the coverage question the query engine's gate asks before it
272 /// derives a trading day: the provider can only change an occurrence's
273 /// answer by holding a record for a trade date that occurrence could be
274 /// assigned to, so a provider answering `false` for the whole window lets
275 /// the query finish at the bare calendar's cost — exactly as if no
276 /// provider were attached. The default answer is `true` — *possibly*,
277 /// which keeps the derivation — so an implementation that does not track
278 /// its own records behaves exactly as it did before this method existed,
279 /// and every existing implementation stays source-compatible.
280 ///
281 /// Returning `false` for a window that in fact holds a record is a
282 /// soundness bug in the implementation, not a tunable: the engine will
283 /// skip the derivation and serve the unmodified normal week for an
284 /// occurrence the record should have moved. [`StaticSessionExceptions`]
285 /// answers from one binary search over its validated, sorted records, so
286 /// an empty record set — a provider that audited a window and found it
287 /// normal — answers `false` for every window. That is what makes an
288 /// audited-normal provider a true no-op (issue #127): a coverage window
289 /// states where records may lie, and a window alone can never change an
290 /// answer.
291 fn may_affect(&self, first: NaiveDate, last: NaiveDate) -> bool {
292 let _ = (first, last);
293 true
294 }
295}
296
297/// A [`SessionExceptionSource`] attached to a calendar with another identity.
298///
299/// Returned by
300/// [`ExchangeCalendar::with_session_exceptions`](super::ExchangeCalendar::with_session_exceptions)
301/// instead of letting one schedule's exception data drive another's answers.
302#[non_exhaustive]
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
304pub struct ExceptionScopeError {
305 /// The identity the calendar represents.
306 pub calendar: CalendarSource,
307 /// The identity the rejected provider is scoped to.
308 pub provider: CalendarSource,
309}
310
311impl core::fmt::Display for ExceptionScopeError {
312 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
313 write!(
314 f,
315 "session-exception provider is scoped to {:?}, not to this calendar's {:?}",
316 self.provider, self.calendar
317 )
318 }
319}
320
321impl std::error::Error for ExceptionScopeError {}