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.

Please guide with a proper code to get marketfeed

=========
Unable to connect to Live Market Feed through Websockets .. Same issue with me i am able to connect web socket but not receiving OHLC. My code was different . if u have working code can assist with which version of python.

Unable to connect to Live Market Feed through Websockets .. Same issue with me i am able to connect web socket but not receiving OHLC. My code was different . if u have working code can assist with which version of python.-

1> i have paid data api as well.

2> Python version Python 3.12.6

3> Name: dhanhq → Version: 2.0.2

4> Here is My Code

from dhanhq import dhanhq, marketfeedimport pandas as pdimport xlwings as xwimport timefrom datetime import date

================= CONFIG =================

CLIENT_ID = “22”ACCESS_TOKEN = “eyJ0”

SYMBOL = “NIFTY”EXPIRY_DATE = date(2026, 1, 27)ATM_STRIKE = 25000 # :red_circle: CHANGE DAILYSTRIKE_GAP = 50STRIKE_RANGE = 10 # ATM ±10EXCEL_UPDATE_MS = 0.5 # 500 ms

=========================================

print(“Starting NIFTY ATM ±10 LIVE SYSTEM”)

---------- STEP 1: LOAD INSTRUMENT MASTER ----------

df = pd.read_csv(

low_memory=False)

df[“SEM_EXPIRY_DATE”] = pd.to_datetime(df[“SEM_EXPIRY_DATE”],errors=“coerce”)

---------- STEP 2: FILTER ATM ±10 STRIKES ----------

lower = ATM_STRIKE - (STRIKE_RANGE * STRIKE_GAP)upper = ATM_STRIKE + (STRIKE_RANGE * STRIKE_GAP)

contracts = df[(df[“SEM_INSTRUMENT_NAME”] == “OPTIDX”) &(df[“SEM_CUSTOM_SYMBOL”].str.contains(“NIFTY”, na=False)) &(df[“SEM_EXPIRY_DATE”].dt.date == EXPIRY_DATE) &(df[“SEM_STRIKE_PRICE”] >= lower) &(df[“SEM_STRIKE_PRICE”] <= upper)][[“SM_SYMBOL_NAME”,“SEM_EXPIRY_DATE”,“SEM_OPTION_TYPE”,“SEM_STRIKE_PRICE”,“SEM_SMST_SECURITY_ID”]].reset_index(drop=True)

print(“Contracts loaded:”, len(contracts))if contracts.empty:raise Exception(“No contracts found”)

---------- STEP 3: EXCEL SETUP ----------

wb = xw.Book(“nifty_live.xlsx”)sheet = wb.sheets[0]sheet.clear()

sheet.range(“A1:J1”).value = [“SYMBOL”, “EXPIRY”, “TYPE”, “STRIKE”,“OPEN”, “HIGH”, “LOW”, “CLOSE”,“PREV CLOSE”, “LTP”]

sheet.range(“A2”).value = contracts[[“SM_SYMBOL_NAME”, “SEM_EXPIRY_DATE”, “SEM_OPTION_TYPE”, “SEM_STRIKE_PRICE”]].values.tolist()

---------- STEP 4: WEBSOCKET SYMBOLS ----------

symbols = [(marketfeed.NSE_FNO, str(x))for x in contracts[“SEM_SMST_SECURITY_ID”]]

