Connection error: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (403 -

garvgoyal888
i am getting this error while trying to access market data and i am getting the same error when i run this code https://github.com/zerodha/pykiteconnect/blob/master/examples/ticker.py




import pandas as pd
from kiteconnect import KiteConnect, KiteTicker
from datetime import datetime
import time

# Set your API Key and Access Token
api_key = '3xxxxx'
api_secret = 'jxxxxxxxxxxxxxxxxxxxxxxtr'

# Instantiate KiteConnect
kite = KiteConnect(api_key=api_key)
kite.set_access_token('Dbxxxxxxxxxxxxxx3dE5X')

# Load the tokens from Excel file
tokens_df = pd.read_excel('instrument_tokens.xlsx')
tokens = tokens_df['Token'].tolist()

# Create an empty DataFrame to store live quotes
live_quotes = pd.DataFrame()

def on_ticks(ws, ticks):
global live_quotes
# Append the received ticks to the live_quotes DataFrame
for tick in ticks:
temp_df = pd.DataFrame({'Timestamp': [datetime.now()],
'Token': [tick['instrument_token']],
'Last Price': [tick['last_price']]})
live_quotes = pd.concat([live_quotes, temp_df])
# Set 'Timestamp' as the index and convert it to datetime
live_quotes.set_index('Timestamp', inplace=True)
live_quotes.index = pd.to_datetime(live_quotes.index)

# Resample and aggregate to create OHLC data for different timeframes
ohlc_5m = live_quotes['Last Price'].resample('5T').ohlc()
ohlc_15m = live_quotes['Last Price'].resample('15T').ohlc()
ohlc_1h = live_quotes['Last Price'].resample('1H').ohlc()

# Save to Excel files
ohlc_5m.to_excel('ohlc_5m.xlsx')
ohlc_15m.to_excel('ohlc_15m.xlsx')
ohlc_1h.to_excel('ohlc_1h.xlsx')

def on_connect(ws, response):
print("WebSocket connected: {}".format(response))
ws.subscribe(tokens)

def on_close(ws, code, reason):
print("WebSocket closed: {} - {}".format(code, reason))


def on_error(ws, code, reason):
print("WebSocket error: {} - {}".format(code, reason))

kws = KiteTicker(api_key, kite.access_token)
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
kws.on_error = on_error

try:
kws.connect(threaded=True)
while True:
time.sleep(1) # To keep the main thread alive
except Exception as e:
print("Error: {}".format(e))
  • rakeshr
    403 -
    You are unauthenticated. Go through the websocket streaming FAQs here.
  • garvgoyal888
    garvgoyal888 edited August 2023
    i used the code given here https://github.com/zerodha/pykiteconnect/blob/master/examples/ticker.py and i am sure the access token is right cause the same token is working on buy sell orders. I have tried connecting to websocket using a normal python websocket code and it work so there is no problem on my machine or local envoirment. I even ran the code on diffrent machine and it gives the same error. Please help me out
  • rakeshr
    Can you paste here the complete error stack trace?
  • garvgoyal888
    Connection error: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden))
    Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden)) it gives this error again and agian non stop
  • garvgoyal888
    please provide help
  • sujith
    It seems like your api_key or access_token is wrong. You may add debug logs and check.
  • garvgoyal888
    can you provide me with debug logs and check code ?
  • rakeshr
    You need to set debug=True in the ticker initialization.
  • garvgoyal888
    2023-08-03 10:04:05+0530 [-] Log opened.
    2023-08-03 10:04:05+0530 [-] failing WebSocket opening handshake ('WebSocket connection upgrade failed (403 - Forbidden)')
    2023-08-03 10:04:05+0530 [-] dropping connection to peer tcp4:3.7.118.97:443 with abort=True: WebSocket connection upgrade failed (403 - Forbidden)
    2023-08-03 10:04:05+0530 [-] Connection error: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden))
    2023-08-03 10:04:05+0530 [-] Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden))
    2023-08-03 10:04:05+0530 [-] will retry in 2 seconds
    2023-08-03 10:04:05+0530 [-] Stopping factory
    2023-08-03 10:04:08+0530 [-] Starting factory
  • garvgoyal888
    please help. thanks
  • rakeshr
    upgrade failed (403 - Forbidden))
    This status code only comes for unauthenticated requests. Go through the exceptions documentation.
  • garvgoyal888
    i have checked it throughy. i am sure my api key and access key are correct cause i am taking trades from the same key in other code.
  • rakeshr
    Can you change the end lines of your code to this and try?
    kws = KiteTicker(api_key, kite.access_token)
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close
    kws.on_error = on_error
    kws.connect(threaded=True)

    while True:
    try:
    time.sleep(1) # To keep the main thread alive
    except Exception as e:
    print("Error: {}".format(e))
  • garvgoyal888
    i added it this is my code



    import logging
    import time
    from kiteconnect import KiteTicker

    logging.basicConfig(level=logging.DEBUG)

    api_key = "sdadsadsada"
    access_token = "xxxxxxxxxxxxxxxxxxxxxxxxxx"

    # Initialise
    kws = KiteTicker(api_key, access_token)

    def on_ticks(ws, ticks):
    # Callback to receive live market data.
    logging.debug("Ticks: {}".format(ticks))

    def on_connect(ws, response):
    # Callback on successful connect.
    # Subscribe to a list of instrument_tokens (RELIANCE and ACC here).
    ws.subscribe([738561, 5633])

    # Set RELIANCE to tick in `full` mode.
    ws.set_mode(ws.MODE_FULL, [738561])

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

    def on_error(ws, code, reason):
    # Callback to receive live market data.
    logging.error("Error : {}".format(reason))

    # Assign the callbacks.
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close
    kws.on_error = on_error

    # Connect to the server in threaded mode
    kws.connect(threaded=True)

    # Infinite loop on the main thread. Nothing after this will run.
    while True:
    try:
    time.sleep(1) # To keep the main thread alive
    except KeyboardInterrupt:
    kws.close()
    except Exception as e:
    print("Error: {}".format(e))\






    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden))
    ERROR:root:Error : connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden))
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden))
  • garvgoyal888
    i am able to connect to ICICI direct api and get live data from there
  • rakeshr
    failed (403 - Forbidden))
    Can you re-check, if there is trailing space in any of the API credential values(api key, secret key or access token).
Sign In or Register to comment.