use chrono::{DateTime, Datelike, Duration, NaiveDate, Timelike, Utc};
use chrono_tz::Tz;
use crate::calendar::exceptions::{DateException, ExceptionBlock, SessionExceptionSource};
use crate::calendar::exchange_calendar::ExchangeCalendar;
use crate::calendar::hours::MarketHours;
use crate::calendar::local_time::{bounded_utc, mk_local_close, mk_local_open};
use crate::calendar::policy::DayPolicy;
use crate::calendar::rule::{SessionKind, SessionRule};
use crate::calendar::schedules::holidays::{Holiday, HolidayKind, HolidayTable};
use crate::calendar::{CalendarResolution, CalendarSource};
use super::gate::{FixedSnapshot, Identified, SourceGate};
use super::{candles, identity, replacement};
const SECONDS_PER_DAY: u32 = 86_400;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum RuleSet {
Sessions(SessionKind),
OrderEntry,
}
#[derive(Clone, Copy)]
pub(in crate::calendar) struct QueryContext<'a, G: SourceGate> {
source: G::Source<'a>,
tz: Tz,
holidays: Option<&'static HolidayTable>,
policy: Option<&'a dyn DayPolicy>,
exceptions: Option<&'a dyn SessionExceptionSource>,
coverage: G::Coverage,
replacement_layer: bool,
builtin_blocks: bool,
}
#[derive(Clone, Copy)]
struct DayClip {
closed: bool,
unavailable: bool,
early_close_ssm: Option<u32>,
late_open_ssm: Option<u32>,
}
impl DayClip {
const NONE: Self = Self {
closed: false,
unavailable: false,
early_close_ssm: None,
late_open_ssm: None,
};
const fn is_none(self) -> bool {
!self.closed
&& !self.unavailable
&& self.early_close_ssm.is_none()
&& self.late_open_ssm.is_none()
}
fn tighten(self, other: Self) -> Self {
Self {
closed: self.closed || other.closed,
unavailable: self.unavailable || other.unavailable,
early_close_ssm: min_option(self.early_close_ssm, other.early_close_ssm),
late_open_ssm: max_option(self.late_open_ssm, other.late_open_ssm),
}
}
}
fn min_option(left: Option<u32>, right: Option<u32>) -> Option<u32> {
match (left, right) {
(Some(left), Some(right)) => Some(left.min(right)),
(value, None) | (None, value) => value,
}
}
fn max_option(left: Option<u32>, right: Option<u32>) -> Option<u32> {
match (left, right) {
(Some(left), Some(right)) => Some(left.max(right)),
(value, None) | (None, value) => value,
}
}
const fn table_can_replace(holidays: Option<&HolidayTable>) -> bool {
match holidays {
Some(table) => table.carries_replacement_blocks(),
None => false,
}
}
pub(in crate::calendar) enum ResolvedHours<'a> {
Borrowed(&'a MarketHours),
Selected(MarketHours),
}
impl AsRef<MarketHours> for ResolvedHours<'_> {
fn as_ref(&self) -> &MarketHours {
match self {
Self::Borrowed(hours) => hours,
Self::Selected(hours) => hours,
}
}
}
impl<'a> QueryContext<'a, FixedSnapshot> {
pub(in crate::calendar) fn fixed(hours: &'a MarketHours) -> Self {
Self {
source: hours,
tz: hours.tz,
holidays: None,
policy: None,
exceptions: None,
coverage: (),
replacement_layer: false,
builtin_blocks: false,
}
}
}
impl<'a> QueryContext<'a, Identified> {
pub(in crate::calendar) fn date_aware(calendar: ExchangeCalendar) -> Self {
let holidays = calendar.holiday_table();
let builtin_blocks = table_can_replace(holidays);
Self {
source: calendar,
tz: calendar.tz(),
holidays,
policy: None,
exceptions: None,
coverage: calendar.coverage(),
replacement_layer: builtin_blocks,
builtin_blocks,
}
}
pub(in crate::calendar) fn overlay(
calendar: ExchangeCalendar,
policy: Option<&'a dyn DayPolicy>,
exceptions: Option<&'a dyn SessionExceptionSource>,
) -> Self {
let holidays = calendar.holiday_table();
let builtin_blocks = table_can_replace(holidays);
Self {
source: calendar,
tz: calendar.tz(),
holidays,
policy,
exceptions,
coverage: calendar.coverage(),
replacement_layer: exceptions.is_some() || builtin_blocks,
builtin_blocks,
}
}
}
impl<'a, G: SourceGate> QueryContext<'a, G> {
pub(super) const fn baseline(self) -> Self {
Self {
source: self.source,
tz: self.tz,
holidays: None,
policy: None,
exceptions: None,
coverage: self.coverage,
replacement_layer: false,
builtin_blocks: false,
}
}
pub(super) const fn tz(self) -> Tz {
self.tz
}
pub(super) const fn policy(self) -> Option<&'a dyn DayPolicy> {
self.policy
}
pub(super) const fn has_overlay(self) -> bool {
self.holidays.is_some() || self.policy.is_some() || self.exceptions.is_some()
}
pub(super) fn require_answerable(self, date: NaiveDate) -> Result<(), G::Error> {
G::require_answerable(self.coverage, date)
}
pub(in crate::calendar) fn require_floor_at(
self,
instant: DateTime<Utc>,
) -> Result<(), G::Error> {
G::require_floor_at(self.coverage, self.tz, instant)
}
pub(super) fn require_floor(self, date: NaiveDate) -> Result<(), G::Error> {
G::require_floor(self.coverage, date)
}
pub(super) fn require_phase_coverage(self, date: NaiveDate) -> Result<(), G::Error> {
G::require_phase_coverage(self.coverage, date)
}
pub(super) fn require_holiday_classification(self, date: NaiveDate) -> Result<(), G::Error> {
G::require_holiday_classification(self.coverage, date)
}
pub(super) fn has_unscoped_refusing_phase_gap_on(self, day: NaiveDate) -> bool {
G::has_unscoped_refusing_phase_gap_on(self.coverage, day)
}
pub(super) fn search_exhausted(self, day: NaiveDate) -> Result<(), G::Error> {
G::search_exhausted(self.coverage, day)
}
pub(in crate::calendar) fn holiday_on(self, trade_date: NaiveDate) -> Option<Holiday> {
self.holidays.and_then(|table| table.holiday_on(trade_date))
}
fn builtin_clip(self, trade_date: NaiveDate) -> DayClip {
if matches!(
self.caller_exception_on(trade_date),
DateException::Closed | DateException::ReplaceSessions(_)
) {
return DayClip::NONE;
}
match self.holiday_on(trade_date).map(Holiday::kind) {
None | Some(HolidayKind::Unsourced | HolidayKind::ReplacementBlocks(_)) => {
DayClip::NONE
}
Some(HolidayKind::Closed) => DayClip {
closed: true,
..DayClip::NONE
},
Some(HolidayKind::EarlyClose { close_ssm }) => DayClip {
early_close_ssm: Some(close_ssm),
..DayClip::NONE
},
Some(HolidayKind::LateOpen { open_ssm }) => DayClip {
late_open_ssm: Some(open_ssm),
..DayClip::NONE
},
Some(HolidayKind::LateOpenAndEarlyClose {
open_ssm,
close_ssm,
}) => DayClip {
early_close_ssm: Some(close_ssm),
late_open_ssm: Some(open_ssm),
..DayClip::NONE
},
}
}
fn policy_clip(self, trade_date: NaiveDate) -> DayClip {
self.policy.map_or(DayClip::NONE, |policy| {
let early_close_ssm = policy.early_close_ssm(trade_date);
let late_open_ssm = policy.late_open_ssm(trade_date);
DayClip {
closed: policy.is_closed(trade_date),
unavailable: early_close_ssm.is_some_and(|ssm| ssm > SECONDS_PER_DAY)
|| late_open_ssm.is_some_and(|ssm| ssm >= SECONDS_PER_DAY),
early_close_ssm,
late_open_ssm,
}
})
}
fn builtin_block_may_exist_on(self, day: NaiveDate) -> bool {
self.builtin_blocks
&& self
.holidays
.is_some_and(|table| table.may_affect(day, day))
}
pub(super) fn replacement_blocks_may_reach(self, first: NaiveDate, last: NaiveDate) -> bool {
if !self.replacement_layer {
return false;
}
if let Some(provider) = self.exceptions
&& provider.may_affect(first, last)
{
return true;
}
self.builtin_blocks
&& self
.holidays
.is_some_and(|table| table.blocks_may_affect(first, last))
}
fn any_layer_may_affect(self, first: NaiveDate, last: NaiveDate) -> bool {
if self
.policy
.is_some_and(|policy| policy.may_affect(first, last))
{
return true;
}
if let Some(provider) = self.exceptions {
match provider.coverage() {
None => return true,
Some(coverage) => {
if coverage.first() <= last
&& first <= coverage.last()
&& provider.may_affect(first, last)
{
return true;
}
}
}
}
self.holidays
.is_some_and(|table| table.may_affect(first, last))
}
pub(super) fn identity(self) -> Option<CalendarSource> {
G::identity(self.source)
}
fn caller_exception_on(self, trade_date: NaiveDate) -> DateException<'a> {
self.exceptions
.map_or(DateException::KnownNormal, |provider| {
provider.exception_on(trade_date)
})
}
pub(super) fn exception_on(self, trade_date: NaiveDate) -> DateException<'a> {
let caller = self.caller_exception_on(trade_date);
if !self.builtin_blocks
|| matches!(
caller,
DateException::Closed | DateException::ReplaceSessions(_)
)
{
return caller;
}
match self.holiday_on(trade_date).map(Holiday::kind) {
Some(HolidayKind::ReplacementBlocks(set)) => DateException::ReplaceSessions(set),
None
| Some(
HolidayKind::Closed
| HolidayKind::EarlyClose { .. }
| HolidayKind::LateOpen { .. }
| HolidayKind::LateOpenAndEarlyClose { .. }
| HolidayKind::Unsourced,
) => caller,
}
}
pub(super) const fn has_replacement_layer(self) -> bool {
self.replacement_layer
}
pub(super) fn trade_date_is_replaced(self, trade_date: NaiveDate) -> bool {
matches!(
self.exception_on(trade_date),
DateException::ReplaceSessions(_)
)
}
pub(super) fn trade_date_is_closed(self, trade_date: NaiveDate) -> bool {
if matches!(self.exception_on(trade_date), DateException::Closed) {
return true;
}
self.builtin_clip(trade_date)
.tighten(self.policy_clip(trade_date))
.closed
}
pub(super) fn trade_date_for_bounds(
self,
open: DateTime<Utc>,
close: DateTime<Utc>,
) -> NaiveDate {
replacement::replacement_trade_date(&self, open)
.unwrap_or_else(|| identity::assign_normal(&self, open, close))
}
pub(super) fn normal_trade_date_for_bounds(
self,
open: DateTime<Utc>,
close: DateTime<Utc>,
) -> NaiveDate {
identity::assign_normal(&self, open, close)
}
pub(super) fn joins_adjacent_same_kind(self) -> bool {
identity::joins_adjacent_same_kind(&self)
}
pub(super) fn has_daily_close_at(self, instant: DateTime<Utc>) -> bool {
G::has_daily_close_at(self.source, instant)
}
pub(super) fn has_weekend_close_at(self, instant: DateTime<Utc>) -> bool {
G::has_weekend_close_at(self.source, instant)
}
pub(super) fn contains_order_entry(self, instant: DateTime<Utc>) -> Result<bool, G::Error> {
let day = bounded_utc(instant, self.tz)
.with_timezone(&self.tz)
.date_naive();
let hit = |open: DateTime<Utc>, close: DateTime<Utc>| {
(open <= instant && instant < close).then_some(())
};
if find_occurrence(&self, day, RuleSet::OrderEntry, false, hit)?.is_some() {
return Ok(true);
}
let Some(yesterday) = day.pred_opt() else {
return Ok(false);
};
if !self.wrapped_occurrence_possible(yesterday, RuleSet::OrderEntry) {
return Ok(false);
}
Ok(find_occurrence(&self, yesterday, RuleSet::OrderEntry, true, hit)?.is_some())
}
pub(super) fn wrapped_occurrence_possible(self, day: NaiveDate, set: RuleSet) -> bool {
let block_reach_last = day
.checked_add_signed(Duration::days(i64::from(-ExceptionBlock::MIN_DAY_OFFSET)))
.is_none_or(|last| self.replacement_blocks_may_reach(day, last));
if block_reach_last {
return true;
}
let weekday = day.weekday().num_days_from_monday() as usize;
let selected = self.profile_for_open_day(day);
rules(selected.as_ref(), set).any(|rule| rule.days[weekday] && rule.wraps_to_next_day())
}
pub(super) fn has_weekly_close_at(self, instant: DateTime<Utc>) -> bool {
if self.has_weekend_close_at(instant) {
return true;
}
identity::joins_adjacent_same_kind(&self) && self.has_daily_close_at(instant)
}
pub(super) fn profile_for_open_day(self, day: NaiveDate) -> ResolvedHours<'a> {
G::profile_for_open_day(self.source, self.tz, day)
}
}
pub(super) fn find_occurrence<G: SourceGate, T>(
context: &QueryContext<'_, G>,
open_day: NaiveDate,
set: RuleSet,
wrapped_only: bool,
mut probe: impl FnMut(DateTime<Utc>, DateTime<Utc>) -> Option<T>,
) -> Result<Option<T>, G::Error> {
context.require_answerable(open_day)?;
let weekday = open_day.weekday().num_days_from_monday() as usize;
let selected = context.profile_for_open_day(open_day);
if matches!(set, RuleSet::OrderEntry) && {
context.has_unscoped_refusing_phase_gap_on(open_day)
|| rules(selected.as_ref(), set)
.any(|rule| rule.days[weekday] && (!wrapped_only || rule.wraps_to_next_day()))
|| context.builtin_block_may_exist_on(open_day)
} {
context.require_phase_coverage(open_day)?;
}
for rule in rules(selected.as_ref(), set)
.filter(|rule| rule.days[weekday] && (!wrapped_only || rule.wraps_to_next_day()))
{
if let Some(bounds) = resolve_rule_bounds(context, open_day, set, rule)? {
if replacement::governs_instant(
context,
bounds,
set,
open_day,
rule.wraps_to_next_day(),
) {
continue;
}
if let Some(found) = probe(bounds.0, bounds.1) {
return Ok(Some(found));
}
}
}
Ok(replacement::find_occurrence(
context,
open_day,
set,
wrapped_only,
probe,
))
}
pub(in crate::calendar) fn builtin_resolves_order_entry(
source: CalendarSource,
date: NaiveDate,
open_ssm: Option<u32>,
close_ssm: u32,
) -> bool {
let calendar = match source {
CalendarSource::Exchange(exchange) => {
crate::calendar::exchange_calendar::calendar_for_exchange(exchange)
}
CalendarSource::MarketHoursKey(key) => {
crate::calendar::exchange_calendar::calendar_for_market_hours_key(key)
}
};
let context = QueryContext::date_aware(calendar);
let weekday = date.weekday().num_days_from_monday() as usize;
let selected = context.profile_for_open_day(date);
let mut unresolved = false;
for rule in rules(selected.as_ref(), RuleSet::OrderEntry) {
if !rule.days[weekday] || rule.close_ssm != close_ssm {
continue;
}
if open_ssm.is_some_and(|open| rule.open_ssm != open) {
continue;
}
match resolve_rule_bounds(&context, date, RuleSet::OrderEntry, rule) {
Ok(Some(_bounds)) => return true,
Ok(None) => {}
Err(_) => unresolved = true,
}
}
unresolved
}
pub(in crate::calendar) fn builtin_has_tradeable_rule(
source: CalendarSource,
day: NaiveDate,
) -> bool {
let calendar = match source {
CalendarSource::Exchange(exchange) => {
crate::calendar::exchange_calendar::calendar_for_exchange(exchange)
}
CalendarSource::MarketHoursKey(key) => {
crate::calendar::exchange_calendar::calendar_for_market_hours_key(key)
}
};
let context = QueryContext::date_aware(calendar);
let weekday = day.weekday().num_days_from_monday() as usize;
let selected = context.profile_for_open_day(day);
rules(selected.as_ref(), RuleSet::Sessions(SessionKind::Both)).any(|rule| rule.days[weekday])
}
pub(super) fn resolve_rule_bounds<G: SourceGate>(
context: &QueryContext<'_, G>,
open_day: NaiveDate,
set: RuleSet,
rule: &SessionRule,
) -> Result<Option<crate::calendar::exchange_calendar::SessionWindow>, G::Error> {
let close_day = if rule.wraps_to_next_day() {
open_day.succ_opt()
} else {
Some(open_day)
};
let Some(close_day) = close_day else {
return Ok(None);
};
let tz = context.tz();
let raw_open = mk_local_open(tz, open_day, rule.open_ssm).with_timezone(&Utc);
let raw_close = mk_local_close(tz, close_day, rule.close_ssm).with_timezone(&Utc);
if raw_open >= raw_close {
return Ok(None);
}
if !context.has_overlay() {
return Ok(Some((raw_open, raw_close)));
}
if let Some((first, last)) =
identity::trade_date_window(context, open_day, set, rule.wraps_to_next_day(), raw_open)
&& !context.any_layer_may_affect(first, last)
{
return Ok(Some((raw_open, raw_close)));
}
if !context.has_daily_close_at(raw_open) {
return Ok(Some((raw_open, raw_close)));
}
let baseline = context.baseline();
let final_close = match candles::candle_end_with(
&baseline,
raw_open,
CalendarResolution::Daily,
SessionKind::Both,
)? {
Some(resolved) => resolved,
None => raw_close,
};
let trade_date = context.normal_trade_date_for_bounds(raw_open, final_close);
if context.has_replacement_layer()
&& (context.trade_date_is_replaced(trade_date)
|| matches!(context.exception_on(trade_date), DateException::Closed))
{
return Ok(None);
}
let clip = context
.builtin_clip(trade_date)
.tighten(context.policy_clip(trade_date));
if clip.closed {
return Ok(None);
}
if clip.is_none() {
return Ok(Some((raw_open, raw_close)));
}
clamp_to_clip(context, clip, trade_date, raw_open, raw_close)
}
fn clamp_to_clip<G: SourceGate>(
context: &QueryContext<'_, G>,
clip: DayClip,
trade_date: NaiveDate,
raw_open: DateTime<Utc>,
raw_close: DateTime<Utc>,
) -> Result<Option<crate::calendar::exchange_calendar::SessionWindow>, G::Error> {
if clip.unavailable {
return Ok(None);
}
let tz = context.tz();
let mut open = raw_open;
let mut close = raw_close;
if let Some(ssm) = clip.early_close_ssm {
let cutoff = mk_local_close(tz, trade_date, ssm).with_timezone(&Utc);
close = close.min(cutoff);
}
if let Some(ssm) = clip.late_open_ssm {
let first_open = candles::candle_start_with(
&context.baseline(),
raw_open,
CalendarResolution::Daily,
SessionKind::Both,
)?
.unwrap_or(raw_open);
let first_local = first_open.with_timezone(&tz);
let first_day = first_local.date_naive();
let first_ssm = first_local.time().num_seconds_from_midnight();
let cutoff_day = if first_day < trade_date && ssm >= first_ssm {
first_day
} else {
trade_date
};
let cutoff = mk_local_open(tz, cutoff_day, ssm).with_timezone(&Utc);
open = open.max(cutoff);
}
Ok((open < close).then_some((open, close)))
}
pub(super) fn rules(hours: &MarketHours, set: RuleSet) -> impl Iterator<Item = &SessionRule> {
let (first, second): (&[SessionRule], &[SessionRule]) = match set {
RuleSet::Sessions(SessionKind::Regular) => (&hours.regular, &[]),
RuleSet::Sessions(SessionKind::Extended) => (&[], &hours.extended),
RuleSet::Sessions(SessionKind::Both) => (&hours.regular, &hours.extended),
RuleSet::OrderEntry => (&hours.order_entry, &[]),
};
first.iter().chain(second)
}