Looping for last n periods

The below code gives positive bars(Close>Open) and negative bars (open>Close) as a percentage of total bars since the Start of intraday. What i want to achieve is to be able to get the same calculation but instead of Start of intraday, say last 10 periods. Can any one suggest some help with the below code to just do the same calculatio for last 10 periods.

Newday=DateNum()!=Ref(DateNum(),-1);
 TotalBars=BarsSince(Newday)+1;
 PosBars=0;
 NegBars=0;
 WinBarscount=0;
 LoseBarscount=0;	
 

 for(i = 0; i <BarCount; i++)
 {
 if(Newday[i]==True) // 
 {
 PosBars[i]=0;
 NegBars[i]=0;
 WinBarscount=0;
 LoseBarscount=0;	
 }

 if(C[i]-O[i]>0)
 {
 WinBarscount++;
 PosBars[i]=WinBarscount;
 NegBars[i]=LoseBarscount;
 }

 if(C[i]-O[i]<=0)
 {
 LoseBarscount++;
 NegBars[i]=LoseBarscount;
 PosBars[i]=WinBarscount;
 }

 }

PosMom=PosBars/(TotalBars+1e-9);
NgMom=NegBars/(TotalBars+1e-9);

Please listen... you do not need any loop for that.

The same goal of your posted looping code can be achieved via array processing.
Seven fast code lines vs. your "endless" lines (+ slower code using AFL loop).
All it takes are SumSince and ValueWhen functions.

dn = DateNum();
newday = dn != Ref( dn, -1);
TotalBars = BarsSince(newday)+1;

upcond = C-O > 0;
PosMom = (SumSince(newday, upcond) + ValueWhen(newday, upcond)) / TotalBars;

dncond = ! upcond;
NgMom = (SumSince(newday, dncond) + ValueWhen(newday, dncond)) / TotalBars;

Use Sum function

period = 10;

TotalBars = Max(1, period);

upcond = C-O > 0;
PosMom = Sum(upcond, TotalBars) / TotalBars;

dncond = ! upcond;
NgMom = Sum(dncond, TotalBars) / TotalBars;

Or shorter.... MA function

period = 10;

TotalBars = Max(1, period);

upcond = C-O > 0;
PosMom = MA(upcond, TotalBars);

dncond = ! upcond;
NgMom = MA(dncond, TotalBars);
6 Likes

Or simpler... using MA (...again)

dn = DateNum();
newday = dn != Ref( dn, -1);
TotalBars = BarsSince(newday)+1;

upcond = C-O > 0;
PosMom = MA(upcond, TotalBars);

dncond = ! upcond;
NgMom = MA(dncond, TotalBars);
6 Likes

Not only does the array processor make the code run faster but it is so much cleaner and more elegant.
Thanks, @fxshrat for the lesson.

2 Likes

thank you @fxshrat for putting this in a simple way. i was breaking my head around it by looping.