Mark
Mark

Reputation: 43

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

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.

Upvotes: 4

Views: 14452

Answers (1)

vitruvius
vitruvius

Reputation: 21121

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

Upvotes: 6

Related Questions