feed = marketfeed.DhanFeed(CLIENT_ID,ACCESS_TOKEN,symbols,1 # :backhand_index_pointing_left: FORCE VERSION = 1 (Ticker))

---------- STEP 5: DATA STORAGE ----------

ohlc = {}last_excel_update = 0

---------- STEP 6: CALLBACK ----------

def on_message(tick):global last_excel_update

token = str(tick[“securityId”])
ltp = tick[“ltp”]
prev_close = tick.get(“prev_close”, ltp)

if token not in ohlc:
ohlc[token] = {
“open”: ltp,
“high”: ltp,
“low”: ltp,
“close”: ltp,
“prev_close”: prev_close
}
else:
ohlc[token][“high”] = max(ohlc[token][“high”], ltp)
ohlc[token][“low”] = min(ohlc[token][“low”], ltp)
ohlc[token][“close”] = ltp

Throttle Excel updates

if time.time() - last_excel_update < EXCEL_UPDATE_MS:
return

last_excel_update = time.time()

idx = contracts.index[
contracts[“SEM_SMST_SECURITY_ID”].astype(str) == token
]

if not idx.empty:
row = idx[0] + 2
data = ohlc[token]

sheet.range(f"E{row}:J{row}").value = [
    data["open"],
    data["high"],
    data["low"],
    data["close"],
    data["prev_close"],
    ltp
]

---------- STEP 7: START ----------

feed.on_message = on_messageprint(“WebSocket running…”)feed.run_forever()

=====================================Output=========================

PS C:\DemoNSEOption> python nifty_atm_10_live_excel.pyStarting NIFTY ATM ±10 LIVE SYSTEMContracts loaded: 84WebSocket running…Traceback (most recent call last):File “C:\DemoNSEOption\nifty_atm_10_live_excel.py”, line 136, infeed.run_forever()File “C:\Users\ASHISH BHANDARI\AppData\Roaming\Python\Python312\site-packages\dhanhq\marketfeed.py”, line 53, in run_foreverself.loop.run_until_complete(self.connect())File “C:\Python312\Lib\asyncio\base_events.py”, line 687, in run_until_completereturn future.result()^^^^^^^^^^^^^^^File “C:\Users\ASHISH BHANDARI\AppData\Roaming\Python\Python312\site-packages\dhanhq\marketfeed.py”, line 73, in connectraise ValueError(f"Unsupported version: {self.version}")ValueError: Unsupported version: 1

=====================Can u assit issue resolve=====================

@Hardik Unable to connect to Live Market Feed through Websockets .. Same issue with me i am able to connect web socket but not receiving OHLC. My code was different . if u have working code can assist with which version of python.-

1> i have paid data api as well.

2> Python version Python 3.12.6

3> Name: dhanhq → Version: 2.0.2

4> Here is My Code

from dhanhq import dhanhq, marketfeedimport pandas as pdimport xlwings as xwimport timefrom datetime import date

================= CONFIG =================

CLIENT_ID = “22”ACCESS_TOKEN = “eyJ0”

SYMBOL = “NIFTY”EXPIRY_DATE = date(2026, 1, 27)ATM_STRIKE = 25000 # :red_circle: CHANGE DAILYSTRIKE_GAP = 50STRIKE_RANGE = 10 # ATM ±10EXCEL_UPDATE_MS = 0.5 # 500 ms

=========================================

print(“Starting NIFTY ATM ±10 LIVE SYSTEM”)

---------- STEP 1: LOAD INSTRUMENT MASTER ----------

df = pd.read_csv(

low_memory=False)

df[“SEM_EXPIRY_DATE”] = pd.to_datetime(df[“SEM_EXPIRY_DATE”],errors=“coerce”)

---------- STEP 2: FILTER ATM ±10 STRIKES ----------

lower = ATM_STRIKE - (STRIKE_RANGE * STRIKE_GAP)upper = ATM_STRIKE + (STRIKE_RANGE * STRIKE_GAP)

contracts = df[(df[“SEM_INSTRUMENT_NAME”] == “OPTIDX”) &(df[“SEM_CUSTOM_SYMBOL”].str.contains(“NIFTY”, na=False)) &(df[“SEM_EXPIRY_DATE”].dt.date == EXPIRY_DATE) &(df[“SEM_STRIKE_PRICE”] >= lower) &(df[“SEM_STRIKE_PRICE”] <= upper)][[“SM_SYMBOL_NAME”,“SEM_EXPIRY_DATE”,“SEM_OPTION_TYPE”,“SEM_STRIKE_PRICE”,“SEM_SMST_SECURITY_ID”]].reset_index(drop=True)

print(“Contracts loaded:”, len(contracts))if contracts.empty:raise Exception(“No contracts found”)

---------- STEP 3: EXCEL SETUP ----------

wb = xw.Book(“nifty_live.xlsx”)sheet = wb.sheets[0]sheet.clear()

sheet.range(“A1:J1”).value = [“SYMBOL”, “EXPIRY”, “TYPE”, “STRIKE”,“OPEN”, “HIGH”, “LOW”, “CLOSE”,“PREV CLOSE”, “LTP”]

sheet.range(“A2”).value = contracts[[“SM_SYMBOL_NAME”, “SEM_EXPIRY_DATE”, “SEM_OPTION_TYPE”, “SEM_STRIKE_PRICE”]].values.tolist()

---------- STEP 4: WEBSOCKET SYMBOLS ----------

symbols = [(marketfeed.NSE_FNO, str(x))for x in contracts[“SEM_SMST_SECURITY_ID”]]

feed = marketfeed.DhanFeed(CLIENT_ID,ACCESS_TOKEN,symbols,1 # :backhand_index_pointing_left: FORCE VERSION = 1 (Ticker))

---------- STEP 5: DATA STORAGE ----------

ohlc = {}last_excel_update = 0

---------- STEP 6: CALLBACK ----------

def on_message(tick):global last_excel_update

token = str(tick[“securityId”])
ltp = tick[“ltp”]
prev_close = tick.get(“prev_close”, ltp)

if token not in ohlc:
ohlc[token] = {
“open”: ltp,
“high”: ltp,
“low”: ltp,
“close”: ltp,
“prev_close”: prev_close
}
else:
ohlc[token][“high”] = max(ohlc[token][“high”], ltp)
ohlc[token][“low”] = min(ohlc[token][“low”], ltp)
ohlc[token][“close”] = ltp

Throttle Excel updates

if time.time() - last_excel_update < EXCEL_UPDATE_MS:
return

last_excel_update = time.time()

idx = contracts.index[
contracts[“SEM_SMST_SECURITY_ID”].astype(str) == token
]

if not idx.empty:
row = idx[0] + 2
data = ohlc[token]

sheet.range(f"E{row}:J{row}").value = [
    data["open"],
    data["high"],
    data["low"],
    data["close"],
    data["prev_close"],
    ltp
]

---------- STEP 7: START ----------

feed.on_message = on_messageprint(“WebSocket running…”)feed.run_forever()

=====================================Output=========================

PS C:\DemoNSEOption> python nifty_atm_10_live_excel.pyStarting NIFTY ATM ±10 LIVE SYSTEMContracts loaded: 84WebSocket running…Traceback (most recent call last):File “C:\DemoNSEOption\nifty_atm_10_live_excel.py”, line 136, infeed.run_forever()File “C:\Users\ASHISH BHANDARI\AppData\Roaming\Python\Python312\site-packages\dhanhq\marketfeed.py”, line 53, in run_foreverself.loop.run_until_complete(self.connect())File “C:\Python312\Lib\asyncio\base_events.py”, line 687, in run_until_completereturn future.result()^^^^^^^^^^^^^^^File “C:\Users\ASHISH BHANDARI\AppData\Roaming\Python\Python312\site-packages\dhanhq\marketfeed.py”, line 73, in connectraise ValueError(f"Unsupported version: {self.version}")ValueError: Unsupported version: 1

=====================Can u assit issue resolve=====================