Need Help - DhanHQ Order Placement using Python

Hi Team Dhan,

I am exploring Dhan HQ to automate Index Options order placement using dhanhq python library. Have gone through Orders - DhanHQ Ver 1.0 / API Document but did not understand how to place a BankNifty SL-L Sell order. Could anyone please help me with the code sample to place BankNifty Intraday SL-L Sell order for any strike price?

Thanks,
Ravi

2 Likes

@PravinJ

Could you please reply to the above question? In addition to the link provided in the above question, I even tried everything in this link ( DhanHQ API Docs - SDK & Libraries) but nothing worked.

I doubt that the documents in these links are either incorrect or not updated. Please look into this.

Thanks,
Ravi

@Naman @Hardik @PravinJ

Could anyone of you please reply to my question in the first message of this thread? Or do let me know if you need additional information or explanation regarding my question.

Thanks,
Ravi

Hi @ravi_krishna

Below is the sample request structure for Stop Loss Limit order.

{
“dhanClientId”:"",
“correlationId”:"",
“transactionType”:“BUY”,
“exchangeSegment”:“NSE_FNO”,
“productType”:“INTRADAY”,
“orderType”:“STOP_LOSS”,
“validity”:“DAY”,
“tradingSymbol”:"",
“securityId”:"",
“quantity”:“25”,
“disclosedQuantity”:"",
“price”:"",
“triggerPrice”:"",
“afterMarketOrder”:false,
“amoTime”:"",
“boProfitValue”:"",
“boStopLossValue”: “”,
“drvExpiryDate”:"",
“drvOptionType”:“CALL”
“drvStrikePrice”:
}

Few fields I have left blank, you need to fill them as per your requirement. APIs are primarily mapped with security id, so you find the security id of desired instrument from the following link https://images.dhan.co/api-data/api-scrip-master.csv

Use quantity in multiple of lot size.

Enter both price & trigger price, check dhan frontend for better reference.

Hope this helps!

1 Like

Hi @Naman

Thank you for the reply. I tried this structure followed by dhan.place_order() function but did not work. dhan.place_order() is expecting a different set of input parameters I guess. Reference Image 1 and Image 2 below. Note that I saved client ID, entry price, trigger price and strike price in separate variables and passing them into the python dictionary.

Image 1:

Image 2:

Could you please correct me if I am doing any mistake in the code?

Thanks,
Ravi

from dhanhq import dhanhq


dhan = dhanhq("client_id","access_token")

# Place an order for Equity Cash
dhan.place_order(security_id= '1333',   #hdfcbank
    exchange_segment= dhan.NSE,
    transaction_type= dhan.BUY,
    quantity=10,
    order_type=dhan.MARKET,
    product_type= dhan.INTRA,
    price=0)

Try this it worked for me

1 Like

Hi @bsjhala

Thank you for sharing the code snippet. I believe this will work and will test once again when markets open. In your case it is an equity security ID and hence the security ID would remain same. But in my case, the security ID changes over the time as and when strike price and expiry dates change. Somehow, I managed to overcome the dynamic security ID problem using the api-scrip-master.csv link provided by Naman.

Thank you both @bsjhala and @Naman. Below is the screenshot of the code and I think the error message would disappear if executed during market hours.

2 Likes

@ravi_krishna

Did your code work next day???

I did not try as I had to travel. Will try in coming week and give you an update.

Hi @bsjhala,

Finally I got some time today to test the code once again, was quite busy since Monday due to tight deadlines in office.

The code worked without any issues and am able to send the orders to Dhan platform. Below is the screenshot of the code (Image 1). Please ignore the failure status at the end, one leg failed due to insufficient funds but the other one went through. Image 2 is the snapshot from Dhan Web showing the orders. Orders were placed with SL-L and entry prices set by our codes are 87.6 and 79.2, same prices you can see in the Dhan Web orders screenshot.

Image 1:

Image 2:

Thanks,
Ravi

3 Likes

@ravi_krishna

Gr8,

Can you pls share complete code…

I am also planning to shift from other Algo platforms to my own coded strategies here on Dhan.

@Naman
Further,I also request, dhan team to add sample codes in their documentation, as other Popular brokers are providing.

Documentation at Dhan Python documentation is minimal that too not correct.

Market live feed data is also must.

Pls Prioritise …

2 Likes

Hi @bsjhala

Sure, will share the complete code through GitHub either tomorrow or on Sunday and will update you here.

Thanks,
Ravi

3 Likes

Hello @bsjhala

We have already added sample code to jumpstart with Python here. We will be making it more elaborate with time.

For Market Feed data, have written about our approach here : Live Market Feed API - #2 by Hardik

2 Likes

@ravi_krishna

Thanks a lot in Advance…

It will be very useful to all Dhan users who are interested in Automating their traded.

DhanHQ Python Documentation are very minimal…

1 Like

@Hardik
Sample codes provided are minimal and detailed documentation are required.

Hi @bsjhala and @Gangavarapu

As promised, sharing the codes. Please check below GitHub link to access the Python code having custom functions created to get live NSE option chain data of any Index/Stock Option derivative and security id dynamically.

Python Code for FNO order placements using DhanHQ

Our code is very easy to understand and use with Dhan platform. It has following custom functions;

  1. get_option_chain_data() - To fetch live option chain data (in .json format) from NSE website
  2. process_option_chain_raw_data() - To process .json format raw data and return option chain as a Pandas data frame
  3. get_security_ID_and_LTP() - This is the only function that we need to call and above two functions are called automatically inside this one. After getting option chain as data frame, this function fetches data from api-scrip-master.csv file from Dhan servers and returns the security_id and it’s last trading price as output (in tuple format)

How to use the code? It’s simple, explained using two examples below :slight_smile:

Example 1 - Placing Nifty 18100 CE Intraday Limit Buy Order (10-Nov-2022 expiry):

security_id, security_ltp = get_security_ID_and_LTP(symbol='NIFTY', expiry_date='2022-11-10', strike_price=18100, option_type='CE')

dhan.place_order(security_id=security_id, exchange_segment=dhan.FNO, transaction_type= dhan.BUY, quantity=50, order_type=dhan.LIMIT, 
                 product_type= dhan.INTRA, price=security_ltp)

Example 2 - Placing ITC 347.5 PE Intraday Limit Sell Order (24-Nov-2022 expiry):

security_id, security_ltp = get_security_ID_and_LTP(symbol='ITC', expiry_date='2022-11-24', strike_price=347.5, option_type='PE')

dhan.place_order(security_id=security_id, exchange_segment=dhan.FNO, transaction_type= dhan.SELL, quantity=3200, order_type=dhan.LIMIT, 
                 product_type= dhan.INTRA, price=security_ltp)

Note:

  1. symbols must be in capital letters and should be as per NSE standards like NIFTY, BANKNIFTY, FINNIFTY, ITC, HDFCBANK etc
  2. expiry_date must be in ‘YYYY-MM-DD’ format
  3. strike_price must be a numerical value like 18100, 41200, 347.5 etc
  4. quantity parameter in dhan.place_order() function must be in multiples of the scrip lot size. For example, single lot of ITC has 3200 quantity and two lots have 3200x2=6400 quantity. Similarly, single lot of BANKNIFTY has 25 quantity and two lots have 25x2=50 quantity.

Hope this helps. :slight_smile:

Let me know in case of any queries or issues while accessing or executing the codes.

Best,
Ravi

10 Likes

@ravi_krishna
Thanks a lot

@Naman @ravi_krishna @Hardik @Gangavarapu

I am Placing AMO Orders for bank Nifty though Dhan API from Excel.

Buy F&O orders are getting placed without any issue. But All the Sell F&O orders are not getting placed.

Following Error is coming :
{“errorCode”:“BAD_REQUEST_ERROR”,“httpStatus”:“BAD_REQUEST”,“internalErrorCode”:“RS-9005”,“internalErrorMessage”:“Insufficient Holding Quantity”}

Can Any one pls Help…

Hi @bsjhala
Can you please share the request structure?

{
“dhanClientId”: “string”,
“correlationId”: “string”,
“transactionType”: “SELL”,
“exchangeSegment”: “NSE_FNO”,
“productType”: “CNC”,
“orderType”: “LIMIT”,
“validity”: “DAY”,
“tradingSymbol”: “”,
“securityId”: “46789”,
“quantity”: 25,
“disclosedQuantity”: 25,
“price”: 25,
“triggerPrice”: “”,
“afterMarketOrder”: true,
“amoTime”: “OPEN”,
“boProfitValue”: “”,
“boStopLossValue”: “”,
“drvExpiryDate”: “2022-11-17”,
“drvOptionType”: “CALL”,
“drvStrikePrice”: “41200”
}

I am Using the above requests. I am able to place AMO Buy F&O orders but error coming in sell order.

I

1 Like