AFL example downloads
Every complete formula in this course is a real .afl file that you can download and
open in AmiBroker’s Formula Editor.
The lessons do not contain their own copy of the code. Each lesson reads the file from disk when the site is built, which means the code you read in a lesson and the file you download here are the same bytes. They cannot drift apart, and if a file were ever missing the site would fail to build rather than quietly show you something that does not exist.
How to use these files
Section titled “How to use these files”- Download the
.aflfile, or use the copy button on the code block in the lesson. - In AmiBroker, open the Formula Editor.
- Paste or open the file, then apply it — as an indicator on a chart, or by sending it to the Analysis window, depending on what the lesson is doing.
- Read the header comment first. Every example states what it assumes: the bar interval, whether prices need to be adjusted, which Analysis settings it expects, and anything about it that is a teaching device rather than something to trade.
A word about what these are
Section titled “A word about what these are”These formulas are written to be read and understood, not to be traded. Several of them deliberately do things you must never do in a live rule — the reality-check studies read future bars on purpose in order to measure what already happened, and they say so at the top of the file in capital letters. Read the header before you reuse anything.
Nothing here is financial advice, and nothing here is a strategy that has been shown to work. See the disclaimer.
199 AFL examples are available to download. Each one is the exact file shown in its lesson — the lesson embeds the file rather than containing its own copy, so the two cannot disagree.
Part 2 Understanding Market Data
- bar-anatomy.aflPart 2 - OHLCV and What a Bar Hides50 lines
- data-sanity-check.aflPart 2 - Data Defects in Practice77 lines
- same-rule-two-series.aflPart 2 - Lab: Prove That Bad Data Breaks Analysis51 lines
- series-integrity-report.aflPart 2 - Survivorship, Delistings and Index Membership54 lines
Part 3 Getting Started with AmiBroker
- import-health-check.aflImport health check75 lines
- price-with-context.aflPrice with context65 lines
- setup-report.aflSetup report51 lines
- universe-audit.aflUniverse audit51 lines
Part 4 Reading Price Charts
- chart-brief-panel.aflPart 4 - Lab: Structured Chart Interpretation104 lines
- log-price-pane.aflPart 4 - Linear versus Logarithmic Scaling58 lines
- market-structure.aflPart 4 - Market Structure: Trends, Ranges and Transitions75 lines
- price-style-explorer.aflPart 4 - Chart Types and What Each One Shows49 lines
- swing-points.aflPart 4 - Swings, Highs and Lows79 lines
Part 5 Support, Resistance and Price Structure
- breakout-definitions.aflPart 5 - Breakouts, Failed Breakouts and Role Reversal74 lines
- consolidation-meter.aflPart 5 - Consolidation and Volatility Contraction67 lines
- level-touch-test.aflPart 5 - Reality Check: Do Support Levels Actually Hold?125 lines
- prior-extreme-levels.aflPart 5 - Support and Resistance as Zones81 lines
- regression-channel.aflPart 5 - Trendlines and Channels74 lines
- structure-map.aflPart 5 - Lab: Map the Structure of a Real Chart116 lines
- trendline-break.aflPart 5 - Trendlines and Channels72 lines
Part 6 Indicators
- indicator-workbench.aflPart 6 - Lab: Indicator Behaviour Workbench87 lines
- ma-response-comparison.aflPart 6 - Moving Averages: SMA and EMA42 lines
- rsi-above-70-chart-test.aflPart 6 - Reality Check: Does RSI Above 70 Mean Sell?80 lines
- rsi-above-70-exploration.aflPart 6 - Reality Check: Does RSI Above 70 Mean Sell?70 lines
Part 7 Candlesticks and Chart Patterns
- candle-anatomy.aflPart 7 - Candlestick Anatomy and Single-Bar Patterns93 lines
- engulfing-and-bars.aflPart 7 - Multi-Bar Candlestick Patterns104 lines
- pattern-base-rate.aflPart 7 - Reality Check: Can We Test Whether a Pattern Predicted Anything?154 lines
- zigzag-repaint-demo.aflPart 7 - Classic Chart Patterns80 lines
Part 8 AFL Programming Fundamentals
- boolean-count.aflPart 8 - Boolean Arrays53 lines
- debug-harness.aflPart 8 - Errors, Debugging and Sanity Checks74 lines
- first-formula.aflPart 8 - Your First Formula49 lines
- regime-colour.aflPart 8 - Logic, Conditionals and IIf()70 lines
- see-the-arrays.aflPart 8 - The Array Model59 lines
- warmup-guard.aflPart 8 - Null Values, Nz() and Warm-Up Periods76 lines
Part 9 Working with Arrays and Historical Bars
- event-anchored-levels.aflPart 9 - ValueWhen(): Carrying a Value Forward75 lines
- forward-return-study.aflPart 9 - Referencing Past Bars with Ref()47 lines
- occurrence-statistics.aflPart 9 - Counting and Accumulating: BarsSince, Cum, Sum65 lines
- prior-window-channel.aflPart 9 - Running Extremes: HHV, LLV and Friends73 lines
- ref-shift-laboratory.aflPart 9 - Referencing Past Bars with Ref()48 lines
- signal-audit-tool.aflPart 9 - Challenge: State or Event?75 lines
- signal-cleaning-workbench.aflPart 9 - Cleaning Signals: ExRem, ExRemSpan and Flip72 lines
- state-event-visualiser.aflPart 9 - State versus Event83 lines
- window-versus-history.aflPart 9 - Running Extremes: HHV, LLV and Friends45 lines
Part 10 Building Custom AFL Indicators
- analysis-panel.aflMulti-indicator analysis panel - Part 10 project.134 lines
- atr-volatility.aflATR volatility indicator - Part 10 project.91 lines
- chart-title.aflAn informative chart title - worked example for Part 10.71 lines
- configurable-ma.aflConfigurable moving average - Part 10 project.121 lines
- parameter-set-demo.aflEvery parameter control in one section - worked example for Part 10.71 lines
- plot-styles-demo.aflPlot styles, scales and layers - worked example for Part 10.68 lines
- signal-markers.aflMarking events without burying the chart - worked example for Part 10.84 lines
- trend-regime.aflTrend regime classifier - Part 10 project.109 lines
Part 11 Reusable AFL Programming
- chart-defaults.aflA deliberately tiny include file, used by Part 11 to demonstrate #include before the full course library is built.50 lines
- chart-with-include.aflPart 11 - Include Files and Building a Library38 lines
- course-library-test.aflSelf-test and demonstration for course-library.afl version 1.00.157 lines
- course-library.aflThe course utility library.313 lines
- defensive-stretch-indicator.aflPart 11 - Defensive AFL: Guarding Against Bad Input and Bad Data112 lines
- normalised-range-indicator.aflPart 11 - User-Defined Functions and Procedures93 lines
- scope-demonstration.aflPart 11 - Variable Scope: local, global and the Traps135 lines
Part 12 Scanning and Exploration
- breakout-forward-study.aflPart 12 - Reality Check: Do High-Volume Breakouts Lead Anywhere?95 lines
- daily-screener.aflPart 12 - Project: Build a Daily Stock Screener113 lines
- empty-scan-broken.aflPart 12 - Challenge: The Scan That Returns Nothing45 lines
- empty-scan-fixed.aflPart 12 - Challenge: The Scan That Returns Nothing (worked solution)86 lines
- exploration-columns.aflPart 12 - Exploration: Filter, AddColumn and AddTextColumn41 lines
- exploration-doctor.aflPart 12 - Challenge: The Scan That Returns Nothing (diagnostic formula)68 lines
- filter-stages.aflPart 12 - Building Screening Filters That Mean Something106 lines
- first-scan.aflPart 12 - Lab: Your First Scan46 lines
- readable-table.aflPart 12 - Conditional Formatting, Sorting and Ranking Columns69 lines
- screen-log.aflPart 12 - Exporting Results and Building a Daily Workflow73 lines
- screener-stage-audit.aflPart 12 - Project: Build a Daily Stock Screener (validation formula)71 lines
- signal-export.aflPart 12 - Exporting Results and Building a Daily Workflow54 lines
Part 13 Ranking and Relative Strength
- filter-then-rank.aflPart 13 - Ranking versus Filtering58 lines
- relative-strength-lookbacks.aflPart 13 - Relative Strength: What It Does and Does Not Mean67 lines
- rs-ranking-tool.aflPart 13 - Project: Market Relative Strength Ranking Tool217 lines
- static-var-inspector.aflPart 13 - Static Variables for Cross-Sectional Work36 lines
- top-ranked-symbols.aflPart 13 - StaticVarGenerateRanks() and Top-N Selection74 lines
- two-pass-momentum-scores.aflPart 13 - Static Variables for Cross-Sectional Work105 lines
- universe-ranks.aflPart 13 - StaticVarGenerateRanks() and Top-N Selection121 lines
Part 14 Multi-Timeframe AFL
- compress-expand-lab.aflCompress / expand laboratory95 lines
- mtf-agreement-scanner.aflMulti-timeframe agreement scanner160 lines
- mtf-alignment-audit.aflMulti-timeframe alignment audit134 lines
- timeframe-anatomy.aflTime frame anatomy86 lines
- weekly-trend-context.aflWeekly trend context on a daily chart129 lines
Part 15 Multi-Symbol Analysis
- alignment-audit.aflCross-symbol alignment audit136 lines
- correlation-stability.aflCorrelation stability audit86 lines
- foreign-scope-demo.aflForeign and SetForeign - what changes, and for how long106 lines
- rebased-comparison.aflRebased comparison and relative strength line115 lines
- relative-strength-comparison.aflRelative strength comparison tool187 lines
Part 16 Market Breadth
- advance-decline-composite.aflAdvance / decline composites113 lines
- breadth-composite-builder.aflMarket breadth composite builder96 lines
- breadth-dashboard.aflMarket breadth dashboard107 lines
- breadth-regime.aflBreadth regime104 lines
- composite-audit.aflComposite audit67 lines
Part 17 Introduction to Real-Time Markets
- data-path-report.aflData path report142 lines
- update-freshness-report.aflUpdate freshness report70 lines
Part 18 Real-Time Data Providers
- data-requirements-audit.aflPart 18 - Choosing a Data Source: A Decision Framework115 lines
- eod-update-audit.aflPart 18 - Free and End-of-Day Sources with AmiQuote88 lines
- outlier-print-scan.aflPart 18 - Appendix: IQFeed87 lines
- plugin-capability-probe.aflPart 18 - Appendix: eSignal and Other Supported Feeds116 lines
Part 19 Creating an Intraday AmiBroker Database
- database-settings-readout.aflDatabase settings readout100 lines
- history-depth-report.aflHistory depth report89 lines
- intraday-completeness-check.aflIntraday completeness check142 lines
Part 20 Trading Sessions, Exchanges and Time Zones
- bar-timestamp-audit.aflBar timestamp audit86 lines
- opening-range-fragile.aflOpening range breakout - fragile version60 lines
- opening-range-robust.aflOpening range breakout - robust version105 lines
- session-profile.aflSession profile102 lines
- session-shift-detector.aflSession shift detector102 lines
- three-clocks-panel.aflThree clocks panel75 lines
- timezone-break-evidence.aflTimezone break evidence65 lines
Part 21 Real-Time Charts
- interval-budget.aflInterval budget - Part 21, Real-Time Charts.79 lines
- layout-status-panel.aflLayout status panel - Part 21, Real-Time Charts.78 lines
- refresh-vs-update.aflTwo clocks - Part 21, Real-Time Charts.90 lines
- stale-data-monitor.aflStale data monitor - Part 21, Real-Time Charts.154 lines
Part 22 Real-Time Quotes and Time & Sales
- quote-field-panel.aflQuote field panel158 lines
- tick-rule-imbalance.aflTick-rule volume imbalance101 lines
Part 23 Real-Time AFL
- context-aware-template.aflPart 23 - Knowing Where You Are: Status() and Execution Context122 lines
- quote-dashboard.aflPart 23 - Project: Real-Time Quote Dashboard337 lines
- refresh-cost-meter.aflPart 23 - RequestTimedRefresh() and Real-Time Performance116 lines
- rt-field-probe.aflPart 23 - GetRTData() and the Live Quote Fields97 lines
Part 24 Real-Time Scanning
- breakout-scanner-audit.aflPart 24 - Project: Intraday Breakout Scanner (validation tool)121 lines
- intraday-breakout-scanner.aflPart 24 - Project: Intraday Breakout Scanner171 lines
- opening-range-panel.aflPart 24 - Defining Intraday Setup Conditions140 lines
- scan-cost-probe.aflPart 24 - Repeat Scanning: Mechanics and Costs73 lines
Part 25 AFL Alerts
- alert-fire-once-audit.aflPart 25 - Duplicate Alerts and How to Stop Them66 lines
- alert-output-basics.aflPart 25 - Alert Mechanisms and AlertIf()71 lines
- breakout-alert-test-harness.aflPart 25 - Project: Real-Time Breakout Alert (offline test harness)62 lines
- realtime-breakout-alert.aflPart 25 - Project: Real-Time Breakout Alert129 lines
Part 26 Bar Replay and Simulated Practice
- replay-alert-harness.aflPart 26 - Replay Exercise: Intraday Setups and Alerts114 lines
- replay-clock.aflPart 26 - Bar Replay: Mechanics and Honest Limits83 lines
- replay-debrief-exploration.aflPart 26 - the debrief step for both replay exercises73 lines
- replay-decision-log.aflPart 26 - Replay Exercise: Reading a Session Live106 lines
- replay-mtf-context.aflPart 26 - Replay Exercise: Intraday Setups and Alerts110 lines
Part 27 From Trading Idea to Trading System
- assumptions-block.aflPart 27 - Execution Assumptions You Must State126 lines
- first-system.aflPart 27 - Project: Your First Complete Trading System148 lines
- minimal-system.aflPart 27 - From Rules to AFL65 lines
- signal-fill-audit.aflPart 27 - From Rules to AFL63 lines
Part 28 AmiBroker Backtesting
- cost-model.aflPart 28 - Costs: Commissions, Slippage and the Spread83 lines
- equal-weight-benchmark.aflPart 28 - Reality Check: Is the Golden Cross Worth Anything?89 lines
- gap-through-stop.aflPart 28 - Stops with ApplyStop()111 lines
- golden-cross-portfolio.aflPart 28 - Reality Check: Is the Golden Cross Worth Anything?102 lines
- portfolio-core.aflPart 28 - Portfolio Backtesting: Many Symbols, One Account116 lines
- position-sizing-bench.aflPart 28 - Position Sizing with SetPositionSize()120 lines
- project-portfolio-system.aflPart 28 - Project: A Realistic Portfolio Backtest141 lines
- same-rules-two-ways.aflPart 28 - Single-Symbol Thinking versus Portfolio Reality87 lines
- signal-audit.aflPart 28 - Backtester Basics: Signals and Trade Prices76 lines
- signals-to-trades.aflPart 28 - Backtester Basics: Signals and Trade Prices78 lines
- stop-exit-visualiser.aflPart 28 - Stops with ApplyStop()89 lines
- stops-workbench.aflPart 28 - Stops with ApplyStop()140 lines
Part 29 Understanding Backtest Results
- report-reference-system.aflPart 29 - Understanding Backtest Results114 lines
- underwater-curve.aflPart 29 - Understanding Backtest Results86 lines
Part 30 Backtesting Mistakes
- break-fix-collection.aflPart 30 - Challenge Collection: Six Broken Backtests194 lines
- cost-sensitivity-backtest.aflPart 30 - Unrealistic Fills, Costs and Liquidity123 lines
- impossible-backtest-repaired.aflPart 30 - Challenge: 180% a Year with a 3% Drawdown (solution formula)130 lines
- impossible-backtest.aflPart 30 - Challenge: 180% a Year with a 3% Drawdown90 lines
- look-ahead-side-by-side.aflPart 30 - Look-Ahead Bias134 lines
- participation-capped-sizing.aflPart 30 - Position Sizing and Portfolio Errors136 lines
- random-signal-benchmark.aflPart 30 - Data Snooping, Curve Fitting and Overfitting98 lines
- regime-split-evidence.aflPart 30 - Insufficient Evidence and Regime Dependence163 lines
- signal-execution-audit.aflPart 30 - Challenge Collection: Six Broken Backtests124 lines
- universe-listing-audit.aflPart 30 - Survivorship and Selection Bias109 lines
Part 31 Optimization
- chosen-parameters.aflPart 31 - Optimization, Lab110 lines
- neighbourhood-sensitivity.aflPart 31 - Optimization91 lines
- optimizable-trend-system.aflPart 31 - Optimization93 lines
Part 32 Out-of-Sample and Walk-Forward Testing
- holdout-guard.aflPart 32 - In-Sample and Out-of-Sample75 lines
- wf-breakout-portfolio.aflPart 32 - Lab: Run a Walk-Forward Analysis104 lines
- wf-equity-plot.aflPart 32 - The AmiBroker Walk-Forward Workflow39 lines
- wf-fixed-baseline.aflPart 32 - Lab: Run a Walk-Forward Analysis (the control)70 lines
Part 33 Monte Carlo and Robustness
- equity-independence-check.aflPart 33 - Monte Carlo and Robustness168 lines
- mc-baseline-system.aflPart 33 - Monte Carlo and Robustness89 lines
- randomised-position-score.aflPart 33 - Monte Carlo and Robustness79 lines
- ruin-laboratory.aflPart 33 - Monte Carlo and Robustness160 lines
Part 34 Risk Management
- atr-position-size.aflPart 34 - Volatility-Based Position Sizing95 lines
- candidate-correlation-exploration.aflPart 34 - Portfolio Exposure, Concentration and Correlation81 lines
- lab-shared-signals.aflPart 34 - Lab: Same Strategy, Three Position-Sizing Models80 lines
- lab-sizing-atr-risk.aflPart 34 - Lab: Same Strategy, Three Position-Sizing Models91 lines
- lab-sizing-fixed-shares.aflPart 34 - Lab: Same Strategy, Three Position-Sizing Models82 lines
- lab-sizing-percent-equity.aflPart 34 - Lab: Same Strategy, Three Position-Sizing Models81 lines
- portfolio-constraints-template.aflPart 34 - Portfolio Exposure, Concentration and Correlation89 lines
- risk-based-position-size.aflPart 34 - Risk Per Trade and Stop Distance93 lines
- underwater-curve.aflPart 34 - Drawdown and Risk of Ruin in Practice60 lines
Part 35 Developing a Complete Trading Research Process
- candidate-review-sheet.aflPart 35 - From Candidate to Decision160 lines
- decision-journal-export.aflPart 35 - Journalling and Separating Two Kinds of Performance119 lines
- pipeline-data-check.aflPart 35 - The Research Lifecycle End to End109 lines
- universe-and-regime.aflPart 35 - Defining Your Universe and Market Regime118 lines
Part 36 Advanced AFL
- correlation-matrix.aflPart 36 - Matrices and Advanced Data Handling134 lines
- custom-backtest-minimal.aflPart 36 - Introduction to the Custom Backtester Interface86 lines
- dynamic-variable-panel.aflPart 36 - Dynamic Variables: VarSet, VarGet and Friends97 lines
- formula-test-harness.aflPart 36 - Advanced Debugging and Tracing91 lines
- quickafl-probe.aflPart 36 - Performance: QuickAFL, Multi-Threading and Cost56 lines
- static-var-inspector.aflPart 36 - Static Variables in Depth60 lines
Capstone Capstone: Build Your Own AmiBroker Trading Research Workstation
- market-dashboard.aflCapstone Component 1 - Market Dashboard195 lines
- mtf-chart.aflCapstone Component 4 - Multi-Timeframe Chart135 lines
- mtf-lookahead-proof.aflCapstone Component 4 - the look-ahead proof93 lines
- realtime-workspace.aflCapstone Component 5 - the Level B/C path (live feed)142 lines
- replay-workspace.aflCapstone Component 5 - the Level A path (no data subscription required)130 lines
- scanner.aflCapstone Component 3 - Scanner115 lines
- stock-exploration.aflCapstone Component 2 - Stock Exploration134 lines
- strategy-audit.aflCapstone Component 7 - the evidence that the backtest was physically possible136 lines
- strategy-sensitivity.aflCapstone Component 8 - parameter sensitivity142 lines
- strategy.aflCapstone Component 6 - The Trading Strategy176 lines