Pivots
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © syntaxgeek

//@version=5
indicator("Pivots", overlay=true)

// <inputs>
i_pivotLength = input.int(title='Pivot Length', defval = 8, tooltip='Length of historical data to reference when searching for pivot highs and lows.')
i_timeframe = input.timeframe(title='Timeframe', defval='')
i_timeframeGapsOn = input.bool(title='Timeframe Gaps?', defval=false)
// </inputs>

// <funcs>
f_renderGaps() =>
    i_timeframeGapsOn ? barmerge.gaps_on : barmerge.gaps_off

f_regSec(f) =>
    request.security(syminfo.tickerid, i_timeframe, f, f_renderGaps())
// </funcs>

// <vars>
v_barsLow = i_pivotLength
v_barsHigh = i_pivotLength
v_pivotHigh = f_regSec(fixnan(ta.pivothigh(v_barsLow, v_barsHigh)[1]))
v_pivotLow = f_regSec(fixnan(ta.pivotlow(v_barsLow, v_barsHigh)[1]))
// </vars>

// <plots>
plot(v_pivotHigh, "Resistance", ta.change(v_pivotHigh) ? na : color.red, 2, offset=-(i_pivotLength + 1), style=plot.style_linebr)
plot(v_pivotLow, "Support", ta.change(v_pivotLow) ? na : color.green, 2, offset=-(i_pivotLength + 1), style=plot.style_linebr)

var v_highLabel = label.new(bar_index, v_pivotHigh, style=label.style_label_lower_left, text=i_timeframe + ' ' + str.tostring(i_pivotLength) + ' High', color=ta.change(v_pivotHigh) ? na : color.red, textcolor=color.black)
label.set_xy(v_highLabel, bar_index , v_pivotHigh)
label.set_color(v_highLabel, ta.change(v_pivotHigh) ? na : color.red)

var v_lowLabel = label.new(bar_index, v_pivotLow, style=label.style_label_lower_left, text=i_timeframe + ' ' + str.tostring(i_pivotLength) + ' Low', color=ta.change(v_pivotLow) ? na : color.green, textcolor=color.black)
label.set_xy(v_lowLabel, bar_index , v_pivotLow)
label.set_color(v_lowLabel, ta.change(v_pivotLow) ? na : color.green)
// </plots>