Training Topics

Why Take an AmiBroker Course?

If you’ve been trading for any length of time, you’ve probably wondered how well a particular technical indicator has identified profitable trade setups in the past. Or perhaps you’re already trading a quantified strategy, but you’d like to tweak the rules a bit to see how that would have changed the historical performance of the system. Maybe you just want to be self-sufficient enough to find your own trading signals on a daily basis rather than waiting for someone else to send you trade alerts.

AmiBroker is a powerful technical analysis program, with advanced charting, back-testing and scanning capabilities. Utilized by traders around the world, it’s the primary tool I use to develop and test trading strategies. Most importantly, it just might be the solution that will help make you a better, more profitable trader by giving you the power to validate your own strategies and find your own trade setups.

Live vs. Recorded Training

There are at least three different ways to become proficient with AmiBroker and to learn the AmiBroker programming language, AFL.

  1. Self-guided, using the extensive AmiBroker help files and tutorials
  2. Recorded training sessions, some of which are available for free on YouTube and others which can be purchased from sites like AlvarezQuantTrading, AmiBroker-Courses, and others
  3. Live interactive training, customized to your specific needs

Recorded training is usually less expensive than live training, simply because it can be sold multiple times without additional time investment from the trainer. However, the course content is entirely fixed, and at best you will get some “office hours” time with the trainer to answer any questions, or perhaps just the ability to interact via email or a discussion forum post.

Live training may cost a bit more but can be targeted to the exact topics that you want to learn more about. You will also have the opportunity to interact directly with the instructor, in real time. For some types of learners, this live interaction is invaluable.

Below is a list of beginning, intermediate, and advanced topics that I have included in prior training courses. If you’re thinking about investing in some live training, you can use the list as a sort of menu to find areas that are of interest and at an appropriate level relative to your current skill set. Of course, I’m always happy to discuss other areas that you want to cover as well.

Beginner Level Topics

These topics are designed for traders who want to use AmiBroker to create simple back tests and/or generate trading signals, but who have little or no familiarity with AFL, the AmiBroker scripting language.

AmiBroker from 10,000 Feet

AmiBroker is a comprehensive technical analysis program, with advanced charting, back-testing and scanning capabilities. For those not familiar with the application, we will quickly cover some of the major areas of functionality. For more information, see the Tutorial section in the AmiBroker help file.

  • Charting
  • Auto Analysis
  • Preferences
  • Help

Data Sources

AmiBroker does not directly provide any useful price data. Rather, it is a set of tools which can be used with data from a variety of providers, including Norgate, CSI, Telechart, Yahoo and others. We will discuss some of the advantages and disadvantages of each of these providers, as well as items that are important to consider for any provider you might decide to use.

  • Providers:
    • Norgate Premium Data
    • CSI Data
    • TeleChart
    • Yahoo, Google
    • eSignal
    • Interactive Brokers
  • Considerations:
    • Frequency of updates
    • Historically adjusted data
    • Delisted securities and survivorship bias
    • Database speed
    • Index constituents
    • Watch Lists & Groups
    • Price

Auto Analysis Window

The Auto Analysis window will be your home base for any of the analysis tasks that you might wish to perform in AmiBroker, including scans and back tests. We will discuss each type of analysis, including what it’s used for, how to configure it, and how to execute it.

  • Scan/Explore/Backtest/Optimize
  • Settings
  • Parameters
  • Watchlists
    • Why they’re useful
    • How to use them
    • How to create them

Coding Scans: Your First AFL Script

A Scan is the quickest, easiest way to generate a set of signals from your trading rules. In this session, we will introduce the AFL scripting language and the tools for creating and running your first script. Fortunately, you need only a limited set of commands to implement a basic script, particularly if you have a template to start from. However, AmiBroker contains a rich set of indicators and other functions that will ultimately allow you to test a wide variety of trading ideas.

  • Built-In Editor vs. External Editors
  • AmiBroker Help
  • Review of the basic AFL Code Template
  • Comments
  • Standard Variables:
    • Open/High/Low/Close
    • Volume/Open Interest/Aux 1/Aux 2
    • Buy/Sell/Short/Cover
    • Pricing
  • How Arrays Work
  • The Ref and MA functions

Coding Explorations

