// Exploration shows data in a result list
Filter = 1;
AddColumn(Close, "Close");
AddColumn(RSI(14), "RSI");
Let’s assemble a complete, tradeable strategy. This is a Volatility Breakout with RSI Filter.
Logic:
//========================================== // COMPLETE AMIBROKER AFL CODE - Breakout System // Author: Professional Trader //==========================================// --- Inputs --- DonchianPeriod = Param("Donchian Period", 20, 5, 50, 1); RSILen = Param("RSI Length", 14, 5, 30, 1); RSI_Threshold = Param("RSI Min", 50, 30, 70, 1); ExitMAPeriod = Param("Exit MA Period", 10, 5, 50, 1);
// --- Indicators --- DonchianHigh = HHV(H, DonchianPeriod); DonchianLow = LLV(L, DonchianPeriod); RSIval = RSI(RSILen); ExitMA = MA(C, ExitMAPeriod);
// --- Entry Conditions --- BuyTrigger = Cross(C, DonchianHigh); TrendFilter = RSIval > RSI_Threshold; Buy = BuyTrigger AND TrendFilter;
// --- Short Conditions (Optional) --- ShortTrigger = Cross(DonchianLow, C); ShortFilter = RSIval < (100 - RSI_Threshold); Short = ShortTrigger AND ShortFilter;
// --- Exits --- Sell = Cross(ExitMA, C); // Price closes below MA Cover = Cross(C, ExitMA); // Price closes above MA for shorts
// --- Position Sizing (Risk 1% of equity) --- RiskPercent = 1; StopLossATR = 2; ATRval = ATR(14); PositionSize = -RiskPercent * (C / StopLossATR / ATRval);
// --- Plotting for Chart Analysis --- Plot(C, "Price", colorWhite, styleCandle); Plot(DonchianHigh, "Upper Band", colorBlue, styleLine); Plot(DonchianLow, "Lower Band", colorBlue, styleLine); Plot(ExitMA, "Exit MA", colorOrange, styleLine);
PlotShapes(Buy * shapeUpArrow, colorGreen, 0, L, -20); PlotShapes(Sell * shapeDownArrow, colorRed, 0, H, 20); PlotShapes(Short * shapeDownArrow, colorPink, 0, H, -20); PlotShapes(Cover * shapeUpArrow, colorLightGrey, 0, L, 20);
// --- Exploration for Scanning --- Filter = Buy OR Short; AddColumn(C, "Close", 1.2); AddColumn(RSIval, "RSI", 1.2); AddColumn(IIf(Buy, "BUY", IIf(Short, "SHORT", "")), "Signal", 1.0);
// --- Backtest Settings --- SetPositionSize(1, spsShares); // 1 share for testing SetOption("InitialEquity", 100000); SetOption("FuturesMode", False); SetOption("PriceBoundChecking", True);
Copy this code into AmiBroker (Analysis -> Formula Editor) and press Backtest. You will see a full equity curve, drawdown, and trade list.
To run code every second, use StaticVar and StaticVarGet to preserve variables between bars.
// --- Real-time Position Tracker --- staticVar = Nz(StaticVarGet("MyPosition"), 0); currentPos = staticVar;if (Buy AND currentPos == 0) currentPos = 1; StaticVarSet("MyPosition", 1); printf("Buy executed at " + WriteVal(C)); amibroker afl code
if (Sell AND currentPos == 1) currentPos = 0; StaticVarSet("MyPosition", 0);
Replace Buy/Sell with Filter for scanning.
// Scan for RSI < 30 with increasing volume
Filter = RSI(14) < 30 AND V > Ref(V, -1) * 1.5;
AddColumn(C, "Close", 1.2);
AddColumn(V, "Volume", 1.0);
AddColumn(RSI(14), "RSI", 1.2);
Run this via Analysis -> Scan and set Mode to "Explore". You now have a real-time stock screener.
Summary
Strengths
Weaknesses
Typical Use Cases
Quality Checklist for AFL Code (what to look for when evaluating a script)
Practical Tips for Working with AFL
Verdict AFL is one of the most efficient and practical languages for traders focused on fast backtesting, custom indicators, and strategy prototyping within the AmiBroker ecosystem. It’s ideal for technical traders and quants who accept some platform lock-in in exchange for high performance and rich backtesting features. Beginners face a learning curve, but the active community and abundant examples help bridge that gap.
Related search suggestions (If you want, I can run searches for these terms next:)
AmiBroker Formula Language (AFL) is a high-level scripting language designed specifically for creating custom indicators, backtesting trading strategies, and automating technical analysis
. It is highly optimized for array processing, allowing users to perform complex financial calculations at speeds comparable to assembly language. Core Components of AFL Identifiers & Constants
: Identifiers are names given to variables and functions (e.g., MyIndicator // Exploration shows data in a result list
). Constants represent fixed values, such as numeric integers or string literals like "Buy Signal" Predefined Price Arrays : AFL uses reserved keywords for standard price fields: : Supports arithmetic ( ), relational ( ), and logical ( ) operators. Built-in Functions
: Features over 70 functions for technical analysis, such as for Moving Averages, Basic Structure and Syntax
AFL formulas consist of expression statements, each of which must end with a semicolon ( ; )
. It is not case-sensitive, making it accessible for beginners. Example: Simple Moving Average Cross Strategy
This script generates a "Buy" signal when a 10-period EMA crosses above a 20-period EMA.
// Define EMAs FastEMA = EMA(Close, 10); SlowEMA = EMA(Close, 20);
// Define Buy/Sell Rules Buy = Cross(FastEMA, SlowEMA); Sell = Cross(SlowEMA, FastEMA);
// Plotting on Chart Plot(Close, "Price", colorDefault, styleCandle); Plot(FastEMA, "Fast EMA", colorRed); Plot(SlowEMA, "Slow EMA", colorBlue);
// Visual Signals PlotShapes(IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, L, -15); PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0, H, -15); Use code with caution. Copied to clipboard Key Use Cases Indicators : Create custom visual tools like Auto Support/Resistance or Supply/Demand zones. Backtesting
: Evaluate strategy performance against historical data to determine net results, drawdowns, and profit factors. Exploration
: Use the "Analysis" window to scan thousands of stocks simultaneously for specific patterns. Optimization
: Fine-tune parameters (like MA periods) to find the most profitable settings. Useful Resources The new AFL Formula Editor features - AmiBroker
AmiBroker Formula Language (AFL) is a high-performance scripting language used for technical analysis, backtesting, and automated trading within the AmiBroker platform. It is widely regarded in the trading community for its array-based processing, which allows it to handle large datasets significantly faster than many competitors. Core Capabilities
Array-Based Processing: Unlike languages that process data point by point (looping), AFL operates on entire data arrays at once, providing lightning-fast execution for backtests and indicators. Let’s assemble a complete, tradeable strategy
Strategy Development: Traders use AFL to design everything from simple moving average crossovers to complex volatility-based breakout systems.
Backtesting and Optimization: It supports sophisticated portfolio-level backtesting and multi-variable optimization to find the most robust strategy parameters.
Custom Visualization: Users can create custom indicators, plot complex levels like Camarilla pivots, and design visual dashboards directly on price charts. Key Features & Syntax
Creating Hull of RSI Based Trend Trading System using Amibroker
A proper review of AmiBroker Formula Language (AFL) code requires evaluating both the technical soundness of the script and its practical effectiveness for trading. AmiBroker Community Forum 1. Reviewing Technical Soundness
Ensure the code is robust and efficient by checking the following: AFL Syntax and Logic: Verify that the code follows proper AFL syntax and that logic for is correctly defined. Variable Scope:
Ensure variables are appropriately scoped and initialized to prevent unexpected values during execution. Array Handling: Since AFL is array-based, verify that functions like are applied correctly to historical data arrays. Optimization of "Foreign" Data: SetForeign()
is used correctly for index filters or cross-symbol analysis without causing data alignment issues. Debugging: Use built-in tools like to log variable values and the AFL Debugger to step through the logic. AmiBroker Community Forum 2. Evaluating Trading Strategy Performance
A good review must assess if the strategy is viable in a live market environment:
Yet, in the hands of a disciplined mind, AFL becomes poetry. Consider a mean-reversion system on a 1-minute chart:
Upper = BBandTop(C, 20, 2);
Lower = BBandBot(C, 20, 2);
Buy = C < Lower AND Ref(C, -1) > Lower AND Volume > 50000;
Sell = C > MA(C, 20);
What is this? It is a story. Price fell below the lower Bollinger Band (fear), but not suddenly—it crossed from above (exhaustion), with sufficient volume (liquidity). The exit? Return to the mean. No greed. No targets. Just the cold embrace of probability.
AFL forces you to articulate your entire belief system. No fuzzy feelings. No "it felt like a top." You must encode even the exit. Even the stop. Even the position size. In doing so, you confront the ugliest parts of your trading psychology—the revenge trading, the diamond hands delusion, the refusal to take a small loss.
Never optimize over the entire dataset.
Add this to your AFL to force OOS testing:
OOS_Start = ParamDate("OOS Start", "2016-01-01");
InSample = DateNum() < OOS_Start;
OptimizeOnly = InSample; // Only optimize in the first period