Bar Number of Current Bar

Hi,

How can I know the Bar Number of current bar in AFL.

I tried using

bi = BarIndex();
sar1 = SAR(0.01);
sarsigs = C < sar1 AND Ref(C,-1) > Ref(sar1,-1);
BarNum = SelectedValue(ValueWhen(sarsigs,bi));

@simran.dm, try this modified code snippet:

bi = BarIndex();
sar1 = SAR(0.01);
sarsigs = C < sar1 AND Ref(C,-1) > Ref(sar1,-1);
// Here I changed SelectedValue() to LastValue()
lastSarSiggBarNum = LastValue(ValueWhen(sarsigs, bi));
_TRACE("Last Bar Num for sarsigs: " + lastSarSiggBarNum);
Plot(Close, "C", colorDefault, styleCandle);
Plot(Sar1, "SAR", colorRed, styleDots);
PlotShapes(sarsigs * shapeStar, colorYellow, 0, sar1, 10); 
PlotText(StrFormat("%1.0f", lastSarSiggBarNum), lastSarSiggBarNum, sar1[lastSarSiggBarNum], colorWhite, colorRed);

currentlySelectedBarNum = SelectedValue(bi);
_TRACE("Currently selected BarNum " + currentlySelectedBarNum);
// plot the current bar text at the close price level
PlotText(StrFormat("%1.0f", currentlySelectedBarNum), currentlySelectedBarNum, C[currentlySelectedBarNum], colorBlack, colorAqua, 10);

It shows the different use of LastValue() versus SelectedValue(). The latter main purpose is in commentary and interpreration code.
There are also some other similar functions that you may want to study (for instance to limit your choice only to visible bars).

When coding I always keep open a page to the AFL Function Reference - Categorized list of functions. It is a very useful resource to explore the vast 'array' :wink: of AmiBroker functions!

3 Likes

Here is the simplest script possible I could think off:

printf("Barindex = "+BarIndex()+"\n");