AFL Shapes Cheat Sheet

The plotshapes() can be used to plot shapes on your chart to indicate signals, stops, and other events and conditions. Figure 1 below gives a quick overview of the shapes that are available and includes a few undocumented ones. A PDF version suitable for printing is here: AFL Shapes Cheat Sheet

afl-shapes.png

Figure 1

Figure 2 shows the small AFL program that was used to explore all the built-in shapes and their numerical values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for ( i = 0; i < BarCount; i++ )
{
    O[i] = C[i] = i;
    H[i] = i + 5;
    L[i] = i - 5;
 
    if ( i % 2 == 0 )  {PlotText( NumToStr( i, 1.0, False ), i, L[i]-2, colorDarkGrey );}
    else  {PlotText( NumToStr( i, 1.0, False ), i, H[i]+.5, colorDarkGrey );}
}
PlotShapes( C, colorRed, 0, C, -10 );
Plot( C, "", colorLightGrey, styleBar );
 
Title = "Hollow = " + NumToStr( shapeHollowCircle - shapeCircle, 0, 0 ) + "\n" + 
	"Small = " + NumToStr( shapeSmallCircle - shapeCircle, 0, 0 );

aflshapesf2.png

Figure 2

With additions by Herman

1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 4.8 out of 5)
Loading ... Loading ...

Weekly High or Low Days

DRAFT

This code reports the probability of the high or low, for the week, occurring on any given day.

In its current form it is designed for running as an exploration and then exporting the results to a spreadsheet for analysis.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//P_WeeklyHL   
// Day of week numerical descriptor is from 0 == Sunday to 6 == Saturday    
// Identifies which day had the low and the high for the week     
// Export to Excel for counting     
// Note Excel has an upper limit of approx 65000 rows   
Filter = 1;   
WeeklyHigh = IIf(DayOfWeek() == 5, HHV(H,5),0);   
Plot(WeeklyHigh,"HighOfWeek(Value)",1,1);   
HSB = HighestSinceBars(DayOfWeek() == 1,H,1);   
HighOfWeekArray = 5 - HSB;   
HighOfWeek = IIf(DayOfWeek() == 5, HighOfWeekArray, 0);   
Plot(HighOfWeek,"HighOfWeek(Day)",2,1);   
AddColumn(HighOfWeek,"HighDayOfWeek",1,1);   
///////////////////////////////////////////   
//WeeklyLow = IIf(DayOfWeek() == 5, LLV(L,5),0);   
//Plot(WeeklyLow,"LowOfWeek(Value)",1,1);   
//LSB = LowestSinceBars(DayOfWeek() == 1,L,1);   
//LowOfWeekArray = 5 - LSB;   
//LowOfWeek = IIf(DayOfWeek() == 5, LowOfWeekArray, 0);   
//Plot(LowOfWeek,"LowOfWeek(Day)",2,1);   
//AddColumn(LowOfWeek,"LowDayOfWeek",1,1);

It can also be inserted into an indicator pane to allow users to cross-check the code output against expected values.

WHLD001

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 2.67 out of 5)
Loading ... Loading ...

Selected Date Range

A bar range, for processing, can be stipulated at the formula level.

The following code plots the Close, over a four month period, using the DateNum function (BarIndex can also be used in a similar way).

1
2
3
4
5
6
7
8
9
10
//P_SelectedRange 
 
///////////Plot a selected date range in the middle of chart using BarIndex or DateNum 
//Plot(IIf(BarIndex() >= 978 AND BarIndex() <= 988,C,Null),"",1,1);
Plot(IIf(DateNum() >= 1050101 AND DateNum() <= 1050430,C,Null),"",1,1); 
 
///////////Plot a selected range at the end of a chart 
LastBarIndex = LastValue(BarIndex()); 
//Plot(IIf(BarIndex() >= LastBarIndex - 10 AND BarIndex() <= LastBarIndex(),C,1)," ",8,1);
//Plot(IIf(BarIndex() >= LastBarIndex - 10,C,1)," ",8,1);

image

If the last line of code is uncommented the Close,for the last 10 bars only, will be plotted.

The formula can be adapted for use in other modes (filter, scan etc).

ATTACHED FILE:

p_selectedrange.afl

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4 out of 5)
Loading ... Loading ...

Abbreviated Identifiers v2

In AFL the identifiers Open, High, Low, Close, Volume, OpenInt and Avg are reserved for price field arrays. Of the small number of variables that are reserved the price identifiers are the only ones that can be abbreviated (OHLCVOI can be used instead of the longer form).

They are not case sensitive and when entered into a formula, in the Formula Editor, they will default to upper case and bold (as shown in the figure below).

image

This is very nice for speeding up formula writing but there is a ‘Catch 22′.

If abbreviated identifiers are used it makes the task of finding and replacing price arrays, using Formula Editor >> Edit >> Replace very tedious e.g. if the ‘writer’ wants to replace all “C’s” with a variable = = ParamField, for example, the Replace tool will pick up every “C” in the code and ask the user to confirm the replacement.

image

Checking Match whole word only in the Text Search Tool will change the criteria so that where “C” is part of a word it will be passed over while “C”, on it’s own, will be treated as a word and highlighted in the search report .

image

Note: The font format for reserved variables can be customized in Tools >> Preferences.

image

A handy tip for searching, with the Text Search Tool, is to position the cursor at the top of the code so that the search will begin from there. If the cursor is lower down the code the search will start from there and it will only traverse to the end before reporting that the search is complete.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Plotting Functions

For the syntactically challenged (is that a word?) plotting functions can provide an ‘explanation’ that can become obscure when put into words.

Here’s a silly little example.

1
2
3
/*PlotDateNum*/ 
 
Plot(DateNum(),"DateNumber",1);

Insert the formula, using daily bars, and scroll the datenum() plot using the keyboard arrows.

PlottingFunctions001

Note: The DateNum plot will display using two decimal points, by default. Ignore them as they are not relevant. They have been edited out of the image in this example.

Now turn to the AFL reference manual for comparison!

SYNTAX         datenum()

RETURNS      ARRAY

FUNCTION    Returns the array with numbers that represent quotation dates coded as follows: 10000 * (year - 1900) + 100 * month + day, so 2001-12-31 becomes 1011231 and 1995-12-31 becomes 951231

Of course, some people will prefer the latter version and some people will prefer the former, depending on their psychological typology.

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5 out of 5)
Loading ... Loading ...

BarCount versus BarIndex

The difference between BarCount and BarIndex can be confusing at first. Plotting can help new users ’see the picture’.

Copy and paste the following code into the Formula Editor and save it as P_BarCount before inserting it as a chart.

1
2
3
4
5
6
7
8
9
10
/*P_BarCount*/ 
 
Plot(BarCount,"BarCount",colorBlue); 
 
Plot(BarIndex(),"BarIndex",colorBlack); 
 
Plot(Cum(1),"Cum",colorRed); 
 
BarsVisible = Status("LastVisibleBar") - Status("FirstVisibleBar");
Plot(BarsVisible,"BarsVisible",colorGreen);

Figure 1.

BarCount001

BarCount is a reserved variable. It is a constant equal to the final count of all the bars, starting from one i.e. it is a one based count equivalent to the LastValue of Cum(1).

BarsVisible has been calculated for the purpose of this demo only. It is the last bar number minus the first bar number (using a one based count). In this example BarsVisible  == 22 -1.

BarIndex() is a function that returns a progressive count of the bars starting from zero i.e. it is a zero based count. The LastValue of BarIndex() always equals BarCount -1.

Note: For this example a small database, that contains only 22 bars of data, has been used (this can be confirmed from the status bar record at the bottom of Figure 1). All of the bars are contained in the screen, and there is no need to scroll forward or back, which makes it easier to understand the behavior of BarCount and BarIndex. In practice, BarsVisible varies as the screen is zoomed in and out while Cum and BarIndex dynamically adjust to the current position of the selector line. Don’t be fooled when applying P_BarCount to larger databases as the plots of BarCount, BarIndex and Cum(1) will all dynamically adjust as the charts are scrolled or zoomed, whereas in other cases they will reference the complete database.

Figure 2.

BarCount002

BarCount and BarIndex() are not normally plotted. In other modes BarCount is referenced as a constant, while the BarIndex() number can be referenced, bar by bar, by using the subscript operator [] i.e. array identifier [expression] .

