use chrono::{DateTime, Datelike, Duration, NaiveDate, Timelike, Utc, Weekday};
use super::gate::SourceGate;
use super::schedule::{QueryContext, RuleSet, rules};
use crate::calendar::local_time::mk_local_close;
use crate::calendar::rule::SessionKind;
use crate::calendar::{CalendarSource, Exchange, MarketHoursKey};
const TRADE_DATE_LOOKAHEAD_DAYS: usize = 14;
const SELF_DATED_AFTER: i64 = 1;
const ROLLING_WINDOW_DAYS: i64 = 18;
const DERIVED_BEFORE: i64 = 1;
const DERIVED_AFTER: i64 = 19;
pub(super) fn trade_date_window<G: SourceGate>(
context: &QueryContext<'_, G>,
open_day: NaiveDate,
set: RuleSet,
wraps: bool,
raw_open: DateTime<Utc>,
) -> Option<(NaiveDate, NaiveDate)> {
if assigns_by_close_date(context) && is_self_dated(context, open_day, set, raw_open) {
let after = if !wraps && matches!(set, RuleSet::Sessions(_)) {
0
} else {
SELF_DATED_AFTER
};
return Some((
open_day,
open_day.checked_add_signed(Duration::days(after))?,
));
}
let (before, after) = match context.identity() {
Some(CalendarSource::Exchange(Exchange::SetThailand)) => {
(DERIVED_BEFORE + 1, DERIVED_AFTER)
}
Some(CalendarSource::MarketHoursKey(
MarketHoursKey::GlobexCryptocurrency
| MarketHoursKey::GlobexEventContractsBtc
| MarketHoursKey::GlobexSilver100Oz,
)) => (DERIVED_BEFORE, DERIVED_AFTER + ROLLING_WINDOW_DAYS),
_ => (DERIVED_BEFORE, DERIVED_AFTER),
};
let first = open_day.checked_sub_signed(Duration::days(before))?;
let last = open_day.checked_add_signed(Duration::days(after))?;
Some((first, last))
}
fn assigns_by_close_date<G: SourceGate>(context: &QueryContext<'_, G>) -> bool {
!matches!(
context.identity(),
Some(
CalendarSource::Exchange(Exchange::SetThailand)
| CalendarSource::MarketHoursKey(
MarketHoursKey::GlobexRoughRice
| MarketHoursKey::GlobexCryptocurrency
| MarketHoursKey::GlobexEventContractsBtc
| MarketHoursKey::GlobexSilver100Oz,
)
)
)
}
fn is_self_dated<G: SourceGate>(
context: &QueryContext<'_, G>,
open_day: NaiveDate,
set: RuleSet,
raw_open: DateTime<Utc>,
) -> bool {
matches!(set, RuleSet::Sessions(_)) || a_session_reaches(context, open_day, raw_open)
}
#[inline(never)]
fn a_session_reaches<G: SourceGate>(
context: &QueryContext<'_, G>,
open_day: NaiveDate,
raw_open: DateTime<Utc>,
) -> bool {
let tz = context.tz();
let weekday = open_day.weekday().num_days_from_monday() as usize;
let selected = context.profile_for_open_day(open_day);
for rule in rules(selected.as_ref(), RuleSet::Sessions(SessionKind::Both)) {
if !rule.days[weekday] {
continue;
}
let close_day = if rule.wraps_to_next_day() {
let Some(next) = open_day.succ_opt() else {
continue;
};
next
} else {
open_day
};
if mk_local_close(tz, close_day, rule.close_ssm).with_timezone(&Utc) > raw_open {
return true;
}
}
false
}
pub(super) fn back_dates_trade_dates<G: SourceGate>(context: &QueryContext<'_, G>) -> bool {
matches!(
context.identity(),
Some(CalendarSource::Exchange(Exchange::SetThailand))
)
}
pub(super) fn joins_adjacent_same_kind<G: SourceGate>(context: &QueryContext<'_, G>) -> bool {
matches!(
context.identity(),
Some(CalendarSource::MarketHoursKey(
MarketHoursKey::GlobexCryptocurrency
| MarketHoursKey::GlobexEventContractsBtc
| MarketHoursKey::GlobexSilver100Oz
))
)
}
pub(super) fn assign_normal<G: SourceGate>(
context: &QueryContext<'_, G>,
open: DateTime<Utc>,
close: DateTime<Utc>,
) -> NaiveDate {
let tz = context.tz();
let default = close.with_timezone(&tz).date_naive();
let Some(source) = context.identity() else {
return default;
};
let local_open = open.with_timezone(&tz);
if matches!(source, CalendarSource::Exchange(Exchange::SetThailand)) {
return if local_open.time().num_seconds_from_midnight() < 3 * 3_600 {
local_open.date_naive().pred_opt().unwrap_or(default)
} else {
local_open.date_naive()
};
}
if matches!(
source,
CalendarSource::MarketHoursKey(MarketHoursKey::GlobexRoughRice)
) {
return if local_open.time().num_seconds_from_midnight() >= 19 * 3_600 {
local_open.date_naive().succ_opt().unwrap_or(default)
} else {
default
};
}
if !matches!(
source,
CalendarSource::MarketHoursKey(
MarketHoursKey::GlobexCryptocurrency
| MarketHoursKey::GlobexEventContractsBtc
| MarketHoursKey::GlobexSilver100Oz
)
) {
return default;
}
let days_to_monday = match local_open.weekday() {
Weekday::Fri if local_open.time().num_seconds_from_midnight() >= 16 * 3_600 => 3,
Weekday::Sat => 2,
Weekday::Sun => 1,
_ => 0,
};
let nominal = if days_to_monday == 0 {
default
} else {
local_open
.date_naive()
.checked_add_signed(Duration::days(days_to_monday))
.unwrap_or(default)
};
if !context.has_overlay() || context.has_weekend_close_at(open) {
return nominal;
}
let mut candidate = nominal;
for _ in 0..=TRADE_DATE_LOOKAHEAD_DAYS {
if !matches!(candidate.weekday(), Weekday::Sat | Weekday::Sun)
&& !context.trade_date_is_closed(candidate)
{
return candidate;
}
let Some(next) = candidate.succ_opt() else {
return nominal;
};
candidate = next;
}
nominal
}