Skip to content

Instantly share code, notes, and snippets.

@kesor
Last active May 23, 2024 23:34
Show Gist options
  • Save kesor/f156b1e1cbe5141ae9527b5f8d351a5b to your computer and use it in GitHub Desktop.
Save kesor/f156b1e1cbe5141ae9527b5f8d351a5b to your computer and use it in GitHub Desktop.
TradingView Pine Script indicator for Pivot points and Support-Resistance lines
//@version=5
indicator("Pivot SRs", overlay=true)
lookback = input.int(12, "Lookaround bars")
number_of_lines = input.int(5, "Lines to keep")
getLastNonNaInfo(series) =>
float lastValue = na
int lastIndex = na
for i = 0 to 1000 // Adjust the range as necessary
if not na(series[i])
lastValue := series[i]
lastIndex := bar_index[i]
break // Exit loop after finding the last non-na value
[lastValue, lastIndex]
ph = ta.pivothigh(high, lookback, lookback)
pl = ta.pivotlow(low, lookback, lookback)
combined = nz(na(ph)) ? pl : ph
plotshape(ph, title="Highs", color=color.red, style=shape.triangledown, size=size.tiny, offset=-lookback, location=location.abovebar)
plotshape(pl, title="Lows", color=color.green, style=shape.triangleup, size=size.tiny, offset=-lookback, location=location.belowbar)
var line[] lines = array.new_line(0)
[last_pl, last_pl_bar] = getLastNonNaInfo(pl)
[last_ph, last_ph_bar] = getLastNonNaInfo(ph)
if (not na(ph))
ph_line = line.new(last_bar_index, high[lookback], last_ph_bar - lookback, high[lookback], color=color.orange, extend=extend.left)
array.unshift(lines, ph_line)
if (not na(pl))
pl_line = line.new(last_bar_index, low[lookback], last_pl_bar - lookback, low[lookback], color=color.orange, extend=extend.left)
array.unshift(lines, pl_line)
if (array.size(lines) >= number_of_lines)
line.delete(array.pop(lines)) // Remove the oldest line first if there are already two lines
var label[] labels = array.new_label(0)
if (not na(ph))
ph_label = label.new(bar_index - lookback, high[lookback], str.tostring(high[lookback],"#.##"), style=label.style_none, yloc=yloc.abovebar, textcolor = color.white)
array.unshift(labels, ph_label)
if (not na(pl))
pl_label = label.new(bar_index - lookback, low[lookback], str.tostring(low[lookback],"#.##"), style=label.style_none, yloc=yloc.belowbar, textcolor = color.white)
array.unshift(labels, pl_label)
if (array.size(labels) > number_of_lines)
label.delete(array.pop(labels))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment