Facing an issue while subscribing for instrument tokens using KiteTicker

KrishHriday
Hello Zerodha Team,

I am facing an issue while subscribing for instrument tokens using KiteTicker. The WebSocket connection succeeds, but the subscription step fails with the following error:

ERROR - Error subscribing to remaining batch 1: close reason without close code

✅ Setup

Python version: 3.7

OS / Environment: Windows 11, running inside VS Code with stable Wi-Fi

API: Kite Connect with paid subscription for live ticks

Access Token: Freshly generated daily, profile fetch works fine

✅ WebSocket Connection

The connection is successful, and the on_connect callback fires with response:

{
"peer": "tcp4:35.154.231.162:443",
"headers": {
"date": "Mon, 08 Sep 2025 10:08:42 GMT",
"connection": "upgrade",
"upgrade": "websocket",
"sec-websocket-accept": "MQ/6rUZw92nuchdiE7p34tl8REw="
},
"version": 18,
"protocol": null,
"extensions": []
}

✅ Code Snippets

on_connect

def on_connect(self, ws, response):
self.is_connected = True
logging.info("WebSocket connected successfully")


on_close

def on_close(self, ws, code, reason):
"""Callback on websocket close"""
logging.error(f"Connection closed: {code} - {reason}")
self.is_connected = False
try:
ws.stop()
except Exception as e:
logging.error(f"Error stopping websocket: {e}")


on_error

def on_error(self, ws, exception):
"""Callback on websocket error"""
logging.error(f"WebSocket error: {exception}", exc_info=True)


Subscription

def subscribe_remaining_tokens(self, delay_seconds=1):
def delayed_subscribe():
time.sleep(delay_seconds)
if not self.is_connected or not self.ticker:
logging.error("Cannot subscribe - connection lost")
return

all_tokens = [int(t) for t in self.instrument_tokens.values()]
remaining_tokens = all_tokens[self.initial_count:]
batch_size = 2

for i in range(0, len(remaining_tokens), batch_size):
batch = remaining_tokens[i:i+batch_size]
try:
logging.info(f"Subscribing to batch {i // batch_size + 1}")
self.ticker.subscribe(batch)
time.sleep(2)
self.ticker.set_mode(self.ticker.MODE_QUOTE, batch)
time.sleep(2)
except Exception as e:
logging.error(f"Error subscribing to batch {i}: {e}", exc_info=True)
time.sleep(5)
threading.Thread(target=delayed_subscribe, daemon=True)
thread.start()
logging.info(f"Scheduled subscription of remaining tokens in {delay_seconds} seconds")


I have also tried subscribing directly inside on_connect using ws.subscribe() and ws.set_mode(), but the issue persists.

✅ What I’ve Checked

Tokens are valid (retrieved from instruments dump and cast to integers)

Access token is correct (profile fetch works fine)

Added delays before subscribing (1–3 seconds)

Tried batch sizes of 2-10 tokens

❌ Issue

Whenever I attempt to subscribe, the connection closes with:

Connection error: 1006 - connection was closed uncleanly (close reason without close code)

❓ Request for Guidance

Could you please help me understand:

The correct approach to subscribe to a large set of tokens (recommended batch size / delay).

Whether this error suggests invalid tokens, timing issue, or server-side rejection.

If there are restrictions on subscription order or maximum tokens per batch.

Thank you in advance for your support.

Best regards,
Krishna
  • Nivas
    The correct approach to subscribe to a large set of tokens (recommended batch size / delay).

    If there are restrictions on subscription order or maximum tokens per batch.
    You may refer to the documentation to know the limits.
    Whether this error suggests invalid tokens, timing issue, or server-side rejection.
    There is no issue with WebSockets at our end. You can initially subscribe to the tokens via the on_connect method. You may refer to the sample code here. Further, you may refer to this thread for a similar discussion regarding subscribe/unsubscribe.
Sign In or Register to comment.