import asyncio
import pandas as pd
from dhanhq import marketfeed
Add your Dhan Client ID and Access Token
client_id = “1103339050”
access_token = “”
Structure for subscribing is (“exchange_segment”,“security_id”)
instruments = [(1, “1333”), (0, “13”)]
Type of data subscription
subscription_code = marketfeed.Quote
Initialize an empty DataFrame to store market feed data
market_data = pd.DataFrame(columns=[‘timestamp’, ‘exchange_segment’, ‘security_id’, ‘type’, ‘LTP’, ‘LTQ’, ‘LTT’, ‘avg_price’, ‘volume’, ‘total_sell_quantity’, ‘total_buy_quantity’, ‘open’, ‘close’, ‘high’, ‘low’])
async def on_connect(instance):
print(“Connected to websocket”)
async def on_message(instance, message):
global market_data
print(“Received:”, message)
# Create a DataFrame from the new message
new_data = pd.DataFrame([{
'timestamp': pd.Timestamp.now(),
'exchange_segment': message['exchange_segment'],
'security_id': message['security_id'],
'type': message['type'],
'LTP': message['LTP'],
'LTQ': message['LTQ'],
'LTT': message['LTT'],
'avg_price': message['avg_price'],
'volume': message['volume'],
'total_sell_quantity': message['total_sell_quantity'],
'total_buy_quantity': message['total_buy_quantity'],
'open': message['open'],
'close': message['close'],
'high': message['high'],
'low': message['low']
}])
# Append the new data to the existing DataFrame
market_data = pd.concat([market_data, new_data], ignore_index=True)
# Print the updated DataFrame
print(market_data.tail())
print(“Subscription code:”, subscription_code)
feed = marketfeed.DhanFeed(
client_id,
access_token,
instruments,
subscription_code,
on_connect=on_connect,
on_message=on_message
)
Run the event loop
async def main():
await feed.run_forever()
asyncio.run(main())
i am using this code and getting error
Task was destroyed but it is pending!
task: <Task pending name=‘Task-2’ coro=<WebSocketCommonProtocol.transfer_data() running at C:\Users\ajay.kumar2\AppData\Roaming\Python\Python312\site-packages\websockets\legacy\protocol.py:963> wait_for= cb=[Task.task_wakeup(), _wait.._on_completion() at C:\Program Files\Python312\Lib\asyncio\tasks.py:534]>
Task was destroyed but it is pending!
task: <Task pending name=‘Task-3’ coro=<WebSocketCommonProtocol.keepalive_ping() running at C:\Users\ajay.kumar2\AppData\Roaming\Python\Python312\site-packages\websockets\legacy\protocol.py:1254> wait_for=>
Task was destroyed but it is pending!
task: <Task pending name=‘Task-4’ coro=<WebSocketCommonProtocol.close_connection() running at C:\Users\ajay.kumar2\AppData\Roaming\Python\Python312\site-packages\websockets\legacy\protocol.py:1301> wait_for=<Task pending name=‘Task-2’ coro=<WebSocketCommonProtocol.transfer_data() running at C:\Users\ajay.kumar2\AppData\Roaming\Python\Python312\site-packages\websockets\legacy\protocol.py:963> wait_for= cb=[Task.task_wakeup(), _wait.._on_completion() at C:\Program Files\Python312\Lib\asyncio\tasks.py:534]>>
Traceback (most recent call last):
File “C:\Users\ajay.kumar2\AppData\Roaming\Python\Python312\site-packages\websockets\legacy\protocol.py”, line 1337, in close_connection
File “C:\Users\ajay.kumar2\AppData\Roaming\Python\Python312\site-packages\websockets\legacy\protocol.py”, line 1355, in close_transport
File “C:\Users\ajay.kumar2\AppData\Roaming\Python\Python312\site-packages\websockets\legacy\protocol.py”, line 1379, in wait_for_connection_lost
File “C:\Program Files\Python312\Lib\asyncio\timeouts.py”, line 145, in timeout
RuntimeError: no running event loop
PS C:\Users\ajay.kumar2\algo> & “C:/Program Files/Python312/python.exe” c:/Users/ajay.kumar2/algo/te.py
Subscription code: 17
C:\Users\ajay.kumar2\AppData\Roaming\Python\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
Traceback (most recent call last):
File “c:\Users\ajay.kumar2\algo\te.py”, line 65, in
asyncio.run(main())
File “C:\Program Files\Python312\Lib\asyncio\runners.py”, line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File “C:\Program Files\Python312\Lib\asyncio\runners.py”, line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Program Files\Python312\Lib\asyncio\base_events.py”, line 687, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File “c:\Users\ajay.kumar2\algo\te.py”, line 63, in main
await feed.run_forever()
^^^^^^^^^^^^^^^^^^
File “C:\Users\ajay.kumar2\AppData\Roaming\Python\Python312\site-packages\dhanhq\marketfeed.py”, line 83, in run_forever
self.loop.run_until_complete(self.connect())
File “C:\Program Files\Python312\Lib\asyncio\base_events.py”, line 663, in run_until_complete
self._check_running()
File “C:\Program Files\Python312\Lib\asyncio\base_events.py”, line 624, in _check_running
raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running
sys:1: RuntimeWarning: coroutine ‘DhanFeed.connect’ was never awaited