Reconnect logic and connection health

Network blips, broker-side maintenance, and daily token expiry all drop your WebSocket connection eventually. A live bot must detect this and recover without human intervention — or fail loudly enough that a human is alerted.

Built-in auto-reconnect

KiteTicker has built-in reconnection with exponential backoff:

kws = KiteTicker(API_KEY, access_token)
kws.enable_reconnect = True          # default True in recent SDK versions
kws.reconnect_max_delay = 60
kws.reconnect_max_tries = 300
kws.connect(threaded=True)

This handles transient drops automatically — your on_connect callback re-fires and resubscribes (chapter 37) when it succeeds.

What auto-reconnect does NOT handle: expired access token

If the drop is caused by your daily access token expiring (chapter 10), reconnect attempts will keep failing with an auth error, retrying forever against a token that will never become valid again until you re-authenticate. Detect this explicitly:

reconnect_failures = 0

def on_close(ws, code, reason):
    global reconnect_failures
    reconnect_failures += 1
    if reconnect_failures > 5:
        send_alert(f"WebSocket repeatedly failing to reconnect: {reason}")
        # trigger re-auth flow or halt trading — do not let it spin silently

def on_connect(ws, response):
    global reconnect_failures
    reconnect_failures = 0   # reset on success

Staleness detection — a connection can be "open" but silent

A subtler failure: the WebSocket reports connected, but no ticks have arrived for an instrument that should be actively trading. Track last-tick timestamps per token and alert on staleness:

import time
last_tick_time = {}

def on_ticks(ws, ticks):
    for t in ticks:
        last_tick_time[t["instrument_token"]] = time.time()

def check_staleness(max_age_seconds=30):
    now = time.time()
    for token, ts in last_tick_time.items():
        if now - ts > max_age_seconds:
            send_alert(f"No ticks for {token} in {now - ts:.0f}s — possible feed issue")

Run check_staleness() on a periodic timer (chapter 92 covers heartbeat patterns) — never assume "connected" means "data is flowing."

Next: 041 — Buffer ticks for downstream processing