WebSocket Connection Issue: HTTP 429 – Was Working Earlier, Now Failing

Hi team,

I’m facing a persistent issue with the Dhan WebSocket connection which was working flawlessly until May 23. Starting yesterday, my connection attempts are consistently failing with the following error:

websockets.exceptions.InvalidStatus: server rejected WebSocket connection: HTTP 429

This seems to be a rate-limiting issue — Too Many Requests — but the same occurs even when I try it from a fresh AWS EC2 instance (new IP). So far I’ve:

:white_check_mark: Verified that I’m using the latest SDK (dhanhq==2.0.2)
:white_check_mark: Ensured my API subscription is active
:white_check_mark: Cross-checked from multiple environments (laptop and cloud)
:white_check_mark: Cross-checked for multiple accounts(different client id and token
:white_check_mark: Reduced the instrument list to just one instrument

Here’s my simplified connection code:

def websocket_process(redis_config):
    print(f"websocket_process--------------")

    watchlist = {
        "NIFTY 29 MAY 24500 CALL": "NFO",
    }

    new_instruments, new_rows, _ = prepare_instruments(watchlist)
    print(f"instruments = {new_instruments}")  # Output: instruments = [(2, '61683', 17)]

    data = marketfeed.DhanFeed(CLIENT_CODE, TOKEN_ID, new_instruments)
    print(f"Establishing connection fr {CLIENT_CODE} --> {TOKEN_ID}")
    data.run_forever()

    while True:
        response = data.get_data()
        if response and 'LTP' in response:
            security_id = response.get('security_id')
            ltp = response.get("LTP")
            print(f"LTP Received for {symbol_security_id_mapping[security_id]} = {ltp}")

Any help from the community or Dhan team would be greatly appreciated! :pray:

I am also facing same issue.

Getting similar kind of different error when using v2 version

 File "/Users/Dhan codebase/JohnWick_orderBlock.py", line 230, in websocket_process
    response = data.get_data()
               ^^^^^^^^^^^^^^^
  File "/Users/.venv/lib/python3.12/site-packages/dhanhq/marketfeed.py", line 57, in get_data
    return self.loop.run_until_complete(self.get_instrument_data()) 
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py", line 685, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/Users/.venv/lib/python3.12/site-packages/dhanhq/marketfeed.py", line 84, in get_instrument_data
    response = await self.ws.recv()
               ^^^^^^^^^^^^^^^^^^^^
  File "/Users/.venv/lib/python3.12/site-packages/websockets/asyncio/connection.py", line 322, in recv
    raise self.protocol.close_exc from self.recv_exc
websockets.exceptions.ConnectionClosedError: no close frame received or sent

Hello @GaneshGani55 @mdjamshed114

If you are using v1 websockets, do note that the same has been deprecated and you will not be able to use the same.

On V2, the parameters required to authenticate are a little different. Hope you have incorporated the same in your flow already. This looks like a case of unauthorised connection, do check for the error code that you will receive in such scenarios.

I am using dhanhq version 2.1.0 and getting the same error - server rejected WebSocket connection: HTTP 429

My api subscriptiion is active .
My python version is 3.10 and websockets version is 13.1

from dhanhq import DhanContext, MarketFeed
import asyncio
import nest_asyncio
nest_asyncio.apply()

client_id = "1000XXXXX"
access_token = """
iXumheETHFIgbhiBsx0WrsU0dIfGV_sorP2xfTsp4StDFfsu8ikkQnnFOj_n8kdcw
               """
instruments =[
    (MarketFeed.IDX, "13", MarketFeed.Ticker), #NIFTY
    (MarketFeed.IDX, "21", MarketFeed.Ticker), #INDIA VIX
    (MarketFeed.IDX, "25", MarketFeed.Ticker), #BANKNIFTY
    (MarketFeed.IDX, "27", MarketFeed.Ticker),  #FINNIFTY
    (MarketFeed.IDX, "442", MarketFeed.Ticker)  #MIDCPNIFTY
    ]

version = "v2"
dhan_context = DhanContext(client_id,access_token.strip())

async def fetchdata():
        print('Gen marketfeed v2 ..')
        data = MarketFeed(dhan_context, instruments, version)
        try:

            while True:
                print('Run forever:')
                data.run_forever()
                print('get data:')
                response = data.get_data()
                print('Response:')
                print((response))
                print('LTP : ',response['LTP'])

        except Exception as e:
            print('Exception:>>',e)

        # Close Connection
        print('Close Connection')
        await data.disconnect()

asyncio.run(fetchdata());

This is my error.

Gen marketfeed v2 ..
Run forever:
Exception:>> server rejected WebSocket connection: HTTP 429
Close Connection
Connection closed!

from where can i download websocket v2 and other related files. Please suggest.

@mdImtiazhussain

Hello @alok.nayak - Is the issue resolved for you. The market feed was working for me till yesterday afternoon and suddenly it stopped working. It displays no error after the initial handshake.