简体   繁体   中英

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

//
// 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
...

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM