AmiBroker Formula Language (AFL) is a high-performance scripting language used to create custom technical indicators, backtest trading strategies, and automate trade execution. Its syntax is similar to C and JScript but optimized specifically for financial data, featuring powerful array-processing capabilities that allow complex calculations to run at near-machine speeds. Core Components of AFL
AFL operates primarily on arrays, which are sequences of data points (like daily closing prices). Instead of writing slow loops to process every bar, AFL allows you to perform operations on the entire array at once.
Predefined Variables: AFL uses standard identifiers for price data: Open, High, Low, Close, Volume, and OpenInt (abbreviated as O, H, L, C, V, OI).
Built-in Functions: There are over 70 native functions for technical analysis, such as MA() for moving averages, RSI() for Relative Strength Index, and MACD(). Syntax Rules: Case Sensitivity: AFL identifiers are not case-sensitive.
Comments: Use // for single-line comments and /* */ for multi-line blocks.
Formatting: Using SectionBegin and SectionEnd is recommended to organize code into logical blocks. Practical Examples of AFL Code 1. Creating a Simple Moving Average Crossover Strategy
This common strategy generates a "Buy" signal when a fast-moving average crosses above a slow-moving average and a "Sell" signal when it crosses below.
// Define moving averages FastMA = MA(Close, 10); SlowMA = MA(Close, 30); // Define Buy/Sell rules using the Cross function Buy = Cross(FastMA, SlowMA); Sell = Cross(SlowMA, FastMA); // Visualizing on the chart Plot(Close, "Price", colorDefault, styleCandle); Plot(FastMA, "Fast MA", colorRed); Plot(SlowMA, "Slow MA", colorBlue); // Add arrows for signals PlotShapes(IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, L, -15); PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0, H, -15); Use code with caution. 2. Advanced Risk Management & Position Sizing
AFL allows you to define exactly how much capital to risk per trade.
Fixed Amount: PositionSize = 1000; // Invest $1000 per trade. amibroker afl code
Percentage of Equity: PositionSize = -25; // Invest 25% of current portfolio. Advanced Features in AmiBroker
Backtesting & Optimization: The Analysis Window uses AFL code to run historical simulations, providing performance metrics like win rate and drawdown.
Explorations (Scanners): You can use the Filter variable to create a custom scanner that finds stocks meeting specific criteria.
AFL Code Assistant (AI): Version 7.00 introduced an AI-based assistant that can write code from natural language descriptions or fix existing errors.
Automation: Using third-party bridges, AFL can be linked to broker APIs (like Zerodha) to automate live order placement. AFL Reference Manual - AmiBroker
AmiBroker Formula Language (AFL) is a high-level, C-style scripting language used to create custom indicators, trading strategies, and scans within the AmiBroker platform. It is designed for rapid execution by processing entire arrays (vectors) of data at once, which eliminates the need for many slow loops common in other languages. 1. Core Capabilities of AFL
Traders use AFL to automate various aspects of their market analysis:
Custom Indicators: Define unique mathematical formulas to visualize price action or volume trends.
Backtesting: Test trading rules against historical data to evaluate potential profitability. AmiBroker
Explorations & Scans: Search through thousands of symbols simultaneously to find stocks meeting specific quantitative or fundamental criteria.
Fundamental Analysis: Filter stocks using data like Earnings Per Share (EPS), debt levels, and net income.
Automation: Integrate with broker APIs via tools like Algo Bridge to execute trades automatically. 2. Basic Syntax & Structure
AFL's syntax is intuitive for those with basic knowledge of Excel formulas or C-based programming. AFL Reference Manual - AmiBroker
The Power of Precision: An Analysis of AmiBroker Formula Language (AFL)
In the high-stakes arena of algorithmic trading, the bridge between a conceptual strategy and market execution is built on code. For many professional traders, that bridge is the AmiBroker Formula Language (AFL), a proprietary scripting language designed for speed, flexibility, and deep technical analysis. Unlike general-purpose languages, AFL is purpose-built to handle financial data series, offering a unique blend of simplicity for beginners and advanced power for quantitative experts. The Architecture of AFL: Array Processing and Efficiency
At its core, AFL is an array processing language. While traditional languages often require complex loops to process price history, AFL treats entire data series—such as a year's worth of closing prices—as a single unit.
Vectorized Execution: Operations are performed on entire arrays simultaneously, which is significantly faster and requires fewer lines of code than iterative loops.
Syntactic Familiarity: The syntax is similar to C and JScript, making it accessible to those with prior programming experience. Part 4: Optimization – Writing Code for Speed
Predefined Variables: AFL includes built-in identifiers for standard data like Open, High, Low, Close, and Volume (often abbreviated as O, H, L, C, V). Core Applications in Systematic Trading
AFL serves as the engine for four primary functions within the AmiBroker platform: AFL Reference Manual - AmiBroker
AmiBroker AFL code is incredibly fast, but poorly written loops can cripple it. AFL is vectorized; loops should be your last resort.
Backtesting is where AFL truly shines. The default settings are good, but professional optimization requires custom metrics.
The core of any system relies on defining two arrays: Buy and Sell.
Buy is "True" (1) on a specific bar, a trade is entered.Sell is "True" (1) on a specific bar, a trade is exited.Example Strategy: Buy when the 50-period Moving Average crosses above the 200-period MA. Sell when it crosses below.
// Define Moving Averages
MA_Short = MA(Close, 50);
MA_Long = MA(Close, 200);
// Generate Signals
Buy = Cross(MA_Short, MA_Long);
Sell = Cross(MA_Long, MA_Short);
// Visualizing Signals
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, Low, -15);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0, High, -15);
| Concept | Description |
|---------|-------------|
| Arrays | All data (Close, Open, Volume) are time-series arrays. |
| Bar index | Refers to a specific bar (0 = first bar, BarCount-1 = last). |
| Static variables | StaticVarGet, StaticVarSet retain values between bars. |
| Lookback/forward | Ref(Array, -1) for previous bar; Ref(Array, +1) for future (caution). |
| Buy/Sell/Short/Cover | Built-in arrays to define trading signals. |
| SetPositionSize | Define position sizing rules. |
| ApplyStop | Add stop-loss, profit target, or trailing stops. |
AFL (Analysis Formula Language) is the proprietary scripting language used by Amibroker — a popular technical analysis and backtesting platform for traders and investors. AFL allows users to create custom indicators, trading systems, scans, and explorations without needing external programming tools.
AFL is C-like in syntax but specifically designed for financial data arrays (price, volume, etc.), making it efficient for processing large historical datasets.
Let's move beyond the basics. Below is a complete Mean Reversion + Trend Filter system.