use chrono::NaiveDate;
use super::{
BlockViolation, DateException, ExceptionBlock, ExceptionCoverage, SessionExceptionSource,
first_block_violation,
};
use crate::calendar::exchange_calendar::CalendarSource;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionExceptionRecord<'a> {
trade_date: NaiveDate,
state: RecordState<'a>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RecordState<'a> {
KnownNormal,
Closed,
ReplaceSessions(&'a [ExceptionBlock]),
}
impl<'a> SessionExceptionRecord<'a> {
#[must_use]
pub const fn known_normal(trade_date: NaiveDate) -> Self {
Self {
trade_date,
state: RecordState::KnownNormal,
}
}
#[must_use]
pub const fn closed(trade_date: NaiveDate) -> Self {
Self {
trade_date,
state: RecordState::Closed,
}
}
#[must_use]
pub const fn replace_sessions(trade_date: NaiveDate, blocks: &'a [ExceptionBlock]) -> Self {
Self {
trade_date,
state: RecordState::ReplaceSessions(blocks),
}
}
#[must_use]
pub const fn trade_date(self) -> NaiveDate {
self.trade_date
}
#[must_use]
pub const fn exception(self) -> DateException<'a> {
match self.state {
RecordState::KnownNormal => DateException::KnownNormal,
RecordState::Closed => DateException::Closed,
RecordState::ReplaceSessions(blocks) => DateException::ReplaceSessions(blocks),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StaticSessionExceptions<'a> {
source: CalendarSource,
coverage: ExceptionCoverage,
records: &'a [SessionExceptionRecord<'a>],
}
impl<'a> StaticSessionExceptions<'a> {
pub const fn new(
source: CalendarSource,
first_covered: NaiveDate,
last_covered: NaiveDate,
records: &'a [SessionExceptionRecord<'a>],
) -> Result<Self, StaticSessionExceptionsError> {
if last_covered.signed_duration_since(first_covered).num_days() < 0 {
return Err(StaticSessionExceptionsError::CoverageBoundsInverted);
}
let mut index = 0;
while index < records.len() {
let current = records[index];
if index > 0
&& current
.trade_date
.signed_duration_since(records[index - 1].trade_date)
.num_days()
<= 0
{
return Err(StaticSessionExceptionsError::DatesNotStrictlyIncreasing { index });
}
if current
.trade_date
.signed_duration_since(first_covered)
.num_days()
< 0
|| last_covered
.signed_duration_since(current.trade_date)
.num_days()
< 0
{
return Err(StaticSessionExceptionsError::RecordOutsideCoverage { index });
}
if let RecordState::ReplaceSessions(blocks) = current.state
&& let Err(error) = validate_blocks(index, blocks)
{
return Err(error);
}
index += 1;
}
Ok(Self {
source,
coverage: ExceptionCoverage {
first: first_covered,
last: last_covered,
},
records,
})
}
#[must_use]
pub const fn source(self) -> CalendarSource {
self.source
}
#[must_use]
pub const fn coverage(self) -> ExceptionCoverage {
self.coverage
}
#[must_use]
pub fn record_on(self, trade_date: NaiveDate) -> Option<SessionExceptionRecord<'a>> {
self.records
.binary_search_by_key(&trade_date, |record| record.trade_date)
.ok()
.and_then(|index| self.records.get(index).copied())
}
#[must_use]
pub fn exception_on(self, trade_date: NaiveDate) -> DateException<'a> {
if !self.coverage.contains(trade_date) {
return DateException::OutOfCoverage;
}
self.record_on(trade_date).map_or(
DateException::KnownNormal,
SessionExceptionRecord::exception,
)
}
#[must_use]
pub const fn records(self) -> &'a [SessionExceptionRecord<'a>] {
self.records
}
}
const fn validate_blocks(
index: usize,
blocks: &[ExceptionBlock],
) -> Result<(), StaticSessionExceptionsError> {
match first_block_violation(blocks) {
None => Ok(()),
Some(BlockViolation::Empty) => {
Err(StaticSessionExceptionsError::EmptyReplacement { index })
}
Some(BlockViolation::OffsetOutOfRange {
block,
open_day_offset,
}) => Err(StaticSessionExceptionsError::BlockOffsetOutOfRange {
index,
block,
open_day_offset,
}),
Some(BlockViolation::OpenOutOfRange { block, open_ssm }) => {
Err(StaticSessionExceptionsError::BlockOpenOutOfRange {
index,
block,
open_ssm,
})
}
Some(BlockViolation::CloseOutOfRange { block, close_ssm }) => {
Err(StaticSessionExceptionsError::BlockCloseOutOfRange {
index,
block,
close_ssm,
})
}
Some(BlockViolation::ClosesAfterTradeDate { block }) => {
Err(StaticSessionExceptionsError::BlockClosesAfterTradeDate { index, block })
}
Some(BlockViolation::NotOrdered { block }) => {
Err(StaticSessionExceptionsError::BlocksNotOrdered { index, block })
}
}
}
impl SessionExceptionSource for StaticSessionExceptions<'_> {
fn source(&self) -> CalendarSource {
StaticSessionExceptions::source(*self)
}
fn coverage(&self) -> Option<ExceptionCoverage> {
Some(StaticSessionExceptions::coverage(*self))
}
fn exception_on(&self, trade_date: NaiveDate) -> DateException<'_> {
StaticSessionExceptions::exception_on(*self, trade_date)
}
fn may_affect(&self, first: NaiveDate, last: NaiveDate) -> bool {
let start = self
.records
.partition_point(|record| record.trade_date < first);
self.records
.get(start)
.is_some_and(|record| record.trade_date <= last)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaticSessionExceptionsError {
CoverageBoundsInverted,
DatesNotStrictlyIncreasing {
index: usize,
},
RecordOutsideCoverage {
index: usize,
},
EmptyReplacement {
index: usize,
},
BlockOffsetOutOfRange {
index: usize,
block: usize,
open_day_offset: i8,
},
BlockOpenOutOfRange {
index: usize,
block: usize,
open_ssm: u32,
},
BlockCloseOutOfRange {
index: usize,
block: usize,
close_ssm: u32,
},
BlockClosesAfterTradeDate {
index: usize,
block: usize,
},
BlocksNotOrdered {
index: usize,
block: usize,
},
}
impl core::fmt::Display for StaticSessionExceptionsError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::CoverageBoundsInverted => {
write!(f, "last covered trade date precedes the first")
}
Self::DatesNotStrictlyIncreasing { index } => write!(
f,
"record at index {index} is not later than its predecessor"
),
Self::RecordOutsideCoverage { index } => write!(
f,
"record at index {index} falls outside the published coverage window"
),
Self::EmptyReplacement { index } => write!(
f,
"replacement record at index {index} carries no blocks; record it as closed"
),
Self::BlockOffsetOutOfRange {
index,
block,
open_day_offset,
} => write!(
f,
"block {block} of record {index} has open_day_offset {open_day_offset} outside {}..={}",
ExceptionBlock::MIN_DAY_OFFSET,
ExceptionBlock::MAX_DAY_OFFSET
),
Self::BlockOpenOutOfRange {
index,
block,
open_ssm,
} => write!(
f,
"block {block} of record {index} has open_ssm {open_ssm} outside 0..86400"
),
Self::BlockCloseOutOfRange {
index,
block,
close_ssm,
} => write!(
f,
"block {block} of record {index} has close_ssm {close_ssm} outside 0..=86400"
),
Self::BlockClosesAfterTradeDate { index, block } => write!(
f,
"block {block} of record {index} opens on its trade date and closes on the next local date"
),
Self::BlocksNotOrdered { index, block } => write!(
f,
"block {block} of record {index} starts before its predecessor"
),
}
}
}
impl std::error::Error for StaticSessionExceptionsError {}