WebSocket (Zerodha/Angel One) disconnects randomly. How do I handle reconnect and keep the stream alive ?

Asked by Sejpalsinh Jadeja · SOLVED
1 reply 1,464 views Jump to solution Reply
Sejpalsinh Jadeja Original Post
AlgoDelta Team

I’m running a live trading algo using WebSocket ticks, but sometimes the connection drops suddenly.

After that, no data comes and the algo just hangs.

Error Message: “Socket Error 1006 connection was closed uncleanly”

Posted Apr 24
Reply

    1 Reply

    Support AlgoDelta
    Support AlgoDelta AlgoDelta Support ·

    Yeah, this will happen in WebSocket because we have to send the heartbeat (ping) or reconnect logic.

    You need 2 things:

    Heartbeat (to detect dead connection)

    Auto-reconnect logic

    Below is the sample code you can refer:

    import time
    import threading
    
    last_tick_time = time.time()
    RECONNECT_TIMEOUT = 5  # seconds
    
    def on_tick(tick):
        global last_tick_time
        last_tick_time = time.time()
        print("Tick:", tick)
    
    def start_socket():
        print("Starting WebSocket...")
        # Actuall broket connect code
        # ws.connect()
    
    def stop_socket():
        print("Stopping WebSocket...")
        # Actual close
        # ws.close()
    
    def reconnect():
        print("Reconnecting...")
        stop_socket()
        time.sleep(1)
        start_socket()
    
    def heartbeat_checker():
        while True:
            time.sleep(1)
            if time.time() - last_tick_time > RECONNECT_TIMEOUT:
                print("No ticks received. Connection seems dead.")
                reconnect()
    
    # Start everything
    start_socket()
    
    threading.Thread(target=heartbeat_checker, daemon=True).start()
    
    # Simulated tick loop
    while True:
        time.sleep(2)
        on_tick({"price": 100})

    Since, websocket are not 100 percent reliabile we need the heartbit or reconnect logic.

    Verified Solution
    • Appreciate your response. I tried the solution provided above and it worked perfectly. Thanks. – Sejpalsinh Jadeja Team Jun 16
    Markdown supported · ```json for code blocks · paste or drop screenshots

    Be specific and kind. Never share API keys, passwords or personal account details.

    Welcome to the community

    Log in or create your account in under a minute.

    1. 1Mobile
    2. 2E-mail
    3. 3Password
    +91

    Have a password?

    By continuing you agree to the community guidelines. We’ll send a one-time code by SMS.