exchange_hours/calendar/rule.rs
1// SPDX-License-Identifier: MIT-0
2
3//! The atom of the calendar: one weekday-masked open/close slice.
4//!
5//! A [`SessionRule`] is stated in the **exchange's** local time as seconds since
6//! local midnight (SSM), never in UTC and never as a wall-clock string; the
7//! local→UTC mapping (including DST) happens at query time in
8//! [`super::local_time`]. [`SessionKind`] selects which of a profile's two rule
9//! sets a query consults.
10
11use serde::{Deserialize, Serialize};
12
13/// Seconds in a nominal 24-hour day, used for normal-week interval arithmetic
14/// only. Deliberately DST-free: the normal-week model counts scheduled seconds,
15/// not elapsed wall-clock seconds.
16pub(crate) const SECONDS_PER_NORMAL_DAY: u64 = 86_400;
17/// Seconds in a nominal seven-day week; the saturation ceiling for
18/// [`super::MarketHours::normal_week_open_seconds`].
19pub(crate) const SECONDS_PER_NORMAL_WEEK: u64 = 7 * SECONDS_PER_NORMAL_DAY;
20
21// Common weekday masks (Mon=0 .. Sun=6) used across presets.
22// Monday–Friday open days (no weekend trading)
23pub(crate) const MON_FRI: [bool; 7] = [true, true, true, true, true, false, false];
24// Monday only.
25pub(crate) const MON_ONLY: [bool; 7] = [true, false, false, false, false, false, false];
26// Monday-Thursday only.
27pub(crate) const MON_THU: [bool; 7] = [true, true, true, true, false, false, false];
28// Friday only.
29pub(crate) const FRI: [bool; 7] = [false, false, false, false, true, false, false];
30// Tuesday only.
31pub(crate) const TUE_ONLY: [bool; 7] = [false, true, false, false, false, false, false];
32// Tuesday-Friday only.
33pub(crate) const TUE_FRI: [bool; 7] = [false, true, true, true, true, false, false];
34// Sunday only.
35pub(crate) const SUN_ONLY: [bool; 7] = [false, false, false, false, false, false, true];
36// Open on Sunday and Mon–Thu (i.e., Sunday evening open, no Friday overnight open)
37pub(crate) const SUN_PLUS_MON_THU: [bool; 7] = [true, true, true, true, false, false, true];
38// Open on all seven weekdays.
39pub(crate) const ALL_DAYS: [bool; 7] = [true, true, true, true, true, true, true];
40
41/// One schedule slice for a market session.
42///
43/// - `days`: Monday=0 .. Sunday=6 mask; `true` enables the rule on that weekday.
44/// - `open_ssm` / `close_ssm`: seconds since local midnight in the exchange time zone.
45/// If `open_ssm < close_ssm` the session is same-day. If
46/// `open_ssm >= close_ssm`, it wraps into the next local day and closes at
47/// `close_ssm` there; equal endpoints therefore encode exactly one complete
48/// local-day span anchored on each enabled opening day.
49/// - Close comparisons are end-exclusive: an instant exactly equal to `close_ssm`
50/// is considered closed.
51///
52/// # Domain invariants
53///
54/// A well-formed rule has `open_ssm < 86_400`, `close_ssm <= 86_400` (the
55/// `86_400` sentinel closes a same-day session exactly at next local
56/// midnight), and at least one enabled weekday. [`SessionRule::new`] enforces
57/// all three; construction by struct literal or via `Deserialize` bypasses them,
58/// so validate untrusted input with [`SessionRule::validate`]. Queries stay
59/// total for out-of-domain values but their answers are unspecified — an
60/// out-of-range `open_ssm` silently degrades the rule.
61#[non_exhaustive]
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63pub struct SessionRule {
64 /// Weekday activation mask (Mon=0 .. Sun=6).
65 pub days: [bool; 7],
66 /// Open time in seconds since local midnight, in `0..86_400`.
67 pub open_ssm: u32,
68 /// Close time in seconds since local midnight, end-exclusive, in
69 /// `0..=86_400`.
70 pub close_ssm: u32,
71}
72
73impl SessionRule {
74 /// Builds a rule after checking the domain invariants listed on
75 /// [`SessionRule`].
76 ///
77 /// # Errors
78 ///
79 /// Returns the first violated invariant: an out-of-range `open_ssm` or
80 /// `close_ssm`, or an all-`false` weekday mask. Equal endpoints are valid
81 /// and represent one complete local-day span.
82 pub fn new(days: [bool; 7], open_ssm: u32, close_ssm: u32) -> Result<Self, SessionRuleError> {
83 let rule = Self {
84 days,
85 open_ssm,
86 close_ssm,
87 };
88 rule.validate()?;
89 Ok(rule)
90 }
91
92 /// Checks the domain invariants listed on [`SessionRule`] without
93 /// consuming the rule — the check for rules that arrived by struct
94 /// literal or `Deserialize` rather than through [`SessionRule::new`].
95 ///
96 /// # Errors
97 ///
98 /// Returns the first violated invariant; see [`SessionRule::new`].
99 pub fn validate(&self) -> Result<(), SessionRuleError> {
100 if self.open_ssm >= SECONDS_PER_NORMAL_DAY_U32 {
101 return Err(SessionRuleError::OpenOutOfRange {
102 open_ssm: self.open_ssm,
103 });
104 }
105 if self.close_ssm > SECONDS_PER_NORMAL_DAY_U32 {
106 return Err(SessionRuleError::CloseOutOfRange {
107 close_ssm: self.close_ssm,
108 });
109 }
110 if !self.days.iter().any(|&enabled| enabled) {
111 return Err(SessionRuleError::NoEnabledDays);
112 }
113 Ok(())
114 }
115
116 /// Returns whether this session closes on the next local day.
117 ///
118 /// Equal endpoints return `true`: they represent one complete local-day
119 /// span anchored on each enabled opening day, not an empty interval.
120 #[must_use]
121 pub const fn wraps_to_next_day(&self) -> bool {
122 self.open_ssm >= self.close_ssm
123 }
124}
125
126/// [`SECONDS_PER_NORMAL_DAY`] in the `u32` domain of [`SessionRule`] fields.
127const SECONDS_PER_NORMAL_DAY_U32: u32 = 86_400;
128// Compile-time tie to the u64 source so the two constants cannot drift.
129// Evaluated during constant evaluation only — this is not a runtime assert.
130const _: () = assert!(SECONDS_PER_NORMAL_DAY_U32 as u64 == SECONDS_PER_NORMAL_DAY);
131
132/// A [`SessionRule`] domain-invariant violation, reported by
133/// [`SessionRule::new`] and [`SessionRule::validate`].
134#[non_exhaustive]
135#[derive(Debug, Clone, Copy, PartialEq, Eq)]
136pub enum SessionRuleError {
137 /// `open_ssm` is not inside `0..86_400`.
138 OpenOutOfRange {
139 /// The rejected open value.
140 open_ssm: u32,
141 },
142 /// `close_ssm` is not inside `0..=86_400`.
143 CloseOutOfRange {
144 /// The rejected close value.
145 close_ssm: u32,
146 },
147 /// Every weekday is disabled, so the rule can never apply.
148 NoEnabledDays,
149}
150
151impl core::fmt::Display for SessionRuleError {
152 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
153 match self {
154 Self::OpenOutOfRange { open_ssm } => {
155 write!(f, "open_ssm {open_ssm} is outside 0..86400")
156 }
157 Self::CloseOutOfRange { close_ssm } => {
158 write!(f, "close_ssm {close_ssm} is outside 0..=86400")
159 }
160 Self::NoEnabledDays => write!(f, "no weekday is enabled"),
161 }
162 }
163}
164
165impl std::error::Error for SessionRuleError {}
166
167/// Selects which session set a query consults.
168///
169/// `MarketHours` keeps `regular` and `extended` rule sets separately; every
170/// open/closed and boundary query takes a `SessionKind` to choose between them.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
172pub enum SessionKind {
173 /// Consult only primary/RTH (`regular`) sessions.
174 Regular,
175 /// Consult only electronic/overnight/auction (`extended`) sessions.
176 Extended,
177 /// Consult regular and extended sessions together.
178 Both,
179}
180
181/// Projects one rule onto the `[0, SECONDS_PER_NORMAL_WEEK)` normal-week axis as
182/// half-open `(start, end)` second offsets, one per enabled weekday.
183///
184/// A wrap rule that runs past Sunday midnight is split into two intervals so the
185/// caller can union them without special-casing the week boundary. Holidays and
186/// DST are deliberately absent: this is the normal-week schedule, not elapsed
187/// time.
188pub(crate) fn normal_week_rule_intervals(rule: &SessionRule) -> Vec<(u64, u64)> {
189 let mut intervals = Vec::with_capacity(8);
190 for (weekday, enabled) in (0_u64..).zip(rule.days) {
191 if !enabled {
192 continue;
193 }
194 let start = weekday
195 .saturating_mul(SECONDS_PER_NORMAL_DAY)
196 .saturating_add(u64::from(rule.open_ssm));
197 let duration = if rule.wraps_to_next_day() {
198 SECONDS_PER_NORMAL_DAY
199 .saturating_sub(u64::from(rule.open_ssm))
200 .saturating_add(u64::from(rule.close_ssm))
201 } else {
202 u64::from(rule.close_ssm - rule.open_ssm)
203 };
204 let end = start.saturating_add(duration);
205 if end <= SECONDS_PER_NORMAL_WEEK {
206 intervals.push((start, end));
207 } else {
208 intervals.push((start, SECONDS_PER_NORMAL_WEEK));
209 intervals.push((0, end.saturating_sub(SECONDS_PER_NORMAL_WEEK)));
210 }
211 }
212 intervals
213}