AmiBroker Explorations allow you to easily extract data, format and present that data in AmiBroker, and export it to a CSV file that can be opened with Excel. In this session we will discuss the variables and functions used to create an Exploration, as well as how to execute an Exploration and export the data.

  • Filter
  • AddColumn, AddTextColumn, AddMultiTextColumn
  • ExRem
  • Walk-through of the Exploration template
  • Executing the Exploration
  • Exporting Results

Interactive Debugger

Recent versions of AmiBroker include an interactive debugger that allows you to execute your AFL step-by-step so that you can see exactly what’s happening with your variables and the flow of execution. In this exercise, we’ll see how to use the debugger and talk about its advantages as well as its limitations.

Coding Indicators

AmiBroker allows you to easily add built-in indicators like RSI and Moving Averages to your charts. But what if you want to plot a custom indicator like Historical Volatility? In this coding session, we will discuss the AFL commands that are required for creating a custom indicator, as well as how to add that indicator to the AmiBroker environment.

  • Plot
  • Param
  • The AmiBroker\Formulas\Custom directory
  • Adding a custom indicator to a chart

Coding: Additional Concepts

In this coding session, we will introduce several more common AFL functions, as well as standard constructs like conditionals (if-then-else) and loops.

  • Common Functions:
    • IIf
    • Min/Max
    • HHV/LLV
  • Logical Operators
  • Conditionals: if & switch
  • Loops: for & while
  • SetOption

Back Testing Mechanics

A back test allows us to see how a trading strategy might have performed over some time period in the past when applied to a specific set of securities. Although the historical results produced by a back test are no guarantee of how the strategy will perform in the future, they can still provide valuable insights into the strategy’s strengths and weaknesses. In this session we will discuss how back testing works in AmiBroker as well as how to troubleshoot a misbehaving back test.

  • Setting the Date Range for the test
  • Specifying a Watch List
  • How a back test works
  • Viewing Results
  • Using Scan or Explore to troubleshoot

More Back Testing Techniques

In this session we will discuss additional concepts that can enhance and expand your back testing repertoire.

  • All Trades vs. All Days vs. Portfolio tests
  • The importance of adjusted prices, delisted securities, historical index constituents
  • Curve Fitting
  • Limit orders
  • Stop Losses and Profit Targets: ApplyStop

Common Mistakes

The more power and flexibility that a tool provides for its user, the more opportunities there are for things to go awry. This is just as true for software tools as it is for motor vehicles and chain saws. In this session we will discuss some common pitfalls that occur when doing analysis within AmiBroker.

  • Looking into the future
  • Wrong entry/exit prices
  • IIf vs If
  • Assignment vs Equality (= and ==)
  • Max Positions

Intermediate Topics

These topics are appropriate for traders who have mastered the basics and are ready to start modeling live trading systems more closely.

Useful Built-In Functions

AmiBroker’s AFL scripting language provides a diverse set of variables, commands and functions that you can use to develop custom indicators, scans, explorations, back tests, and explorations. In fact, the AFL help file lists over 350 AFL functions. In this session we will discuss a few of the functions that you will find most useful as you begin to develop more advanced AFL scripts.

  • Status
  • Lookup
  • _TRACE()
  • SetTradeDelays
  • Foreign/SetForeign
  • Sum, Cum
  • BarsSince, SumSince
  • ValueWhen, LastValue

User-Defined Functions

AmiBroker allows you to write your own functions which can be called just like the built-in functions provided by the platform. In this session we will discuss:

  • Function Definitions
  • Scope
  • Execution
  • Design Considerations

Static Variables & Ranking

Static variables have a different scope and lifetime than regular (local) variables in AmiBroker. They also play a critical role when using AmiBroker’s ranking functions.

  • StaticVarSet / StaticVarGet
  • StaticVarSetText / StaticVarGetText
  • StaticVarAdd
  • StaticVarRemove
  • StaticVarGenerateRanks

TimeFrame Manipulation

When you run a back test, AmiBroker allows you to select the base duration for each “bar” of the test. This is also known as the timeframe or periodicity. You can test 1-minute bars, daily bars, weekly bars, etc. Sometimes, however, you want to use multiple timeframes within a single test. For example, perhaps you use a market timing rule that compares the current weekly close of SPY to the weekly closes over the past year. In this section we’ll illustrate the use of the AFL functions for manipulating timeframes.

  • Interval
  • TimeFrame Set/Restore
  • TimeFrame Compress/Expand
  • TimeFrameGetPrice

Scaling & the Position Size Array

