use std::borrow::Cow;
use chrono::{DateTime, Datelike, Duration, NaiveDate, Timelike, Utc};
use chrono_tz::Tz;
use super::local_time::{is_holiday, mk_local_open};
use super::period::latest_close_at_or_before;
use super::rule::{SECONDS_PER_NORMAL_WEEK, normal_week_rule_intervals};
use super::session::{next_session_after, next_session_after_with};
use super::{Exchange, SessionKind, SessionRule};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarketHours {
pub exchange: Exchange,
pub tz: Tz,
pub regular: Cow<'static, [SessionRule]>,
pub extended: Cow<'static, [SessionRule]>,
pub has_daily_close: bool,
pub has_weekend_close: bool,
}
impl MarketHours {
#[inline]
pub(crate) fn iter_rules(&self, kind: SessionKind) -> impl Iterator<Item = &SessionRule> + '_ {
let (regular, extended): (&[SessionRule], &[SessionRule]) = match kind {
SessionKind::Regular => (&self.regular, &[]),
SessionKind::Extended => (&[], &self.extended),
SessionKind::Both => (&self.regular, &self.extended),
};
regular.iter().chain(extended.iter())
}
#[must_use]
pub fn normal_week_open_seconds(&self) -> u64 {
let mut intervals = self
.iter_rules(SessionKind::Both)
.flat_map(normal_week_rule_intervals)
.collect::<Vec<_>>();
intervals.sort_unstable();
let mut merged = Vec::<(u64, u64)>::new();
for (start, end) in intervals {
if let Some((_, previous_end)) = merged.last_mut()
&& start <= *previous_end
{
*previous_end = (*previous_end).max(end);
} else {
merged.push((start, end));
}
}
merged
.into_iter()
.map(|(start, end)| end.saturating_sub(start))
.sum::<u64>()
.min(SECONDS_PER_NORMAL_WEEK)
}
#[must_use]
pub fn is_open(&self, t: DateTime<Utc>) -> bool {
self.is_open_with(t, SessionKind::Both)
}
#[must_use]
pub fn is_open_with(&self, t: DateTime<Utc>, kind: SessionKind) -> bool {
let local = t.with_timezone(&self.tz);
let today = local.date_naive();
let w_today = local.weekday().num_days_from_monday() as usize;
let ssm = local.num_seconds_from_midnight();
if !is_holiday(self, today)
&& self.iter_rules(kind).any(|r| {
if !r.days[w_today] {
return false;
}
if r.open_ssm <= r.close_ssm {
ssm >= r.open_ssm && ssm < r.close_ssm
} else {
ssm >= r.open_ssm && !is_holiday(self, today + Duration::days(1))
}
})
{
return true;
}
let yday_date = today - Duration::days(1);
if is_holiday(self, yday_date) || is_holiday(self, today) {
return false;
}
let yday = yday_date.weekday().num_days_from_monday() as usize;
self.iter_rules(kind).any(|r| {
if r.open_ssm <= r.close_ssm {
return false;
}
if !r.days[yday] {
return false;
}
ssm < r.close_ssm
})
}
#[must_use]
pub fn is_open_regular(&self, t: DateTime<Utc>) -> bool {
self.is_open_with(t, SessionKind::Regular)
}
#[must_use]
pub fn is_open_extended(&self, t: DateTime<Utc>) -> bool {
self.is_open_with(t, SessionKind::Extended)
}
#[must_use]
pub fn is_maintenance(&self, t: DateTime<Utc>) -> bool {
let max_gap = Duration::hours(6);
if self.is_open(t) {
return false;
}
let Some((next_open, _close)) = next_session_after(self, t) else {
return false;
};
if next_open - t >= max_gap {
return false;
}
latest_close_at_or_before(self, t, SessionKind::Both)
.is_some_and(|prev_close| next_open - prev_close < max_gap)
}
#[must_use]
pub fn is_closed_all_day_in_calendar(
&self,
day: NaiveDate,
calendar_tz: Tz,
kind: SessionKind,
) -> bool {
fn midnight_utc_for(tz: Tz, d: NaiveDate) -> DateTime<Utc> {
mk_local_open(tz, d, 0).with_timezone(&Utc)
}
let start_utc = midnight_utc_for(calendar_tz, day);
let end_utc = day.succ_opt().map_or(DateTime::<Utc>::MAX_UTC, |next| {
midnight_utc_for(calendar_tz, next)
});
if self.is_open_with(start_utc, kind) {
return false;
}
match next_session_after_with(self, start_utc, kind) {
Some((next_open, _next_close)) => next_open >= end_utc,
None => true,
}
}
#[inline]
#[must_use]
pub fn is_closed_all_day_on(&self, local_day: NaiveDate, kind: SessionKind) -> bool {
self.is_closed_all_day_in_calendar(local_day, self.tz, kind)
}
#[inline]
#[must_use]
pub fn is_closed_all_day_at(
&self,
ts_utc: DateTime<Utc>,
calendar_tz: Tz,
kind: SessionKind,
) -> bool {
let day = ts_utc.with_timezone(&calendar_tz).date_naive();
self.is_closed_all_day_in_calendar(day, calendar_tz, kind)
}
}