Ariza
Ariza

Reputation: 15

Pine script loop on bar index

I wanna check a condition for past n bars.

So if I want to do it for a specific number, i will use something like this, for 5 last bars:

cond = close > open
conditions = cond and cond[1] and cond[2] and cond[3] and cond[4] and cond[5]

But i need to use this method inside a function (for custom bar index numbers back)

I mean something like this:

check(condition,length)=>
    for i = 1 to length
        condition[bar_index] and condition[bar_index+i]

so i can use it like : check(close>open,5) I expect the answer be true or false.

I've tried many more loops but i can't get the one i need. Please tell me how to use it in function with a for loop.

Upvotes: 0

Views: 2451

Answers (2)

NVRM
NVRM

Reputation: 13146

Nowhere documented, inline example:

close[ta.barssince(time < timestamp("2021-11-07T14:30:00"))]

Upvotes: 1

AnyDozer
AnyDozer

Reputation: 2568

//@version=4
study("Help (check)")

check(_condition,_length) =>
    _check = true
    for i = 0 to _length
        _check := _check and _condition[i]


cond = close > open
conditions = cond and cond[1] and cond[2] and cond[3] and cond[4] and cond[5]

//bgcolor(conditions ? color.black : na)
bgcolor(check(cond,5) ? color.blue : na)

Upvotes: 0

Related Questions