Principle:51bitquant Ai hedge fund crypto Threaded Async Bridge
| Knowledge Sources | |
|---|---|
| Domains | Concurrency, Real_Time_Streaming |
| Last Updated | 2026-10-28 14:00 GMT |
Overview
A concurrency pattern that runs an asyncio event loop inside a background thread so synchronous (blocking) application code can drive async I/O — such as websocket streams — through simple callback registrations.
Description
Python's `asyncio` is single-threaded by design, but many trading and backtest entry points are synchronous. The threaded-async bridge runs a dedicated worker thread whose `run()` calls `loop.run_until_complete(socket_listener())`, creating the async clients and idling while sockets are active. Callers from the main thread register a stream by passing a callback; the manager creates the socket, marks it running in a `_socket_running` dict, and schedules a listener task on the loop. The listener awaits `recv()` and invokes the callback (sync or async, via `asyncio.iscoroutinefunction`) for each message. Stopping is cooperative: individual sockets are flagged off; a final `stop()` also tears down the async client with a bounded timeout so the thread cannot hang. This keeps the async API's ergonomics while presenting a blocking-friendly facade.
Usage
Use this pattern when the application entry point is synchronous (a script, a notebook, a non-async framework) but needs continuous websocket data. Subclass the base, override `_before_socket_listener_start` to initialize the async manager, and add `start_*` methods that build sockets and call `start_listener`. Avoid sharing un-protected state between the worker thread and the main thread.
Theoretical Basis
The bridge is an isomorphism between the sync and async domains:
Failed to parse (syntax error): {\displaystyle \text{Thread}.\text{run}() \mapsto \text{loop}.\text{run\_until\_complete}(\text{listener}) }
Failed to parse (syntax error): {\displaystyle \text{register}(\text{callback}, \text{socket}) \mapsto \text{loop}.\text{create\_task}(\text{listen}(\text{socket}, \text{callback})) }
with a cooperative stop via a shared liveness flag .
Pseudo-code logic:
# Abstract algorithm (NOT real implementation)
def run(self):
self.loop.run_until_complete(self.listener())
async def listener(self):
self.client = await AsyncClient.create()
while self._running or self._sockets:
await asyncio.sleep(0.2)
async def start_listener(self, socket, callback):
async with socket as s:
while running[path]:
msg = await wait_for(s.recv(), 3)
await callback(msg) if iscoro else callback(msg)