kws.connect() Not connecting.

Hi Team,

I have tried to connect kws.connect(). i am first time using. so, When i try to call kws.connect(). It is not responding.

Could any one help me to connect.
  • sujith
    You will not receive a response like HTTP API call. You need to set callback on_connect and then call connect. You can refer to the Websocket API usage here.
  • Kiran_Podgu
    from kiteconnect import KiteConnect
    from kiteconnect import KiteConnect, KiteTicker
    import json
    import time
    import pandas as pd

    def load_api_keys():
    with open('Zerodha credentials.json', 'r') as file:
    config = json.load(file)
    api_key = config['api_key']
    api_secret = config['api_secret']
    return api_key, api_secret
    except FileNotFoundError:
    "Config file not found. Please create a 'config.json' file with your API key and API secret."
    except KeyError as e:
    print(f"Config file is missing the key: {e}")
    api_key, api_secret = load_api_keys()
    kite = KiteConnect(api_key=api_key)
    request_token_url = kite.login_url()
    data = kite.generate_session(request_token, api_secret)
    if 'access_token' in data:
    access_token = data['access_token']
    def on_ticks(ws, ticks):
    if not ticks:
    print("No response from Kite for data.")
    for tick in ticks:
    if tick['instrument_type'] == 'NFO':
    print("NFO Stock Tick Data:", tick)
    with open('tick_data.json', 'a') as file:
    json.dump(tick, file)
    file.write('\n') # Add a new line after each tick
    print("No tick data received from the API or Kite server.")
    if not ticks and "Connection closed: 1006" in str(ws):
    print("Connection is closed because the market is closed.")
    def on_connect(ws, response):
    ws = KiteTicker(api_key, access_token)
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect

    while True:
    print("Connecting to WebSocket...")
    print("WebSocket connection successful.")
    break # Exit the loop if connection is successful
    except Exception as e:
    print("Error connecting to WebSocket:", e)
    print("Retrying in 5 seconds...")
    time.sleep(5) # Retry after 5 seconds

    while True:
    print("Waiting for ticks...")
    except KeyboardInterrupt:
    # Close the WebSocket connection when interrupted
    print("WebSocket connection closed.")

    Here is my complete syntax. but i am not getting the tick information and it is not getting printed on the terminal. Can you please help. i am thinking the information is not getting from kite.
  • Kiran_Podgu
    Is this syntax is correct which pasted.

    ws = websocket.WebSocketApp("wss://", on_message=on_message)

    If no, What changes i need to make.
Sign In or Register to comment.