Kite websocket disonnection

kiranbvsn
Hi, I want to know how to always try to reconnect to the WebSocket once it got disconnected either due to an issue in API or an internet disconnect, is there any way... I wrote the below code...but it's not working as expected. could you please guide me
def on_close(ws, code, reason): 
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
if current_time > '15:30:01':
ws.stop()
sys.exit()
else:
success = False
while not success:
success = reconnect_to_websocket(kws)
print(success)
if not success:
time.sleep(30)

def reconnect_to_websocket(kws, timeout=30):
start_time = time.time()
feed2 = False
while not feed2:
if check_internet_connection():
kws.connect(threaded=True)
while not kws.is_connected():
if time.time() - start_time > timeout:
# indicate the failure to connect to the WebSocket
return False
time.sleep(1)
feed2 = True
else:
time.sleep(5)
return True

Any help is greatly appreciated.




  • kiranbvsn
    I just want to keep on trying till the websocket connection has been estabilished
  • sujith
    sujith edited February 2023
    You don't have to do it. pykiteconnect does it for you. You just need to enable reconnect here.
    PS: Default reconnect_max_tries attempt is 50. You can assign an increased value if you feel the disconnection time could be more on your end. The code comment here explains more.
  • kiranbvsn
    yes, thank you @sujith, I modified the code, few questions,
    1. Even if it says the default is 50, If I change the default to the maximum allowed (300), it still works correctly?
    2. Also I've tested if the default value is exhausted and no reconnect hits, still if I try to make the kws.connect() in the same code (after a certain time).. it still connects and subscriptions are still valid.
    Note: I've tested at my side by disconnecting the wifi

    Now, my point is if Zerodha from their side resets the WebSocket..due to some API issue..how can I check now, if the tokens are still subscribed. for example, what will ticks return if I reconnect the WebSocket again without getting the actual data?
  • rakeshr
    Even if it says the default is 50, If I change the default to the maximum allowed (300), it still works correctly?
    Yes
    if I try to make the kws.connect() in the same code (after a certain time)
    Are you adding a sleep condition here? As, once you initiate kws.connect() in the main thread, it's an infinite loop.
  • kiranbvsn
    kiranbvsn edited February 2023
    Thank you @rakeshr and @sujith, the issue is resolved
This discussion has been closed.