BarIndex subscript examples (from the AFL reference manual):

Close [0] represents the first available Close value.

High [BarCount -1] represents the last available High value.

Note: The BarsVisible code was copied from a YahooGroup discussion on ‘How to determine the number of visible bars on a chart’ at  AmiBrokerYahooGroup message #114546

ATTACHED FORMULA FILE: P_BarCount.afl

  • To download .afl files right click on the link and pick Save Target As. Then enter Program Files/AmiBroker/Formulas/Custom as the path to access them from within AmiBroker > View > Charts. 
  • Written using AmiBroker Standard Edition v4.9 and Yahoo!Finance EOD data.

1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 4.4 out of 5)
Loading ... Loading ...

Introduction to AFL

The AmiBroker Programming Language (AFL) is a very unique and powerful programming language but to use it effectively you have to understand how it works and how to properly use the AFL functions. For the newcomer to programming, this may represent a steep learning curve and it may take a little persistence to find the answers to all your questions. To write documentation on any topic that leaves no questions unanswered is an impossible task, all help documentation assumes a minimum level of familiarity with the topic studied. The problem is that this prerequisite minimum level of understanding is set by the subjective judgment of the author. The results is that, for the individual user, some topics are covered excessively while others are skimmed over because the author assumed that everybody is basically familiar with the topic. Users on the other hand often assume that their lack of knowledge is shared by all beginners and, if the Help file inadequately explains something, claim that the documentation is badly written. Of course their view is just as relative and subjective as those of the author.

This situation exist in various degrees in all documentation and cannot be prevented. The way for you to cope with this is to stay calm (there have been some heated posts on the lists) and do your own research research. If you still can’t understand something and/or can’t find the answer to your specific question you can email AmiBroker Technical Support for help or post your question on one of the AmiBroker forums:

Amibroker Users’ Group
AmiBroker Automated-Trading
AmiBroker Trading Systems
AmiBroker AFL

There are some other Yahoo forums you may want to look at, especially if you are multilingual. For a more general search targeting groups in any language click here.

If you believe your question is of general interest you can ask your question using the comment field below. But please be specific; questions like ‘How do I use AFL’ would require a book to answer and is way beyond the scope of what volunteers can contribute.

Of course we welcome your solutions to specific AFL problems, either as an author with a post (requires registration) in this category, or in the comment field below.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

How Many Trading Days In A Year?

Sometimes it is useful to know the number of trading days in a year e.g. to annualize returns from a system that trades on a daily basis.

On other occasions, index data can contain errors, and the number of daily bars, in a year, can be compared to the exchange calendar, for the relevant index, to check on this failing.

To count the number of trading days in a calendar year (for any equity market):

a) download the .afl file attached to this post and save it in Program Files/AmiBroker/Formulas/Custom,

b) open AmiBroker and display any index, for the market of interest, in a chart e.g. ^DJI;
c) find p-barsinyear in the Charts list and right click on it, then Insert it as an indicator, (it will be plotted in a new pane in the bottom section of the Chart window);
d) click in the Chart to position the Selector Line in the BarsInYear chart, just after the end of the year being measured (where the cumulative line becomes a constant in the upper section of the chart);
e) read the BarsInYear total from the Chart Title (highlighted in yellow).

(Note that this calculation requires daily bars and also that it is set to calculate the number of trading days for the last full year at the time of writing i.e. 2006. To calculate the number of trading days for a different year e.g. 2007, change the 106 to 107 in both of the DateNum() number sequences).

1
2
3
4
5
6
7
8
9
10
/*P_BarsInYear*/
 
InYearFlag = IIf(DateNum() >= 1060101 AND DateNum() <= 1061231,1,0);
InYear = Cum(InYearFlag);
Plot(InYear,"BarsInYear",colorBlack,styleLine);
 
// Logic.
// line 3 returns one if a bar is within the calendar range, or zero if not, and assigns it to the variable InYearFlag;
// line 4 cumulates the ones from line 3 and assigns the result to the InYear variable;
// line 5 plots the cumulated result in a chart;

BIY001

Attached Files:

Right click and Save Target As to save .afl files to the desktop at Program Files/AmiBroker/Formulas/Custom and access them as formulas within AmiBroker Charts.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...