โœ–

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

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

  • Author
    Posts
    • ๐Ÿ“ Question Details

      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”

    • 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.

Viewing 1 reply thread
×

Start a Discussion

Get help from the AlgoDelta community.

×

Welcome Back!

Enter your email to sign in or create an account. No passwords needed.

โณ

Pending Approval

โš ๏ธ

Delete This?

Are you sure you want to delete this? This action is permanent and cannot be undone.

Scroll to Top