Webhook Queries

Thanks for the reply.
Yeah, i have checked the sample script. in fact i have extracted most of the dhan webhook integration logic from the sample script and integrated it into my script.
Entries are triggering perfectly, i have tried may ways but i have failed miserably.
as per my strategy, most of the entry and exits will happen in the same bar.
so i have used alert(freq=alert.freq_all) but still it didn’t work either.

As per your suggestion i have made little changes to the logic, Please check!

if (strategy.position_size == 0) // No active position
if (longEntryCondition)
strategy.order(“Long”, strategy.long)
alert(long_msg, freq=alert.freq_all) // Trigger alert for long entry
if (shortEntryCondition)
strategy.order(“Short”, strategy.short)
alert(short_msg, freq=alert.freq_all) // Trigger alert for short entry

if (strategy.position_size > 0) // Long position active
if (shortEntryCondition)
strategy.order(“Short”, strategy.short, qty=size)
alert(short_msg, freq=alert.freq_all) // Trigger alert for short entry
else
strategy.exit(“Long Exit”, from_entry=“Long”, qty=size, stop=useStopLoss, limit=useTakeProfit)
alert(long_exit_msg, freq=alert.freq_all) // Trigger alert for long exit

if (strategy.position_size < 0) // Short position active
if (longEntryCondition)
strategy.order(“Long”, strategy.long, qty=size)
alert(long_msg, freq=alert.freq_all) // Trigger alert for long entry
else
strategy.exit(“Short Exit”, from_entry=“Short”, qty=size, stop=useStopLoss, limit=useTakeProfit)
alert(short_exit_msg, freq=alert.freq_all) // Trigger alert for short exit

// 2. Risk Management Exits (Outside Alerts)
strategy.exit(“Exit Long”, from_entry=“Long”, profit=useTakeProfit, loss=useStopLoss, trail_points=useTrailStop, trail_offset=useTrailOffset)
strategy.exit(“Exit Short”, from_entry=“Short”, profit=useTakeProfit, loss=useStopLoss, trail_points=useTrailStop, trail_offset=useTrailOffset)

Thank You!

The stop exits in the if condition will not fire on the same bar. It will fire only on the next bar or any other bar after entry bar.

The stop exits outside the if condition will fire on the entry bar but here u have not pasted the alert message JSON. So it won’t fire orders in Dhan. Also, use the alert_message parameter in the strategy.exit() to pass the JSON instead of a separate alert() call.

https://www.tradingcode.net/tradingview/strategy-exit-function/

1 Like

Thank You so much @t7support ,

I have made the corrections which you have mentioned.
Webhook integration is working flawlessly!!

I can’t ask for more, I was struggling with the issues for so long, but now I’ll be very thankful for your support.
I wish other traders will find this thread useful.

Thank You!

3 Likes

@t7support

Hello,

I have a little issue with placing orders with Sensex, i have subscription for Real-time market data for BSE.

I don’t see any issues with the Pine Script, cause orders are being placed for both the nifty and bank nifty properly.
Only Sensex isn’t working.
Please check the below Alert Log.

You seem to have extra outside quotes in the alert log. Compare with working alert logs and fix.

//@version=5
strategy(“XXXX Strategy with Dhan Integration”, overlay=true)

//Webhook Settings
groupWebhook = “Webhook Settings”
secretCode = input.string(defval=“”, title=“Secret Code”, group=groupWebhook)
symbol = input.string(defval=“NIFTY”, title=“Symbol”, options=[“NIFTY”, “FINNIFTY”, “BANKNIFTY”, “MIDCPNIFTY”, “BANKEX”, “SENSEX”], group=groupWebhook)
quantity = input.int(defval=1, title=“Lots”, minval=1, group=groupWebhook)
expiryDate = input.string(defval=“2024-10-17”, title=“Expiry Date”, group=groupWebhook)

//Auto Strike Selection Settings
opt_level = input.int(1, title=“Option Depth Level”, minval=1)

// Define the strike price step based on the selected symbol
var float strikeStep = na
if (symbol == “BANKNIFTY” or symbol == “SENSEX” or symbol == “BANKEX”)
strikeStep := 100
else if (symbol == “NIFTY” or symbol == “FINNIFTY”)
strikeStep := 50
else if (symbol == “MIDCPNIFTY”)
strikeStep := 25

upBound_buy = ta.highest(high, 20)
upBound_sell = ta.highest(high, 20)
downBound_short = ta.lowest(low, 20)
downBound_cover = ta.lowest(low, 20)

callbuytext = math.floor(upBound_buy / strikeStep) * strikeStep - opt_level * strikeStep
callselltext = math.floor(upBound_sell / strikeStep) * strikeStep - opt_level * strikeStep
putbuytext = math.ceil(downBound_short / strikeStep) * strikeStep + opt_level * strikeStep
putselltext = math.ceil(downBound_cover / strikeStep) * strikeStep + opt_level * strikeStep

// Risk Management Settings
groupRisk = “Risk Management”
inpTakeProfit = input.int(defval=15000, title=“Take Profit”, minval=0, group=groupRisk)
inpStopLoss = input.int(defval=3000, title=“Stop Loss”, minval=0, group=groupRisk)
inpTrailStop = input.int(defval=100, title=“Trailing Stop Loss”, minval=0, group=groupRisk)
inpTrailOffset = input.int(defval=1, title=“Trailing Stop Loss Offset”, minval=0, group=groupRisk)

// Logic Settings
XXXXXXXXXXX

//Risk Management Values
XXXXXXXXXXX

//Buy and Sell Strategy Conditions
XXXXXXXXXXXX

size = math.abs(strategy.position_size) // Find absolute value of position size to exit position properly

// Determine the exchange based on the selected symbol
var string exchange = “”
if (symbol == “NIFTY” or symbol == “BANKNIFTY” or symbol == “FINNIFTY” or symbol == “MIDCPNIFTY”)
exchange := “NSE”
else if (symbol == “BANKEX” or symbol == “SENSEX”)
exchange := “IDX”

//Dhan Webhook Messages - Dynamic Construct

long_msg = ‘{“secret”:"’ + secretCode + ‘“,“alertType”:“multi_leg_order”,“order_legs”:[{“transactionType”:“B”,“orderType”:“MKT”,“quantity”:”’ + str.tostring(quantity) + ‘“,“exchange”:”’ + exchange + ‘“,“symbol”:”’ + symbol + ‘“,“instrument”:“OPT”,“productType”:“I”,“sort_order”:“1”,“price”:“0”,“option_type”:“CE”,“strike_price”:”’ + str.tostring(callbuytext) + ‘.0",“expiry_date”:"’ + expiryDate + ‘"}]}’
short_msg = ‘{“secret”:"’ + secretCode + ‘“,“alertType”:“multi_leg_order”,“order_legs”:[{“transactionType”:“B”,“orderType”:“MKT”,“quantity”:”’ + str.tostring(quantity) + ‘“,“exchange”:”’ + exchange + ‘“,“symbol”:”’ + symbol + ‘“,“instrument”:“OPT”,“productType”:“I”,“sort_order”:“1”,“price”:“0”,“option_type”:“PE”,“strike_price”:”’ + str.tostring(putbuytext) + ‘.0",“expiry_date”:"’ + expiryDate + ‘"}]}’
long_exit_msg = ‘{“secret”:"’ + secretCode + ‘“,“alertType”:“multi_leg_order”,“order_legs”:[{“transactionType”:“S”,“orderType”:“MKT”,“quantity”:”’ + str.tostring(quantity) + ‘“,“exchange”:”’ + exchange + ‘“,“symbol”:”’ + symbol + ‘“,“instrument”:“OPT”,“productType”:“I”,“sort_order”:“1”,“price”:“0”,“option_type”:“CE”,“strike_price”:”’ + str.tostring(callselltext) + ‘.0",“expiry_date”:"’ + expiryDate + ‘"}]}’
short_exit_msg = ‘{“secret”:"’ + secretCode + ‘“,“alertType”:“multi_leg_order”,“order_legs”:[{“transactionType”:“S”,“orderType”:“MKT”,“quantity”:”’ + str.tostring(quantity) + ‘“,“exchange”:”’ + exchange + ‘“,“symbol”:”’ + symbol + ‘“,“instrument”:“OPT”,“productType”:“I”,“sort_order”:“1”,“price”:“0”,“option_type”:“PE”,“strike_price”:”’ + str.tostring(putselltext) + ‘.0",“expiry_date”:"’ + expiryDate + ‘"}]}’

//Date Range Settings
groupDateRange = “Date Range for Backtesting”
startDate = input.time(timestamp(“2023-01-01 00:00”), title=“Start Date”, group=groupDateRange)
endDate = input.time(timestamp(“2024-12-31 23:59”), title=“End Date”, group=groupDateRange)

// Only run the strategy if the current time is within the date range
inDateRange = (time >= startDate and time <= endDate)

//Submit Orders Based on Signals

if (inDateRange and strategy.position_size == 0) // No active position
if (longEntryCondition)
strategy.order(“Long”, strategy.long)
alert(long_msg, freq=alert.freq_all) // Trigger alert for long entry
if (shortEntryCondition)
strategy.order(“Short”, strategy.short)
alert(short_msg, freq=alert.freq_all) // Trigger alert for short entry

