diff --git a/piker/brokers/ib/api.py b/piker/brokers/ib/api.py index be2a11cf..806a2ef6 100644 --- a/piker/brokers/ib/api.py +++ b/piker/brokers/ib/api.py @@ -99,6 +99,7 @@ from .symbols import ( ) from ...log import get_logger from .venues import ( + DEFAULT_HISTORY_TZ, is_expired, is_venue_open, sesh_times, @@ -672,7 +673,7 @@ class Client: await self.ib.reqContractDetailsAsync(contract) )[0] # convert to makt-native tz - tz: str = details.timeZoneId or 'EST' + tz: str = details.timeZoneId or DEFAULT_HISTORY_TZ end_dt = end_dt.in_tz(tz) first_dt: DateTime = from_timestamp(first).in_tz(tz) last_dt: DateTime = from_timestamp(last).in_tz(tz) diff --git a/piker/brokers/ib/venues.py b/piker/brokers/ib/venues.py index 7c529978..e54b7b59 100644 --- a/piker/brokers/ib/venues.py +++ b/piker/brokers/ib/venues.py @@ -22,6 +22,7 @@ by ICE and friends. ''' from __future__ import annotations +import dataclasses from datetime import ( # noqa datetime, date, @@ -50,6 +51,7 @@ from pendulum import ( from piker.log import get_logger log = get_logger(__name__) +DEFAULT_HISTORY_TZ: str = 'EST' if TYPE_CHECKING: from ib_async import ( @@ -138,8 +140,12 @@ def is_expired( con_deats: ContractDetails, ) -> bool: ''' - Simple predicate whether the provided contract-deats match and - already lifetime-terminated instrument. + Simple predicate for whether the provided contract details + describe an already-expired instrument. + + Return True only after the expiry date has passed in the venue's + timezone. Use EST when IB omits the timezone. A contract with no + reported expiry date returns False. ''' expiry_str: str = con_deats.realExpirationDate @@ -147,7 +153,8 @@ def is_expired( return False expiry_dt: datetime = parse(expiry_str) - return expiry_dt.date() >= now().date() + tz: str = con_deats.timeZoneId or DEFAULT_HISTORY_TZ + return expiry_dt.date() < now(tz).date() def has_weekend( @@ -176,7 +183,7 @@ def has_holiday( is contained in a known "cash hours" closure. ''' - tz: str = con_deats.timeZoneId + tz: str = con_deats.timeZoneId or DEFAULT_HISTORY_TZ con: Contract = con_deats.contract exch: str = ( con.primaryExchange @@ -266,6 +273,12 @@ def iter_sessions( `ibas.ContractDetails.tradingSessions() -> TradingSession`s. ''' + if not con_deats.timeZoneId: + con_deats = dataclasses.replace( + con_deats, + timeZoneId=DEFAULT_HISTORY_TZ, + ) + sesh: TradingSession for sesh in con_deats.tradingSessions(): yield Interval(*sesh) @@ -344,7 +357,7 @@ def is_venue_closure( open, close = maybe_oc # ensure times are in mkt-native timezone - tz: str = con_deats.timeZoneId + tz: str = con_deats.timeZoneId or DEFAULT_HISTORY_TZ start = gap.start.in_tz(tz) start_t = start.time() end = gap.end.in_tz(tz) diff --git a/tests/providers/test_ib_schedule.py b/tests/providers/test_ib_schedule.py index 88553aec..ce39f732 100644 --- a/tests/providers/test_ib_schedule.py +++ b/tests/providers/test_ib_schedule.py @@ -23,8 +23,14 @@ from datetime import UTC, datetime from types import SimpleNamespace from zoneinfo import ZoneInfo +from ib_async import ( + Contract, + ContractDetails, +) +import pendulum import pytest +from piker.brokers.ib import venues from piker.brokers.ib.venues import normalize_schedule from piker.brokers.ib.api import Client @@ -361,3 +367,104 @@ def test_schedule_retry_shares_timeout( assert timeouts == [0.01] assert calls == 2 assert cancelled + + +@pytest.mark.parametrize( + ('expiry', 'expired'), + [ + pytest.param('20261126', True, id='already-expired'), + pytest.param('20261127', False, id='expires-today'), + pytest.param('20261128', False, id='future-expiry'), + pytest.param('', False, id='unspecified-expiry'), + ], +) +def test_expiry_uses_the_trading_date( + expiry: str, + expired: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + ''' + Check ``venues.is_expired()`` against the venue's trading date. + + - The reversed comparison treated future expiries as expired. + At 01:00 UTC on Nov 28, New York is still on Nov 27. + - Only the Nov 26 expiry has passed. Nov 27 remains eligible + until local midnight. Later and unspecified expiries also pass. + + ''' + def fixed_now(tz: str = 'UTC') -> pendulum.DateTime: + ''' + Express the fixed UTC instant in the requested timezone. + + ''' + return pendulum.datetime(2026, 11, 28, 1, tz='UTC').in_tz(tz) + + monkeypatch.setattr(venues, 'now', fixed_now) + details: ContractDetails = ContractDetails( + timeZoneId='America/New_York', + realExpirationDate=expiry, + ) + assert venues.is_expired(details) is expired + + +def test_session_times_with_missing_timezone() -> None: + ''' + Parse IB trading hours when ``ContractDetails.timeZoneId`` is ''. + + - ``ContractDetails.tradingSessions()`` read the empty zone from + the broker record even after history selected its EST fallback. + - A 09:30 to 13:00 EST session spans 14:30 to 18:00 UTC. + Check both instants and the local times history receives. + - The caller's record must retain the original empty zone. + + ''' + details: ContractDetails = ContractDetails( + tradingHours='20261127:0930-20261127:1300', + ) + session: pendulum.Interval + (session,) = venues.iter_sessions(details) + utc_open: datetime = datetime(2026, 11, 27, 14, 30, tzinfo=UTC) + assert session.start == utc_open + assert session.end == datetime(2026, 11, 27, 18, tzinfo=UTC) + + opened: pendulum.Time + closed: pendulum.Time + opened, closed = venues.sesh_times(details) + assert (opened.hour, opened.minute) == (9, 30) + assert (closed.hour, closed.minute) == (13, 0) + assert details.timeZoneId == '' + + +def test_missing_sessions() -> None: + ''' + Report missing IB hours to the caller of ``venues.sesh_times()``. + + With a valid timezone and no trading hours, selecting the first + session used to raise ``StopIteration``. Require the diagnostic + ``ValueError`` so callers can identify missing session data. + + ''' + details: ContractDetails = ContractDetails(timeZoneId='EST') + with pytest.raises(ValueError, match='no trading-session info'): + venues.sesh_times(details) + + +@pytest.mark.parametrize('exchange', ['IDEALPRO', 'PAXOS']) +def test_unmapped_venue_calendar(exchange: str) -> None: + ''' + Keep an unknown calendar from establishing a holiday closure. + + ``exchange_calendars.get_calendar()`` raises + ``InvalidCalendarName`` for these venues. Check that + ``venues.has_holiday()`` returns False for both. + + ''' + details: ContractDetails = ContractDetails( + contract=Contract(exchange=exchange), + ) + start: pendulum.DateTime = pendulum.datetime(2026, 11, 27) + gap: pendulum.Interval = pendulum.interval( + start, + start.add(hours=1), + ) + assert venues.has_holiday(details, gap) is False