exchange-hours 1.2.2

Exchange trading hours, session boundaries, and calendar-aware bar boundaries. UTC in, UTC out.
Documentation
// SPDX-License-Identifier: MIT-0

//! Exchange trading hours, session boundaries, and calendar-aware bar boundaries.
//!
//! `exchange-hours` answers three questions about a `chrono::DateTime<Utc>`
//! instant: is this venue or product family open, what are the bounds of the
//! containing (or next) trading session, and where does a bar of a given
//! [`CalendarResolution`] start and end without spanning a closed period. It
//! holds no runtime state, performs no I/O, and never returns a local time — a
//! schedule's own zone is used only internally, to interpret session rules and
//! resolve DST deterministically.
//!
//! # Quick start
//!
//! CME equity-index futures match 17:00→16:00 CT and accept weekday orders from
//! 16:45; RTH runs 08:30–15:15 CT:
//!
//! ```
//! use chrono::{TimeZone, Utc};
//! use chrono_tz::US;
//! use exchange_hours::{
//!     CalendarResolution, Exchange, candle_end, hours_for_exchange, next_session_after,
//!     session_bounds,
//! };
//!
//! let ct = |y, m, d, hh, mm| {
//!     US::Central
//!         .with_ymd_and_hms(y, m, d, hh, mm, 0)
//!         .single()
//!         .expect("valid CT instant")
//!         .with_timezone(&Utc)
//! };
//!
//! // Every snapshot request carries the caller's instant: the crate never
//! // reads a clock, so a backtest and a live query run identical code. A
//! // live caller passes their own `Utc::now()` at the application edge.
//! let hours = hours_for_exchange(Exchange::Cme, ct(2026, 8, 24, 10, 0));
//!
//! // Monday mid-morning sits inside the regular session. Boundary queries
//! // return `Option`: `None` means no matching session exists in the bounded
//! // search horizon (for example, on a pre-go-live date).
//! let monday_10am = ct(2026, 8, 24, 10, 0);
//! assert!(hours.is_open_regular(monday_10am));
//! let (open, close) = session_bounds(&hours, monday_10am).expect("CME trades this week");
//! assert_eq!(open, ct(2026, 8, 24, 8, 30));
//! assert_eq!(close, ct(2026, 8, 24, 15, 15)); // end-exclusive
//!
//! // 16:30 CT is the daily maintenance break: closed, inside an inter-trade-date
//! // gap (16:00→16:45) no longer than the documented four-hour bound.
//! let monday_evening = ct(2026, 8, 24, 16, 30);
//! assert!(!hours.is_open(monday_evening));
//! assert!(hours.is_maintenance(monday_evening));
//!
//! // After Friday's close the next SESSION is Sunday's 17:00 matching open, not
//! // Saturday. Sunday's 16:00 Pre-Open accepts orders but matches nothing, so it
//! // is an order-entry phase rather than a session.
//! let friday_after_close = ct(2026, 8, 28, 16, 30);
//! let (next_open, _) = next_session_after(&hours, friday_after_close).expect("reopens Sunday");
//! assert_eq!(next_open, ct(2026, 8, 30, 17, 0));
//! assert!(hours.is_order_entry_only(ct(2026, 8, 30, 16, 0)));
//! assert!(!hours.is_open(ct(2026, 8, 30, 16, 0)));
//!
//! // Bar boundaries follow the same rules: a daily bar closes at the venue's
//! // session close, not at midnight.
//! let daily_close = candle_end(&hours, monday_10am, CalendarResolution::Daily);
//! assert_eq!(daily_close, Some(ct(2026, 8, 24, 16, 0)));
//! ```
//!
//! # Model
//!
//! A fixed venue snapshot is a [`MarketHours`] value: a time zone plus `regular`
//! `extended` and `order_entry` [`SessionRule`] sets, each rule a weekday mask
//! and an open/close pair in seconds since local midnight. `regular` and
//! `extended` are tradeable, so `is_open` means a trade can print; `order_entry`
//! holds pre-open queues and post-close order windows where nothing matches. [`ExchangeCalendar`] is the
//! date-aware surface for either an [`Exchange`] venue identity or a
//! [`MarketHoursKey`] product family; [`CalendarSource`] reports which identity
//! it carries. [`PolicyCalendar`] applies a caller's [`DayPolicy`] overrides to
//! the same query surface without changing the underlying profile;
//! [`StaticDayPolicy`] is the validated hard-coded record format for those
//! boundary-level overrides. A special day that scalar boundaries cannot state
//! — an intraday pause and reopen, a regular-only early close while extended
//! trading continues — is stated instead as an ordered [`ExceptionBlock`] set
//! replacing a whole trade date, either by a built-in holiday row
//! ([`HolidayKind::ReplacementBlocks`]) or through a caller's
//! [`SessionExceptionSource`]; [`StaticSessionExceptions`] is that provider's
//! validated table format.
//! Three conventions decide every answer —
//! weekdays are Monday = 0 through Sunday = 6; closes are **end-exclusive**, so
//! the instant equal to a close is closed and adjacent sessions never overlap;
//! and `open_ssm >= close_ssm` marks a session that **wraps** into the next local
//! day. Equal endpoints encode one complete local-day span, which supports
//! exact 24-hour sessions without making a venue always open.
//!
//! Ambiguous and skipped local times are resolved deterministically: opens take
//! the earliest valid mapping, closes the latest, and a wall-clock inside a
//! spring-forward gap snaps to the first representable instant after it.
//!
//! Built-in fixed status/boundary/candle queries and date-aware
//! status/boundary/trade-date/candle queries allocate nothing and inspect
//! bounded static rule sets. [`ExchangeCalendar`] is
//! `Copy + Send + Sync + 'static`; work performed inside a caller's
//! [`DayPolicy`] is outside that guarantee.
//!
//! # Scope
//!
//! Built-in profiles are **normal-week** templates; a holiday never bends one,
//! and holidays reach a calendar through the per-family tables described below
//! and through the caller's own layers. A caller can overlay sourced closed
//! trade dates, early final closes, and late first opens through
//! [`DayPolicy`], and complete replacement
//! trading days through [`SessionExceptionSource`]. Both layers ship with
//! **zero** built-in data: the crate provides the model, the validation, and
//! the engine, and the caller owns every record. Precedence is fixed — the
//! exception layer resolves the trading day, then the policy overlays it
//! exactly as it overlays a normal week, and two replacement layers never
//! compose.
//!
//! Per-family holiday tables sit underneath those two layers, as the innermost
//! one: [`ExchangeCalendar::holiday_on`] reports the built-in row for a trade
//! date, [`ExchangeCalendar::holiday_coverage`] reports the window a family was
//! audited over, and [`ExchangeCalendar::without_holidays`] detaches the table.
//! Tables ship for the served CME product families and the 2026 venue block;
//! an identity with no table answers `None` from both readers and is
//! unaffected by the layer. The `Holidays` column of the verification ledger is
//! the authority on which identities carry one and over which window.
//!
//! The coverage contract sits above all of those layers. [`SUPPORT_FLOOR`] is
//! the permanent floor, 1 January 2010 in the venue's own local-date domain;
//! [`ExchangeCalendar::coverage`] reports, for one identity, where its normal
//! week is sourced rather than carried, what its holiday layer asserts, and
//! which venue-local ranges it answers completely; and [`CalendarQueryError`]
//! is the vocabulary for the dates it does not. The metadata is **additive**:
//! no existing query signature changed with it, and an unsupported date is
//! still whatever that query returns today rather than an error.
//!
//! Product-level variations outside a profile remain out of scope. In
//! particular, this crate does not
//! map symbols, roots, product codes, or MICs to [`MarketHoursKey`] values; a
//! caller's instrument catalog must select the exact supported family.
//!
//! # Entry points
//!
//! - [`hours_for_exchange`] — venue → the fixed snapshot in effect at the
//!   caller's instant. This is the only venue selection path; there is no
//!   clock-less "current" selector, because the crate never reads a clock
//!   (the caller's instant *is* the clock).
//! - [`calendar_for_exchange`] — a date-aware calendar that reselects the
//!   applicable profile while scanning sessions and bar boundaries.
//! - [`session_profile`] / [`hours_for_market_hours_key`] — futures profiles
//!   addressed by [`MarketHoursKey`] (product family) rather than by venue;
//!   [`session_profile`] exposes the fixed-current static table and
//!   [`hours_for_market_hours_key`] selects the sourced snapshot at the
//!   caller's instant.
//! - [`calendar_for_market_hours_key`] — the same date-aware calendar surface
//!   for a product family. Use [`ExchangeCalendar::source`] to retain its exact
//!   [`CalendarSource`] identity. Identity-specific topology, including CME
//!   cryptocurrency's multi-day weekend bounds and following-business-day
//!   assignment, is available here; a detached fixed snapshot preserves exact
//!   open/closed state but not those coalesced bounds or trade dates.
//! - [`ExchangeCalendar::coverage`] — what an identity's calendar can answer:
//!   its sourced normal-week start, its holiday layer's contract, the
//!   venue-local ranges it covers completely, and the ranges it does not, each
//!   with a reason. For an identity that ships a table,
//!   [`ExchangeCalendar::without_holidays`] narrows it to the normal-week
//!   contract; the identities without one are unchanged. Paired with [`CalendarQueryError`], the four
//!   coverage error cases a caller must keep apart.
//! - [`ExchangeCalendar::with_day_policy`] — a borrowed [`PolicyCalendar`]
//!   overlay for caller-supplied closed days, early closes, and late opens.
//! - [`ExchangeCalendar::with_session_exceptions`] — the same overlay carrying
//!   a caller-supplied [`SessionExceptionSource`], which replaces whole trade
//!   dates. Attaching a provider scoped to another identity is refused with
//!   [`ExceptionScopeError`]; [`PolicyCalendar::session_exception_on`] reports
//!   the provider's [`DateException`] for a date, the only way to separate an
//!   audited-normal date from one outside the provider's coverage.
//! - [`ExchangeCalendar::trade_date`] and [`ExchangeCalendar::session_state`]
//!   — one containing-session trade date and one mutually exclusive
//!   [`SessionState`] classification per instant. An always-open profile has no
//!   final close, so its trade date is `None`.
//! - [`MarketHours::is_open`] and friends, [`session_bounds`],
//!   [`next_session_after`], [`candle_start`], [`candle_end`].

#![forbid(unsafe_code)]

mod calendar;

pub use calendar::*;