exchange-hours 0.2.2

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

//! Point-in-time hours: the profile a venue actually published at an instant.
//!
//! Cutover dates are compared in the venue's **own** local zone, not UTC — a
//! rule change announced for "2016-03-04" took effect on that Chicago date, and
//! comparing in UTC would shift the boundary by hours. Only venues with a
//! recorded change appear here; everything else falls through to
//! [`hours_for_exchange`](super::hours_for_exchange), so this module is an
//! overlay, never a second venue table.
//!
//! **Known unsourced history.** MEMX and MIAX Pearl Equities extended their
//! early sessions to 04:00 ET in real, recent changes (MEMX per its own
//! insights posts; MIAX Pearl per alert 2024-11-13), but no primary source in
//! hand states a day-level effective date for either — so, on the same
//! no-fabricated-dates principle as the Blue Ocean beta exclusion, neither has
//! a cutover here and `hours_for_exchange_as_of` returns **current** hours for
//! those two venues at every `as_of`. Backtests before their rollouts will see
//! more pre-market than the venue actually ran. The match arm below marks
//! where the cutovers land once an effective date is sourced.

use std::borrow::Cow;

use chrono::{DateTime, NaiveDate, Utc};
use chrono_tz::{America, Europe, Tz, US};

use crate::calendar::profiles::{
    BLUE_OCEAN_PROFILE, C1_PROFILE_POST_2024_08_26, C1_PROFILE_PRE_2024_08_26,
    CBOT_PROFILE_POST2013, CBOT_PROFILE_PRE2013, CFE_PROFILE, CFE_PROFILE_PRE_2021_12_06,
    CFE_PROFILE_PRE2014, CME_PROFILE_POST2016, CME_PROFILE_PRE2016, EUREX_PROFILE_NO_ASIAN,
    EUREX_PROFILE_WITH_ASIAN, IEX_PROFILE_POST2015, IEX_PROFILE_PRE2015, NYSE_TEXAS_PROFILE,
    US_EQUITIES_PROFILE, US_EQUITY_EARLY_0700_PROFILE, from_profile,
};
use crate::calendar::{Exchange, MarketHours};

use super::hours_for_exchange;

/// Builds a cutover date at compile time. Used only to initialise the `const`
/// cutover items below: an invalid literal fails the build during constant
/// evaluation, so no panic path exists at runtime.
#[expect(
    clippy::panic,
    reason = "const-eval only: this arm is how an invalid date literal becomes a \
              build failure, and a `const` item cannot reach it at runtime"
)]
const fn cutover(year: i32, month: u32, day: u32) -> NaiveDate {
    match NaiveDate::from_ymd_opt(year, month, day) {
        Some(date) => date,
        None => panic!("invalid hard-coded cutover date"),
    }
}

/// True when `as_of`, read as a calendar date in the venue's **own** zone,
/// falls before `cutover`.
///
/// Every arm of [`hours_for_exchange_as_of`] compares dates this way: a rule
/// change announced for a date took effect on that *venue-local* date, so
/// comparing in UTC would shift the boundary by hours.
fn is_before(as_of: DateTime<Utc>, tz: Tz, cutover: NaiveDate) -> bool {
    as_of.with_timezone(&tz).date_naive() < cutover
}

/// A profile with no sessions at all: what a venue's hours were before it went
/// live. Every boundary query over these hours returns `None`, which is the
/// no-session contract rather than a zero-length trading day.
///
/// The rule sets borrow a static empty slice rather than owning an empty
/// `Vec`, matching how every other profile is built. Neither allocates; the
/// point is that one construction shape covers all of them.
fn no_sessions(exchange: Exchange, tz: Tz) -> MarketHours {
    MarketHours {
        exchange,
        tz,
        regular: Cow::Borrowed(&[]),
        extended: Cow::Borrowed(&[]),
        has_daily_close: true,
        has_weekend_close: true,
    }
}

/// Cboe Options (C1): GTH close extended 09:15 -> 09:25 ET.
const C1_GTH_CUTOVER: NaiveDate = cutover(2024, 8, 26);
/// CME equity index: short window close moved 16:15 -> 16:00 CT.
const CME_CUTOVER: NaiveDate = cutover(2016, 3, 4);
/// EUREX: Asian trading window added.
const EUREX_ASIAN_CUTOVER: NaiveDate = cutover(2018, 12, 10);
/// IEX: extended pre/post sessions introduced.
const IEX_EXTENDED_CUTOVER: NaiveDate = cutover(2015, 8, 21);
/// CFE: overnight ETH introduced.
const CFE_ETH_CUTOVER: NaiveDate = cutover(2014, 6, 1);
/// CFE: queuing period abolished, RTH close moved to 15:00 CT.
const CFE_QUEUING_CUTOVER: NaiveDate = cutover(2021, 12, 6);
/// NYSE Texas: go-live.
const NYSE_TEXAS_GO_LIVE: NaiveDate = cutover(2025, 3, 31);
/// Blue Ocean ATS: production launch.
const BLUE_OCEAN_GO_LIVE: NaiveDate = cutover(2021, 10, 5);
/// CBOT: grain trading hours reduced.
const CBOT_CUTOVER: NaiveDate = cutover(2013, 4, 8);
/// Cboe EDGX Equities: early trading session moved 07:00 -> 04:00 ET.
const EDGX_EARLY_CUTOVER: NaiveDate = cutover(2021, 3, 8);
/// Cboe BZX Equities: early trading session moved 07:00 -> 04:00 ET.
const BZX_EARLY_CUTOVER: NaiveDate = cutover(2025, 5, 1);

