Buffer ticks for downstream processing

A tick buffer is a queue between a market-data feed and its consumers. The WebSocket callback enqueues updates quickly; a worker builds candles, updates a cache or computes signals. Buffer capacity limits memory, while queue age reveals whether consumers are acting on stale prices.

Chapter 38 introduced pushing ticks to a queue instead of processing inline. This chapter builds that into a proper producer-consumer pipeline, and covers what to do when the consumer falls behind.

import logging, queue, threading, time

class TickBuffer:
    def __init__(self, maxsize: int = 10000):
        self.q = queue.Queue(maxsize=maxsize)
        self.dropped = 0

    def put(self, tick: dict):
        try:
            self.q.put_nowait(tick)
        except queue.Full:
            self.dropped += 1   # never block the WebSocket thread

    def consume_forever(self, handler):
        while True:
            tick = self.q.get()
            try:
                handler(tick)
            except Exception:
                logging.exception("Error processing tick")
            finally:
                self.q.task_done()
buffer = TickBuffer()
kws.on_ticks = lambda ws, ticks: [buffer.put(t) for t in ticks]

consumer_thread = threading.Thread(target=buffer.consume_forever, args=(process_tick,), daemon=True)
consumer_thread.start()

Why bounded queue + drop-on-full, not unbounded

An unbounded queue can exhaust memory when processing stays slower than incoming data. This bounded example drops the new incoming tick when full; it preserves older queued ticks, so it does not guarantee a fresh latest-price view.

For a latest-price display, consider coalescing updates by instrument. For tick-by-tick signals, volume aggregation or OHLC reconstruction, dropped ticks can change the result: record gaps, pause affected calculations and rebuild from an authoritative source where available. Track queue depth, oldest-tick age and drop rate, not only the cumulative counter.

Alert on sustained drops

def check_buffer_health(buffer: TickBuffer, threshold: int = 50):
    if buffer.dropped > threshold:
        send_alert(f"Tick buffer dropped {buffer.dropped} ticks — consumer is falling behind")

Never process ticks synchronously inside strategy logic that also places orders

Keep the tick-consumption thread separate from anything that blocks on network I/O (order placement, chapter 44+) for more than a few milliseconds — otherwise a slow order-placement call delays processing of every subsequent tick behind it in the queue.

Next: 042 — Build an in-memory live price cache