VWAP of last days in intraday chart

Again I have some difficulties to translate some easylanguage code into afl.
First I calculate, for exemple in a 5 min chart, the VWAP (Volume-Weighted Average Price)
which generates a dynamical line like a moving average.
Now I want to conserve when the date changes the previous last value in a way that I get the
4 last static values for the past 4 days.
In easylanguage this is simple as I can roll 4 variables until they are filled

If date > date[1] then begin
D4 = D3;
D3 = D2;
D2 = D1;
D1 = vwapp;
vwapp = 0;
end;

So the last VWAP is conserved in D1 and the new VWAP is reset to 0
to start the new day. At the end I have conserved this way the final
VWAP values for the 4 last days.
But I just can't find the way to do this with afl. Neither with 'Lastvalue'
nor with something like

NewDay = Day() != Ref( Day(), -1 );
D1 = ValueWhen( NewDay,VWAP, 1 );

neither with static variables, nothing works.
So I would be grateful for any suggestion.

Not tested,....

function SumSinceInclusive( condition, array )
{
  return SumSince( condition, array ) + ValueWhen( condition, array );
}
EndOfDay = Day() != Ref(Day(), 1);
DayStart = Day() != Ref(Day(), -1);
DayVolume = SumSinceInclusive( DayStart, Volume); 
vWapDay = SumSinceInclusive( DayStart, (H + L + C) / 3 * Volume); 
vWapDay = vWapDay / Max(DayVolume, 0.00001);
Plot(vWapDay, "\nVWap", colorRed, styleThick);
D2 = ValueWhen(EndOfDay, vWapDay, 1);
D3 = ValueWhen(EndOfDay, vWapDay, 2);
D4 = ValueWhen(EndOfDay, vWapDay, 3);
Plot(D2, "D2", colorblue, styleThick);
Plot(D3, "D3", colorGreen, styleThick);
Plot(D4, "D4", colorOrange, styleThick);

3 Likes

Thank you very much. This indeed resolves basically the problem. I just added the D1
which was paradoxically lacking to get all the 4 days added.
There is just a little problem remaining. In smaller timeframes the lines simply disappear.
In the hourly all the 5 lines are visible, in 15 min only 4 lines remain, in 5 min only the
VWAP line is visible and in 1 min chart all lines have disappeared. It seems that
the price where the lines are anchored must be in the visible window, so lines tend also
to disappear when one scrolls through the chart.

Read and see if helps
https://www.amibroker.com/kb/2008/07/03/quickafl/

That's perfect now.
By just adding in the beginning

SetBarsRequired( 1500, 0 );

it covers all necessary data for 1 minute chart and a fortiory for lower timeframes.
And it's still fast enough. :slight_smile:
Thank you very much !

I think I found a more precise way to calculate the barsrequired
but I guess it's even more time consuming :slight_smile:

function bars_of_today()
{
dt = DateTime();
dn = DateNum();
newday = dn != Ref( dn, -1);
bars_today = BarsSince(newday) + 1;
return bars_today;
}
bt = EndValue( bars_of_today()  );
SetBarsRequired( bt );