Reuse persistent feeds by resolved market endpoint
A chart could open a dated IB future through search, detach, then request its continuous alias against the same datad. Lookup by the request spelling missed the existing feed and tried to allocate a second history writer on its SHM. Failed startup could leave the quote producer running without a sampler to drain its channel. Resolve metadata before allocation and key `_FeedsBus.feeds` only by canonical, broker-qualified FQME. Recheck under the allocation lock and return the existing `Flume` without starting another producer. Require `get_mkt_info()` rather than trying provisional quote subscriptions to discover endpoint identity. Split the decision/lifetime from allocation: - `maybe_allocate_persistent_feed()` resolves/reuses, or opens a feed-local `trio` nursery for a new endpoint; - `allocate_persistent_feed()` starts quote/history children and returns the descriptor, writable buffers and sampling inputs; - the `maybe_` parent publishes and starts back the `Flume`, then handles readiness, buffer seeding and the blocking sampler call; - cancel/join the local children when that operating body exits, including normal sampler return and failed history startup. Preserve startup ordering, explain task/scope ownership, qualify request-name logging and configure the shared data logger itself. This is lifetime cleanup, not independent restart supervision. Human verified the alias reopen fix and found full Binance boots with/without the patch felt comparable on AC; no latency benchmark or startup-speedup claim is implied. Regression suites are retained for a separate test commit. (this patch was generated in some part by `opencode` using `openai/gpt-6-astra` (`openai`))wkt/land_datad_names
parent
cd1235128d
commit
3289c26030
|
|
@ -39,6 +39,7 @@ from typing import (
|
||||||
Any,
|
Any,
|
||||||
AsyncContextManager,
|
AsyncContextManager,
|
||||||
Awaitable,
|
Awaitable,
|
||||||
|
Callable,
|
||||||
Sequence,
|
Sequence,
|
||||||
TYPE_CHECKING,
|
TYPE_CHECKING,
|
||||||
)
|
)
|
||||||
|
|
@ -82,6 +83,7 @@ from ._sampling import (
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from .flows import Flume
|
from .flows import Flume
|
||||||
from tractor.discovery._addr import Address
|
from tractor.discovery._addr import Address
|
||||||
|
from tractor.ipc._shm import ShmArray
|
||||||
from tractor.msg.types import Aid
|
from tractor.msg.types import Aid
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -128,7 +130,10 @@ class _FeedsBus(Struct):
|
||||||
'''
|
'''
|
||||||
brokername: str
|
brokername: str
|
||||||
nursery: trio.Nursery
|
nursery: trio.Nursery
|
||||||
feeds: dict[str, tuple[dict, dict]] = {}
|
# `_FeedsBus.feeds` holds one descriptor per resolved,
|
||||||
|
# broker-qualified market endpoint. Request aliases belong to
|
||||||
|
# provider resolution, not this registry.
|
||||||
|
feeds: dict[str, Flume] = {}
|
||||||
|
|
||||||
task_lock: trio.StrictFIFOLock = trio.StrictFIFOLock()
|
task_lock: trio.StrictFIFOLock = trio.StrictFIFOLock()
|
||||||
|
|
||||||
|
|
@ -233,11 +238,13 @@ def get_feed_bus(
|
||||||
)
|
)
|
||||||
assert not _bus.feeds
|
assert not _bus.feeds
|
||||||
|
|
||||||
assert _bus.brokername == brokername, "Uhhh wtf"
|
assert _bus.brokername == brokername, (
|
||||||
|
f'Uhhh wtf, mismatched `_FeedBus.brokername != {brokername!r}'
|
||||||
|
)
|
||||||
return _bus
|
return _bus
|
||||||
|
|
||||||
|
|
||||||
async def allocate_persistent_feed(
|
async def maybe_allocate_persistent_feed(
|
||||||
bus: _FeedsBus,
|
bus: _FeedsBus,
|
||||||
sub_registered: trio.Event,
|
sub_registered: trio.Event,
|
||||||
|
|
||||||
|
|
@ -247,36 +254,257 @@ async def allocate_persistent_feed(
|
||||||
start_stream: bool = True,
|
start_stream: bool = True,
|
||||||
init_timeout: float = 616,
|
init_timeout: float = 616,
|
||||||
|
|
||||||
task_status: TaskStatus[FeedInit] = trio.TASK_STATUS_IGNORED,
|
task_status: TaskStatus[Flume] = trio.TASK_STATUS_IGNORED,
|
||||||
|
|
||||||
) -> None:
|
) -> None:
|
||||||
'''
|
'''
|
||||||
Create and maintain a "feed bus" which allocates tasks for real-time
|
Allocate or reuse a data feed, deliver a `Flume` handle.
|
||||||
streaming and optional historical data storage per broker/data provider
|
|
||||||
backend; this normally task runs *in* a `datad` actor.
|
|
||||||
|
|
||||||
If none exists, this allocates a ``_FeedsBus`` which manages the
|
- The caller holds ``_FeedsBus.task_lock`` until startup
|
||||||
lifetimes of streaming tasks created for each requested symbol.
|
completes.
|
||||||
|
- Require provider metadata via `get_mkt_info()` before
|
||||||
|
quote/history task starts.
|
||||||
|
- Report an existing ``Flume`` immediately, without opening a
|
||||||
|
nursery or quote subscription for that endpoint.
|
||||||
|
- Otherwise await ``allocate_persistent_feed()`` for its allocated
|
||||||
|
state, report startup, and run sampling in this parent task.
|
||||||
|
|
||||||
|
task/scope architecture::
|
||||||
|
|
||||||
2 tasks are created:
|
{> _FeedsBus.nursery
|
||||||
- a real-time streaming task which connec
|
|_>( maybe_allocate_persistent_feed [parent task]
|
||||||
|
>> resolve endpoint; check _FeedsBus.feeds
|
||||||
|
>> reuse: started(flume), then return
|
||||||
|
>{ tn [new endpoint only]
|
||||||
|
|_>> await allocate_persistent_feed [same task]
|
||||||
|
|_>( mod.stream_quotes [child task] )
|
||||||
|
|_>( manage_history [child task] )
|
||||||
|
>> return allocated state
|
||||||
|
>> publish Flume; started(flume)
|
||||||
|
>> await live/subscriber readiness
|
||||||
|
>> await sample_and_broadcast [same task]
|
||||||
|
>c} finally: cancel tn children, nursery exit
|
||||||
|
>) maybe_allocate_persistent_feed exit
|
||||||
|
|
||||||
|
sclang-syntax:
|
||||||
|
(> task-start
|
||||||
|
{> scope-open
|
||||||
|
>> in-task work.
|
||||||
|
|
||||||
|
``tn`` owns all children, errors propagate to
|
||||||
|
`_FeedsBus.nursery`; (currently) no restart supervision is
|
||||||
|
provided.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
# load backend module
|
# load backend module
|
||||||
|
mod: ModuleType
|
||||||
try:
|
try:
|
||||||
mod = get_brokermod(brokername)
|
mod = get_brokermod(brokername)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
mod = get_ingestormod(brokername)
|
mod = get_ingestormod(brokername)
|
||||||
|
|
||||||
|
# Prefer resolving before opening a quote subscription: some
|
||||||
|
# backends share one subscription for aliases of a contract,
|
||||||
|
# so opening and then cancelling a duplicate can disturb it.
|
||||||
|
# Native details stay opaque here; only `MktPair` identity
|
||||||
|
# participates in the `_FeedsBus.feeds` lookup.
|
||||||
|
get_mkt_info: Callable[
|
||||||
|
[str],
|
||||||
|
Awaitable[tuple[MktPair, object]|None],
|
||||||
|
]|None = getattr(
|
||||||
|
mod,
|
||||||
|
'get_mkt_info',
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if get_mkt_info is None:
|
||||||
|
raise NotImplementedError(
|
||||||
|
f'{brokername!r} must expose get_mkt_info() before '
|
||||||
|
f'allocating a persistent feed for {symstr!r}'
|
||||||
|
)
|
||||||
|
|
||||||
|
# Providers own metadata caching. In this datad process,
|
||||||
|
# `piker.brokers.ib.symbols.get_mkt_info()` is decorated with
|
||||||
|
# `async_lifo_cache()`, keyed by request spelling, so its
|
||||||
|
# later streaming call can reuse this result. Distinct
|
||||||
|
# aliases can still require a lookup each. This is in-memory
|
||||||
|
# caching, not persistent `SymbologyCache` support or a
|
||||||
|
# guarantee about other providers' caches.
|
||||||
|
with trio.fail_after(init_timeout):
|
||||||
|
resolved: tuple[MktPair, object]|None = (
|
||||||
|
await get_mkt_info(symstr)
|
||||||
|
)
|
||||||
|
|
||||||
|
if resolved is None:
|
||||||
|
raise ValueError(
|
||||||
|
f'{brokername!r} returned no market metadata for {symstr!r}'
|
||||||
|
)
|
||||||
|
|
||||||
|
mkt: MktPair
|
||||||
|
_provider_details: object
|
||||||
|
mkt, _provider_details = resolved
|
||||||
|
fqme: str = mkt.fqme
|
||||||
|
existing_flume: Flume|None = bus.feeds.get(fqme)
|
||||||
|
if existing_flume is not None:
|
||||||
|
log.info(f'Reusing feed for alias {symstr!r} -> {fqme!r}')
|
||||||
|
task_status.started(existing_flume)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Only a new endpoint needs operating tasks. Own its quote/history
|
||||||
|
# children here so failed startup cannot leave a producer in
|
||||||
|
# `bus.nursery` without a sampler. The allocating parent runs
|
||||||
|
# sampling until completion/cancellation; this is lifetime
|
||||||
|
# ownership, not failure containment or restart supervision.
|
||||||
|
tn: trio.Nursery
|
||||||
|
async with (
|
||||||
|
trionics.collapse_eg(),
|
||||||
|
trio.open_nursery() as tn,
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
flume: Flume
|
||||||
|
rt_shm: ShmArray
|
||||||
|
hist_shm: ShmArray
|
||||||
|
quote_stream: trio.MemoryReceiveChannel[dict]
|
||||||
|
feed_is_live: trio.Event
|
||||||
|
sum_tick_vlm: bool
|
||||||
|
(
|
||||||
|
flume,
|
||||||
|
rt_shm,
|
||||||
|
hist_shm,
|
||||||
|
quote_stream,
|
||||||
|
feed_is_live,
|
||||||
|
sum_tick_vlm,
|
||||||
|
) = await allocate_persistent_feed(
|
||||||
|
tn=tn,
|
||||||
|
mod=mod,
|
||||||
|
mkt=mkt,
|
||||||
|
symstr=symstr,
|
||||||
|
loglevel=loglevel,
|
||||||
|
init_timeout=init_timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
# `_FeedsBus.feeds` registers only resolved endpoints.
|
||||||
|
# Publish after allocation, while `bus.task_lock` is
|
||||||
|
# still held by the caller awaiting our startup result.
|
||||||
|
bus.feeds[fqme] = flume
|
||||||
|
|
||||||
|
# signal the ``open_feed_bus()`` caller task to continue
|
||||||
|
# since we now have (some) history pushed to SHM.
|
||||||
|
task_status.started(flume)
|
||||||
|
|
||||||
|
if not start_stream:
|
||||||
|
await trio.sleep_forever()
|
||||||
|
|
||||||
|
# begin real-time updates of shm and tsdb once the feed
|
||||||
|
# goes live; the backend indicates quotes have begun.
|
||||||
|
await feed_is_live.wait()
|
||||||
|
|
||||||
|
# NOTE: if no high-freq sampled data has (yet) loaded,
|
||||||
|
# seed the buffer with history - handy for backends
|
||||||
|
# without 1s OHLC but with slower data such as 1m OHLC.
|
||||||
|
if (
|
||||||
|
not len(rt_shm.array)
|
||||||
|
and
|
||||||
|
hist_shm.array.size
|
||||||
|
):
|
||||||
|
rt_shm.push(hist_shm.array[-3:-1])
|
||||||
|
ohlckeys: list[str] = ['open', 'high', 'low', 'close']
|
||||||
|
rt_shm.array[ohlckeys][-2:] = (
|
||||||
|
hist_shm.array['close'][-1]
|
||||||
|
)
|
||||||
|
rt_shm.array['volume'][-2:] = 0
|
||||||
|
|
||||||
|
# set fast buffer time step to 1s
|
||||||
|
ts: int = round(time.time())
|
||||||
|
rt_shm.array['time'][0] = ts
|
||||||
|
rt_shm.array['time'][1] = ts + 1
|
||||||
|
|
||||||
|
elif hist_shm.array.size == 0:
|
||||||
|
i: int
|
||||||
|
for i in range(100):
|
||||||
|
await trio.sleep(0.1)
|
||||||
|
if hist_shm.array.size > 0:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
await tractor.pause()
|
||||||
|
raise RuntimeError(
|
||||||
|
f'History (1m) Shm for {fqme} is empty!?'
|
||||||
|
)
|
||||||
|
|
||||||
|
# wait for the spawning caller to register its
|
||||||
|
# subscriber send-stream entry before sampling.
|
||||||
|
await sub_registered.wait()
|
||||||
|
|
||||||
|
# Run OHLC sampling/broadcasting in this parent task.
|
||||||
|
# `manage_history()` registers the separate incrementer.
|
||||||
|
try:
|
||||||
|
log.info(f'Starting sampler task for {fqme}')
|
||||||
|
await sample_and_broadcast(
|
||||||
|
bus=bus,
|
||||||
|
rt_shm=rt_shm,
|
||||||
|
hist_shm=hist_shm,
|
||||||
|
quote_stream=quote_stream,
|
||||||
|
brokername=brokername,
|
||||||
|
sum_tick_vlm=sum_tick_vlm,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
log.warning(f'{fqme} feed task terminated')
|
||||||
|
finally:
|
||||||
|
# on sampler return we stop the quote/history siblings
|
||||||
|
# too: nursery exit alone would wait forever.
|
||||||
|
tn.cancel_scope.cancel()
|
||||||
|
|
||||||
|
|
||||||
|
async def allocate_persistent_feed(
|
||||||
|
tn: trio.Nursery,
|
||||||
|
mod: ModuleType,
|
||||||
|
mkt: MktPair,
|
||||||
|
symstr: str,
|
||||||
|
loglevel: str,
|
||||||
|
init_timeout: float,
|
||||||
|
) -> tuple[
|
||||||
|
Flume,
|
||||||
|
ShmArray,
|
||||||
|
ShmArray,
|
||||||
|
trio.MemoryReceiveChannel[dict],
|
||||||
|
trio.Event,
|
||||||
|
bool,
|
||||||
|
]:
|
||||||
|
'''
|
||||||
|
Allocate a new endpoint's quote/history tasks and feed descriptor.
|
||||||
|
|
||||||
|
``maybe_allocate_persistent_feed()`` has resolved the endpoint
|
||||||
|
and checked ``_FeedsBus.feeds`` under its allocation lock. It
|
||||||
|
owns ``tn`` and keeps the children alive after this function
|
||||||
|
returns. Return the ``Flume``, writable realtime/history SHM
|
||||||
|
handles, quote receiver, live-readiness event and volume policy.
|
||||||
|
The caller publishes the descriptor, reports startup and runs
|
||||||
|
sampling without reattaching to the original writable buffers.
|
||||||
|
|
||||||
|
Provider ``FeedInit`` supplies quote/write options. Its market
|
||||||
|
endpoint must agree with the metadata resolved before allocation;
|
||||||
|
no reuse decision or fallback subscription is performed here.
|
||||||
|
|
||||||
|
'''
|
||||||
|
|
||||||
# mem chan handed to broker backend so it can push real-time
|
# mem chan handed to broker backend so it can push real-time
|
||||||
# quotes to this task for sampling and history storage (see below).
|
# quotes to this task for sampling and history storage
|
||||||
|
# (see below).
|
||||||
|
send: trio.MemorySendChannel[dict]
|
||||||
|
quote_stream: trio.MemoryReceiveChannel[dict]
|
||||||
send, quote_stream = trio.open_memory_channel(616)
|
send, quote_stream = trio.open_memory_channel(616)
|
||||||
|
|
||||||
# data sync signals for both history loading and market quotes
|
# data sync signals for both history loading and market quotes
|
||||||
some_data_ready = trio.Event()
|
some_data_ready = trio.Event()
|
||||||
feed_is_live = trio.Event()
|
feed_is_live = trio.Event()
|
||||||
|
|
||||||
|
# Feed operating tasks:
|
||||||
|
# - `mod.stream_quotes()` runs as a child of `tn` and supplies
|
||||||
|
# realtime quotes through `quote_stream`.
|
||||||
|
# - `manage_history()` runs as another child of `tn`, loading
|
||||||
|
# history and maintaining configured storage backends.
|
||||||
|
# - The caller awaits `sample_and_broadcast()` after allocation
|
||||||
|
# to consume quotes, update SHM and broadcast to subscribers.
|
||||||
|
#
|
||||||
# establish broker backend quote stream by calling
|
# establish broker backend quote stream by calling
|
||||||
# ``stream_quotes()``, a required broker backend endpoint.
|
# ``stream_quotes()``, a required broker backend endpoint.
|
||||||
init_msgs: (
|
init_msgs: (
|
||||||
|
|
@ -291,66 +519,80 @@ async def allocate_persistent_feed(
|
||||||
(
|
(
|
||||||
init_msgs,
|
init_msgs,
|
||||||
first_quote,
|
first_quote,
|
||||||
) = await bus.nursery.start(
|
) = await tn.start(
|
||||||
partial(
|
partial(
|
||||||
mod.stream_quotes,
|
mod.stream_quotes,
|
||||||
send_chan=send,
|
send_chan=send,
|
||||||
feed_is_live=feed_is_live,
|
feed_is_live=feed_is_live,
|
||||||
|
|
||||||
# NOTE / TODO: eventualy we may support providing more then
|
# NOTE / TODO: eventualy we may support providing
|
||||||
# one input here such that a datad daemon can multiplex
|
# more then one input here such that a datad daemon
|
||||||
# multiple live feeds from one task, instead of getting
|
# can multiplex multiple live feeds from one task,
|
||||||
# a new request (and thus new task) for each subscription.
|
# instead of getting a new request (and thus new
|
||||||
|
# task) for each subscription.
|
||||||
symbols=[symstr],
|
symbols=[symstr],
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
# TODO: this is indexed by symbol for now since we've planned (for
|
# TODO: this is indexed by symbol for now since we've planned
|
||||||
# some time) to expect backends to handle single
|
# (for some time) to expect backends to handle single
|
||||||
# ``.stream_quotes()`` calls with multiple symbols inputs to just
|
# ``.stream_quotes()`` calls with multiple symbols inputs to just
|
||||||
# work such that a backend can do its own multiplexing if desired.
|
# work such that a backend can do its own multiplexing if
|
||||||
|
# desired.
|
||||||
#
|
#
|
||||||
# Likely this will require some design changes:
|
# Likely this will require some design changes:
|
||||||
# - the .started() should return some config output determining
|
# - the .started() should return some config output determining
|
||||||
# whether the backend does indeed multiplex multi-symbol quotes
|
# whether the backend does indeed multiplex multi-symbol quotes
|
||||||
# internally or whether separate task spawns should be done per
|
# internally or whether separate task spawns should be done per
|
||||||
# symbol (as it is right now).
|
# symbol (as it is right now).
|
||||||
# - information about discovery of non-local host daemons which can
|
# - information about discovery of non-local host daemons which
|
||||||
# be contacted in the case where we want to support load disti
|
# can be contacted in the case where we want to support load
|
||||||
# over multi-use clusters; eg. some new feed request is
|
# disti over multi-use clusters; eg. some new feed request is
|
||||||
# re-directed to another daemon cluster because the current one is
|
# re-directed to another daemon cluster because the current
|
||||||
# at max capacity.
|
# one is at max capacity.
|
||||||
# - the same ideas ^ but when a local core is maxxed out (like how
|
# - the same ideas ^ but when a local core is maxxed out (like
|
||||||
# binance does often with hft XD
|
# how binance does often with hft XD
|
||||||
# - if a datad is non-local then we can't just allocate a mem
|
# - if a datad is non-local then we can't just allocate a mem
|
||||||
# channel here and have the datad write it, we instead need
|
# channel here and have the datad write it, we instead need
|
||||||
# a small streaming machine around the remote feed which can then
|
# a small streaming machine around the remote feed which can
|
||||||
# do the normal work of sampling and writing shm buffers
|
# then do the normal work of sampling and writing shm buffers
|
||||||
# (depending on if we want sampling done on the far end or not?)
|
# (depending on if we want sampling done on the far end or
|
||||||
|
# not?)
|
||||||
init: FeedInit = validate_backend(
|
init: FeedInit = validate_backend(
|
||||||
mod,
|
mod,
|
||||||
[symstr],
|
[symstr],
|
||||||
init_msgs, # NOTE: only 1 should be delivered for now..
|
init_msgs, # NOTE: only 1 should be delivered for now..
|
||||||
)
|
)
|
||||||
mkt: MktPair = init.mkt_info
|
|
||||||
fqme: str = mkt.fqme
|
fqme: str = mkt.fqme
|
||||||
|
startup_fqme: str = init.mkt_info.fqme
|
||||||
|
if startup_fqme != fqme:
|
||||||
|
raise ValueError(
|
||||||
|
f'Quote startup endpoint {startup_fqme!r} differs from '
|
||||||
|
f'resolved endpoint {fqme!r}'
|
||||||
|
)
|
||||||
|
|
||||||
# HISTORY storage, run 2 tasks:
|
# Await the history startup handshake for its SHM handles.
|
||||||
# - a history loader / maintainer
|
# `tn.start_soon()` would not return those handles or propagate
|
||||||
# - a real-time streamer which consumers and sends new data to any
|
# a startup failure directly to this awaiter.
|
||||||
# consumers as well as writes to storage backends (as configured).
|
#
|
||||||
|
# Historical service-nursery startup hang:
|
||||||
# XXX: neither of these will raise but will cause an inf hang due to:
|
|
||||||
# https://github.com/python-trio/trio/issues/2258
|
# https://github.com/python-trio/trio/issues/2258
|
||||||
# bus.nursery.start_soon(
|
# Starting into `bus.nursery` from outside its cancellation
|
||||||
# await bus.start_task(
|
# scope can leave startup waiting for a sibling which failed.
|
||||||
|
# Here we start into local `tn` from inside its scope, so its
|
||||||
|
# cancellation reaches this pending startup too. Do not replace
|
||||||
|
# this with `bus.start_task()` without revisiting that ownership.
|
||||||
|
|
||||||
|
izero_hist: int
|
||||||
|
hist_shm: ShmArray
|
||||||
|
izero_rt: int
|
||||||
|
rt_shm: ShmArray
|
||||||
(
|
(
|
||||||
izero_hist,
|
izero_hist,
|
||||||
hist_shm,
|
hist_shm,
|
||||||
izero_rt,
|
izero_rt,
|
||||||
rt_shm,
|
rt_shm,
|
||||||
) = await bus.nursery.start(
|
) = await tn.start(
|
||||||
partial(
|
partial(
|
||||||
manage_history,
|
manage_history,
|
||||||
mod=mod,
|
mod=mod,
|
||||||
|
|
@ -361,8 +603,7 @@ async def allocate_persistent_feed(
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
# yield back control to starting nursery once we receive either
|
# Return allocation state once history has reported data ready.
|
||||||
# some history or a real-time quote.
|
|
||||||
log.info(
|
log.info(
|
||||||
f'loading OHLCV history: {fqme!r}\n'
|
f'loading OHLCV history: {fqme!r}\n'
|
||||||
)
|
)
|
||||||
|
|
@ -373,8 +614,8 @@ async def allocate_persistent_feed(
|
||||||
flume = Flume(
|
flume = Flume(
|
||||||
|
|
||||||
# TODO: we have to use this for now since currently the
|
# TODO: we have to use this for now since currently the
|
||||||
# MktPair above doesn't render the correct output key it seems
|
# MktPair above doesn't render the correct output key it
|
||||||
# when we provide the `MktInfo` here?..?
|
# seems when we provide the `MktInfo` here?..?
|
||||||
mkt=mkt,
|
mkt=mkt,
|
||||||
|
|
||||||
first_quote=first_quote,
|
first_quote=first_quote,
|
||||||
|
|
@ -388,26 +629,6 @@ async def allocate_persistent_feed(
|
||||||
_has_vlm=init.shm_write_opts['has_vlm'],
|
_has_vlm=init.shm_write_opts['has_vlm'],
|
||||||
)
|
)
|
||||||
|
|
||||||
# for ambiguous names we simply register the
|
|
||||||
# flume for all possible name (sub) sets.
|
|
||||||
# feed to that name (for now).
|
|
||||||
bus.feeds.update({
|
|
||||||
symstr: flume,
|
|
||||||
fqme: flume,
|
|
||||||
mkt.bs_fqme: flume,
|
|
||||||
})
|
|
||||||
|
|
||||||
# signal the ``open_feed_bus()`` caller task to continue since
|
|
||||||
# we now have (some) history pushed to the shm buffer.
|
|
||||||
task_status.started(init)
|
|
||||||
|
|
||||||
if not start_stream:
|
|
||||||
await trio.sleep_forever()
|
|
||||||
|
|
||||||
# begin real-time updates of shm and tsb once the feed goes live and
|
|
||||||
# the backend will indicate when real-time quotes have begun.
|
|
||||||
await feed_is_live.wait()
|
|
||||||
|
|
||||||
# NOTE: if not configured otherwise, we always sum tick volume
|
# NOTE: if not configured otherwise, we always sum tick volume
|
||||||
# values in the OHLCV sampler.
|
# values in the OHLCV sampler.
|
||||||
sum_tick_vlm: bool = True
|
sum_tick_vlm: bool = True
|
||||||
|
|
@ -417,72 +638,43 @@ async def allocate_persistent_feed(
|
||||||
True,
|
True,
|
||||||
)
|
)
|
||||||
|
|
||||||
# NOTE: if no high-freq sampled data has (yet) been loaded,
|
return (
|
||||||
# seed the buffer with a history datum - this is most handy
|
flume,
|
||||||
# for many backends which don't sample @ 1s OHLC but do have
|
rt_shm,
|
||||||
# slower data such as 1m OHLC.
|
hist_shm,
|
||||||
if (
|
quote_stream,
|
||||||
not len(rt_shm.array)
|
feed_is_live,
|
||||||
and hist_shm.array.size
|
sum_tick_vlm,
|
||||||
):
|
)
|
||||||
rt_shm.push(hist_shm.array[-3:-1])
|
|
||||||
ohlckeys = ['open', 'high', 'low', 'close']
|
|
||||||
rt_shm.array[ohlckeys][-2:] = hist_shm.array['close'][-1]
|
|
||||||
rt_shm.array['volume'][-2:] = 0
|
|
||||||
|
|
||||||
# set fast buffer time step to 1s
|
|
||||||
ts = round(time.time())
|
|
||||||
rt_shm.array['time'][0] = ts
|
|
||||||
rt_shm.array['time'][1] = ts + 1
|
|
||||||
|
|
||||||
elif hist_shm.array.size == 0:
|
|
||||||
for i in range(100):
|
|
||||||
await trio.sleep(0.1)
|
|
||||||
if hist_shm.array.size > 0:
|
|
||||||
break
|
|
||||||
else:
|
|
||||||
await tractor.pause()
|
|
||||||
raise RuntimeError(f'History (1m) Shm for {fqme} is empty!?')
|
|
||||||
|
|
||||||
# wait the spawning parent task to register its subscriber
|
|
||||||
# send-stream entry before we start the sample loop.
|
|
||||||
await sub_registered.wait()
|
|
||||||
|
|
||||||
# start sample loop and shm incrementer task for OHLC style sampling
|
|
||||||
# at the above registered step periods.
|
|
||||||
try:
|
|
||||||
log.info(f'Starting sampler task for {fqme}')
|
|
||||||
await sample_and_broadcast(
|
|
||||||
bus,
|
|
||||||
rt_shm,
|
|
||||||
hist_shm,
|
|
||||||
quote_stream,
|
|
||||||
brokername,
|
|
||||||
sum_tick_vlm
|
|
||||||
)
|
|
||||||
finally:
|
|
||||||
log.warning(f'{fqme} feed task terminated')
|
|
||||||
|
|
||||||
|
|
||||||
@tractor.context
|
@tractor.context
|
||||||
async def open_feed_bus(
|
async def open_feed_bus(
|
||||||
ctx: tractor.Context,
|
ctx: tractor.Context,
|
||||||
brokername: str,
|
brokername: str,
|
||||||
symbols: list[str], # normally expected to the broker-specific fqme
|
symbols: list[str], # provider-native requests; see below
|
||||||
|
|
||||||
loglevel: str = 'error',
|
loglevel: str = 'error',
|
||||||
tick_throttle: float | None = None,
|
tick_throttle: float|None = None,
|
||||||
start_stream: bool = True,
|
start_stream: bool = True,
|
||||||
allow_remote_ctl_ui: bool = False,
|
allow_remote_ctl_ui: bool = False,
|
||||||
|
|
||||||
) -> dict[
|
) -> None:
|
||||||
str, # fqme
|
|
||||||
tuple[dict, dict] # pair of dicts of the initmsg and first quotes
|
|
||||||
]:
|
|
||||||
'''
|
'''
|
||||||
Open a data feed "bus": an actor-persistent per-broker task-oriented
|
Open client subscriptions to persistent market endpoint feeds.
|
||||||
data feed registry which allows managing real-time quote streams per
|
|
||||||
symbol.
|
``symbols`` normally contains provider-native names: for IB,
|
||||||
|
``qqq.nasdaq`` or ``mnq.cme.20261218``. Their canonical piker
|
||||||
|
FQMEs include the broker: ``qqq.nasdaq.ib`` and
|
||||||
|
``mnq.cme.20261218.ib``. A continuous request such as ``mnq.cme``
|
||||||
|
must also resolve its expiry before selecting a canonical feed.
|
||||||
|
|
||||||
|
- Look up explicit names in ``_FeedsBus.feeds``. For unresolved
|
||||||
|
names, start the allocator and use its returned ``Flume``.
|
||||||
|
- Serialize allocation with ``_FeedsBus.task_lock`` and register
|
||||||
|
descriptors only under resolved, broker-qualified FQMEs.
|
||||||
|
- On client closure, remove its ``_FeedsBus._subscribers`` entries
|
||||||
|
while the feed writers remain in the service nursery.
|
||||||
|
|
||||||
'''
|
'''
|
||||||
if loglevel is None:
|
if loglevel is None:
|
||||||
|
|
@ -503,7 +695,7 @@ async def open_feed_bus(
|
||||||
# TODO: check for any stale shm entries for this symbol
|
# TODO: check for any stale shm entries for this symbol
|
||||||
# (after we also group them in a nice `/dev/shm/piker/` subdir).
|
# (after we also group them in a nice `/dev/shm/piker/` subdir).
|
||||||
# ensure we are who we think we are
|
# ensure we are who we think we are
|
||||||
servicename = tractor.current_actor().name
|
servicename: str = tractor.current_actor().name
|
||||||
assert 'datad' in servicename
|
assert 'datad' in servicename
|
||||||
assert brokername in servicename
|
assert brokername in servicename
|
||||||
|
|
||||||
|
|
@ -511,44 +703,58 @@ async def open_feed_bus(
|
||||||
sub_registered = trio.Event()
|
sub_registered = trio.Event()
|
||||||
|
|
||||||
flumes: dict[str, Flume] = {}
|
flumes: dict[str, Flume] = {}
|
||||||
|
symbol: str
|
||||||
for symbol in symbols:
|
for symbol in symbols:
|
||||||
|
|
||||||
# if no cached feed for this symbol has been created for this
|
# if no cached feed for this symbol has been created for this
|
||||||
# datad yet, start persistent stream and shm writer task in
|
# datad yet, start persistent stream and shm writer task in
|
||||||
# service nursery
|
# service nursery
|
||||||
flume = bus.feeds.get(symbol)
|
requested_fqme: str = symbol
|
||||||
|
if not symbol.endswith(f'.{brokername}'):
|
||||||
|
requested_fqme = f'{symbol}.{brokername}'
|
||||||
|
|
||||||
|
flume: Flume|None = bus.feeds.get(requested_fqme)
|
||||||
if flume is None:
|
if flume is None:
|
||||||
# allocate a new actor-local stream bus which
|
# allocate a new actor-local stream bus which
|
||||||
# will persist for this `datad`'s service lifetime.
|
# will persist for this `datad`'s service lifetime.
|
||||||
async with bus.task_lock:
|
async with bus.task_lock:
|
||||||
await bus.nursery.start(
|
# Another subscriber may have registered this name
|
||||||
partial(
|
# in `_FeedsBus.feeds` while we waited for the lock.
|
||||||
allocate_persistent_feed,
|
# Re-read it to reuse that feed; allocate only if
|
||||||
|
# the requested endpoint is still absent.
|
||||||
|
flume = bus.feeds.get(requested_fqme)
|
||||||
|
if flume is None:
|
||||||
|
flume = await bus.nursery.start(
|
||||||
|
partial(
|
||||||
|
maybe_allocate_persistent_feed,
|
||||||
|
|
||||||
bus=bus,
|
bus=bus,
|
||||||
sub_registered=sub_registered,
|
sub_registered=sub_registered,
|
||||||
brokername=brokername,
|
brokername=brokername,
|
||||||
# here we pass through the selected symbol in native
|
# here we pass through the selected
|
||||||
# "format" (i.e. upper vs. lowercase depending on
|
# symbol in native "format" (i.e. upper
|
||||||
# provider).
|
# vs. lowercase depending on provider).
|
||||||
symstr=symbol,
|
symstr=symbol,
|
||||||
loglevel=loglevel,
|
loglevel=loglevel,
|
||||||
start_stream=start_stream,
|
start_stream=start_stream,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
|
||||||
# TODO: we can remove this?
|
|
||||||
# assert isinstance(bus.feeds[symbol], tuple)
|
|
||||||
|
|
||||||
# XXX: ``.first_quote`` may be outdated here if this is secondary
|
# XXX: ``.first_quote`` may be outdated here if this is
|
||||||
# subscriber
|
# secondary subscriber
|
||||||
flume: Flume = bus.feeds[symbol]
|
|
||||||
mkt: MktPair = flume.mkt
|
mkt: MktPair = flume.mkt
|
||||||
bs_fqme: str = mkt.bs_fqme
|
bs_fqme: str = mkt.bs_fqme
|
||||||
fqme: str = mkt.fqme
|
fqme: str = mkt.fqme
|
||||||
assert brokername in fqme
|
assert brokername in fqme
|
||||||
|
|
||||||
if mkt.suffix:
|
# TODO: we can remove this?
|
||||||
log.warning(f'{brokername} expanded symbol {symbol} -> {bs_fqme}')
|
# assert isinstance(bus.feeds[fqme], tuple)
|
||||||
|
|
||||||
|
if requested_fqme != fqme:
|
||||||
|
log.warning(
|
||||||
|
f'{brokername!r} expanded symbol '
|
||||||
|
f'{symbol!r} -> {bs_fqme!r}'
|
||||||
|
)
|
||||||
|
|
||||||
# pack for ``.started()`` sync msg
|
# pack for ``.started()`` sync msg
|
||||||
flumes[fqme] = flume
|
flumes[fqme] = flume
|
||||||
|
|
@ -570,6 +776,7 @@ async def open_feed_bus(
|
||||||
await trio.sleep_forever()
|
await trio.sleep_forever()
|
||||||
|
|
||||||
# real-time stream loop
|
# real-time stream loop
|
||||||
|
stream: tractor.MsgStream
|
||||||
async with (
|
async with (
|
||||||
ctx.open_stream(
|
ctx.open_stream(
|
||||||
# NOTE we allow this since it's common to have the live
|
# NOTE we allow this since it's common to have the live
|
||||||
|
|
@ -579,11 +786,13 @@ async def open_feed_bus(
|
||||||
) as stream,
|
) as stream,
|
||||||
):
|
):
|
||||||
|
|
||||||
local_subs: dict[str, set[tuple]] = {}
|
local_subs: dict[str, set[Sub]] = {}
|
||||||
|
fqme: str
|
||||||
|
flume: Flume
|
||||||
for fqme, flume in flumes.items():
|
for fqme, flume in flumes.items():
|
||||||
# re-send to trigger display loop cycle (necessary especially
|
# re-send to trigger display loop cycle (necessary
|
||||||
# when the mkt is closed and no real-time messages are
|
# especially when the mkt is closed and no real-time
|
||||||
# expected).
|
# messages are expected).
|
||||||
await stream.send({fqme: flume.first_quote})
|
await stream.send({fqme: flume.first_quote})
|
||||||
|
|
||||||
# set a common msg stream for all requested symbols
|
# set a common msg stream for all requested symbols
|
||||||
|
|
@ -591,12 +800,12 @@ async def open_feed_bus(
|
||||||
flume.stream = stream
|
flume.stream = stream
|
||||||
|
|
||||||
# Add a real-time quote subscription to feed bus:
|
# Add a real-time quote subscription to feed bus:
|
||||||
# This ``sub`` subscriber entry is added to the feed bus set so
|
# This ``sub`` subscriber entry is added to the feed
|
||||||
# that the ``sample_and_broadcast()`` task (spawned inside
|
# bus set so that the ``sample_and_broadcast()`` task
|
||||||
# ``allocate_persistent_feed()``) will push real-time quote
|
# (spawned inside ``allocate_persistent_feed()``) will
|
||||||
# (ticks) to this new consumer.
|
# push real-time quote (ticks) to this new consumer.
|
||||||
cs: trio.CancelScope | None = None
|
cs: trio.CancelScope|None = None
|
||||||
send: trio.MemorySendChannel | None = None
|
tx: trio.MemorySendChannel|None = None
|
||||||
if tick_throttle:
|
if tick_throttle:
|
||||||
flume.throttle_rate = tick_throttle
|
flume.throttle_rate = tick_throttle
|
||||||
|
|
||||||
|
|
@ -604,10 +813,11 @@ async def open_feed_bus(
|
||||||
# chan and only pushes them to the target
|
# chan and only pushes them to the target
|
||||||
# actor-consumer at a max ``tick_throttle``
|
# actor-consumer at a max ``tick_throttle``
|
||||||
# (instantaneous) rate.
|
# (instantaneous) rate.
|
||||||
send, recv = trio.open_memory_channel(2**10)
|
rx: trio.MemoryReceiveChannel
|
||||||
|
tx, rx = trio.open_memory_channel(2**10)
|
||||||
|
|
||||||
# NOTE: the ``.send`` channel here is a swapped-in
|
# NOTE: ``tx`` is a swapped-in ``trio`` memory
|
||||||
# trio mem chan which gets `.send()`-ed by the normal
|
# channel which gets ``.send()``-ed by the normal
|
||||||
# sampler task but instead of being sent directly
|
# sampler task but instead of being sent directly
|
||||||
# over the IPC msg stream it's the throttle task
|
# over the IPC msg stream it's the throttle task
|
||||||
# does the work of incrementally forwarding to the
|
# does the work of incrementally forwarding to the
|
||||||
|
|
@ -615,21 +825,21 @@ async def open_feed_bus(
|
||||||
cs: trio.CancelScope = await bus.start_task(
|
cs: trio.CancelScope = await bus.start_task(
|
||||||
uniform_rate_send,
|
uniform_rate_send,
|
||||||
tick_throttle,
|
tick_throttle,
|
||||||
recv,
|
rx,
|
||||||
stream,
|
stream,
|
||||||
)
|
)
|
||||||
|
|
||||||
sub = Sub(
|
sub: Sub = Sub(
|
||||||
ipc=stream,
|
ipc=stream,
|
||||||
send_chan=send,
|
send_chan=tx,
|
||||||
throttle_rate=tick_throttle,
|
throttle_rate=tick_throttle,
|
||||||
_throttle_cs=cs,
|
_throttle_cs=cs,
|
||||||
rc_ui=allow_remote_ctl_ui,
|
rc_ui=allow_remote_ctl_ui,
|
||||||
)
|
)
|
||||||
|
|
||||||
# TODO: add an api for this on the bus?
|
# TODO: add an api for this on the bus?
|
||||||
# maybe use the current task-id to key the sub list that's
|
# maybe use the current task-id to key the sub list
|
||||||
# added / removed? Or maybe we can add a general
|
# that's added / removed? Or maybe we can add a general
|
||||||
# pause-resume by sub-key api?
|
# pause-resume by sub-key api?
|
||||||
bs_fqme = fqme.removesuffix(f'.{brokername}')
|
bs_fqme = fqme.removesuffix(f'.{brokername}')
|
||||||
local_subs.setdefault(
|
local_subs.setdefault(
|
||||||
|
|
@ -667,7 +877,8 @@ async def open_feed_bus(
|
||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
finally:
|
finally:
|
||||||
log.info(
|
log.info(
|
||||||
f'Stopping {symbol}.{brokername} feed for {ctx.chan.uid}')
|
f'Stopping {requested_fqme!r} feed for {uid!r}'
|
||||||
|
)
|
||||||
|
|
||||||
if tick_throttle:
|
if tick_throttle:
|
||||||
# TODO: a one-cancels-one nursery
|
# TODO: a one-cancels-one nursery
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue