I want to develop an indicator that plots a label when a stock drops by 10% from the recent high.
The code I wrote initially works fine, but I keep plotting a 10% drop label after 10% on all candles.
I changed the code so that when a stock drops 10% from the previous high, the plot 10% drop label only once. If the stock drops an additional 10%, then it plots a 20% label.
//@version=5
indicator(title='Drop10%', shorttitle='Drop10%', precision=2, overlay=true, max_bars_back=1000)
// Define length for the highest high
length = input.int(50, minval=1, title='Lookback Period for High')
// Calculate the highest high over the lookback period
recentHigh = ta.highest(high, length)
// Calculate the percentage drops
drop10 = recentHigh * 0.90
drop20 = recentHigh * 0.80
// Flags to track if labels have been plotted
var bool drop10LabelPlotted = false
var bool drop20LabelPlotted = false
// Conditions for the drops
drop10Condition = close <= drop10
drop20Condition = close <= drop20
// Reset the flags if the price goes above the recent high
if close > recentHigh
drop10LabelPlotted := false
drop20LabelPlotted := false
// Plot the labels if conditions are met and flags are not set
if drop10Condition and not drop10LabelPlotted
label.new(bar_index, na, text='10%', color=color.red, textcolor=color.white, style=label.style_label_down, yloc=yloc.abovebar)
drop10LabelPlotted := true
if drop20Condition and not drop20LabelPlotted
label.new(bar_index, na, text='20%', color=color.red, textcolor=color.white, style=label.style_label_down, yloc=yloc.abovebar)
drop20LabelPlotted := true
The problem now is “if close > recentHigh” won’t reset the ‘drop10LabelPlotted’ and ‘drop20LabelPlotted’ and it won’t plot any label.
Any help would be much appreciated.