Search code examples
pine-scriptpine-script-v5trading

Use bar_index from label plot to get length/lookback input for another function


I'm currently trying to combine two indicators where the first function shows the lowest bar since n'th days. When found it plots a label with price on that bar_index. Now, I'd like to add the regression channel indicator but with that bar_index as an input on the length / lookback.

Function 1 (lowest label):

//@version=5
indicator("Test", "", true)

lowLB = input(20, "Low Lookback")

lo = ta.lowest(lowLB)
lowestBarOffset = - ta.lowestbars(lowLB)

// Create label on bar zero only.
var lbl = label.new(na, na, "", color = color.rgb(190, 190, 190), style=label.style_label_upper_right)
// When a new low is found, move the label there and update its text and tooltip.
    if ta.change(lo)
    // Build label and tooltip strings.
    labelText = "Low: " + str.tostring(lo, format.mintick)
    tooltipText = "Offest in bars: " + str.tostring(lowestBarOffset) + "\nLow: " + str.tostring(low[lowestBarOffset], format.mintick)
    // Update the label's position, text and tooltip.
    label.set_xy(lbl, bar_index[lowestBarOffset], lo)
    label.set_text(lbl, labelText)
    label.set_tooltip(lbl, tooltipText)

Function 2 (regression channel snippet):

lengthInput = input(<INPUT_FROM_FUNCTION_1>, title="Length")    <------- ?
sourceInput = input.source(close, title="Source")

group1 = "Channel Settings"
useUpperDevInput = input.bool(true, title="Upper Deviation", inline = "Upper Deviation", group = group1)
upperMultInput = input.float(2.0, title="", inline = "Upper Deviation", group = group1) 
.....

How can I get the number of bars from the current bar to where the label is plotted in Function 1 as lengthInput in Function 2?

Tried looking at this code but I'm still having problems adapting it: Using bar_index as length for other highest()

I'm assuming I have to use barstate in some manner?


Solution

  • In your Function 1, the number of bars to where the label is plotted is :

    lowestBarOffset
    

    To get it as lengthInput in Function 2, use :

    lengthInput = lowestBarOffset // instead of lengthInput = input(...