Subscribe to instrument tokens
Subscribe inside on_connect, using tokens from your watchlist (chapter 35) — never a hardcoded list, and never before the connection is live.
from watchlist import Watchlist
wl = Watchlist()
def on_connect(ws, response):
tokens = wl.tokens()
ws.subscribe(tokens)
ws.set_mode(ws.MODE_FULL, tokens) # or MODE_LTP / MODE_QUOTE
print(f"Subscribed to {len(tokens)} instruments")
kws.on_connect = on_connect
kws.connect(threaded=True)
Three subscription modes — pick the cheapest one that works
| Mode | Payload | Use for |
|---|---|---|
MODE_LTP | price only | Simple price-triggered logic, max instrument count |
MODE_QUOTE | price + OHLC + volume | Most signal logic |
MODE_FULL | + 5-level depth + OI | Slippage estimation, F&O OI tracking |
MODE_FULL uses significantly more bandwidth per tick — don't default to it for a 500-instrument watchlist if you only need LTP for most of them. Mix modes per instrument if needed:
ws.set_mode(ws.MODE_FULL, high_priority_tokens)
ws.set_mode(ws.MODE_LTP, rest_of_watchlist_tokens)
Resubscribing after reconnect
Every reconnect (chapter 40) triggers on_connect again — since subscriptions live in on_connect, they're automatically reapplied. This is why subscription logic belongs there and not in a one-time setup function called before connect().
Unsubscribing
ws.unsubscribe([token_to_remove])
Use this when a strategy exits a position and no longer needs live prices for that instrument — trimming the watchlist keeps tick volume (and your processing load) proportional to what you actually need.