use chrono::{Datelike as _, Utc, Weekday};
use chrono_tz::Tz;
use super::SUPPORT_FLOOR;
use crate::calendar::exchange_calendar::{calendar_for_exchange, calendar_for_market_hours_key};
use crate::calendar::local_time::mk_local_open;
use crate::calendar::schedules::sourcing;
use crate::calendar::{CalendarQueryError, CalendarSource, MarketHours, SessionRule};
const OPEN_DAY_ANCHOR_SSM: u32 = 86_399;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NormalWeekBaseline {
profile: MarketHours,
weekday: Weekday,
}
impl NormalWeekBaseline {
#[must_use]
pub fn identity(&self) -> CalendarSource {
self.profile.source
}
#[must_use]
pub fn tz(&self) -> Tz {
self.profile.tz
}
#[must_use]
pub const fn weekday(&self) -> Weekday {
self.weekday
}
#[must_use]
pub const fn profile(&self) -> &MarketHours {
&self.profile
}
pub fn tradeable_rules(&self) -> impl Iterator<Item = SessionRule> + use<'_> {
self.weekday_rules(
self.profile
.regular
.iter()
.chain(self.profile.extended.iter()),
)
}
pub fn order_entry_rules(&self) -> impl Iterator<Item = SessionRule> + use<'_> {
self.weekday_rules(self.profile.order_entry.iter())
}
fn weekday_rules<'a>(
&'a self,
rules: impl Iterator<Item = &'a SessionRule> + 'a,
) -> impl Iterator<Item = SessionRule> + 'a {
let weekday_index = self.weekday.num_days_from_monday() as usize;
rules.copied().filter(move |rule| rule.days[weekday_index])
}
}
impl core::fmt::Display for NormalWeekBaseline {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "normal week {}: ", weekday_name(self.weekday))?;
let mut tradeable: Vec<(u32, u32, bool)> = self
.tradeable_rules()
.map(|rule| (rule.open_ssm, rule.close_ssm, rule.wraps_to_next_day()))
.collect();
tradeable.sort_unstable();
if tradeable.is_empty() {
write!(f, "no ordinary session")?;
}
for (index, (open_ssm, close_ssm, wraps)) in tradeable.iter().enumerate() {
if index > 0 {
write!(f, ", ")?;
}
write!(f, "open {}", window_text(*open_ssm, *close_ssm, *wraps))?;
}
let mut order_entry: Vec<(u32, u32, bool)> = self
.order_entry_rules()
.map(|rule| (rule.open_ssm, rule.close_ssm, rule.wraps_to_next_day()))
.collect();
order_entry.sort_unstable();
for (open_ssm, close_ssm, wraps) in order_entry {
write!(
f,
", order entry {}",
window_text(open_ssm, close_ssm, wraps)
)?;
}
Ok(())
}
}
fn window_text(open_ssm: u32, close_ssm: u32, wraps: bool) -> String {
if wraps {
format!("{}-{} (+1)", clock_text(open_ssm), clock_text(close_ssm))
} else {
format!("{}-{}", clock_text(open_ssm), clock_text(close_ssm))
}
}
fn clock_text(ssm: u32) -> String {
let (hour, rest) = (ssm / 3_600, ssm % 3_600);
let (minute, second) = (rest / 60, rest % 60);
if second == 0 {
format!("{hour:02}:{minute:02}")
} else {
format!("{hour:02}:{minute:02}:{second:02}")
}
}
fn weekday_name(weekday: Weekday) -> &'static str {
match weekday {
Weekday::Mon => "Monday",
Weekday::Tue => "Tuesday",
Weekday::Wed => "Wednesday",
Weekday::Thu => "Thursday",
Weekday::Fri => "Friday",
Weekday::Sat => "Saturday",
Weekday::Sun => "Sunday",
}
}
pub(crate) fn for_error(error: CalendarQueryError) -> Option<NormalWeekBaseline> {
let source = error.source();
let date = error.date();
if date < SUPPORT_FLOOR {
return None;
}
let declared = sourcing::declared(source);
if declared.carried_below.is_some_and(|carried| date < carried) {
return None;
}
let calendar = match source {
CalendarSource::Exchange(exchange) => calendar_for_exchange(exchange),
CalendarSource::MarketHoursKey(key) => calendar_for_market_hours_key(key),
};
let tz = calendar.tz();
let anchor = mk_local_open(tz, date, OPEN_DAY_ANCHOR_SSM).with_timezone(&Utc);
let profile = calendar.hours_at(anchor);
Some(NormalWeekBaseline {
weekday: date.weekday(),
profile,
})
}