use chrono::{DateTime, Datelike, Duration, NaiveDate, Utc};
use super::local_time::{is_holiday, mk_local_close};
use super::{MarketHours, SessionKind};
pub(crate) fn next_daily_close_after_with(
hours: &MarketHours,
t: DateTime<Utc>,
kind: SessionKind,
) -> Option<DateTime<Utc>> {
let tz = hours.tz;
let mut day = t.with_timezone(&tz).date_naive();
for _ in 0..21 {
if let Some(close) = daily_close_for_local_day(hours, day, kind)
&& close > t
{
return Some(close);
}
day += Duration::days(1);
}
None
}
fn closes_landing_on_day(
hours: &MarketHours,
day: NaiveDate,
kind: SessionKind,
) -> impl Iterator<Item = DateTime<Utc>> + '_ {
let tz = hours.tz;
let day_is_holiday = is_holiday(hours, day);
let yday = day - Duration::days(1);
let yday_is_holiday = is_holiday(hours, yday);
let w_today = day.weekday().num_days_from_monday() as usize;
let w_yday = yday.weekday().num_days_from_monday() as usize;
hours.iter_rules(kind).filter_map(move |r| {
if day_is_holiday {
return None;
}
let lands_on_day = if r.open_ssm <= r.close_ssm {
r.days[w_today]
} else {
!yday_is_holiday && r.days[w_yday]
};
lands_on_day.then(|| mk_local_close(tz, day, r.close_ssm).with_timezone(&Utc))
})
}
pub(crate) fn daily_close_for_local_day(
hours: &MarketHours,
day: NaiveDate,
kind: SessionKind,
) -> Option<DateTime<Utc>> {
closes_landing_on_day(hours, day, kind).max()
}
pub(crate) fn latest_close_at_or_before(
hours: &MarketHours,
t: DateTime<Utc>,
kind: SessionKind,
) -> Option<DateTime<Utc>> {
let day = t.with_timezone(&hours.tz).date_naive();
for offset in 0..=1 {
let close = closes_landing_on_day(hours, day - Duration::days(offset), kind)
.filter(|close| *close <= t)
.max();
if close.is_some() {
return close;
}
}
None
}
pub(crate) fn next_weekly_close_after_with(
hours: &MarketHours,
t: DateTime<Utc>,
kind: SessionKind,
) -> Option<DateTime<Utc>> {
let tz = hours.tz;
let mut c = next_daily_close_after_with(hours, t, kind)?;
loop {
let c_local = c.with_timezone(&tz);
let c_week = (c_local.iso_week().year(), c_local.iso_week().week());
let Some(c_next) = next_daily_close_after_with(hours, c + Duration::nanoseconds(1), kind)
else {
return Some(c);
};
let n_local = c_next.with_timezone(&tz);
let n_week = (n_local.iso_week().year(), n_local.iso_week().week());
if n_week != c_week {
return Some(c); }
c = c_next;
}
}
pub(crate) fn next_monthly_close_after_with(
hours: &MarketHours,
t: DateTime<Utc>,
kind: SessionKind,
) -> Option<DateTime<Utc>> {
let tz = hours.tz;
let mut c = next_daily_close_after_with(hours, t, kind)?;
loop {
let c_local = c.with_timezone(&tz);
let c_month = (c_local.year(), c_local.month());
let Some(c_next) = next_daily_close_after_with(hours, c + Duration::nanoseconds(1), kind)
else {
return Some(c);
};
let n_local = c_next.with_timezone(&tz);
let n_month = (n_local.year(), n_local.month());
if n_month != c_month {
return Some(c); }
c = c_next;
}
}