3

Say I have condition 1 and condition 2. If condition 1 and condition 2 was met within up to, say, 5 bars, then I want to perform some action. As an example let's say condition 1 was met at current close, and condition 2 was fulfilled 5 bars ago, then I want to perform some action. How do I formulate that in Pine?

condition1 = ...
condition2 = ...

if (condition1(close)==true or condition1(close-2)==true  or             
condition1(close-3)==true  or condition1(close-4)==true  or     
condition1(close-5)==true)

and (condition2(close)==true or condition2(close-2)==true  or             
condition2(close-3)==true  or condition2(close-4)==true  or     
condition2(close-5)==true)

then...

Could it perhaps be formulated something like:

if condition1(close:close-5)== true and condition2(close:close-5)== true then ...

I have read e.g. this thread: Change background for only the last 5 bars: A Very Simple Problem I can't crack It sounds like a similar problem, but I am unsure about how to implement it.

User4536124
  • 37
  • 1
  • 11

1 Answers1

5

a) You would need to use ta.barssince() function.

https://www.tradingview.com/pine-script-reference/v5/#fun_ta%7Bdot%7Dbarssince

//@version=5
indicator("My Script")

/// let's say condition 1 was met at current close, and condition 2 was fulfilled 5 bars ago, then I want to perform some action

ema10 = ta.ema(close, 10)
condition1 = close > open
condition2 = ta.crossover(ema10, close)


x = false

if condition1 and ta.barssince(condition2) == 5
    x := true


plot(ema10)    
bgcolor(condition2? color.orange:na)
bgcolor(x?color.green:na)

b) Another approach is to use history-referencing operator [].

https://www.tradingview.com/pine-script-docs/en/v5/language/Operators.html#history-referencing-operator

//@version=5
indicator("My Script")

// lets say you want to check if condition2 if true for 5 bars, and condition1 is true in the current bar

ema10 = ta.ema(close, 10)
condition1 = ta.crossover(ema10, close) 
condition2 = close > open

condition3 = condition2[1] and condition2[2] and condition2[3] and condition2[4] and condition2[5]


x = false

if condition1 and condition3
    x := true

plot(ema10)    
bgcolor(condition2? color.orange:na)
bgcolor(x?color.green:na)




Starr Lucky
  • 1,578
  • 1
  • 7
  • 8
  • The orange bar should show where the ema10 crosses the close bar, but that is not the case in the plots? https://www.tradingview.com/chart/ZARAUD/bGbIl50V-orange-bar/ – User4536124 Dec 15 '21 at 18:10
  • updated figure where the issues are highlighted: https://www.tradingview.com/chart/ZARAUD/1ihdIfgr-orange-bar/ – User4536124 Dec 15 '21 at 18:17
  • for the answer to the above comments: https://stackoverflow.com/questions/70368687/ema-not-plotting-correctly-or-human-error/70370099#70370099 – User4536124 Dec 16 '21 at 20:33