use chrono::{DateTime, NaiveDate, Utc};
use chrono_tz::Tz;
use super::source::CalendarSource;
use crate::calendar::schedules::holidays::{self, Holiday, HolidayCoverage, HolidayTable};
use crate::calendar::{
CalendarCoverage, Exchange, MarketHours, MarketHoursKey, hours_for_exchange,
hours_for_market_hours_key,
};
const TZ_RESOLUTION_INSTANT: DateTime<Utc> = DateTime::<Utc>::UNIX_EPOCH;
pub type SessionWindow = (DateTime<Utc>, DateTime<Utc>);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ExchangeCalendar {
source: CalendarSource,
holidays: bool,
}
impl ExchangeCalendar {
#[must_use]
pub const fn new(exchange: Exchange) -> Self {
Self {
source: CalendarSource::Exchange(exchange),
holidays: true,
}
}
#[must_use]
pub const fn for_market_hours_key(key: MarketHoursKey) -> Self {
Self {
source: CalendarSource::MarketHoursKey(key),
holidays: true,
}
}
#[must_use]
pub const fn without_holidays(self) -> Self {
Self {
source: self.source,
holidays: false,
}
}
#[must_use]
pub fn holiday_on(self, trade_date: NaiveDate) -> Option<Holiday> {
self.holiday_table()
.and_then(|table| table.holiday_on(trade_date))
}
#[must_use]
pub fn holiday_coverage(self) -> Option<HolidayCoverage> {
self.holiday_table().map(HolidayTable::coverage)
}
pub(in crate::calendar) const fn holiday_table(self) -> Option<&'static HolidayTable> {
if self.holidays {
holidays::table_for(self.source)
} else {
None
}
}
#[must_use]
pub const fn coverage(self) -> CalendarCoverage {
CalendarCoverage::new(self.source, self.holidays)
}
#[must_use]
pub const fn source(self) -> CalendarSource {
self.source
}
#[must_use]
pub const fn exchange(self) -> Option<Exchange> {
match self.source {
CalendarSource::Exchange(exchange) => Some(exchange),
CalendarSource::MarketHoursKey(_) => None,
}
}
#[must_use]
pub const fn market_hours_key(self) -> Option<MarketHoursKey> {
match self.source {
CalendarSource::Exchange(_) => None,
CalendarSource::MarketHoursKey(key) => Some(key),
}
}
#[must_use]
pub fn hours_at(self, instant: DateTime<Utc>) -> MarketHours {
match self.source {
CalendarSource::Exchange(exchange) => hours_for_exchange(exchange, instant),
CalendarSource::MarketHoursKey(key) => hours_for_market_hours_key(key, instant),
}
}
#[must_use]
pub fn tz(self) -> Tz {
match self.source {
CalendarSource::Exchange(exchange) => {
hours_for_exchange(exchange, TZ_RESOLUTION_INSTANT).tz
}
CalendarSource::MarketHoursKey(key) => {
hours_for_market_hours_key(key, TZ_RESOLUTION_INSTANT).tz
}
}
}
}
#[must_use]
pub const fn calendar_for_exchange(exchange: Exchange) -> ExchangeCalendar {
ExchangeCalendar::new(exchange)
}
#[must_use]
pub const fn calendar_for_market_hours_key(key: MarketHoursKey) -> ExchangeCalendar {
ExchangeCalendar::for_market_hours_key(key)
}