Now Live: Live Market Feed on DhanHQ Trading APIs

Hello @vigisbig

Welcome to Dhan Community!

  1. There is a limit of 5000 instruments per socket. Do note that the 100 symbols limitation is on subscription packet. This means, while subscribing instruments on websocket, you need to ensure that you do in batches of 100 (if you want data for 5000 stocks, then you need to send 50 binary subscription packet with 100 instruments each).

  2. No. But we do send Previous Close packet with Ticker Data, which can be stored and used to calculate percentage change.

@rahulbajaj
Understood. You will need a library for sure in Java to encode and decode text to binary.

@chandangowdatk
No. Data APIs are now available to all users at a subscription cost of ₹499 + taxes per month.

If anyone has standard python code to take an intraday position with stoploss, target and exit. Please share. Both for Stock and Options positions will be useful. In the tutorial last episode was hectic and code (using asyncio) was not shared. Since the code is same, working code templates are useful. we could modify it as per our need.

Would Ritwik Dashora be making videos about websocket too? How to subscribe, manage subscriptions etc? Or is there any standard code I can follow to subscribe to stocks (500). I have made progress in Python and made everything that I have chatting with ChatGPT, unfortunately it does not know anything about your API as yet.

I tried using the live market feed using Python , getting following error message :
+++++++++++++
Subscription code : 15

Warning (from warnings module):
File “C:\Users\nit11\AppData\Local\Programs\Python\Python311\Lib\site-packages\dhanhq\marketfeed.py”, line 79
self.connect()
RuntimeWarning: coroutine ‘DhanFeed.connect’ was never awaited
<dhanhq.marketfeed.DhanFeed object at 0x000001C448319790>
Connected to websocket
Connected to websocket
Authorization failed: ‘float’ object has no attribute ‘encode’
Not authorized. Please authorize first.
++++++++++++
Could you help me solve this issue… Am able to login to Dhan using the API key generated and have subscribed to DATAAPI too.

1 Like

Hello @nit111kg

Over here, authorisation is getting failed due to incorrect Client ID or Access Token data type. Kindly ensure that you are passing Client Id & Access Token as strings.

Hi,
I am writing a code where my instrument list is as below:
instruments = [(0,“25”),(2,str(token))]
in the above instrument list first symbol is fixed as BankNifty Index. second token is read from the excel file sheet which is generally generated whever an order is executed from excel and generally second token is from banknifty options.
Now the issue i am having is that initially when i run the feed, it return the Banknifty symbol LTP & LTT to excel which is absolutly fine. Once an order triggers and we have the BankNifty Option symbol available on sheet, the feed does not update the instrument list. can you please help in resolving this

Hello @vikassaini

Welcome to Dhan Community! Excited to know you are building your system on top of Dhan APIs and Market Feed.

Over here, I am assuming the connection is already open when the order is placed and you intend to subscribe to additional instruments. You can use subscribe_symbols function to subscribe to additional instruments while you are already connected via the websocket.

I am facing same issue as it has been freezed since last 15 minute …provide possible solution…as user id and token is correct in this case…

Hello @Jay007

Welcome to Dhan Community! Looks like you have entered subscription_code as 5, which is not valid. Requesting you to check the enum values on Documentation, and if possible share code above this so that we can check the status here.

from dhanhq.dhanhq import dhanhq
from dhanhq.marketfeed import DhanFeed
user_id=“1100700528”
access_token=“lcklkIjkZucH5f5DHuuEK34OQO2p7WKlDA”
dhan=dhanhq(user_id,access_token)
#security_id=“11536”
#exchange_segment=“NSE_EQ”
#instrument_type=“EQUITY”
#df=dhan.intraday_minute_data(security_id,exchange_segment,instrument_type)
#print(df)
instruments=[(0,“25”)]
subscription_code=5
async def on_connect(instance):
print(“Connected to websocket”)
async def on_message(ws, message):
print(“Received:”, message)
ws.subscribe_symbols(subscription_code,instruments)
feed = DhanFeed(user_id,
access_token,
instruments,
subscription_code,
on_connect=on_connect,
on_message=on_message)
feed.run_forever()

AIM- **I AM TRYING TO FECTH THE LIVE OI DATA FOR BN


i am using this feed response code to fetch oi data…

@Hardik - yes you are correct, connection is already open when the order is placed. I did subscribe the instrument list but still it is only giving BankNIfty Index data and not adding the Option new symbol in list. but when i restart the code , it gives data for both symbols. below is the code , can you please suggest if any issue in code:
token = str(int(dhandatafeed.range(‘H2’).value))
instruments = [(0,“25”),(2,str(token))]
subscription_code = marketfeed.Ticker

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

async def on_message(ws,message):
ws.subscribe_symbols(marketfeed.Ticker,instruments)

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()

@Hardik

is there any issue in feed, getting no data
self.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Connected to websocket
Connected to websocket
Connection has been closed

Hello @vikassaini

Can you check now and also confirm since when are you getting this error?

This is simply because once connection is established and instruments are subscribed, it will not subscribe to additional instruments unless stated. So, you will have to create a function which on successful order execution at your end subscribes to this additional instrument separately, using subscribe_symbols function.

If you look at the documentation, this is the response_code and not request_code. OI data is sent along with quote data for which subscription_code is 17.

Hi @Hardik,

I am trying the sample market feed code as is, and I get the following warning (attached screenshot) :

The code works but with warning:

  1. Above warning
  2. Connected to websocket (is displayed twice)

Is this normal ?

Thanks,
pradeep

Hello @gpradeep

Great to see you around after so long and excited to know you are using Live Market Feed.

Yes, the warning attached is normal, where async function is not being awaited for connect() function. Will try to fix this in upcoming releases.

The reason for printing ‘Connected to websocket’ twice is because python is trying to keep connection awake till the handshake is done. This will not open two connections simultaneously, so nothing which will get affected on getting market data.

Again, will keep on upgrading library with further optimisations. Also, the library is open source, so you can contribute to the same as well.

1 Like

Thank you much @Hardik. This was very helpful.

Regards,
pradeep

Hi @Hardik,

There seems to be a bug while subscribing to additional symbols in marketfeed call

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

And this is because the subscribe_symbols() function internally calls create_subscription_packet() with an additional parameter subscribe=True @ line 333, which is not a input parameter in create_subscription_packet().

Am sure you will see this issue with function unsubscribe_symbols() - it has additional parameter subscribe=False

And the function create_subscription_packet() never uses the subscribe - guess that means you cannot unsubscribe.

Regards,
pradeep

1 Like

Hello @gpradeep

Thanks for highlighting this, will take a look. Meanwhile, if you are able to resolve this, you can raise a PR on Github - GitHub - dhan-oss/DhanHQ-py: The official Python client for communicating with the Dhan API.

We are building all code libraries as open source, and it would be great if you can contribute!

Hi @Hardik , I am trying to access market feed using websockets. Earlier in youtube video, dhanSDK.py was used, which I am not able to find in the git or anywhere else. However, I got different code on git:

instruments = [(1, “1333”),(0,“13”)]

subscription_code = marketfeed.Ticker

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()

But when I used, it is giving error :

Exception ignored in: <coroutine object DhanFeed.connect at 0x7dfb5c44f760>
Traceback (most recent call last):
File “”, line 1, in
KeyError: ‘import
Exception ignored in: <coroutine object DhanFeed.connect at 0x7dfb5c44f760>
Traceback (most recent call last):
File “”, line 1, in
KeyError: ‘import
Subscription code : 19

RuntimeError: This event loop is already running

Help me resolve this issue to connect with market feed and in setting up the code. Thank you.