Marketfeed python program error is coming - Resolved!

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

Hello @neha123

This error is displayed when you are running the code in Jupyter notebook or any other python environment where the loop is already running.

You can use the below code instead to create tasks for event loop:

This asyncio solution is not working for me

tried all methods like asyncio.run_coroutine_threadsafe(), asyncio.run(), asyncio.create_task(), none worked

asyncio.run_coroutine_threadsafe(feed.run_forever())

  • File “/Users/username/Documents/python/py-trader/py-env/lib/python3.12/site-packages/dhanhq/marketfeed.py”, line 83, in run_forever*
  • self.loop.run_until_complete(self.connect())*
  • File “/Users/username/Documents/python/py-trader/py-env/lib/python3.12/site-packages/nest_asyncio.py”, line 98, in run_until_complete*
  • return f.result()*
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/futures.py”, line 203, in result*
  • raise self._exception.with_traceback(self._exception_tb)*
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/tasks.py”, line 316, in __step_run_and_handle_result*
  • result = coro.throw(exc)*
  • File “/Users/username/Documents/python/py-trader/py-env/lib/python3.12/site-packages/dhanhq/marketfeed.py”, line 88, in connect*
  • self.ws = await websockets.connect(WSS_URL)*
  • File “/Users/username/Documents/python/py-trader/py-env/lib/python3.12/site-packages/websockets/legacy/client.py”, line 647, in await_impl_timeout*
  • return await self.await_impl()*
  • File “/Users/username/Documents/python/py-trader/py-env/lib/python3.12/site-packages/websockets/legacy/client.py”, line 651, in await_impl*
  • _transport, _protocol = await self._create_connection()*
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py”, line 1077, in create_connection*
  • infos = await self._ensure_resolved(*
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py”, line 1453, in _ensure_resolved*
  • return await loop.getaddrinfo(host, port, family=family, type=type,*
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py”, line 898, in getaddrinfo*
  • return await self.run_in_executor(*
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/futures.py”, line 287, in await*
  • yield self # This tells Task to wait for completion.*
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/tasks.py”, line 385, in __wakeup*
  • future.result()*
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/futures.py”, line 203, in result*
  • raise self._exception.with_traceback(self._exception_tb)*
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/concurrent/futures/thread.py”, line 58, in run*
  • result = self.fn(*self.args, *self.kwargs)
  • File “/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/socket.py”, line 963, in getaddrinfo*
  • for res in _socket.getaddrinfo(host, port, family, type, proto, flags):*

socket.gaierror: [Errno 8] nodename nor servname provided, or not known

Hello @Pranav_Deshmukh

Welcome to Dhan Community!

This is a different error. Can you help us with the code you are running and what changes you have done to run asyncio?

Hi Hardik,

Actually after a bit of googling I found issue is something related to certificate.

Found a solution here :

As per them root cause is -

Root cause

The point is Python 3 no longer counts on MacOS’ openSSL. It depends on its own openSSL bundled which doesn’t have access to MacOS’ root certificates.

@Pranav_Deshmukh

Alright, did you find the solution as well?

Yes Solution is present in that link - I followed that Install certificate command and installed certifi.

I worked

1 Like