/// Time-aware market hours: returns the exchange-level `MarketHours` profile appropriate
/// for the provided `as_of` timestamp. Defaults to the latest profile if no historical
/// revision is defined for the exchange.
///
/// Cutover semantics: `as_of` is converted to the venue's local calendar date
/// and compared against the effective date. The new profile applies from the
/// venue-local **midnight** of the effective date — an `as_of` at exactly that
/// midnight already sees the new hours, and one nanosecond before it sees the
/// old ones.
///
/// Known gap: [`Exchange::MemxEq`] and [`Exchange::MiaxPearlEq`] changed their
/// extended hours in recent years but have **no recorded cutover** (no
/// day-level primary source), so this function returns their *current* hours
/// for every `as_of` — see the module documentation.
#[must_use]
pub fn hours_for_exchange_as_of(exch: Exchange, as_of: DateTime<Utc>) -> MarketHours {
    match exch {
        // Cboe EDGX Equities: the 04:00 ET early session began 2021-03-08;
        // before that the early session opened 07:00 ET.
        // Source: Cboe press release, "Cboe EDGX Equities Exchange To
        // Introduce Early Trading Hours, Beginning March 8" (2021-02-08) —
        // early trading from 4:00 a.m. ET with order acceptance from
        // 3:30 a.m. ET, effective Monday, March 8, 2021.
        Exchange::CboeEdgx => {
            if is_before(as_of, America::New_York, EDGX_EARLY_CUTOVER) {
                from_profile(Exchange::CboeEdgx, &US_EQUITY_EARLY_0700_PROFILE)
            } else {
                from_profile(Exchange::CboeEdgx, &US_EQUITIES_PROFILE)
            }
        }

        // Cboe BZX Equities: the 04:00 ET early session began 2025-05-01.
        // Source: Cboe release notice #54236 — "Effective May 1, 2025, Cboe
        // BZX Equities Exchange (BZX) will begin accepting orders at 2:30
        // a.m. ET and will commence the Early Trading Session at 4:00 a.m.
        // ET. … Currently, BZX begins accepting orders at 6:00 a.m. ET and
        // commences the Early Trading Session at 7:00 a.m. ET."
        Exchange::CboeBzx => {
            if is_before(as_of, America::New_York, BZX_EARLY_CUTOVER) {
                from_profile(Exchange::CboeBzx, &US_EQUITY_EARLY_0700_PROFILE)
            } else {
                from_profile(Exchange::CboeBzx, &US_EQUITIES_PROFILE)
            }
        }

        // Cboe Options (C1): GTH end extended from 09:15 → 09:25 ET on 2024-08-26.
        Exchange::CboeOptionsC1 => {
            if is_before(as_of, America::New_York, C1_GTH_CUTOVER) {
                from_profile(Exchange::CboeOptionsC1, &C1_PROFILE_PRE_2024_08_26)
            } else {
                from_profile(Exchange::CboeOptionsC1, &C1_PROFILE_POST_2024_08_26)
            }
        }

        // CME equity index defaults:
        //  - < 2016-03-04: RTH 08:30–15:15; short window 15:30–16:15
        //  - >= 2016-03-04: RTH 08:30–15:15; short window 15:30–16:00
        Exchange::Cme => {
            if is_before(as_of, US::Central, CME_CUTOVER) {
                from_profile(Exchange::Cme, &CME_PROFILE_PRE2016)
            } else {
                from_profile(Exchange::Cme, &CME_PROFILE_POST2016)
            }
        }

        // EUREX: Asian hours added 2018-12-10. Before that, omit the 01:00–08:00 slice.
        Exchange::Eurex => {
            if is_before(as_of, Europe::Berlin, EUREX_ASIAN_CUTOVER) {
                from_profile(Exchange::Eurex, &EUREX_PROFILE_NO_ASIAN)
            } else {
                from_profile(Exchange::Eurex, &EUREX_PROFILE_WITH_ASIAN)
            }
        }

        // IEX: Pre 08:00–09:30 and Post 16:00–17:00 begin 2015-08-21; before then, use RTH only.
        // Source: IEX Trading Alert #2015-015 (2015-07-13), "Effective Friday,
        // August 21, 2015, IEX will begin to rollout extended hours trading with
        // Pre-Market and Post-Market Sessions."
        // (https://iextrading.com/trading/alerts/2015/015/)
        Exchange::Iex => {
            if is_before(as_of, America::New_York, IEX_EXTENDED_CUTOVER) {
                from_profile(Exchange::Iex, &IEX_PROFILE_PRE2015)
            } else {
                from_profile(Exchange::Iex, &IEX_PROFILE_POST2015)
            }
        }

        // CFE (VIX): before 2014-06-01, approximate as RTH + curb only (no
        // overnight). From 2014-06-01 to 2021-12-05, RTH ends 15:15 CT and ETH
        // resumes at 15:30 after a dead 15-minute queuing period. From
        // 2021-12-06 the queuing period is gone and RTH ends 15:00 CT, flowing
        // seamlessly into ETH until 16:00.
        //
        // Source for the 2021 cutover: Cboe notice C2021102603, "Effective
        // December 6, 2021 … CFE will eliminate the queuing period which occurs
        // between 3:15 p.m. CT and 3:30 p.m. CT, Monday through Friday … CFE
        // will also redefine regular trading hours as 8:30 a.m. CT to 3:00 p.m.
        // CT". The date is corroborated by the CFE Rulebook amendment history,
        // which stamps Rule 1202 and seven other rules "December 6, 2021
        // (21-028)". Rule filing CFE-2021-028 (2021-11-04) carries the redline.
        Exchange::Cfe => {
            if is_before(as_of, US::Central, CFE_ETH_CUTOVER) {
                from_profile(Exchange::Cfe, &CFE_PROFILE_PRE2014)
            } else if is_before(as_of, US::Central, CFE_QUEUING_CUTOVER) {
                from_profile(Exchange::Cfe, &CFE_PROFILE_PRE_2021_12_06)
            } else {
                from_profile(Exchange::Cfe, &CFE_PROFILE)
            }
        }

        // NYSE Texas: go-live 2025-03-31; before that, no trading sessions.
        Exchange::NyseTexas => {
            if is_before(as_of, America::New_York, NYSE_TEXAS_GO_LIVE) {
                no_sessions(Exchange::NyseTexas, America::New_York)
            } else {
                from_profile(Exchange::NyseTexas, &NYSE_TEXAS_PROFILE)
            }
        }

        // Blue Ocean ATS: production launch 2021-10-05; prior to that, no sessions.
        // Source: Blue Ocean Technologies, "Announcing Launch of Blue Ocean ATS
        // Afterhours Trading" (2021-10-05) — "the official launch of The Blue
        // Ocean ATS, known as BOATS. After going live in beta in June 2021…"
        // (https://blueocean-tech.io/2021/10/05/announcing-launch-of-blue-ocean-ats-afterhours-trading/)
        // The June 2021 beta is deliberately excluded: no primary source gives it
        // a day-level date, and pre-production beta liquidity is not tradable
        // history. The 20:00→04:00 ET Sun–Thu mask matches the venue's SEC Form
        // ATS-N, which also explains the missing Friday session (the NYSE TRF is
        // unavailable to report Saturday).
        Exchange::BlueOceanAts => {
            if is_before(as_of, America::New_York, BLUE_OCEAN_GO_LIVE) {
                no_sessions(Exchange::BlueOceanAts, America::New_York)
            } else {
                from_profile(Exchange::BlueOceanAts, &BLUE_OCEAN_PROFILE)
            }
        }

        // CBOT: reduced hours effective 2013-04-08; before that, use 17:00–07:45 overnight and 08:30–13:15 day.
        Exchange::Cbot => {
            if is_before(as_of, US::Central, CBOT_CUTOVER) {
                from_profile(Exchange::Cbot, &CBOT_PROFILE_PRE2013)
            } else {
                from_profile(Exchange::Cbot, &CBOT_PROFILE_POST2013)
            }
        }

        // MEMX and MIAX Pearl Equities: deliberately NO cutover — their
        // early-session extensions to 04:00 ET are real but unsourced at day
        // level, so every `as_of` gets current hours rather than an invented
        // boundary (see the module doc). When a primary source with an
        // effective date is found, replace this arm with the dated
        // pre/post-profile selection, mirroring the CboeBzx arm above.
        #[expect(
            clippy::match_same_arms,
            reason = "identical to the default arm today, but kept separate as the \
                      documented marker for where the sourced cutovers land"
        )]
        Exchange::MemxEq | Exchange::MiaxPearlEq => hours_for_exchange(exch),

        // Default: return the current exchange profile.
        _ => hours_for_exchange(exch),
    }
}