How to Close Web Socket?

babansfolio
@sujith and Team,

Please help to share procedure to close web-socket.
Idea is to introduce auto-close on kite connect post-market hour.

I found following methods, but not working.
==========================================================================
# Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close

def on_close(ws, code, reason):
# On connection close stop the main loop
# Reconnection will not happen after executing `ws.stop()`
ws.stop()

kws.connect()
==========================================================================
  • sujith
    But where are you calling the close method?
  • babansfolio
    babansfolio edited April 2018
    @sujith :

    Close method has been called inside forloop.


    ======================================================================
    from kiteconnect import KiteConnect
    from kiteconnect import KiteTicker

    # Initialise
    kite = KiteConnect(api_key)
    kite.set_access_token(access_token)
    kws = KiteTicker(api_key, access_token)


    def on_ticks(ws, ticks):
    for tick in ticks:
    # want to exit on condition of after 3:30
    ws.close()


    def on_close(ws, code, reason):
    # On connection close stop the main loop
    # Reconnection will not happen after executing `ws.stop()`
    ws.stop()


    # Callback for successful connection.
    def on_connect(ws, response):
    ws.subscribe(token_list)
    ws.set_mode(ws.MODE_FULL, token_list)
    #ws.set_mode(ws.MODE_LTP, tokens)


    # Assign the callbacks.
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close
    # Infinite loop on the main thread. Nothing after this will run.
    # You have to use the pre-defined callbacks to manage subscriptions.
    # kws.connect(threaded=True)
    kws.connect()
    ===============================================================
  • babansfolio
    @sujith : if possible pls help, sample code (except the internal structure of foorloop ) has been shared above.
  • zartimus
    @babansfolio Closing websocket inside for loop is wrong. This is pretty straightforward thing. You can simply compare if datetime is post 3:30, call `ws.close()` inside on_ticks.
  • sachin_verma9
    one solution is to set a flag with your method and when next tick comes, you have access to ws object. Just use ws.stop() then.
Sign In or Register to comment.