KarlEs
KarlEs

Reputation: 71

How to declare a consideration period for conditions in PineScript?

How to declare a consideration period for conditions in PineScript?

I want PineScript to check if two conditions are/were met in the same time period.

Example:

IndexValue = 0

If in the same week the RSI was > 20 and the MACD was > 25, then the IndexValue should increase by one (+1). This means that the two indicators do not have to be true on the same day. Even if both generate a signal on different days in the same week, the condition is considered fulfilled and the IndexValue should increase by one.

So the program should simply check the two conditions in 7-day periods and increase the index value by one if both are true in the same week.

Many thanks in advance!

Upvotes: 0

Views: 118

Answers (2)

Rohit Agarwal
Rohit Agarwal

Reputation: 1368

After calculating rsi and macd, you can create a variable which will be set to true whenever both conditions are met in a week. At end of week, we will check for the variable and increment index and reset the variable for next week. Example below

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

rsi=ta.rsi(close,14)
[macd,signal,histogram]=ta.macd(close,12,26,9)
var IndexValue =0 
var conditiontrueinweek=false
if rsi>20 and macd>1
    conditiontrueinweek:=true
bi=request.security(syminfo.tickerid,"W",bar_index)
if bi>bi[1] //check if new week has started
    if conditiontrueinweek
        IndexValue:=IndexValue+1
    conditiontrueinweek:=false
plot(IndexValue)

Upvotes: 0

EliseBee
EliseBee

Reputation: 31

//
// use request.security to access the values from the same week
// 
RSIval = request.security(syminfo.tickerid, "W", ta.rsi(..) )
MACDval = request.security(syminfo.tickerid, "W", ta.macd(..) )
if RSIval > 20 and MACDval > 25
...

Upvotes: 0

Related Questions