Unable to connect to Live Market Feed through Websockets

Hello there, @Hardik @Mohseen_Usmani

I want to have live market feed through dhan websocket. I tried several codes but it is not connecting to websockets. Following is my code.

Can anyone please help on this? Where I am getting wrong thing?

import threading
import asyncio
from dhanhq import marketfeed
import logging

logging.basicConfig(level=logging.DEBUG)

Replace with your actual credentials

client_id = “Dhan Client ID”
access_token = “Access Token”

Define instruments to subscribe to (adjust as needed)

instruments = [
(marketfeed.NSE, “1333”, marketfeed.Ticker),
# Additional instruments can be added here
]

version = “v2”
data = marketfeed.DhanFeed(client_id, access_token, instruments, version)

— Patch the connect method —

Save the original async connect method

original_async_connect = data.connect

def sync_connect():
# In the separate thread, create a new event loop,
# run the async connect, then close the loop.
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
try:
result = new_loop.run_until_complete(original_async_connect())
finally:
new_loop.close()
return result

Replace the async connect with our synchronous version

data.connect = sync_connect

— Function to start the feed —

def start_feed():
try:
# run_forever is a blocking call that will use our patched connect.
data.run_forever()
except Exception as e:
print(“Error:”, e)

Start the feed in a separate thread

feed_thread = threading.Thread(target=start_feed, daemon=True)
feed_thread.start()

print(“Feed started successfully.”)
print(“Current ws connection:”, data.ws)

Response -
Feed Started Successfully.
Current ws connection: None

I am trying first for a sample stock then in main code there will be a list of security ID for which I will need live feed.

Please help.

Hello @Harit_Dobariya

The library takes care of everything, will have to run and test why the patch connect is not working. Any specific reason for using this approach on top of existing async.

Hello @Hardik ,

New to python coding. And taking help from online AI tools which led me to this point. However, after your comments, using following code also gives me the error - “‘ClientConnection’ object has no attribute ‘closed’”,

import asyncio
import nest_asyncio
from dhanhq import marketfeed

# Apply for Jupyter/Colab
nest_asyncio.apply()

# Replace with your credentials
client_id = "YOUR_CLIENT_ID"
access_token = "YOUR_ACCESS_TOKEN"

# Sample instruments
instruments = [
    (marketfeed.NSE, "1333", marketfeed.Ticker),
    (marketfeed.NSE, "1333", marketfeed.Full),
]

version = "v2"

async def run_market_feed_test():
    try:
        # Create the WebSocket feed instance
        feed = marketfeed.DhanFeed(client_id, access_token, instruments, version)

        # Connect to WebSocket
        await feed.connect()
        print("✅ Connected to Dhan MarketFeed WebSocket")

        # Subscribe to instruments
        await feed.subscribe_symbols(instruments)
        print("✅ Subscribed to instruments")

        # Test: Loop for 30 seconds to simulate receiving ticks
        for i in range(15):
            print(f"⏱️ Tick check {i+1}: (simulating, no real data after-hours)")
            await asyncio.sleep(2)

    except Exception as e:
        print(f"❌ Exception: {e}")
    finally:
        await feed.disconnect()
        print("✅ Disconnected from WebSocket")

# Start the test coroutine
asyncio.create_task(run_market_feed_test())

Request for the expert’s help pls.