How to close and connect the websocket purposely

Dileep
Hi .. Any one kindly help me.. In between the market hours i want to close and connect to the websocket. Below is the sample code.
def on_ticks(ws,ticks):
//Some logic
kws.close()
time.sleep(1)
kws.connect()

def on_connect(ws, response):
ws.subscribe(Tokens)
ws.set_mode(ws.MODE_FULL,Tokens)

kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.connect()

But sometimes in between i am getting the error as "429 - TooManyRequests". How to avoid this error. Is there is any way to cleanly close the connection?
Thanks in advance.
  • sujith
    You can call this method to close the Websocket connection.
  • Dileep

    Hi @sujith thanks for the response. PFA. Is this is the correct way.Please guide me if i need to modify anything.
  • Dileep
    Hi @sujith @rakeshr after implementing above code still getting the error as
    kiteconnect.ticker - ERROR - Connection error: 1006 - connection was closed uncleanly (WebSocket closing handshake timeout (peer did not finish the opening handshake in time))
    Can you advise me to close the connection gracefully.
  • ANL
    ANL edited September 10
    I cant understand why you put kws.stop() , kws.conect() inside on_ticks() ?
    Don't put any tick calculations inside on_ticks() it will block your ticks if you do that.

    try this:
    def on_close(ws, code, reason):
    ws.stop()


    Include this thread when connecting with the kite ticker , kws.connect(threaded=True) instead of just kws.connect()
Sign In or Register to comment.