AFL includes hundreds of built-in functions for technical analysis.
For portfolio-level money management or tracking consecutive wins/losses, you need static variables. These persist across symbols in a backtest.
Warning: Improper use of StaticVar causes look-ahead bias.
// Section 1: Parameters (User adjustable) MAfastPeriod = Param("Fast MA Period", 10, 2, 50, 1); MAslowPeriod = Param("Slow MA Period", 30, 10, 200, 1);// Section 2: Calculate Indicators FastMA = MA(C, MAfastPeriod); SlowMA = MA(C, MAslowPeriod);
// Section 3: Define Signals Buy = Cross(FastMA, SlowMA); Sell = Cross(SlowMA, FastMA);
// Section 4: Visualization Plot(C, "Price", colorBlack, styleCandle); Plot(FastMA, "Fast MA", colorGreen, styleLine); Plot(SlowMA, "Slow MA", colorRed, styleLine); PlotShapes(Buy * shapeUpArrow, colorBrightGreen, 0, Low, -15); PlotShapes(Sell * shapeDownArrow, colorRed, 0, High, -15);
This is the "Hello World" of AmiBroker AFL code. It works, but it is not profitable. Let’s move to advanced logic.
To make a code flexible, variables are exposed to the Amibroker "Parameters" dialog using the Param function.
// Syntax: Param("Name", Default, Min, Max, Step, Suffix)
Periods = Param("MA Periods", 14, 2, 200, 1);
Since you requested a "paper" on Amibroker AFL Code, I have structured this response as a comprehensive technical guide or white paper. It covers the architecture, syntax, and practical application of the Amibroker Formula Language (AFL).
When using loops, always set LookBack to the minimum period required. For example:
SetBarsRequired( 500, 100 ); This tells AmiBroker to only load 500 bars, saving memory.
As your AmiBroker AFL code grows, readability saves hours. Adopt this standard:
Unlike Python or C++, AFL is inherently vector-based. This means an operation applies to the entire price array simultaneously.
Example:
// This single line calculates a 20-period SMA for every bar in the chart
SMA_20 = MA(C, 20);
In a non-vector language, you would need a loop. In AFL, this vectorization makes backtesting blazing fast.