3

In Pine-script, I need to assign the value of the previous bar to the current bar based on a condition of the current bar in a custom indicator.

I have tried various methods of coding this resulting in either an internal server error or compile errors.

Pseudo-code:

If currentbar >= upperthreshold
   indicatorvalue = value1
Elseif currentbar <= lowerthreshold
   indicatorvalue = value2
Else
   indicatorvalue = indicatorvalue[currentbar-1]

The expected result is an indicator plot alternating between the 2 values in the pseudo-code provided, since the value of each bar falling between the thresholds is set to the value of the preceding bar.

Mark
  • 33
  • 1
  • 1
  • 4

1 Answers1

6

When you want to refer previous values, you can use the History Referencing Operator [].

Then all you need to do is check your conditions and use [] with := operator when you want to re-assign a value to a previously defined variable.

Here is a small example based on your pseudocode. The background color changes depending on your conditions. I have also plotted two horizontal lines to see the upper/lower thresholds. This way you can see that the background color stays the same when the price is between upper and lower threshold.

//@version=3
study("My Script", overlay=true)

upper_threshold = input(title="Upper Threshold", type=integer, defval=7000)
lower_threshold = input(title="Lower Threshold", type=integer, defval=6000)

color_value = gray

if (close >= upper_threshold)
    color_value := green
else 
    if (close <= lower_threshold)
        color_value := red
    else
        color_value := nz(color_value[1])

bgcolor(color=color_value, transp=70)

hline(price=upper_threshold, title="Upper Line", color=olive, linestyle=dashed, linewidth=2)
hline(price=lower_threshold, title="Lower Line", color=orange, linestyle=dashed, linewidth=2)

enter image description here

vitruvius
  • 15,740
  • 3
  • 16
  • 26
  • Perfect, thank you. One thing that I don't quite understand: In the line "color_value := nz(color_value[1])" I would've expected "n-1" in brackets to reference the value in the bar preceding the current bar to replace NaN (and the requisite check to ensure n>0) ... why just "1"? Thanks again! – Mark Jun 05 '19 at 17:46
  • 2
    That’s the way [] operator works. For example, close[0] means current close price. close[1] means close price of one bar ago. close[2] means close price of two bars ago. Did you read the link in my answer? – vitruvius Jun 06 '19 at 18:46
  • Saw the link only after posting the comment. :\ Thanks for the follow up! – Mark Jun 07 '19 at 19:37