Get current price of security id

I want to get current price for security_id=‘43895’

Can anyone please help me?

Hello @Vaibhav722

You can use Live Market Feed on DhanHQ Trading APIs to be able to get current price and other data for any instrument.

1 Like

By the way, I want only the current price for securityID instead of running it forever. Just to place a limit order.

feed = marketfeed.DhanFeed(client_id,
access_token,
[(2, “46464”)],
marketfeed.Ticker,
on_connect=on_connect,
on_message=on_message)

Could you please help me?

Hello, gentle reminder on above question

Hello @Vaibhav722

The code added here is not very clear. Are you trying to connect to websocket and then get price, in that case feed will be running forever. You can take value from feed whenever the order is placed.

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

feed = marketfeed.DhanFeed(client_id,
access_token,
[(2, “46464”)],
marketfeed.Ticker,
on_message=on_message)

feed.run_forever()

This code I’m talking about, actually this run forever so I don’t want it as no need of that data, and it should just return current price

Hello @Vaibhav722

This is built on websocket protocol which is intended for keeping established connection and then sending/receiving messages. You can fetch one time data as well, but you will have to open and close socket each time.

You will have to create a function which closes socket on receiving first data packet.

from dhanhq import dhanhq
from dhanhq import marketfeed
import threading
import asyncio

class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls, *args, **kwargs)
            cls._instance.DHAN_CLIENT_ID = None
            cls._instance.DHAN_ACCESS_TOKEN = None
            cls._instance.dhan = None
            cls._instance.CUREENT_SEC_PRICE = None
        return cls._instance

    def connectDhanCred(self, item):
        self.DHAN_CLIENT_ID = item['CLIENT_ID']
        self.DHAN_ACCESS_TOKEN = item['ACCESS_TOKEN']
        self.dhan = dhanhq(self.DHAN_CLIENT_ID, self.DHAN_ACCESS_TOKEN)
        
    def getDhan(self):
        return self.dhan

    async def on_message(self, instance, message):
        if(message.get('type', "None") == "Ticker Data"):
            current_price = message.get('LTP') 
            if current_price is not None:
                self.CUREENT_SEC_PRICE = current_price

    def fetch_current_price(self, securityId):
        # Create the market feed instance
        feed = marketfeed.DhanFeed(self.DHAN_CLIENT_ID,
                                self.DHAN_ACCESS_TOKEN,
                                [(2, str(securityId))],
                                marketfeed.Ticker,
                                on_message=self.on_message)
        # Run the feed until it's closed
        feed.run_forever()
        
    def fetchCurrentPriceInThread(self, securityId):
        thread = threading.Thread(target=self.fetch_current_price, args=(securityId,))
        thread.start()
        
    def get_current_price(self):
        return self.CURRENT_SEC_PRICE


Running following code:

singleton.fetchCurrentPriceInThread(46464)
print("break")
print(singleton.get_current_price())

ERROR:

Exception in thread Thread-1 (fetch_current_price):
Traceback (most recent call last):
  File "/opt/homebrew/Cellar/python@3.11/3.11.6_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1045, in _bootstrap_inner
    self.run()
  File "/opt/homebrew/Cellar/python@3.11/3.11.6_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 982, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/vaibhav/Downloads/pyWebhook-main/eeSingleton.py", line 35, in fetch_current_price
    feed = marketfeed.DhanFeed(self.DHAN_CLIENT_ID,
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/vaibhav/Downloads/pyWebhook-main/venv/lib/python3.11/site-packages/dhanhq/marketfeed.py", line 76, in __init__
    self.loop = asyncio.get_event_loop()
                ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/python@3.11/3.11.6_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/asyncio/events.py", line 677, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-1 (fetch_current_price)'.

As singleton.fetchCurrentPriceInThread(46464) running forever, next code not running. Can you please help me in this issue?

@Vaibhav722

I am not sure if Singleton will work here, as the connection has to be established and then you receive the quotes. For this, loop has to be created to keep the connection open and re-connect on drop off.

Rather than doing this, can you keep the websocket connection open in background and only subscribe to instruments when you want to fetch price and then unsubscribe?

1 Like