Programatically closing the Websocket

karthi289
Hi

I have implemented the following code in python for consuming websocket :
#####
from kiteconnect import KiteTicker
kws = KiteTicker(api_key, access_token)

tick_stock = [t['instrument_token']]
def on_ticks(ws, ticks):
# Callback to receive ticks.
print("Ticks: ",(ticks[0].get("last_price")), ticks[0].get("last_trade_time"))

def on_connect(ws, response):
# Callback on successful connect.
# Subscribe to a list of instrument_tokens (RELIANCE and ACC here).
ws.subscribe(tick_stock)
# Set RELIANCE to tick in `full` mode.
ws.set_mode(ws.MODE_FULL, tick_stock)
time.sleep(30)
ws.unsubscribe(tick_stock)
kws.close()


def on_close(ws, code, reason):
# On connection close stop the main loop
# Reconnection will not happen after executing `ws.stop()`
print("Closing ws connection: ", 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()

#####

Question :
I want to consume the websocket ticks only for the next n seconds (Eg., 20 seconds) and close the connection automatically..

How do I implement the same ?
  • Nivas
    You might find this similar discussion here helpful for understanding how to stop the WebSocket connection. You could consider tweaking it by using a sleep function to close the connection after a few seconds.
Sign In or Register to comment.