if (inDateRange and strategy.position_size > 0) // Long position active
if (shortEntryCondition)
strategy.order(“Short”, strategy.short, qty=size)
alert(short_msg, freq=alert.freq_all) // Trigger alert for short entry
else
strategy.exit(“Long Exit”, from_entry=“Long”, qty=size, stop=useStopLoss, limit=useTakeProfit, alert_message=long_exit_msg) // Trigger alert for long exit

if (inDateRange and strategy.position_size < 0) // Short position active
if (longEntryCondition)
strategy.order(“Long”, strategy.long, qty=size)
alert(long_msg, freq=alert.freq_all) // Trigger alert for long entry
else
strategy.exit(“Short Exit”, from_entry=“Short”, qty=size, stop=useStopLoss, limit=useTakeProfit, alert_message=short_exit_msg) // Trigger alert for short exit

//Risk Management Exits (Outside Alerts)
if (inDateRange)
strategy.exit(“Exit Long”, from_entry=“Long”, profit=useTakeProfit, loss=useStopLoss, trail_points=useTrailStop, trail_offset=useTrailOffset, alert_message=long_exit_msg)
strategy.exit(“Exit Short”, from_entry=“Short”, profit=useTakeProfit, loss=useStopLoss, trail_points=useTrailStop, trail_offset=useTrailOffset, alert_message=short_exit_msg)

// Alert message - {{strategy.order.alert_message}}

I have checked for extra quotes in the webhook construct, but i couldn’t find the issue, It would be so helpful if you could point it out

And I hope other traders find this structure helpful, all they need to do is to enter there core logic in.

Thank You!!

1 Like

U can ignore my “extra quote” reference. That’s how the alert log message appears when we keep the mouse over it.

When u created the alert for SENSEX did u paste the webhook URL correctly ? Am not seeing any obvious error in u r script.

Yes i did copy and paste the Webhook URL and Secret Code accurately!!

Then I don’t know why it is not firing for SENSEX options.

@t7support

Hello, I have just check the script.
for MidCap entries and exits have fired accurately and orders have been places in Dhan, but signals didn’t fire for Bankex.
We only have issues with Sensex and Bankex!!

1 Like

@Hardik any issue with firing orders for BSE contracts via webhooks ?

Hello @t7support @Prudhvi_Prasanth

Checking this.

1 Like

I also checked now. Orders doesn’t fire for BSE contracts via webhooks.

Hello @Prudhvi_Prasanth @t7support

Yes, just checked this. There is a parameter which is getting incorrectly populated while generating JSON. For BSE Bankex/Sensex orders, it is take exchange as IDX, which should be BSE.

We will release fix on frontend soon, but you can customise this, it is a workaround for now.

2 Likes

After changing to BSE in the webhook construct, it’s working!!

1 Like

Worked for me too…:+1: But this was just for testing.

2 Likes

@Hardik @t7support

I have few question to ask!

  1. My strategy works best in 1D time frame, So the issue is after Pre-Market we’ll be getting the % of the gap up/gap down. When we get that, my strategy gives a Buy/Sell signal as per the Gap up/Gap down, for instance today i got a signal when the pre-market is closed at around 9:07:51am but once when the market is open Orders did not got placed in Dhan.

  2. My strategy is more like scalping, so once the signal is generated, there is a slight delay when orders are being placed, by then huge momentum is happening and I’m getting trapped cause few trades will enter and exit in the same candle. I understand they’ll be a slight delay when we use Webhook integration. It would be fantastic if we could reduce this delay.

  3. This might be a random thought, Correct me if i sound lame. but what if, if you could add an option to add a pine script strategy indicator into the Dhan Charts itself? In this case i hope there will be no need to use Webhook integration, and there will no delay when Signals are generated and placing order.

In a strategy file u need to force calculation on every tick and check for realtime bar state if u want to fire orders based on signals that are generated at pre market close. Otherwise it will fire alert at pre market tick but because market is not open u r order won’t be executed.

TV alert to Exchange execution time is less than 1Sec typically. I would assume that is fast enough for most of the retail.

Stock brokers like Dhan use free charting library for charting in their platform. Tradingview doesn’t expose pine script feature to this free library. Therefore this feature implementation may not happen at the broker end.

1 Like

So, i have to use Force real-time calculations on each tick
calc_on_every_tick=True

and checking the market state to place order after market is open.

var bool marketOpen = na
if (hour(time) >= 9 and minute(time) >= 15)
marketOpen := true
else
marketOpen := false

Right?

@t7support and thank you for your response on other issues too.

1 Like

This is needed only if u need to check bar states.

This should be enough to do what you are looking for.

1 Like