Pine Script - Last bar with low value specified

76 views Asked by At

I've been working on an indicator in Pine Script that involves identifying the last candle (closest to the current time) with a low value specified by the user. However, I'm encountering a challenge where the functions 'barcolor' and 'plotshape' mark all bars on the chart whose low value matches the given price, instead of only marking the last relevant candle.

Here's a snippet of the indicator code I'm using:

// Indicator code
//@version=5
indicator(title = "Lowest Bar Finder", shorttitle = "LowBar", overlay = true)

// User input for pointX
var float pointX = na
pointX := input.price(title = "Low price", tooltip = "Enter low price to find last bar", defval = 1, confirm = true)

// Find pointXBar
var pointXArray = array.new_int()
pointXBars = bar_index - ta.barssince(pointX == low)
array.push(pointXArray, pointXBars)
pointXBar = array.last(pointXArray)

// Color and mark pointXBar
barcolor(bar_index == pointXBar ? color.rgb(255, 255, 255) : na)
plotshape(bar_index == pointXBar ? pointX : na, title = "pointX", location = location.belowbar, style = shape.triangleup, color = color.rgb(255, 0, 0), text = "pointX", textcolor = color.rgb(255, 0, 0), size = size.large)

I'm aiming to pinpoint the index of the last candle (pointXBar) with the specified low value to use it for subsequent calculations within the indicator. Could someone assist me in clearly defining the index of pointXBar, ensuring it represents the last candle with the specified low value closest to the current time? By the way, I'm new in coding... Any guidance or insights would be greatly appreciated. Thank you.

1

There are 1 answers

1
vitruvius On

Your script will be executed on every bar. That means, you cannot call barcolor() or plotshape() just for the last condition.

If you want to mark that bar, you can use a label instead and delete the old one with label.delete(). So, you would always have one label that is pointing to the last event.