Reputation: 37
//@version=4
In the "for loop" piece of code "for i = index_cross to 50"
(lines 22 - 24) I'm looking for the rsi[i] < oversold
value. I have the "max_bars_back=50" but the script keeps giving me the indicator error: Pine cannot determine the referencing lenght of a series. Try using max_bars_back in the study or strategy function.
1 study("error max bars back", overlay=false, max_bars_back=50)
2
3 //input
4 oversold = input(30, title="oversold")
5 rsiLen = input(14, title="rsi len")
6
7 //rsi and ema
8 rsi = rsi(close, rsiLen)
9 ema1 = ema(close, 21)
10 ema2 = ema(close,50)
11
12 //condition 1
13 cross=crossover(ema1, ema2)
14
15 //index of condition (used in the for loop)
16 index_cross = 0
17 if cross
18 index_cross := bar_index
19
20 //condition 2
21 bool rsi_valid = false
22 for i = index_cross to 50
23 if rsi[i] < oversold
24 rsi_valid := true
25
26 //final condition and plot
27 a = rsi_valid == true ? 1 : 0
28 plot(a, color=color.white)
My goal with this script is to determine if "from the crossover to 50 bars before" the rsi has been < 30(oversold). Thank you for the support.
Upvotes: 0
Views: 1812
Reputation: 21362
You actually don't need a for loop. You can use a different algorithm.
You can just use a counter and increment it whenever rsi is oversold and reset it otherwise. So, for each bar that has rsi oversold, you would do counter = counter + 1
and if at anytime it becomes overbought, simply counter = 0
.
When your "cross" happens, look if your counter is > 50. That would mean that the during the last 50 bars rsi is oversold.
Algorithm:
var oversoldCnt = 0 // A counter for consecutive rsi oversold bars
oversoldCnt := iff(rsi < oversold, oversoldCnt + 1, 0) // Increase the counter if rsi is still oversold, reset otherwise
Together with your code:
//@version=4
study("error max bars back", overlay=false, max_bars_back=50)
//input
oversold = input(30, title="oversold")
rsiLen = input(14, title="rsi len")
//rsi and ema
rsi = rsi(close, rsiLen)
ema1 = ema(close, 21)
ema2 = ema(close,50)
var oversoldCnt = 0 // A counter for consecutive rsi oversold bars
oversoldCnt := iff(rsi < oversold, oversoldCnt + 1, 0) // Increase the counter if rsi is still oversold, reset otherwise
//condition 1
cross=crossover(ema1, ema2)
bool rsi_valid = cross and (oversoldCnt > 50)
//final condition and plot
a = rsi_valid == true ? 1 : 0
plot(a, color=color.white)
I simplified your code, so the whole thing might not work as you wish but I hope the algorithm is clear. Let me know if you have any questions.
Upvotes: 1