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.