Skip to main content

Crate exchange_hours

Crate exchange_hours 

Source
Expand description

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

Structs§

CalendarCoverage
What one identity’s calendar can answer, as of the shipped data.
CompleteRanges
Ascending iterator over the spans an identity answers completely.
CoverageGap
One span inside the supported domain this identity cannot answer completely.
CoverageGaps
Ascending iterator over the spans an identity cannot answer completely, each with its reason.
DateRange
One inclusive, ascending venue-local date span.
DayOverride
One caller-supplied override for a venue-local trade date.
ExceptionBlock
One block of a replacement trading day.
ExceptionCoverage
The inclusive venue-local trade-date window a provider claims to have audited.
ExceptionScopeError
A SessionExceptionSource attached to a calendar with another identity.
ExchangeCalendar
A deterministic, date-aware calendar for one exchange or product family.
FuturesSessionProfile
A timezone-aware set of normal-week futures session rules.
Holiday
One built-in holiday row, as reported to a caller.
HolidayCoverage
The venue-local trade-date windows a built-in table audited.
MarketHours
Normal-week trading-hours definition.
NoPolicy
A policy that leaves every normal-week session unchanged.
NormalWeekBaseline
The sourced normal-week baseline one coverage refusal sits inside.
ParseExchangeError
The error Exchange’s FromStr returns for a string that is not a canonical venue name.
ParseMarketHoursKeyError
The error MarketHoursKey’s FromStr implementation returns for an unknown name.
PhaseGap
A completeness gap one identity declares about itself: a known internal gap that no date walk over the identity’s tables can find.
PolicyCalendar
A date-aware calendar with the caller’s own day overlays applied.
SessionExceptionRecord
One caller-supplied record for a venue-local trade date.
SessionRule
One schedule slice for a market session.
StaticDayPolicy
An allocation-free DayPolicy over caller-owned, sorted records.
StaticSessionExceptions
An allocation-free SessionExceptionSource over caller-owned records.

Enums§

CalendarQueryError
Why an identity-backed date-aware query cannot answer.
CalendarResolution
Bar resolution / time interval for candle-boundary computations.
CalendarSource
Identifies the schedule selected by an ExchangeCalendar.
CoverageGapReason
Why a span inside the supported domain is not complete.
DateCoverage
The coverage verdict for one venue-local date.
DateException
What a provider knows about one venue-local trade date.
EvidenceTier
The evidence tier behind one recorded fact (LAW-PRIMARY-SOURCES).
ExceptionBlockKind
Which of a profile’s rule sets a replacement block belongs to.
Exchange
Identifies an exchange or trading venue.
HolidayContract
What the built-in holiday layer asserts for one calendar.
HolidayKind
What a built-in table records about one venue-local trade date.
MarketHoursKey
Names a normal-week product-family market-hours profile.
PhaseGapShape
The dates one declared gap applies to, within its own span.
SessionKind
Selects which session set a query consults.
SessionRuleError
A SessionRule domain-invariant violation, reported by SessionRule::new and SessionRule::validate.
SessionState
The effective state of a schedule at one UTC instant.
StaticDayPolicyError
A StaticDayPolicy record-set invariant violation.
StaticSessionExceptionsError
A StaticSessionExceptions record-set invariant violation.

Constants§

SUPPORT_FLOOR
The permanent support floor, 1 January 2010 in the venue’s own local-date domain (LAW-COVERAGE; the 2026-09-27 amendment moved it back from 2025-01-01).

Traits§

DayPolicy
Day-level schedule overrides supplied by a caller.
SessionExceptionSource
A caller-owned provider of replacement trading days.

Functions§

calendar_for_exchange
Creates a date-aware calendar for exchange.
calendar_for_market_hours_key
Creates a date-aware calendar for a product-family key.
candle_end
Returns candle_end_with over regular and extended sessions.
candle_end_with
Returns the session-aware bar close after instant for resolution and kind, or None when no advancing bar exists.
candle_start
Returns candle_start_with over regular and extended sessions.
candle_start_with
Returns the bar open paired with candle_end_with for kind.
hours_for_all
Builds the MarketHours in effect at as_of for each exchange, preserving input order.
hours_for_apac_equities
Builds the MarketHours in effect at as_of for the built-in Asia-Pacific equities set.
hours_for_eu_equities
Builds the MarketHours in effect at as_of for the built-in EU-equities set.
hours_for_exchange
Returns the fixed schedule snapshot in effect for exch at as_of.
hours_for_global_equities
Builds the MarketHours in effect at as_of for the major-global equities set.
hours_for_market_hours_key
Resolves the fixed MarketHours snapshot in effect for key at as_of.
hours_for_us_equities
Builds the MarketHours in effect at as_of for the built-in US-equities exchange set.
hours_map_apac_equities
Builds an Exchange-keyed map at as_of for the Asia-Pacific equities set.
hours_map_eu_equities
Builds an Exchange-keyed BTreeMap at as_of for the built-in EU-equities set.
hours_map_for
Builds a deterministic Exchange-keyed map of the MarketHours in effect at as_of.
hours_map_global_equities
Builds a fixed-snapshot map at as_of for the other major-global equities set.
hours_map_us_equities
Builds an Exchange-keyed BTreeMap at as_of for the built-in US-equities set.
next_session_after
Returns next_session_after_with over regular and extended sessions.
next_session_after_with
Returns the first session of kind opening strictly after instant.
next_session_open_after
Returns only the next regular-or-extended session open after instant.
session_bounds
Returns session_bounds_with over regular and extended sessions.
session_bounds_with
Returns the [open, close) UTC bounds of the session of kind containing instant, or the next session when instant is closed.
session_profile
Returns the fixed-current normal-week futures session profile for key.
time_end_of_day
Returns the next trading-day close after instant.