from dhanhq import marketfeed
Add your Dhan Client ID and Access Token
#client_id = “Dhan Client ID”
#access_token = “Access Token”
Structure for subscribing is (“exchange_segment”,“security_id”)
Maximum 100 instruments can be subscribed, then use ‘subscribe_symbols’ function
instruments = [(1, “1333”),(0,“13”)]
Type of data subscription
subscription_code = marketfeed.Ticker
Ticker - Ticker Data
Quote - Quote Data
Depth - Market Depth
async def on_connect(instance):
print(“Connected to websocket”)
async def on_message(instance, message):
print(“Received:”, message)
print(“Subscription code :”, subscription_code)
feed = marketfeed.DhanFeed(client_id,
access_token,
instruments,
subscription_code,
on_connect=on_connect,
on_message=on_message)
feed.run_forever()
Output is:
C:\Users\abc\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\dhanhq\marketfeed.py:79: RuntimeWarning: coroutine ‘DhanFeed.connect’ was never awaited
self.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
RuntimeError Traceback (most recent call last)
Cell In[17], line 37
27 print(“Subscription code :”, subscription_code)
29 feed = marketfeed.DhanFeed(client_id,
30 access_token,
31 instruments,
32 subscription_code,
33 on_connect=on_connect,
34 on_message=on_message)
—> 37 feed.run_forever()
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\dhanhq\marketfeed.py:83, in DhanFeed.run_forever(self)
81 def run_forever(self):
82 “”“Starts the WebSocket connection and runs the event loop.”“”
—> 83 self.loop.run_until_complete(self.connect())
File C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.752.0_x64__qbz5n2kfra8p0\Lib\asyncio\base_events.py:661, in BaseEventLoop.run_until_complete(self, future)
650 “”“Run until the Future is done.
651
652 If the argument is a coroutine, it is wrapped in a Task.
(…)
658 Return the Future’s result, or raise its exception.
659 “””
660 self._check_closed()
→ 661 self._check_running()
663 new_task = not futures.isfuture(future)
664 future = tasks.ensure_future(future, loop=self)
File C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.752.0_x64__qbz5n2kfra8p0\Lib\asyncio\base_events.py:620, in BaseEventLoop._check_running(self)
618 def _check_running(self):
619 if self.is_running():
→ 620 raise RuntimeError(‘This event loop is already running’)
621 if events._get_running_loop() is not None:
622 raise RuntimeError(
623 ‘Cannot run the event loop while another loop is running’)
RuntimeError: This event loop is already running