Bound Asynchronous Work Inside a Strategy Callback
A strategy callback runs on a hot path. Every tick that arrives wants attention, and anything you await inside that callback holds the loop's attention until it returns. If you let an unbounded coroutine sit there, one slow operation stalls everything behind it. This post is a practical follow-up to Reducing Latency in a Trading Bot. That post covered where latency comes from. This one is narrower: how to put hard bounds on async work inside a single callback so a slow path fails fast instead of piling up.
The callback we are talking about is on_market_tick(self, market, tick, ctx), with an optional on_start(ctx). It is a coroutine. Prices on the tick are Decimal values; bid and ask can be absent, and the timestamp is a datetime. Keep that in mind: the examples below use Decimal deliberately, because Python's decimal module supports exact decimal representation and a user-alterable precision, which matters when you compare prices and compute sizes.
Why an unbounded await is a problem
Picture a callback that does some bookkeeping, then awaits a coroutine with no upper bound on how long it can take. If that coroutine hangs, the callback never returns. Ticks keep arriving. Depending on how the runtime schedules them, you either queue work you can never catch up on, or you process stale data long after it mattered. Either way, the decision you eventually make is based on a price that has moved.
The fix is a deadline. Decide the maximum time a piece of work is allowed to run, enforce it, and have a defined behavior when the deadline passes. That is the whole discipline: bound the work, bound the wait, and handle the timeout path on purpose.
Two primitives: wait_for and timeout
Python's asyncio gives you two clean ways to apply a deadline. asyncio.wait_for(aw, timeout) waits for a single awaitable to complete, and if a timeout occurs it cancels the awaitable and raises TimeoutError.
The newer option is the asyncio.timeout(delay) context manager, added in Python 3.11. It returns an asynchronous context manager that limits the time spent waiting on whatever runs inside the block. When the deadline passes it cancels the current task, and the context manager converts that internal cancellation into a TimeoutError. One important detail from the docs: that TimeoutError can only be caught outside the context manager, not inside it. Timeout context managers can also be safely nested, which is useful when an outer budget wraps several inner steps.
A subtle gotcha the docs are explicit about: asyncio.wait_for is a coroutine, not a plain function like create_task. It does not start executing until you await it. If you build two wait_for objects and await them one after another, they run in sequence, not concurrently.
A standalone, labeled example
The snippet below is a conceptual, standalone example. It is NOT a tested Banger integration and does not claim any specific external call is supported by a hosted sandbox. It shows the shape of a bounded callback: a short synchronous decision, an optional bounded async step, and an explicit timeout branch. Treat the compute_signal coroutine as a placeholder for local work you control, not as an arbitrary network call. The tick field names below (bid, ask) match the documented tick interface; substitute the actual field for whatever the runtime delivers.
import asyncio
from decimal import Decimal
# Conceptual example only. Not executed, not a hosted integration.
# on_market_tick(self, market, tick, ctx) is the callback signature.
# tick.bid and tick.ask are Decimal values and may be absent.
MAX_WORK_SECONDS = 0.05 # 50 ms budget, chosen for illustration
async def on_market_tick(self, market, tick, ctx):
# 1) Cheap, synchronous guard first. Quotes may be absent.
if tick.bid is None:
return
price = tick.bid # a Decimal
# 2) Bound any async step with an explicit deadline.
try:
async with asyncio.timeout(MAX_WORK_SECONDS):
score = await compute_signal(price) # local work you control
except TimeoutError:
# Deadline passed. The inner task was cancelled.
# Do nothing this tick rather than act on stale work.
return
# 3) Only now, outside the timeout block, decide.
if score > Decimal("0"):
# Placement is a separate, deliberate call. Omitted here.
passThe equivalent with the older primitive is await asyncio.wait_for(compute_signal(price), timeout=MAX_WORK_SECONDS) wrapped in the same try/except TimeoutError. Pick whichever matches your Python version. The behavior you care about is identical: on timeout, the inner awaitable is cancelled and you take the timeout branch.
Cancellation is not optional cleanup
When a timeout fires, cancellation propagates into the awaitable as a CancelledError. If your bounded work holds a resource, acquired a lock, or started a partial write, the cancellation point is where that half-done state lives. Two rules keep this sane:
- Make bounded work idempotent or trivially abandonable, so a cancelled run leaves nothing you have to reconcile on the next tick.
- Do not swallow CancelledError inside the bounded block. Let it propagate so the timeout actually takes effect. Catch TimeoutError outside the block, as the asyncio docs require.
Backpressure: the bound you cannot skip
Timeouts bound one callback invocation. Backpressure bounds the relationship between arrival rate and processing rate across many invocations. If ticks arrive faster than your callback drains them, a per-call timeout alone does not save you, because you can still fall behind by starting fresh work on every tick while older work is still in flight.
A simple, honest pattern is a single-slot guard: if a previous bounded job is still running, drop or coalesce the new tick instead of launching a second one. In prediction markets the freshest tick is usually the one worth acting on, so coalescing to the latest price is often the right default.
# Conceptual sketch of backpressure via a single in-flight slot.
# self._busy is a bool initialized in on_start.
async def on_market_tick(self, market, tick, ctx):
if self._busy:
return # drop this tick; a job is already running
self._busy = True
try:
async with asyncio.timeout(MAX_WORK_SECONDS):
await compute_signal(tick.bid)
except TimeoutError:
return
finally:
self._busy = FalseThe trade-off is explicit: you drop ticks under load rather than queue unbounded work. That is a feature. An unbounded queue just moves the failure somewhere less visible.
Where Banger fits, and what it does not promise
Banger is a paper-research runtime for prediction-market strategies. You write a Python strategy or clone one, and run it in paper mode against current market data without venue keys. Public live deployments are blocked in the current beta. A paper result is evidence under a particular data, fill, fee, and valuation model, not proof of real venue execution. The patterns above are about keeping your callback responsive; they do not change what a paper fill represents, and they do not imply any external call is available inside a hosted sandbox. If a capability is not in the current docs, assume it is not shipped and omit it.
If you want to experiment, keep the bounded work local and deterministic so your paper runs stay reproducible against a selected market ticker. For the exact current callback contract and runtime behavior, read the primary source: the Banger docs. You can also explore paper research by signing up at /sign-up. No fills, returns, or venue execution are promised here.