In PineScript (version 4), I’m trying to draw half-straight lines starting from swing high-low pivot points. The challenge is that I can’t figure out how to selectively draw only the lines closest to the current price.
Ideally, only two lines should be displayed: one starting from the closest pivot point above the current price, and another from the closest pivot point below the current price.
I believe the solution involves storing the distances between the current price and pivot points in an array, then selectively drawing only the lines corresponding to the minimum distances. However, I’m not sure how to implement this in PineScript.
Can anyone provide guidance on how to achieve this selective drawing of the closest pivot lines in PineScript?
Here is the script to draw half-straight lines from swing high-low pivot points.
//@version=4
study("Pivot High Low Points for monitor", overlay=true)
// Input parameters
lb = input(defval=5, title="Left Bars")
rb = input(defval=5, title="Right Bars")
line_length = input(defval=10, title="Line Length", minval=0)
show_high_lines = input(defval=true, title="Show High Lines", type=input.bool)
show_low_lines = input(defval=true, title="Show Low Lines", type=input.bool)
show_labels = input(defval=true, title="Show Labels", type=input.bool)
// New input for custom timeframe
custom_timeframe = input(title="Custom Timeframe", type=input.resolution, defval="")
mb = lb + rb + 1
// Function to get data from custom timeframe
get_custom_data(src) =>
security(syminfo.tickerid, custom_timeframe, src)
// Pivot High and Low calculations using custom timeframe
custom_high = get_custom_data(high)
custom_low = get_custom_data(low)
custom_close = get_custom_data(close)
pivot_high = iff(not na(custom_high[mb]), iff(highestbars(custom_high, mb) == -lb, custom_high[lb], na), na)
pivot_low = iff(not na(custom_low[mb]), iff(lowestbars(custom_low, mb) == -lb, custom_low[lb], na), na)
// Plot pivot points
plotshape(pivot_high, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, offset=-lb, transp=50)
plotshape(pivot_low, style=shape.triangleup, location=location.belowbar, color=color.lime, size=size.small, offset=-lb, transp=50)
// Draw lines and labels from pivot points if line_length > 0
if line_length > 0
if not na(pivot_high)
if show_high_lines
line.new(x1=bar_index[lb], y1=pivot_high, x2=bar_index[lb] + line_length, y2=pivot_high, color=color.red, width=1)
if show_labels
label.new(x=bar_index[lb], y=pivot_high, text=tostring(pivot_high, "#.#####"), color=color.red, style=label.style_none, textcolor=color.red, size=size.large, yloc=yloc.abovebar)
if not na(pivot_low)
if show_low_lines
line.new(x1=bar_index[lb], y1=pivot_low, x2=bar_index[lb] + line_length, y2=pivot_low, color=color.lime, width=1)
if show_labels
label.new(x=bar_index[lb], y=pivot_low, text=tostring(pivot_low, "#.#####"), color=color.lime, style=label.style_none, textcolor=color.lime, size=size.large, yloc=yloc.belowbar)