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.
  • Gjain75
    is there a way the socket can be closed in console?
  • rakeshr
    For python client, you can use stop callback to disconnect the WebSocket connection.
  • DD1365


    I have been using the above logic (last 4 lines, the last line, 'raise SystemExit' is what I use, you guys can write whatever you need) to disconnect the WebSocket connection successfully. The given logic has an advantage over the kws.on_close call, let me share that from my experience:

    If the on_close function is defined in your code then if anytime due to any reason connection is lost or interrupted due to network issues then the on_close call gets triggered and Websocket will stop running. Instead if you use the above logic to close the WebSocket connection then your connection also gets closes neatly and also if ever there is network interruption then the WebSocket will keep waiting till network connection is re-established and your code will not break.

    If any clarification is required, feel free to drop me a mail at: [email protected] / [email protected]
  • confused_investor
    import logging
    from kiteconnect import KiteTicker


    logging.basicConfig(level=logging.DEBUG)

    with open('api_key.csv', 'r') as file:
    api_key_um = file.read()
    with open('access_token.csv', 'r') as file:
    access_token_um = file.read()

    # Initialise
    kws = KiteTicker(api_key, access_token)

    count = 0
    tokens = [256265]


    def on_ticks(ws, ticks):
    logging.info("Ticks: {}".format(ticks))
    global count
    count += 1
    print(count)
    if count > 5:
    kws.close()

    def on_connect(ws, response):
    ws.subscribe(tokens)
    ws.set_mode(ws.MODE_LTP, tokens)

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

    # 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()


    This my code and I get the following error
    INFO:root:Ticks: [{'tradable': False, 'mode': 'ltp', 'instrument_token': 256265, 'last_price': 18367.8}]
    1
    INFO:root:Ticks: [{'tradable': False, 'mode': 'ltp', 'instrument_token': 256265, 'last_price': 18368.95}]
    2
    INFO:root:Ticks: [{'tradable': False, 'mode': 'ltp', 'instrument_token': 256265, 'last_price': 18368.3}]
    3
    INFO:root:Ticks: [{'tradable': False, 'mode': 'ltp', 'instrument_token': 256265, 'last_price': 18368.15}]
    4
    INFO:root:Ticks: [{'tradable': False, 'mode': 'ltp', 'instrument_token': 256265, 'last_price': 18368.2}]
    5
    INFO:root:Ticks: [{'tradable': False, 'mode': 'ltp', 'instrument_token': 256265, 'last_price': 18368.05}]
    6
    ERROR:kiteconnect.ticker:Connection closed: None - None


    Why am I getting error?
Sign In or Register to comment.