piker/tests/test_sampling_tick_times.py

168 lines
5.3 KiB
Python

# piker: trading gear for hackers Copyright (C) 2018-present Tyler
# Goodlet (in stewardship of pikers)
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public
# License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
'''
Startup backlog admission without changing current-slot sampling.
'''
from types import SimpleNamespace
import numpy as np
import pytest
import trio
from piker.data import _sampling
from piker.brokers.ib import _util as ib_util
@pytest.mark.parametrize('scale', [
1, 1000, 1_000_000, 1_000_000_000,
])
def test_trade_time_units(scale: int) -> None:
'''
Normalize epoch units without interpreting provider semantics.
'''
assert ib_util.trade_time_s({
'time': 1_790_360_484 * scale,
}) == 1_790_360_484.
@pytest.mark.parametrize('raw', [None, True, float('nan'), -1])
def test_missing_trade_time(raw: object) -> None:
'''
Invalid stamps leave the existing receipt-time path available.
'''
assert ib_util.trade_time_s({'time': raw}) is None
@pytest.mark.parametrize('broker', ['ib', 'other'])
@pytest.mark.parametrize('bar_offset', [-1., 0., 1.])
def test_startup_admission_preserves_write_before_notify(
monkeypatch: pytest.MonkeyPatch,
broker: str,
bar_offset: float,
) -> None:
'''
Exclude IB startup backlog without imposing event-time placement.
``31c0a366`` waited for the sampler's row label to match tick
timestamps during steady state, blocking quote delivery.
Its rounded comparisons also misclassified half-second ticks.
Feed old queued packets, a packet exactly at consumption startup,
then later data including the observed .5589051 offset and an old
stamp after startup has ended. Hold the row labels fixed, ahead
of or behind packet time. Require zero waits and both SHM writes
completed before each subscriber notification. Non-IB timestamps
must not be interpreted as local packet receipt time at all.
This is explicitly a startup exclusion policy, not proof of exact
deduplication against provider history or event-time OHLC parity.
'''
start_s: float = 1_793_717_591.
dtype = [(name, 'f8') for name in (
'time', 'open', 'high', 'low', 'close', 'volume',
)]
rt = np.array([
(start_s + bar_offset, 100., 100., 100., 100., 0.),
], dtype=dtype)
hist = rt.copy()
stamps: list[float|None] = [
start_s - 5.,
start_s - .01,
start_s,
start_s + .5589051,
start_s + 2.,
start_s - 5.,
None,
]
sizes: list[float] = [12013., 99., 2., 3., 4., 5., 1.]
expected: list[float] = []
accumulated: float = 0.
for index, size in enumerate(sizes):
if broker != 'ib' or index >= 2:
accumulated += size
expected.append(accumulated)
delivered: list[dict] = []
async def notify(message: dict) -> None:
'''
Read both SHM buffers at the notification boundary.
'''
index: int = len(delivered)
assert rt['volume'][-1] == expected[index]
assert hist['volume'][-1] == expected[index]
if broker != 'ib' or index >= 2:
assert rt['close'][-1] == hist['close'][-1]
assert rt['close'][-1] == (101. + index)
delivered.append(message)
async def forbidden_wait(delay: float) -> None:
'''
Fail if trade admission waits for the sampler clock.
'''
pytest.fail(f'Timestamp admission waited {delay}s')
clock = SimpleNamespace(
time_ns=lambda: int(start_s * 1_000_000_000),
)
monkeypatch.setattr(
ib_util, 'time',
clock,
)
monkeypatch.setattr(_sampling.trio, 'sleep', forbidden_wait)
sub = SimpleNamespace(
throttle_rate=0.,
ipc=SimpleNamespace(send=notify),
)
bus = SimpleNamespace(get_subs=lambda _: [sub])
async def replay() -> None:
'''
Drain a finite input through the production sampler/fanout.
'''
tx, rx = trio.open_memory_channel(len(stamps))
async with tx, rx:
for index, stamp in enumerate(stamps):
tx.send_nowait({'asset.venue': {
'ticks': [{
'type': 'trade',
'time': stamp,
'price': 101. + index,
'size': sizes[index],
}],
}})
await tx.aclose()
with trio.fail_after(1):
await _sampling.sample_and_broadcast(
bus=bus,
rt_shm=SimpleNamespace(array=rt),
hist_shm=SimpleNamespace(array=hist),
quote_stream=rx,
brokername=broker,
)
trio.run(replay)
assert len(delivered) == len(stamps)
assert rt['time'][-1] == start_s + bar_offset