Skip to content
Level 3 · AFL DeveloperLessonPart 08 · page 1 of 924 min
24Minutes
3AFL functions
8Sources
StandardRequires
AFL functions taught here3

What AFL Is and Where It Runs

By the end of this lesson you will know what kind of language AFL is, where you type it, which button does what in the Formula Editor, and the single fact that surprises almost everyone: the same text you write once can be executed by six different parts of AmiBroker, and you do not control when any of them decide to run it.

That last point is worth settling before you write a line, because it explains a family of confusions that otherwise take weeks to shake off.

The official description is admirably narrow. AFL is “a special programming language used to define and create custom indicators, scans, explorations, backtests and guru commentaries”. It is not a general-purpose language. There is no user interface toolkit, no networking, no way to write an application in it. It exists to express one thing well: a calculation over a symbol’s price history, whose result AmiBroker then does something with.

That narrowness is a feature. Because AmiBroker knows the shape of the problem in advance, it can supply the price history as ready-made data, supply a large library of technical calculations, run your formula across thousands of symbols in parallel, and hand the results to a charting engine or a portfolio backtester. You write the part that is specific to your idea. Everything around it already exists.

The official Knowledge Base article on this is blunt: “we should never assume that certain formula will only be executed e.g. N-times during certain timeframe.” A chart formula is re-evaluated on any click, scroll or zoom; on a symbol change; on an interval change; after a data import; on View -> Refresh. In the Analysis window it runs once per symbol, in several parallel threads. AmiBroker also runs your formula on its own initiative: when it syntax-checks it, when the Parameters window is first shown, and at the start of an Optimization so it can read the parameter ranges.

There is one detail worth remembering from that article because it looks like a bug when you meet it: formulas on chart sheets that are not the active tab are not executed at all. A non-active sheet, in AmiBroker’s words, “just doesn’t exist” — it is created when you click the tab and destroyed when another sheet becomes active.

The practical consequence is a rule you should adopt now and never relax: any formula that has a side effect outside itself — writing a file, sending an alert, incrementing a counter — must be written so that running it twice does no harm. Most of what you write in this course only produces arrays, which is safe, because producing the same array twice costs nothing but time.

Analysis -> Formula Editor opens the window you will spend the rest of the course in. It is a code editor with syntax highlighting, brace matching, auto-indentation, code folding, line numbers, bookmarks and in-line error reporting.

The toolbar is the part worth memorising, because two of its buttons do much more than their names suggest:

Control What it does
Formula Name (an edit field) The name the formula is saved under. Type a name here, then press Save.
Check syntax Parses the formula and reports errors without running or applying anything.
Apply indicator Saves, then applies this formula as the chart in the currently selected pane — once.
Analysis Saves, selects the formula in the Analysis window, and repeats the most recently used analysis operation.

Two things follow immediately. First, the Analysis button is not a “send to Analysis window” button; it re-runs whatever you last did there, so pressing it can launch a backtest you did not ask for. Second, Apply indicator applies the formula once, whereas Tools -> Insert chart inserts it as a new pane and can be used repeatedly.

The toolbar button says Check syntax. The menu item, under Tools, says Verify syntax. They are the same action. Learners routinely hunt the menus for a “Check syntax” entry that does not exist, so it is worth knowing both words.

Checking syntax finds only what the parser can find: unknown identifiers, malformed expressions, mismatched brackets, missing semicolons. It cannot tell you that your logic is wrong, and it deliberately does not run your formula over the whole database — the syntax check uses at most a couple of hundred recent bars. A formula can pass the syntax check cleanly and still be nonsense, and it can pass the syntax check and then fail at run time on a symbol with very little history.

Two more editor habits pay for themselves quickly. Put the caret inside or just after a function name and press F1 to open that function’s page in the official reference — this is far more reliable than remembering argument order. And press Ctrl+Space for auto-complete; when you type an opening parenthesis, a tooltip shows the parameters of the function you are inside, including for nested calls.

Here is the fact that reframes everything. The same formula text can be executed by several different parts of AmiBroker, and each of them reads a different part of the result. Status( "action" ) tells a running formula which one it is in.

One formula, several consumers

  1. The databaseSix stored arrays per symbol: open, high, low, close, volume, open interestinput
  2. Your AFL formulaDerives further arrays from those, using operators and built-in functions
  3. Chart pane (actionIndicator)Reads what you passed to Plot()
  4. Commentary and Interpretation (actionCommentary)Reads the text your formula produces
  5. Scan (actionScan)Reads Buy, Sell, Short, Cover
  6. Exploration (actionExplore)Reads Filter and the columns you added
  7. Backtest and Optimization (actionBacktest, actionPortfolio)Reads the signal arrays and simulates trading them

The documented values of Status( "action" ) are actionIndicator, actionCommentary, actionScan, actionExplore, actionBacktest and actionPortfolio, the last being the second phase of a portfolio backtest. A finer-grained Status( "actionex" ) exists as well, distinguishing cases such as syntax verification and optimization setup.

You rarely need to test the context, and you should not reach for it early — a formula that assigns both Plot() calls and a Buy array simply works in a chart and in the Analysis window, because each consumer ignores what it does not need. The reason to know about contexts now is diagnostic. When a formula behaves differently in a chart and in the Analysis window, the first question is no longer “what is wrong with my code” but “which of these two contexts am I actually looking at, and what does it read”.

A formula is a plain text file with an .afl extension. Files saved into the Formulas subfolder of the AmiBroker directory appear in the Charts tree, which is how the built-in indicators get there.

Three consequences from the official FAQ, all of which will bite eventually:

  • If you add a file with an external editor, the Charts tree does not notice until you choose View -> Refresh All.
  • If you modify a formula that shipped with AmiBroker, the next upgrade will overwrite it. Save your modified version under a new name, or better, in your own subfolder.
  • You can drag an .afl file from Windows Explorer onto the Analysis formula window to load it; shortcuts (.lnk) do not work, only real .afl files.

Start a habit now: keep your own work in a clearly named subfolder of Formulas, and give formulas descriptive names. By Part 12 you will have dozens of them, and test3.afl will tell you nothing.

AFL has grown by accretion since the late 1990s, and the layers are still visible. The modulus operator arrived in AFL 1.7 and the bit-wise operators in 2.1; #include came with AmiBroker 4.20; the Param family, BarIndex(), Nz() and IsNull() with 4.30; local and global with 4.36; if/else and for/while loops — and _TRACE() — with 4.40, which is why so much older code contains no loops at all; dynamic variables with 4.60 and 4.80; compound assignment and the switch/case family with 5.00; full multi-threading with 5.50; matrices with 6.00; the integrated visual debugger with 6.10; static variable declarations with 6.30; and, in 7.00, an AI-based code assistant inside the editor. The practical upshot for you is that AFL code found on the internet may be extremely old, and old AFL is not wrong so much as differently idiomatic — code that assigns to graph0 instead of calling Plot() is using a mechanism the guide itself now marks obsolete.

AmiBroker 7.00 added an AI-based AFL Code Assistant to the Formula Editor, with Ask, Fix and Explain buttons. Two facts from its official page are worth knowing before you rely on it. It does not work out of the box — it requires one-time configuration of an external language model, and without a separately purchased AFL Code Wizard licence key it is limited to five responses per run. And when configured against a cloud model, it sends both your question and the formula you are editing to that provider; the documentation says plainly that this “is no different from using OpenAI/Google website directly”. Neither fact makes it a bad tool. Both are things to decide about deliberately rather than discover later.

AFL is a narrow language for describing calculations over price history, and the description is evaluated by AmiBroker whenever it needs the answer — on a schedule you do not control, in one of six contexts, each of which reads a different part of what your formula produced. You write it in the Formula Editor, where Check syntax parses without running, Apply indicator puts the formula on the current chart pane, and Analysis re-runs whatever you last did in the Analysis window. Formulas are .afl text files in the Formulas folder, they belong in your own subfolder, and they are the part of your setup worth backing up.

The next lesson writes one.

Check your understanding

Question 1. You press the Analysis button in the Formula Editor and a portfolio backtest starts running. What happened?
Show the answer and why

Answer: The Analysis button saves the formula, selects it in the Analysis window and repeats the most recent analysis operation

The button does three things, and the third one surprises people. If the last thing you did in the Analysis window was a backtest, that is what it repeats. Use Check syntax when you only want to know whether the formula parses.

Question 2. A formula that only calls Plot() is sent to the Analysis window and run as a Scan. What should you expect?
Show the answer and why

Answer: No results, and an error about missing Buy/Sell assignments

Each execution context reads a different part of what the formula produced. A Scan reads Buy, Sell, Short and Cover; a formula that never assigns them has produced nothing a Scan can report, and AmiBroker raises Error 701. Plot() itself is perfectly legal there — it is simply ignored.

Question 3. Which of these are reasons AmiBroker might execute your chart formula without you asking it to? Select all that apply.
Show the answer and why

Answer: You scrolled or zoomed the chart, You opened the Parameters window for the first time, You clicked a different chart sheet tab, An Optimization started and needs to read the parameter ranges

All four are documented triggers. This is why formulas with side effects must be safe to run repeatedly, and why counting how many times your formula has run is never a sound technique.

Question 4. You edit one of the formulas that shipped with AmiBroker, save it under its original name, and upgrade AmiBroker a month later. What is the documented outcome?
Show the answer and why

Answer: Your edit is overwritten

The official FAQ states that shipped formulas are overwritten on upgrade. Save modified versions under a new name, or in your own subfolder of Formulas, and back that folder up — it is the only part of your setup that cannot be rebuilt from the data.

Sources for this lesson

8 verified · checked 2026-08-31

  1. 01AmiBroker User's Guide — AFL Reference Manualamibroker.com/guide/a_language.html2026-08-31
  2. 02AmiBroker User's Guide — AFL Editoramibroker.com/guide/w_afledit.html2026-08-31
  3. 03AmiBroker User's Guide — Creating your own indicatorsamibroker.com/guide/h_indbuilder.html2026-08-31
  4. 04AFL Function Reference — Statusamibroker.com/guide/afl/status.html2026-08-31
  5. 05AmiBroker User's Guide — Drag and drop charting FAQamibroker.com/guide/h_dragdrop.html2026-08-31
  6. 06AmiBroker Knowledge Base — When and how often AFL code is executedamibroker.com/kb/2015/02/03/when-and-how-often-afl-code-is-executed2026-08-31
  7. 07AmiBroker User's Guide — What's newamibroker.com/guide/whatsnew.html2026-08-31
  8. 08AmiBroker User's Guide — AI-based AFL Code Assistantamibroker.com/guide/h_codeassistant.html2026-08-31

Every technical claim on this page was checked against the official AmiBroker documentation on the date shown. Where the course disagrees with folklore, the source is how you can tell which one to trust.