import asyncio
import nest_asyncio
from dhanhq import marketfeed
Allow nested event loops in Jupyter Notebook
nest_asyncio.apply()
Add your Dhan Client ID and Access Token
client_id = “XXX”
access_token = “yyy”
Structure for subscribing is (exchange_segment, “security_id”, subscription_type)
instruments = [
(marketfeed.NSE, “1333”, marketfeed.Ticker), # Ticker - Ticker Data
(marketfeed.NSE, “1333”, marketfeed.Quote), # Quote - Quote Data
(marketfeed.NSE, “11915”, marketfeed.Ticker),
]
sub_instruments = [(marketfeed.NSE, “14436”, marketfeed.Ticker)]
unsub_instruments = [(marketfeed.NSE, “1333”, marketfeed.Ticker)]
async def main():
try:
# Initialize DhanFeed
data = marketfeed.DhanFeed(client_id, access_token, instruments)
# Connect to the feed
await data.connect()
print("Connection established")
# Run the feed in an infinite loop
while True:
response = await data.get_data() # Use await for async operations
print(response)
except Exception as e:
print(f"Error: {e}")
finally:
if 'data' in locals() and data:
await data.disconnect() # Properly disconnect from the feed
print("Disconnected")
Run the async function
asyncio.run(main())
I am running this on juypter notebook and the output is Authorizing…
Authorization successful!
Connection established