I have come across this a few times on different occasions but couldnt work out why code was failing, this time around I “graph” the variables so I could check them on each candle. So what I am seeing is that when “BarsToCheck” is set to 10 the IF statement is found to be true and the code goes on to set s2 to TRUE, however if I then set BarsToCheck to 15 to include more candles it finds the IF statement to be false and not run the rest of the code?
If the condition exists in 10 candles it has to exist in 15 right? I have included a screen grab hovering over the same candle so that you can see that the IF statement fails(s2 is not set to TRUE/1) if it has to check more candles(even though the selection is bigger and the result should be the same in my eyes)..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Changable variables
BarsToCheck=15
// Short conditions
// EMA 50 is below 200 for a downtrend
s1=(ema50<ema200)
// Price has closed above the 50 EMA in the last N candles
FYI I just figured this out, and now I feel silly but I will leave it up for anyone ELSE (excuse the pun) who runs in to this.
It was because I was using an ELSE clause in my code block. As in if it finds the condition to be true in on the Nth candle it then overwrites that with the remaining for loops. I have set the s2 variable to false to begin with outside the loop and now there isnt an issue as it doesnt get overwritten:
1
2
3
4
5
6
7
s2=0// placed the false setting here and now it works :-)
Yes of course, the loop will go the end as long as you don’t BREAK it, so your s2 variable could be set to 0 even if you have set it to 1 previously in the loop.
Your first version could be modified with a BREAK at first iteration that found that your Close[i]>ema50 is found:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Changable variables
BarsToCheck=15
// Short conditions
// EMA 50 is below 200 for a downtrend
s1=(ema50<ema200)
// Price has closed above the 50 EMA in the last N candles
To help us continually offer you the best experience on ProRealCode, we use cookies. By clicking on "Continue" you are agreeing to our use of them. You can also check our "privacy policy" page for more information.Continue