How to Auto-Close Trade After Auto Buying Options Using Webhook, Tradingview + Dhan

I’m trying to automate the whole process using pine editor alerts + Dhan via webhook. When my entry is recognized by tradingview the alert is shown and I get a buy order at Dhan.

However when exit is recognised by tradingview, instead of closing the trade it, it submits a buy order again.

How to alleviate this so that when strategy.exit is recognized at Tradingview dhan also exits the stock instead of buying more?

Code (which is put at message on create alert tab) shown below

secret":“*****”,“alertType”:“multi_leg_order”,“order_legs”:[{“transactionType”:“B”,“orderType”:“MKT”,“quantity”:“1”,“exchange”:“NSE”,“symbol”:“BANKNIFTY”,“instrument”:“OPT”,“productType”:“I”,“sort_order”:“1”,“price”:“0”,“option_type”:“CE”,“strike_price”:“52600.0”,“expiry_date”:“2024-07-03”}]}

Hello @malayilneil1

Welcome to Dhan Community!

This is because you are using Buy JSON for using it to exit your long position as well.

“transactionType”:“S”

You need to use the above transaction type to be able to close the position with the Sell order. Essentially there will be two JSON configurations, one for buying and another one for selling.

Hey @hardik thanks for the text! Need your help to solve it.

How can I do that for the same Alert? You can only put one message on the alert right?

Any variable I can use + add to pine editor to achieve this?

Hello @malayilneil1

Yes. Essentially either you need to place two separate alerts, based on two different conditions (which should be generated by your indicator criteria). And then you can add two different JSON on each.

Or you can use Pinescript and use a variable like “transactionType”:“{strategy.long}” and “transactionType”:“{strategy.short}” for dynamically adding Buy or Sell.