I am trying to find the number of consecutive down closes within only the last 20 bars. How can I adjust this loop to accomplish this?
LDC_LookBack = 19;
for ( i = 0; i < LDC_LookBack; i++ )
{
ConsecDwnClosCnt = 0;
}
for ( i = LDC_LookBack; i < BarCount; i++ )
{
if ( Close[i] < Close[i-1] )
{
ConsecDwnClosCnt++;
}
else
{
ConsecDwnClosCnt = 0;
}
LDC_ConsecDwnClosesCnt[i] = ConsecDwnClosCnt;
}
So, in the above code I need to add something that will reset LDC_ConsecDwnClosesCnt to zero on the twentieth bar back from the current bar so that the count only starts within the last twenty bars.
1 Like
@vjsworld this is "AmiBroker world" my good man
Think in arrays not loops.
I'm on my phone so can't code it but you just need to code the consecutive downs as a condition, then Sum(condition, 20).
@vjsworld, if I understand your goal correctly, I think something like this would work:
LDC_Lookback = 20;
isDownClose = C < Ref(C,-1);
cntConsecDownCloses = BarsSince(!isDownClose);
LDC_ConsecDownCloses = Min(cntConsecDownCloses, LDC_Lookback);
Matt I feel he needs to clarify his question, is he looking for the longest "run" or the total number of consecutive down closes. (I think his loop is looking for the run)
It's the longest run within the last 20 bars... So, starting with the 20th bar ago, start counting number of down closes, and reset every time there is not a down close. Whatever the largest count is at the end of the 20 bars is the number I need.
I originally assumed you were looking for the longest run, but since your loop was not tracking any sort of max value, I gave you non-looping code that provided similar functionality: what is the length of the down close run that ended on the current bar?
Without your requirement to reset the count at the beginning of the 20 bar lookback, the longest run is easy to find:
LDC_Lookback = 20;
isDownClose = C < Ref(C,-1);
cntConsecDownCloses = BarsSince(!isDownClose);
LDC_MaxDownCloseRun = HHV(cntConsecDownCloses, LDC_Lookback);
Still considering whether there is an elegant solution to "reset" the count at the beginning of the lookback.
1 Like
That's the reason I went with the loop. I could not think of a way to do it without......
I think that this will achieve your goal. However, you should test it to confirm:
function BarsUntil(array)
{
bu = Reverse(BarsSince(Reverse(array)));
return bu;
}
LDC_Lookback = 20;
isDownClose = C < Ref(C,-1);
fwdRunLength = BarsUntil(!isDownClose);
lastRunLength = BarsSince(!isDownClose);
maxRunLength = Max(Ref(HHV(fwdRunLength, LDC_Lookback - lastRunLength), -lastRunLength), lastRunLength);
By looking at the remaining length of each run (fwdRunLength) we eliminate the problem of needing a "reset" at the beginning of your lookback window. That must means we have to deal with the last run in the lookback window by ignoring it when we calculate the "initial max" length using Ref(HHV())
, and then include the length of that run when we use Max()
to get the final answer.
7 Likes