Scaling into trades can be a powerful tool for increasing gains. In this session we will discuss how to implement a basic scaling strategy for an All Trades test.

  • The 2/3/5 scale in
  • Review the Scale-In Code Template
  • Average entry price
  • Interpreting the trade list

Portfolio Considerations

Simulating how a strategy would actually be traded as part of a portfolio is a big step up from simply generating trading signals or running an “all trades” test. In this session we’ll discuss money management issues like position sizing and margin, as well as mechanics like prioritizing your trade signals and limiting the number of open positions.

  • Max Positions
  • SetPositionSize
  • Position Score
  • Margin
  • Futures Contract Specs: Round Lot Size, Point Value, Tick Size, Margin Deposit

Optimization

An optimization allows you to automatically execute a set of back tests in which each test has a unique set of input parameters. Each test (combination of parameters) typically corresponds to a specific strategy variation. For example, we might want to test a strategy in which the RSI threshold for trade entry varies from 10 to 25 in increments of 5. In this session we will discuss how to convert the AFL for a back test into an optimization.

  • How to set up
  • The Optimize function
  • Using the Switch function to handle odd increments
  • Exhaustive vs. Smart Optimization

Advanced Topics

These topics are appropriate for traders who want to use AmiBroker to create complex back tests and optimizations using the Custom Back-Tester (CBT) interface.

AmiBroker Execution Architecture

To write effective code, it’s important to understand how AmiBroker processes your AFL, and what happens in the background. Some of the topics we’ll cover in the session include:

  • Execution Phases 1 & 2
  • Number of Bars
  • Pad & Align
  • Multithreading
  • Status(“stocknum”)

AmiBroker Object Model

AmiBroker is built on an object-oriented architecture, and it exposes part of the object model during Phase 2 execution. In this session, we will cover the various classes that you can use during Phase 2:

  • Backtester
  • Signal
  • Trade
  • Stats
  • Collections and iteration

Introduction to the CBT

The Custom Back Tester Interface, or CBT, is one of the most powerful tools available in AmiBroker. Writing your own back testing code gives you an enormous amount of control over how your trading signals are executed as well as opening a myriad of possibilities for reporting and metrics. In this section we will introduce the CBT and discuss the simplest possible implementation of a custom back testing procedure.

  • Why is it useful?
  • Three levels: high/medium/low
  • CBT-specific functions: SetBacktestMode & SetCustomBacktestProc

High-Level CBT and Custom Metrics

Using the high-level CBT is a great way to implement custom metrics without having to handle the intricacies of processing all the trade signals. In this session we will discuss both per-trade custom metrics and summary custom metrics and illustrate how those are implemented using a code template.

  • Custom Trade Metrics
  • Custom Portfolio/Summary Metrics
  • Key functions: GetBacktesterObject, bo.Backtest, bo.ListTrades
  • Review the Trade Metrics Code Template
  • Review the Portfolio Metrics Code Template

Mid-Level CBT

The mid-level CBT allows you to modify entry and exit signals while still having AmiBroker do most of the heavy lifting of signal processing. Topics we will cover in this session include:

  • Key functions: bo.PreProcess, bo.ProcessTradeSignals, bo.PostProcess
  • Bar-by-Bar loop
  • Example Tasks: Interest on Cash, Hedging
  • Reviewthe Mid-Level Code Template

Low-Level CBT

The low-level CBT is the go-to interface for AmiBroker power users who are implementing advanced back tests and optimizations. We will discuss the types of problems that can be solved with this construct, particularly in the context of portfolio tests, and illustrate the solutions with example code.

  • Types of tasks that typically require the Low Level CBT
    • Applying a custom interest rate such as T-Bill to available cash
    • Hedging
    • Portfolio test with limits and/or scale-ins
    • Controlling order of entries and exits
  • Review the Low-Level CBT Code Template

Rotational Systems

Rotational systems hold trading instruments in a portfolio based on a ranking system. Instruments are held until they get pushed out by a higher-ranked security or fail some other fundamental test for being included in the portfolio, like being delisted from a particular index. AmiBroker includes a built-in rotational trading mode that allows you to easily build a simple rotational system. We will compare the functionality provided by the platform with the types of more advanced features that you may wish to implement, including:

  • Supplemental exit conditions such as stops and profit targets
  • Rebalancing open positions
  • Rotating from multiple candidate pools
  • Concurrent long and short rotations

Multi-Strategy Systems

In this session we will discuss the challenges of combining multiple trading strategies in a single system, as well as the shortcut technique of co