Marketfeed api - sample python code error

Hello @anuragkngr

Welcome to Dhan Community!

If you want to subscribe to two different formats of data, you can do the same by subscribing to packets with the required subscription code. You can use subscribe_instruments function for the same.

In case you want to establish two different socket connections itself, you will have to run it on two different terminal.

Hi Hardik

Please notice the LTT difference of 1 minute in the websocket data for crudeoil
I am using the above code of yours, please let me know any suggestions.

Received:
{‘type’: ‘Previous Close’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘prev_close’: ‘28.70’, ‘prev_OI’: 1159344128}
2024-04-30 12:25:06.224369 - <class ‘dict’> - {‘type’: ‘Previous Close’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘prev_close’: ‘28.70’, ‘prev_OI’: 1159344128}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.80’, ‘LTT’: ‘12:21:22’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.80’, ‘LTT’: ‘12:27:08’}
2024-04-30 12:27:08.497690 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.80’, ‘LTT’: ‘12:27:08’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.80’, ‘LTT’: ‘12:27:08’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘31.20’, ‘LTT’: ‘12:27:29’}
2024-04-30 12:29:26.957504 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘31.20’, ‘LTT’: ‘12:27:29’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.60’, ‘LTT’: ‘12:29:26’}
2024-04-30 12:29:29.709710 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.60’, ‘LTT’: ‘12:29:26’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.60’, ‘LTT’: ‘12:29:26’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.50’, ‘LTT’: ‘12:29:27’}
2024-04-30 12:29:29.773128 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.50’, ‘LTT’: ‘12:29:27’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.50’, ‘LTT’: ‘12:29:27’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘31.20’, ‘LTT’: ‘12:30:07’}
2024-04-30 12:31:26.956118 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘31.20’, ‘LTT’: ‘12:30:07’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘31.40’, ‘LTT’: ‘12:31:26’}
2024-04-30 12:31:42.128144 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘31.40’, ‘LTT’: ‘12:31:26’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘31.80’, ‘LTT’: ‘12:31:42’}
2024-04-30 12:31:43.324319 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘31.80’, ‘LTT’: ‘12:31:42’}
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘30.50’, ‘LTT’: ‘12:36:11’}

Sorry this is working now . It looks like i have been closing the file:

with open(f"{fname}{datetime.date.today()}.csv",‘a’,newline=‘’) as file:
writer = csv.writer(file)
print_log(message)
exchng_seg = message[‘exchange_segment’]
sec_id = message[‘security_id’]
ltp = message[‘LTP’]
ltt = message[‘LTT’]
row = [exchng_seg, sec_id, ltp, ltt]
writer.writerow(row)
#file.close()

After commenting file.close it appears to be working .
Thanks

1 Like

Running into the same issue again receiving ticks very slowly looks like there is a gap of 20 to 30 seconds and more sometimes

Commented all the code and just using the base code:

async def on_message(instance, message):
print_log("Received: " , print_console=True)
print_log(message, print_console=True)

Looks like there is a 1 minute delay happening screenshot below also

Received:
2024-04-30 14:14:47.367632 - <class ‘str’> - Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.00’, ‘LTT’: ‘14:13:15’}
2024-04-30 14:14:47.380721 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.00’, ‘LTT’: ‘14:13:15’}
CRUDEOIL
2024-04-30 14:14:49.537246 - <class ‘str’> - CRUDEOIL
Received:
{‘type’: ‘Previous Close’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘prev_close’: ‘28.70’, ‘prev_OI’: 1159344128}
2024-04-30 14:14:49.561809 - <class ‘dict’> - {‘type’: ‘Previous Close’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘prev_close’: ‘28.70’, ‘prev_OI’: 1159344128}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.00’, ‘LTT’: ‘14:13:15’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.10’, ‘LTT’: ‘14:15:45’}
2024-04-30 14:15:55.875883 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.10’, ‘LTT’: ‘14:15:45’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘27.70’, ‘LTT’: ‘14:15:54’}
2024-04-30 14:15:55.918546 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘27.70’, ‘LTT’: ‘14:15:54’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘27.70’, ‘LTT’: ‘14:15:54’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘27.70’, ‘LTT’: ‘14:15:57’}
2024-04-30 **14:16:07.**419726 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘27.70’, ‘LTT’: ‘14:15:57’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘27.70’, ‘LTT’: '14:16:07’}
2024-04-30 14:17:01.826983 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘27.70’, ‘LTT’: ‘14:16:07’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.00’, ‘LTT’: '14:17:01’}
2024-04-30 14:17:38.922890 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.00’, ‘LTT’: ‘14:17:01’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.00’, ‘LTT’: '14:17:38’}
2024-04-30 14:17:42.688781 - <class ‘dict’> - {‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.00’, ‘LTT’: ‘14:17:38’}
CRUDEOIL

I have run it again the delay is gradually increasing which defeats the purpose of webscokets:

Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘27.90’, ‘LTT’: ‘15:07:12’}
CRUDEOIL
Received:
{‘type’: ‘Previous Close’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘prev_close’: ‘28.70’, ‘prev_OI’: 1159344128}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.70’, ‘LTT’: ‘15:08:20’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.70’, ‘LTT’: ‘15:08:29’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.70’, ‘LTT’: ‘15:08:56’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.70’, ‘LTT’: ‘15:08:56’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.70’, ‘LTT’: ‘15:09:08’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.60’, ‘LTT’: ‘15:09:58’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.60’, ‘LTT’: ‘15:09:58’}
CRUDEOIL
Received:
{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 428868, ‘LTP’: ‘28.60’, ‘LTT’: ‘15:11:06’}
CRUDEOIL

