Average only the last X qualified daily bars from an intraday chart

I have a strategy that uses intraday bars, but I need to get an average of the last X daily closing prices only when the daily open was greater than the daily close. So I need to find the last X occurrences of "dOpen > dClose" and then average the daily closing prices of those days.

I can successfully accomplish this with a loop on the intraday bars, but I need it on the daily bars from the intraday chart/analysis.

I originally tried it like this:

TimeFrameSet( inDaily );
for (i = 0; i < BarCount; i++)
{
//loop logic
}
RestoreTimeFrame();

But that does not work. It seems you cannot switch timeframes then loop. I've read in the manual how you can acquire daily data from intraday using:
dClose = TimeFrameGetPrice( "C", inDaily, -1 );

But the issue is that I do not know how many daily bars back I must go to find the last X qualified daily occurrences to then average. Could anyone please give me insight on how to accomplish this?

Has been explained here

2 Likes

@vjsworld,

My previous response was only half of actual response as I had to go...

Now, as to your actual "problem"...
There is not any problem and you do not need any loop for that.
All you need it below code example using Sparse* functions.

PS: Do not use for sale! I am not doing your job and you get paid for my spent time.

/// @link https://forum.amibroker.com/t/average-only-the-last-x-qualified-daily-bars-from-an-intraday-chart/8271/2
/// by fxshrat@gmail.com
MA_period = 5;
tmfrm = inDaily;
TimeFrameSet( tmfrm );
    cond = C > O;
    compC = SparseCompress(cond, C);
    Avg_D = SparseExpand(cond, MA(compC, MA_period));
TimeFrameRestore();

expandmode = expandLast;
cond =  TimeFrameExpand(cond, tmfrm , expandmode );
Avg_D = TimeFrameExpand(Avg_D, tmfrm, expandmode );

Plot( C, "Price", colorDefault, styleCandle );
Plot( ValueWhen( cond, Avg_D), "Avg_D", colorRed );

As you can see in picture... average is calculated only on daily bars where C > O.

405

5 Likes

Very nice @fxshrat !!!
Thank you