Connect to the WebSocket ticker
REST polling (ltp(), quote()) is fine for occasional checks but too slow and rate-limited for reacting to every tick. Kite's KiteTicker streams live prices over a persistent WebSocket connection.
from kiteconnect import KiteTicker
from config import API_KEY
kws = KiteTicker(API_KEY, access_token)
def on_connect(ws, response):
print("Connected")
def on_close(ws, code, reason):
print("Closed:", code, reason)
def on_error(ws, code, reason):
print("Error:", code, reason)
kws.on_connect = on_connect
kws.on_close = on_close
kws.on_error = on_error
kws.connect(threaded=True) # non-blocking, runs in a background thread
threaded=True is essential for any bot that also needs to do other work (place orders, run signal logic) on the main thread — without it, connect() blocks forever.
Connection lifecycle callbacks you should always wire up
on_connect— subscribe to your watchlist tokens here (chapter 37), not at import time — a fresh connection has no subscriptions yet.on_close— log it; if this fires unexpectedly during market hours, your bot has gone blind and needs to reconnect (chapter 40).on_error— log the code/reason; some are recoverable (transient network), others mean your access token expired and no amount of reconnecting will fix it without re-auth (chapter 10).
One ticker connection, not one per instrument
A single KiteTicker connection handles up to 3000 instrument subscriptions (check current docs for the exact cap) — never open multiple WebSocket connections to work around this; you'll hit per-account connection limits instead.