Skip to main content

exchange_hours/
lib.rs

1// SPDX-License-Identifier: MIT-0
2
3//! Exchange trading hours, session boundaries, and calendar-aware bar boundaries.
4//!
5//! `exchange-hours` answers three questions about a `chrono::DateTime<Utc>`
6//! instant: is this venue or product family open, what are the bounds of the
7//! containing (or next) trading session, and where does a bar of a given
8//! [`CalendarResolution`] start and end without spanning a closed period. It
9//! holds no runtime state, performs no I/O, and never returns a local time — a
10//! schedule's own zone is used only internally, to interpret session rules and
11//! resolve DST deterministically.
12//!
13//! # Quick start
14//!
15//! CME equity-index futures match 17:00→16:00 CT and accept weekday orders from
16//! 16:45; RTH runs 08:30–15:15 CT:
17//!
18//! ```
19//! use chrono::{TimeZone, Utc};
20//! use chrono_tz::US;
21//! use exchange_hours::{
22//!     CalendarResolution, Exchange, candle_end, hours_for_exchange, next_session_after,
23//!     session_bounds,
24//! };
25//!
26//! let ct = |y, m, d, hh, mm| {
27//!     US::Central
28//!         .with_ymd_and_hms(y, m, d, hh, mm, 0)
29//!         .single()
30//!         .expect("valid CT instant")
31//!         .with_timezone(&Utc)
32//! };
33//!
34//! // Every snapshot request carries the caller's instant: the crate never
35//! // reads a clock, so a backtest and a live query run identical code. A
36//! // live caller passes their own `Utc::now()` at the application edge.
37//! let hours = hours_for_exchange(Exchange::Cme, ct(2026, 8, 24, 10, 0));
38//!
39//! // Monday mid-morning sits inside the regular session. Boundary queries
40//! // return `Option`: `None` means no matching session exists in the bounded
41//! // search horizon (for example, on a pre-go-live date).
42//! let monday_10am = ct(2026, 8, 24, 10, 0);
43//! assert!(hours.is_open_regular(monday_10am));
44//! let (open, close) = session_bounds(&hours, monday_10am).expect("CME trades this week");
45//! assert_eq!(open, ct(2026, 8, 24, 8, 30));
46//! assert_eq!(close, ct(2026, 8, 24, 15, 15)); // end-exclusive
47//!
48//! // 16:30 CT is the daily maintenance break: closed, inside an inter-trade-date
49//! // gap (16:00→16:45) no longer than the documented four-hour bound.
50//! let monday_evening = ct(2026, 8, 24, 16, 30);
51//! assert!(!hours.is_open(monday_evening));
52//! assert!(hours.is_maintenance(monday_evening));
53//!
54//! // After Friday's close the next SESSION is Sunday's 17:00 matching open, not
55//! // Saturday. Sunday's 16:00 Pre-Open accepts orders but matches nothing, so it
56//! // is an order-entry phase rather than a session.
57//! let friday_after_close = ct(2026, 8, 28, 16, 30);
58//! let (next_open, _) = next_session_after(&hours, friday_after_close).expect("reopens Sunday");
59//! assert_eq!(next_open, ct(2026, 8, 30, 17, 0));
60//! assert!(hours.is_order_entry_only(ct(2026, 8, 30, 16, 0)));
61//! assert!(!hours.is_open(ct(2026, 8, 30, 16, 0)));
62//!
63//! // Bar boundaries follow the same rules: a daily bar closes at the venue's
64//! // session close, not at midnight.
65//! let daily_close = candle_end(&hours, monday_10am, CalendarResolution::Daily);
66//! assert_eq!(daily_close, Some(ct(2026, 8, 24, 16, 0)));
67//! ```
68//!
69//! # Model
70//!
71//! A fixed venue snapshot is a [`MarketHours`] value: a time zone plus `regular`
72//! `extended` and `order_entry` [`SessionRule`] sets, each rule a weekday mask
73//! and an open/close pair in seconds since local midnight. `regular` and
74//! `extended` are tradeable, so `is_open` means a trade can print; `order_entry`
75//! holds pre-open queues and post-close order windows where nothing matches. [`ExchangeCalendar`] is the
76//! date-aware surface for either an [`Exchange`] venue identity or a
77//! [`MarketHoursKey`] product family; [`CalendarSource`] reports which identity
78//! it carries. [`PolicyCalendar`] applies a caller's [`DayPolicy`] overrides to
79//! the same query surface without changing the underlying profile;
80//! [`StaticDayPolicy`] is the validated hard-coded record format for those
81//! boundary-level overrides. A special day that scalar boundaries cannot state
82//! — an intraday pause and reopen, a regular-only early close while extended
83//! trading continues — is stated instead as an ordered [`ExceptionBlock`] set
84//! replacing a whole trade date, either by a built-in holiday row
85//! ([`HolidayKind::ReplacementBlocks`]) or through a caller's
86//! [`SessionExceptionSource`]; [`StaticSessionExceptions`] is that provider's
87//! validated table format.
88//! Three conventions decide every answer —
89//! weekdays are Monday = 0 through Sunday = 6; closes are **end-exclusive**, so
90//! the instant equal to a close is closed and adjacent sessions never overlap;
91//! and `open_ssm >= close_ssm` marks a session that **wraps** into the next local
92//! day. Equal endpoints encode one complete local-day span, which supports
93//! exact 24-hour sessions without making a venue always open.
94//!
95//! Ambiguous and skipped local times are resolved deterministically: opens take
96//! the earliest valid mapping, closes the latest, and a wall-clock inside a
97//! spring-forward gap snaps to the first representable instant after it.
98//!
99//! Built-in fixed status/boundary/candle queries and date-aware
100//! status/boundary/trade-date/candle queries allocate nothing and inspect
101//! bounded static rule sets. [`ExchangeCalendar`] is
102//! `Copy + Send + Sync + 'static`; work performed inside a caller's
103//! [`DayPolicy`] is outside that guarantee.
104//!
105//! # Scope
106//!
107//! Built-in profiles are **normal-week** templates; a holiday never bends one,
108//! and holidays reach a calendar through the per-family tables described below
109//! and through the caller's own layers. A caller can overlay sourced closed
110//! trade dates, early final closes, and late first opens through
111//! [`DayPolicy`], and complete replacement
112//! trading days through [`SessionExceptionSource`]. Both layers ship with
113//! **zero** built-in data: the crate provides the model, the validation, and
114//! the engine, and the caller owns every record. Precedence is fixed — the
115//! exception layer resolves the trading day, then the policy overlays it
116//! exactly as it overlays a normal week, and two replacement layers never
117//! compose.
118//!
119//! Per-family holiday tables sit underneath those two layers, as the innermost
120//! one: [`ExchangeCalendar::holiday_on`] reports the built-in row for a trade
121//! date, [`ExchangeCalendar::holiday_coverage`] reports the window a family was
122//! audited over, and [`ExchangeCalendar::without_holidays`] detaches the table.
123//! Tables ship for the served CME product families and the 2026 venue block;
124//! an identity with no table answers `None` from both readers and is
125//! unaffected by the layer. The `Holidays` column of the verification ledger is
126//! the authority on which identities carry one and over which window.
127//!
128//! The coverage contract sits above all of those layers. [`SUPPORT_FLOOR`] is
129//! the permanent floor, 1 January 2010 in the venue's own local-date domain;
130//! [`ExchangeCalendar::coverage`] reports, for one identity, where its normal
131//! week is sourced rather than carried, what its holiday layer asserts, and
132//! which venue-local ranges it answers completely; and [`CalendarQueryError`]
133//! is the vocabulary for the dates it does not. The metadata is **additive**:
134//! no existing query signature changed with it, and an unsupported date is
135//! still whatever that query returns today rather than an error.
136//!
137//! Product-level variations outside a profile remain out of scope. In
138//! particular, this crate does not
139//! map symbols, roots, product codes, or MICs to [`MarketHoursKey`] values; a
140//! caller's instrument catalog must select the exact supported family.
141//!
142//! # Entry points
143//!
144//! - [`hours_for_exchange`] — venue → the fixed snapshot in effect at the
145//!   caller's instant. This is the only venue selection path; there is no
146//!   clock-less "current" selector, because the crate never reads a clock
147//!   (the caller's instant *is* the clock).
148//! - [`calendar_for_exchange`] — a date-aware calendar that reselects the
149//!   applicable profile while scanning sessions and bar boundaries.
150//! - [`session_profile`] / [`hours_for_market_hours_key`] — futures profiles
151//!   addressed by [`MarketHoursKey`] (product family) rather than by venue;
152//!   [`session_profile`] exposes the fixed-current static table and
153//!   [`hours_for_market_hours_key`] selects the sourced snapshot at the
154//!   caller's instant.
155//! - [`calendar_for_market_hours_key`] — the same date-aware calendar surface
156//!   for a product family. Use [`ExchangeCalendar::source`] to retain its exact
157//!   [`CalendarSource`] identity. Identity-specific topology, including CME
158//!   cryptocurrency's multi-day weekend bounds and following-business-day
159//!   assignment, is available here; a detached fixed snapshot preserves exact
160//!   open/closed state but not those coalesced bounds or trade dates.
161//! - [`ExchangeCalendar::coverage`] — what an identity's calendar can answer:
162//!   its sourced normal-week start, its holiday layer's contract, the
163//!   venue-local ranges it covers completely, and the ranges it does not, each
164//!   with a reason. For an identity that ships a table,
165//!   [`ExchangeCalendar::without_holidays`] narrows it to the normal-week
166//!   contract; the identities without one are unchanged. Paired with [`CalendarQueryError`], the four
167//!   coverage error cases a caller must keep apart.
168//! - [`ExchangeCalendar::with_day_policy`] — a borrowed [`PolicyCalendar`]
169//!   overlay for caller-supplied closed days, early closes, and late opens.
170//! - [`ExchangeCalendar::with_session_exceptions`] — the same overlay carrying
171//!   a caller-supplied [`SessionExceptionSource`], which replaces whole trade
172//!   dates. Attaching a provider scoped to another identity is refused with
173//!   [`ExceptionScopeError`]; [`PolicyCalendar::session_exception_on`] reports
174//!   the provider's [`DateException`] for a date, the only way to separate an
175//!   audited-normal date from one outside the provider's coverage.
176//! - [`ExchangeCalendar::trade_date`] and [`ExchangeCalendar::session_state`]
177//!   — one containing-session trade date and one mutually exclusive
178//!   [`SessionState`] classification per instant. An always-open profile has no
179//!   final close, so its trade date is `None`.
180//! - [`MarketHours::is_open`] and friends, [`session_bounds`],
181//!   [`next_session_after`], [`candle_start`], [`candle_end`].
182
183#![forbid(unsafe_code)]
184
185mod calendar;
186
187pub use calendar::*;