Handle LTP-mode ticks

def on_ticks(ws, ticks):
    for tick in ticks:
        print(tick["instrument_token"], tick["last_price"])

kws.on_ticks = on_ticks

MODE_LTP tick shape:

{
  "tradable": True,
  "mode": "ltp",
  "instrument_token": 408065,
  "last_price": 1478.9,
}

on_ticks fires on the WebSocket thread — keep it fast

on_ticks runs inside the ticker's background thread. Anything slow in here (a database write, a network call, heavy computation) delays processing of subsequent ticks, and under threaded=True can cause the internal receive buffer to back up. The correct pattern: do the minimum in on_ticks (update an in-memory cache, push to a queue) and process on a separate consumer thread/loop.

import queue

tick_queue = queue.Queue()

def on_ticks(ws, ticks):
    for tick in ticks:
        tick_queue.put_nowait(tick)   # non-blocking, never do work here directly

def consumer_loop():
    while True:
        tick = tick_queue.get()
        # actual signal logic goes here, on a different thread
        process_tick(tick)

Common bug: mutating shared state without a lock

If your consumer thread and, say, an order-management thread both touch a shared "current positions" dict, guard it with a threading.Lock — a tick handler firing hundreds of times a second against unsynchronized shared state is a classic source of intermittent, hard-to-reproduce bugs.

import threading
state_lock = threading.Lock()

def update_price_cache(token, price):
    with state_lock:
        price_cache[token] = price

Next: 039 — Handle full-mode ticks (depth, OI)