Hello @saisaigraph

I checked this, even running the code on my local system. It seems to be working as expected, where the data is getting updated as and when there is change in price. You can verify the data updates on Dhan or any other platform as well.


Dear Team
please guide as subscribed to data api showing error RuntimeWarning: coroutine ‘DhanFeed.connect’ was never awaited
self.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Connected to websocket
Connected to websocket
Authorization failed: ‘int’ object has no attribute ‘encode’
Not authorized. Please authorize first.

even after stating error what i am missing here , it should subscribe… whereas i have already subscribed for data api website doesnot allow to attach two screenshots. and i should get feed from websocket…

subscribe_symbols function is not working. It’s thorwing below error

DhanFeed.create_subscription_packet() got an unexpected keyword argument ‘subscribe’

subscribe=True this argument is not expected in create_subscription_packet function.

asyncio.ensure_future(self.ws.send(self.create_subscription_packet(symbols, feed_request_code, subscribe=True)))

@Hardik : can you please check this.

Hello @Ritesh_Srivastava

Welcome to MadeForTrade community!

Are you trying to add additional symbols using the subscribe_symbols function? If yes, we are reworking on this on the library end itself.

1 Like

@Hardik : another query regarding, marketfeed connect method, the connection to websockets closes silently after running for couple of hours with “print(“Connection has been closed”)” this message and the exception is suppressed. How do we reconnect in this case?

Hello @Ritesh_Srivastava

We updated the library today to v1.3.2, which should minimise such issue. In case the connection get’s closed, you can always reinitiate with get_data function (which is added in v1.3.2).

1 Like

Hi Hardik,
I am new to dhan API trying get the marketfeed code run on colab notebook. It’s not working . Can you provide the sample ntebook which can fetch the LTP in real-time.
For you reference I am using folowwing code:
import nest_asyncio
nest_asyncio.apply()

from dhanhq import marketfeed
import asyncio

client_id = CLIENT_ID
access_token = ACCESS_TOKEN

instruments = [(1, “1333”),(0,“13”)]
subscription_code = marketfeed.Ticker

Usage Example

Define callback functions outside DhanFeed initialization

def on_connect(instance):
print(“Connected to websocket”)

def on_message(instance, message):
print(“Received:”, message)

print(“Subscription code :”, subscription_code)

Initialize DhanFeed without callback arguments

Pass “v2” or “v1” as the version argument instead of subscription_code

feed = marketfeed.DhanFeed(client_id, access_token, instruments, version=“v2”) # Or version=“v1”

Attach callback functions using instance methods

feed.on_connect = on_connect
feed.on_message = on_message

Remove the first call to feed.run_forever() as it’s blocking.

feed.run_forever()

Instead of creating a task for run_forever, run it directly in the event loop

asyncio.create_task(feed.run_forever())

loop = asyncio.get_event_loop()
loop.run_until_complete(feed.run_forever()) # Run the feed within the current event loop

Hello @rishabh_thareja

Welcome to MadeForTrade community!

What is the error that you are getting on this?

Hi Hardik,
Thanks for your immediate reply , I am getting this error.
TypeError: An asyncio.Future, a coroutine or an awaitable is required

Kindly also verify If the code I shared is correct or not

@rishabh_thareja

Looks like you are using an earlier version of code with the new library. Sharing the updated hands-on code: GitHub - dhan-oss/DhanHQ-py: The official Python client for communicating with the Dhan API.

Hey Hardik, thanks a ton. The marketfeed code worked started fetching real-time data continuously. I will continue to explore dhan API and will connect with you for any future clarification. Thanks man

1 Like

Hey Hardik,
today I ran the same code for market feed getting this error:
This event loop is already running
:27: RuntimeWarning: coroutine ‘DhanFeed.connect’ was never awaited
print(e)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
:30: RuntimeWarning: coroutine ‘DhanFeed.disconnect’ was never awaited
data.disconnect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Hello @rishabh_thareja

By any chance, you are calling disconnect function right after the connection is made? Also, have you used asyncio or any additional loops?

Hi @Hardik
This is the code I tried using from dhanHQ github

from dhanhq import marketfeed

Add your Dhan Client ID and Access Token

client_id = CLIENT_ID
access_token = ACCESS_TOKEN

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, “1333”, marketfeed.Full), # Full - Full Packet
(marketfeed.NSE, “11915”, marketfeed.Ticker),
(marketfeed.NSE, “11915”, marketfeed.Full)]

version = “v2” # Mention Version and set to latest version ‘v2’

In case subscription_type is left as blank, by default Ticker mode will be subscribed.

try:
data = marketfeed.DhanFeed(client_id, access_token, instruments, version)
while True:
data.run_forever()
response = data.get_data()
print(response)

except Exception as e:
print(e)

Close Connection

data.disconnect()

Subscribe instruments while connection is open

sub_instruments = [(marketfeed.NSE, “14436”, marketfeed.Ticker)]

data.subscribe_symbols(sub_instruments)

Unsubscribe instruments which are already active on connection

unsub_instruments = [(marketfeed.NSE, “1333”, 16)]

data.unsubscribe_symbols(unsub_instruments)