Code on GitHub not working

below is the code from ur GitHub. Is this working?
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”, 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)

I installed python library “pip install dhanhq” and pasted the code Visual Studio and getting below issue -

Hello @Himanshu_S

Welcome to MadeForTrade community!

Have you installed dhanhq library on your system? Looks like the library is not present and you are trying to run the code.

I have it installed. What is missing?

Hey @Himanshu_S

I am hoping you are passing your actual Client ID and Access Token here?

I am.

Not sure why it sometimes shows error in dhanhq.

Can you please give me a websocket code which will give an output. I just want to understand the flow and analyze the response.

Can you highlight issue with this code? at bottom, you can see that I got the response once with an error. I am a newbie.

Hello @Himanshu_S

Can you check if you are on DhanHQ v2.0.2. Also, you do not need to call data.subscribe_symbols function later.

here is the detail. how to upgrade. I tried upgrading, but no luck -

Yes, this is the latest one. It is 2.0.2, my bad.

Can you check the installed websockets version as well? And try without the subscribe_instruments function?

everything in one screenshot below. note that I have used 2 symbols this time. got a response for only one and then the same error.

Not sure, why it is working in .py file, and not working in .ipynb file. But its working now and I am able to fetch it values in the excel file. Will try to place the order from excel file tmrw.

I am getting this intermittent error “Incomplete message received: {‘type’: ‘Previous Close’, ‘exchange_segment’: 2, ‘security_id’: 46695, ‘prev_close’: ‘680.10’, ‘prev_OI’: 1218763872}”

I am using

print(“Incomplete message received:”, message)

@Hardik
Can you please respond to above message. Also I am getting error msg “SSL connection is closed”.

Hello @Himanshu_S

What is the logic behind printing this? And on SSL connection getting closed, is there any situation where the code is getting stopped by network layer?

Logic below. You can guide me if it’s wrong

try:
    # Initialize the Dhan Feed with subscription details
    data = marketfeed.DhanFeed(client_id, access_token, instruments, version)
    # # Start the feed
    # print("Starting to receive market feed data...")
    while True:
        data.run_forever()  # Maintain a persistent connection
        message = data.get_data()  # Fetch the data from feed
        print(message)
        # Process the message
        if message:
            # Extract security_id and LTP
            
            security_id = message.get('security_id')
            ltp = message.get('LTP')
            # print(f"Security ID: {security_id}, LTP: {ltp}")

            /// code to print data in excel////

        else:
                print("Incomplete message received:", message)
except Exception as e:
    # Handle exceptions
    print("An error occurred:", str(e))

here
instruments = [(marketfeed.MCX, “439833”, marketfeed.Ticker), (marketfeed.MCX, “439834”, marketfeed.Ticker), (marketfeed.MCX, “439838”, marketfeed.Ticker)].

Normal output is, when there is no error -

{‘type’: ‘Ticker Data’, ‘exchange_segment’: 5, ‘security_id’: 439839, ‘LTP’: ‘162.90’, ‘LTT’: ‘17:22:40’}

I don’t understand why I am getting previous close -

{‘type’: ‘Previous Close’, ‘exchange_segment’: 5, ‘security_id’: 439834, ‘prev_close’: ‘212.50’, ‘prev_OI’: 1165283328}

Coming to your network layer question, like I said I am new to this, so I don’t know how to investigate this issue. Please advise.

Hi @Hardik

Your response awaited. I have another query over here. below is the portion of my code where I am trying to place order from excel file based on condition. I am capturing the all the values and time of execution within IF condition. order placement is not working. Is this the right approach?

from dhanhq import dhanhq

                            dhan = dhanhq(client_id,access_token)
                            print("placing BUY order now....")
                            sheet_TT.range(f"Q{i}").value = (f"security_id : {symbol} : {type(symbol)} : quantity : {qty} : {type(qty)} : order_type : {order_t} : {type(order_t)} : product_type : {product_t} : {type(product_t)} : limitPrice : {limitPrice} : {type(limitPrice)}: time : {current_time} : {type(current_time)}")
                            time.sleep(1)
                            dhan.place_order(security_id=symbol,           # Nifty PE
                                exchange_segment=dhan.NSE_FNO,
                                transaction_type=dhan.BUY,
                                quantity=qty,
                                order_type=order_t,
                                product_type=product_t,
                                price=limitPrice)

In sheet_TT.range(f"Q{i}"), I got the value as -

security_id : 37101 : <class ‘int’> : quantity : 50 : <class ‘int’> : order_type : dhan.LIMIT : <class ‘str’> : product_type : dhan.MARGIN : <class ‘str’> : limitPrice : 290.0 : <class ‘float’>: time : 2024-12-04 12:55:09.702892+05:30 : <class ‘datetime.datetime’>

Hello @Himanshu_S

Over here, previous close packet is sent with Ticker Packet, in order for you to calculate day change if you wish to. You can skip the packet for your code to run smoothly.

On the second one, not sure if this is the right method, will highly depend on the functionality that you expect via the sheet.

Hi @Hardik

I have mentioned that its coming as an incomplete message, where I am not getting LTP. Why is this happening, is the ask?

I am skipping it, but that does not satisfy the purpose. LTP value is the first and very basic requirement to go for a paid subscription.

I have shared the screenshot and logic for printing “Incomplete message”.

Screenshot below shows that I am receiving message without LTP. And bcoz of this, my excel is not getting updated. Are you able to understand the problem over here?

And there is no mention about “SSL connection is closed”

@Hardik

I noticed, I have given you the complete logic. refer below -

try:
    # Initialize the Dhan Feed with subscription details
    data = marketfeed.DhanFeed(client_id, access_token, instruments, version)
    # # Start the feed
    # print("Starting to receive market feed data...")
    while True:
        data.run_forever()  # Maintain a persistent connection
        message = data.get_data()  # Fetch the data from feed
        timestamp = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S")
        print(message)

        # Process the message
        if message:
            # Extract security_id and LTP
            
            security_id = message.get('security_id')
            ltp = message.get('LTP')
            # print(f"Security ID: {security_id}, LTP: {ltp}")

            # Print the information if available
            if security_id and ltp:
            
            //// code to print in excel and place orders/////

            else:
                 print(f"Incomplete message received:", {"timestamp": timestamp, "message": message})

except Exception as e:
    # Handle exceptions gracefully
    print(f"An error occurred at timestamp {timestamp}:", str(e))
type or paste code here

Whenever the message comes without LTP it will execute and print the “else:” condition. I hope, I am able to make you understand the issue with it.

Please let me know about the resolution, so I can decide if it worth continuing with Data API paid subscription.

Hello @Himanshu_S

I got this part where you are printing Incomplete message if it is previous close packet. But post that, you are getting the LTP printed successfully. Now, what is the next step you want to do here.

On the SSL close error, you will have to check on your end only, as neither this is a library issue or server side issue.