CSCheatsheets
Open Varsity · Beginner

AmiBroker AFL

AmiBroker Formula Language from arrays and Plot to parameters, shapes, GFX, explorations and scanners, Buy/Sell/Short/Cover, ExRem and no repainting, ApplyStop, sizing, backtest reports, optimisation, five strategies, multi-timeframe, alerts and OpenAlgo orders.

9sections
41cards
3diagrams
0%known

00AmiBroker AFL: atlas and routes

The AmiBroker Formula Language from a first plotted line to scanners, trading systems, honest backtests, optimisation, a five-strategy playbook, alerts and order automation through OpenAlgo. Condensed from OpenAlgo's free Open Varsity course. Educational, not investment advice.

How to use this sheet#

  1. New to AFL: "think in arrays" first; everything else is built on columns of values.
  2. Building a system: trading systems → the non-repainting recipe → backtesting → the playbook.
  3. Going live: alerts, OpenAlgo automation, and the system skeleton at the end. Rehearse in OpenAlgo's analyzer (sandbox) mode first.
Educational, not investment advice. Condensed in our own words from OpenAlgo Open Varsity: AmiBroker AFL. Code here is short illustrative AFL; check function details in the AmiBroker guide (amibroker.com/guide).

One formula, four jobs#

Run it asFromYou get
IndicatorFormula Editor → ApplyLines and shapes on a chart pane
ExplorationAnalysis → ExploreA table: one row per symbol or bar
ScanAnalysis → ScanBuy/Sell/Short/Cover hits across symbols, with alerts
BacktestAnalysis → BacktestSimulated trades and a full report

The code doesn't change between modes; the button you press decides the job. Data is separate from logic, so one formula runs on any symbol and timeframe. AmiBroker dates from 1995, AFL from 1999; save every formula as a named .afl file (e.g. ch02-rsi.afl).

Check yourself 2 questions
  1. Which run mode gives a table with one row per symbol or bar?

    Show answer

    Exploration (Analysis → Explore).

  2. Which mode produces simulated trades and a report?

    Show answer

    Backtest.

Takeaway The same AFL file runs as an indicator, an exploration, a scan or a backtest depending on where you run it.

The non-repainting recipe#

flowchart TD
  R["Raw signal: Buy = Cross(fast, slow)"] --> D["Delay one bar: Buy = Ref(Buy, -1)"]
  D --> X["Clean: Buy = ExRem(Buy, Sell) and the matching Sell line"]
  X --> P["Price: BuyPrice = ValueWhen(Buy, Open)"]
  P --> Z["SetTradeDelays(0, 0, 0, 0): one delay mechanism only"]

The alternative is to keep signals on the cross bar and use SetTradeDelays(1,1,1,1). Doing both lags fills two bars.

Main card on honest backtesting: Quant trading → Also in Algo trading · Algo trading · Technical · Quant trading.

Check yourself 2 questions
  1. Why Ref(Buy, -1)?

    Show answer

    To act on the closed bar, so the signal can't repaint.

  2. If you use Ref(-1), what should SetTradeDelays be?

    Show answer

    SetTradeDelays(0, 0, 0, 0): one delay mechanism only.

Takeaway Raw signal, delay one bar with Ref(-1), clean with an ExRem pair, price at the next open, and use only one delay mechanism.

01The AFL language: arrays, functions, logic and time

OpenAlgo Open Varsity · AmiBroker AFL · chapters 1–4 and 7–12 (what is AmiBroker, how AFL thinks, price arrays, built-in functions, conditions, Ref, Cross, BarsSince, dates and sessions, loops, functions)

Think in arrays#

  • Every AFL variable is a column with one value per bar. Write the calculation once; AFL fills every bar (vectorised).
  • Comparisons give 1/0 columns: Close > MA(Close, 20) is true or false on each bar, the seed of every signal. Colours and shapes are just named numbers too (shapeNone = 0).
  • Text is the exception: strings are produced per bar for display (Title, exploration), not stored as arrays.
  • The Title shows the last bar, or the clicked bar, but the variable is still the whole column. Debug by sketching a small table: one row per bar, one column per variable.
  • AFL is case-insensitive; statements end with ;; comments are // and /* */.
Check yourself 2 questions
  1. What does Close > MA(Close, 20) produce?

    Show answer

    A 1/0 array: true or false on each bar.

  2. Do you need a loop to compute an average across bars?

    Show answer

    No. AFL is vectorised: write it once and it fills every bar.

Takeaway Every AFL variable is a column with one value per bar; comparisons give 1/0 columns that seed every signal.

Price arrays, variables and operators#

// O H L C V and OpenInt are loaded for you
range    = High - Low;
body     = abs(Close - Open);
typical  = (High + Low + Close) / 3;   // brackets matter
chg      = (Close - Open) / Open * 100;
Plot(typical, "Typical", colorYellow, styleLine | styleThick);
  • (H+L+C)/3 and H+L+C/3 differ: precedence is brackets, then * /, then + −. Add brackets whenever unsure.
  • % gives a remainder (every-Nth-bar logic). Name variables for what they hold, and plot a variable temporarily to inspect it by hovering.
  • OpenInt matters for F&O data such as NIFTY futures.
Check yourself 2 questions
  1. Why do (H+L+C)/3 and H+L+C/3 differ?

    Show answer

    Division binds tighter, so only C is divided in the second.

  2. How do you compute the candle body size?

    Show answer

    abs(Close − Open).

Takeaway O, H, L, C, V and OpenInt are preloaded arrays; brackets matter because of operator precedence.

Built-in functions: arguments in, array out#

FamilyFunctionsNotes
AveragesMA(arr, n), EMA(arr, n), WMA(arr, n)Any array works: EMA(Volume, 20)
MomentumRSI(14), MACD(12, 26), Signal(12, 26, 9)bullish = MACD(12,26) > Signal(12,26,9);
Volatility, bandsATR(n), BBandTop(arr, 20, 2), BBandBot(arr, 20, 2)ATR is in price units, not %
WindowsSum(arr, n), HHV(arr, n), LLV(arr, n)Rolling n bars; Donchian = HHV/LLV
All history so farHighest(arr), Lowest(arr)Cumulative, not a window

Nest freely (EMA(RSI(14), 5) evaluates inside out), but split long nests into named steps. Windows need time to fill: MA(Close, 3) is blank on the first two bars. Check argument order and defaults in the reference: array first, period second; RSI() equals RSI(14).

Check yourself 2 questions
  1. Can EMA be applied to volume?

    Show answer

    Yes: EMA(Volume, 20); any array works.

  2. What units is ATR in?

    Show answer

    Price units, not percent.

Takeaway Built-ins take arrays and return arrays: averages, momentum and volatility work on any array.

Conditions, AND/OR and IIf#

upTrend = Close > EMA(Close, 50);
longOK  = upTrend AND (RSI(14) > 50)
          AND (Volume > MA(Volume, 20));
upDays  = Sum(Close > Ref(Close, -1), 20);  // true counts as 1
barCol  = IIf(upTrend, colorGreen, colorRed);
zone    = IIf(RSI(14) > 70, colorRed,
          IIf(RSI(14) < 30, colorGreen, colorYellow));
  • Comparisons: > < >= <= == !=; logic AND OR NOT (or && || !), all bar by bar.
  • IIf(cond, a, b) picks per bar and returns an array (numbers, colours, levels). Nested IIf: first true branch wins; keep it to 3–4 levels.
  • = assigns, == compares: IIf(trend = 1, …) silently sets trend. Bracket each condition; check both sides share a scale (Close > 50 on a ₹2,400 stock is always true).
Check yourself 2 questions
  1. How do you count up-days in the last 20 bars?

    Show answer

    Sum(Close > Ref(Close, -1), 20).

  2. What does IIf do?

    Show answer

    Picks one of two values on each bar based on a condition.

Takeaway Combine conditions with AND and OR; IIf picks a value per bar; Sum of a condition counts true bars.

Looking back: Ref, Cross, BarsSince#

CallMeans
Ref(C, -1)Previous bar (negative = past)
Ref(C, +n)Future data: never in Buy/Sell/Short/Cover
Cross(a, b)True only on the bar a rises through b
BarsSince(cond)0 on the event bar, then +1 a bar
HHV/LLV(arr, n), HHVBarsWindow extreme, and bars since it
ValueWhen(cond, arr)arr at the last true cond
  • Use Cross for entries; a plain > fires on every bar of a trend.
  • Shift channels back a bar: Close > Ref(HHV(High, 20), -1), or the current bar sets its own level and a breakout can never happen.
  • BarsSince counts from bar 1 before the first event: guard early bars.
Check yourself 2 questions
  1. Why is Ref(C, +1) dangerous in Buy rules?

    Show answer

    It reads future data: look-ahead.

  2. What does Cross(a, b) return?

    Show answer

    True only on the bar where a rises through b.

Takeaway Ref with negative offsets looks back; positive Ref is future data and must never feed signals.

Dates, times and the session#

newDay   = DateNum() != Ref(DateNum(), -1);   // safer than Day()
barNum   = 1 + BarsSince(newDay);
dayOpen  = ValueWhen(newDay, Open);
dayHigh  = HighestSince(newDay, High);
tn       = TimeNum();                          // 09:15 = 91500
inWindow = tn >= 93000 AND tn < 143000;
squareOff = tn >= 151500;
  • Day() 1–31, Month(), Year(), DayOfWeek() (0 Sun … 6 Sat; NSE trades 1–5), DateNum() = (year − 1900)·10000 + month·100 + day (26 Jun 2026 = 1260626), Interval() in seconds (300 = 5-minute).
  • Clock functions only mean something on intraday data. Write 91500, not 091500. Never find the session's last bar with Ref(…, 1) (future data); use the clock.
  • newDay underpins VWAP, opening ranges and day highs/lows; TimeFrameGetPrice("O", inDaily) fetches the daily open directly.
Check yourself 2 questions
  1. How is 9:15 represented by TimeNum?

    Show answer

    91500.

  2. How do you get today's open on intraday bars?

    Show answer

    ValueWhen(newDay, Open).

Takeaway Detect a new day with DateNum, anchor session values with ValueWhen and HighestSince, and window trades with TimeNum.

Loops: only when arrays can't#

out = Null;                       // initialise first
out[0] = Close[0];
for (i = 1; i < BarCount; i++)    // start at 1 to read i-1
{
    out[i] = 0.9 * out[i-1] + 0.1 * Close[i];
}
  • Vectorise by default. Loop only when bar i needs the previous result of the same output: trailing stops, Supertrend, parabolic SAR, state machines.
  • Compute indicators before the loop; carry state in scalars and reset it on exit; ratchet with Max()/Min().
  • Never read [i+1] in a signal; every while must move toward its exit; don't name variables atr, ma or rsi (they shadow built-ins).
Check yourself 2 questions
  1. When is a loop necessary in AFL?

    Show answer

    When each bar depends on the previous value of the same output.

  2. Why start the loop at i = 1?

    Show answer

    So out[i−1] exists to read.

Takeaway Loop only when bar i needs the previous result of the same output, as in trailing stops or Supertrend.

Functions, procedures and #include#

function SmoothRSI(period, smooth)
{
    raw = RSI(period);
    return EMA(raw, smooth);          // nothing after return runs
}
procedure DrawLevel(value, col, label)
{
    Plot(value, label, col, styleDashed | styleNoLabel);
}
s = SmoothRSI(14, 3);                 // order matters: (14, 3)
DrawLevel(HHV(High, 20), colorGreen, "20-bar high");
  • A function returns a value; a procedure acts (plots) and returns nothing. Arguments match by position.
  • Variables inside are local; share with global x; declared in both places, sparingly.
  • Keep tested helpers in MyLibrary.afl in the Include folder and add #include <MyLibrary.afl>: fix once, every formula benefits. Guard divisions: IIf(b == 0, 0, a / b).
Check yourself 2 questions
  1. What happens to code after return in a function?

    Show answer

    It doesn't run.

  2. Function versus procedure?

    Show answer

    A function returns a value; a procedure performs an action.

Takeaway Functions return values, procedures just act, and #include shares code across formulas.

02Charting and visualisation

OpenAlgo Open Varsity · AmiBroker AFL · chapters 2, 5–6 and 13–17 (formula editor, plotting, parameters, shapes and text, colours, title, panes and Foreign, GFX)

The editor and Plot#

_SECTION_BEGIN("Price and MA");
Plot(C, "Close", colorDefault, styleNoTitle | GetPriceStyle());
Plot(MA(C, 20), "MA 20", colorRed, styleLine | styleThick);
Plot(0, "", colorWhite, styleDashed);       // reference line
_SECTION_END();
Shape (pick one)Modifiers (stack with |)
styleLine, styleCandle, styleBar, styleHistogram, styleAreastyleThick, styleDots, styleDashed, styleNoTitle, styleNoLabel, styleOwnScale
  • Apply replaces the pane (use while developing); Insert adds without erasing. _SECTION_BEGIN/END groups controls in the Parameters window.
  • Same units as price (MAs, bands, VWAP) overlay the price pane; RSI, MACD and volume get their own pane or styleOwnScale. Never mix two shapes.
  • Colours: colorRed etc., ColorRGB(r, g, b), colorDefault, colorCycle. Keep a consistent meaning: green bullish, red bearish, grey neutral.
Check yourself 2 questions
  1. How do you combine style flags?

    Show answer

    With |, e.g. styleLine | styleThick.

  2. What's the role of _SECTION_BEGIN/_SECTION_END?

    Show answer

    To group code into named sections.

Takeaway Plot draws arrays with a shape style plus stackable modifiers; wrap code in _SECTION_BEGIN and _SECTION_END.

Parameters: tune without editing#

ControlReturns
Param("Length", 20, 1, 100, 1)Number (label, default, min, max, step)
ParamToggle("Show", "Off|On", 1)0 or 1
ParamList("Mode", "Fast|Slow")Text: compare with == "Slow"
ParamColor, ParamStyleA colour, a style flag
ParamField("Apply to", 3)A price array (3 = Close)
ParamStr, ParamDate, ParamTimeText, date, TimeNum-style time
ParamTrigger("Test")True once per click (an event)

Right-click the chart → Parameters. Parametrise what a user might tune (periods, multipliers, thresholds, colours), not fixed maths. _TRACE("text") writes to Window → Log for debugging. Later, swap Param for Optimize to sweep values.

Check yourself 2 questions
  1. What does ParamToggle return?

    Show answer

    0 or 1.

  2. How do you compare a ParamList choice?

    Show answer

    With == against the text, e.g. == "Slow".

Takeaway Param, ParamToggle, ParamList and friends expose settings you can tune without editing code.

Arrows, shapes and text#

upShape = IIf(Buy, shapeUpArrow, shapeNone);
dnShape = IIf(Sell, shapeDownArrow, shapeNone);
PlotShapes(upShape, colorGreen, 0, Low, -20);
PlotShapes(dnShape, colorRed, 0, High, -20);
// 1/0 × shape
PlotShapes(Cover * shapeStar, colorRed, 0, Low, -12);
  • PlotShapes(shape, colour, layer, y, offset): anchor at Low or High; offset is screen pixels, negative pushes down, positive up, whatever the anchor.
  • Always use shapeNone on false bars. Shapes: up/down arrows (and small), square, star, circles, digits 0–9.
  • PlotText(text, bar, price, textColour, bgColour) in a loop for a few key labels only; hundreds slow the chart. Layer shapes back to front for bold markers, and keep one convention across strategies.
Check yourself 2 questions
  1. How do you draw an up arrow only on Buy bars?

    Show answer

    PlotShapes(IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, Low, −20).

  2. Why does Cover * shapeStar work?

    Show answer

    Cover is 1/0, so the product is the shape on cover bars and zero elsewhere.

Takeaway PlotShapes takes a shape array (shape × 1/0 condition), a colour and an offset from a price.

Colours, ribbons and candles#

candleCol = IIf(MACD() > 0, colorGreen, colorRed);
Plot(C, "Price", candleCol, styleCandle);
ribbon = IIf(C > EMA(C, 50), colorGreen, colorRed);
Plot(1, "", ribbon,
     styleArea | styleOwnScale | styleNoLabel, 0, 1);
fill = ColorBlend(colorYellow, colorBlack, 0.9);
PlotOHLC(lo, lo, hi, hi, "", fill, styleCloud);   // shade a band

One pattern everywhere: condition → IIf colour array → Plot's colour slot. A ribbon needs styleOwnScale and the 0–1 range or it squashes the candles. Keep to one or two ribbons, light fills, and define custom colours once at the top.

Check yourself 2 questions
  1. How do you colour candles by MACD sign?

    Show answer

    Plot C with styleCandle and colour IIf(MACD() > 0, colorGreen, colorRed).

  2. What makes a ribbon independent of the price scale?

    Show answer

    styleOwnScale.

Takeaway Colour arrays from IIf can colour candles and draw regime ribbons on their own scale.

Title and StrFormat#

_N(Title = StrFormat(
    "{{NAME}} {{DATE}} O %g H %g L %g C %g (%.1f%%)",
    O, H, L, C, SelectedValue(ROC(C, 1))));
regime = WriteIf(C > EMA(C, 50), "Bullish", "Bearish");
Title  = Title + "\n" + regime;
  • Placeholders fill left to right: %g trims trailing zeros, %.2f fixes decimals, %% is a literal percent. Count and order must match.
  • Tokens: {{NAME}}, {{DATE}}, {{INTERVAL}}, {{VALUES}}. \n starts a second line.
  • WriteIf returns text, IIf numbers; NumToStr(x, 1.2) formats a number; SelectedValue(arr) reads the bar under the cursor.
Check yourself 2 questions
  1. What does %g do in StrFormat?

    Show answer

    Prints a number trimming trailing zeros.

  2. How do you print a literal percent sign?

    Show answer

    %%.

Takeaway StrFormat fills placeholders left to right to build an informative chart title.

Panes and other symbols#

idx   = Foreign("NIFTY-I", "C");       // one field, date-aligned
rs    = Close / idx;                    // relative strength
Plot(rs, "RS", colorWhite, styleLine | styleOwnScale);
SetForeign("NIFTY-I");                  // whole indicators on it
    idxATR = ATR(14);
RestorePriceArrays();                   // always pair them
  • Foreign reads a field, PlotForeign draws a symbol, SetForeign swaps all price arrays until RestorePriceArrays(); forget the restore and later code silently uses the other symbol.
  • RS direction is what matters: rising = leading. Ratios (a / b), spreads and Correlation(C, Foreign(x, "C"), n) are the building blocks of pairs work.
  • Check the ticker string matches your database (NIFTY-I vs NIFTY); parameterise it with ParamStr; put comparisons in their own pane.
Check yourself 2 questions
  1. How do you compute relative strength against NIFTY?

    Show answer

    Close / Foreign("NIFTY-I", "C").

  2. What must always follow SetForeign?

    Show answer

    RestorePriceArrays().

Takeaway Foreign reads one field from another symbol, date-aligned; SetForeign switches all arrays and must be paired with RestorePriceArrays.

GFX dashboards#

w = Status("pxchartwidth");  h = Status("pxchartheight");
isLong = Flip(Buy, Sell);
GfxSelectPen(colorGreen, 2);
if (SelectedValue(isLong)) GfxSelectSolidBrush(colorDarkGreen);
else GfxSelectSolidBrush(colorDarkRed);       // GFX wants single values
GfxRoundRect(20, h - 120, 260, h - 20, 12, 12);   // box first
GfxSetBkMode(1);                                 // transparent text background
GfxSelectFont("Tahoma", 13, 700);
GfxSetTextColor(colorWhite);
GfxTextOut(WriteIf(SelectedValue(isLong), "LONG", "FLAT"), 36, h - 110);
GfxTextOut("Close " + NumToStr(SelectedValue(C), 1.2), 36, h - 80);
  • Pixels, origin top-left, y grows downward; drawings stay fixed while price scrolls. Later calls paint over earlier ones: boxes first, text last.
  • GFX takes single values, never arrays: wrap with SelectedValue() or LastValue(). Anchor to Status("pxchartwidth") / "pxchartheight" so resizing doesn't break it.
  • Use GFX for status panels and small tables; lines, bands and arrows belong to Plot and PlotShapes. Wrap the panel in a ParamToggle so it can be hidden.
Check yourself 2 questions
  1. Why use SelectedValue in GFX code?

    Show answer

    GFX needs single values, not arrays.

  2. How do you get the chart's pixel width?

    Show answer

    Status("pxchartwidth").

Takeaway GFX functions draw pixel-level dashboards using single values from SelectedValue or LastValue.

03Exploration and scanning

OpenAlgo Open Varsity · AmiBroker AFL · chapters 18–20 (exploration, building a scanner, filtering and ranking)

Exploration: Filter and columns#

Filter = 1;  // every bar, every symbol
AddColumn(Close, "LTP", 1.2);                 // 2 decimals
AddColumn(RSI(14), "RSI", 1.2);
AddColumn(Volume, "Volume", 1.0);             // no decimals
trendTxt = WriteIf(C > EMA(C, 50), "Bullish", "Bearish");
AddTextColumn(trendTxt, "Trend");
  • An exploration runs one formula over many symbols and prints a table instead of simulating trades. Set Apply to (current, all, a watchlist) and Range (last n bars, dates, all) before pressing Explore.
  • Filter is the row switch; "1 recent bar" gives one row per symbol, a wide range with Filter = 1 gives thousands.
  • Numbers go to AddColumn, text to AddTextColumn. Format 1.2 = 2 decimals, 1.0 none, 1.3 three. Keep columns few and purposeful.
Check yourself 2 questions
  1. What does Filter = 1 do?

    Show answer

    Shows every bar of every symbol.

  2. How many decimals does format 1.2 show?

    Show answer

    Two.

Takeaway Filter decides which bars appear; AddColumn and AddTextColumn define the table.

A signal scanner#

bull = Cross(MACD(12, 26), Signal(12, 26, 9));
bear = Cross(Signal(12, 26, 9), MACD(12, 26));
Filter = bull OR bear;  // only hits survive
AddTextColumn(WriteIf(bull, "Bullish", "Bearish"), "Signal");
AddColumn(MACD(12, 26), "MACD", 1.2);  // show the trigger value
volSpike  = Volume > Ref(HHV(Volume, 30), -1);
yearHigh  = High > Ref(HHV(High, 252), -1);
  • A scanner is an exploration whose Filter is the signal. Change the condition, not the machinery; always add the value that triggered the hit so results sort.
  • Patterns: momentum flips (Cross), extremes (RSI 70/30), breakouts (price AND volume), volume spikes and 52-week highs compared with the previous bar's window.
  • Explore gives a sortable table for screening; Scan reports Buy/Sell/Short/Cover and can fire alerts. Save the formula, watchlist and range together as an .apx project.
Check yourself 2 questions
  1. How do you show only MACD crossover bars?

    Show answer

    Filter = bull OR bear.

  2. How do you label each hit's direction?

    Show answer

    AddTextColumn(WriteIf(bull, "Bullish", "Bearish"), ...).

Takeaway Set Filter to the signal condition so only hits survive, and show the trigger value as a column.

Filter, sort, colour and rank#

relVol = Volume / MA(Volume, 20);
r      = RSI(14);
Filter = (relVol > 1.5) AND (Close > EMA(Close, 50));
AddColumn(Close, "Close", 1.2);
AddColumn(relVol, "RelVol", 1.2);                          // column 3
bk = IIf(r > 70, colorRed, IIf(r < 30, colorGreen, colorDarkGrey));
AddColumn(r, "RSI", 1.2, colorWhite, bk);                   // text, background
SetSortColumns(-3);                                         // busiest first

Add one condition at a time and watch the row count: an empty list usually means the last clause is too strict. Column 1 is the symbol, so your first AddColumn is column 2; negative numbers sort descending. Relative volume (Volume / MA(Volume, 20)) surfaces unusual activity. "Let the filter earn its place first; add the polish second."

Check yourself 2 questions
  1. Relative volume formula?

    Show answer

    Volume / MA(Volume, 20).

  2. How do you colour an RSI column?

    Show answer

    Pass a background colour array from IIf to AddColumn.

Takeaway Filter with relative volume and trend, colour cells by value, and sort or rank in the result list.

04Building trading systems

OpenAlgo Open Varsity · AmiBroker AFL · chapters 21–24 (Buy, Sell, Short, Cover, clean signals, stops and targets, sizing and delays)

Buy, Sell, Short and Cover#

ArrayJob
BuyOpens a long
SellCloses the long (never opens a short)
ShortOpens a short
CoverCloses the short (never opens a long)
Fast = EMA(Close, 10);
Slow = EMA(Close, 20);
Buy  = Cross(Fast, Slow);
Sell = Cross(Slow, Fast);
// Short = Sell; Cover = Buy;   // always-in-the-market variant

Reserved, case-insensitive 1/0 arrays; unused ones default to no signal. While long, further Buys are ignored until a Sell. Every Buy needs an exit. Fills default to the signal bar's close; set BuyPrice, SellPrice, ShortPrice, CoverPrice to change that. Start long-only (cash shorts may be unavailable).

Check yourself 2 questions
  1. Does Sell open a short?

    Show answer

    No. Sell only closes a long; Short opens a short.

  2. How do you make a system always in the market?

    Show answer

    Short = Sell; Cover = Buy.

Takeaway Buy opens a long, Sell closes it, Short opens a short, Cover closes it; Sell never opens a short.

Clean signals and no repainting#

Buy  = Ref(Cross(Fast, Slow), -1);     // act on the closed bar
Sell = Ref(Cross(Slow, Fast), -1);
Buy  = ExRem(Buy, Sell);               // first of each run only
Sell = ExRem(Sell, Buy);               // always as a pair
BuyPrice  = ValueWhen(Buy, Open);      // next-bar open, realistic
SellPrice = ValueWhen(Sell, Open);
SetTradeDelays(0, 0, 0, 0);            // one delay mechanism only
inLong = Flip(Buy, Sell);  // 1 on every bar in the trade
  • Choppy markets make Cross fire repeatedly; ExRem keeps buys and sells strictly alternating (edges), while Flip gives the in-trade state (fill).
  • Repainting: the live bar is unfinished, so a cross can appear and vanish. Acting on the previous closed bar costs the cross bar but makes the backtest honest.
  • Ref(…, −1) plus a non-zero trade delay lags fills by two bars and distorts the report.
Check yourself 2 questions
  1. Why apply ExRem to both Buy and Sell?

    Show answer

    So signals alternate, keeping only the first of each run.

  2. What's a realistic BuyPrice after a delayed signal?

    Show answer

    The next bar's open: ValueWhen(Buy, Open).

Takeaway Delay signals one bar, apply ExRem as a pair, and price fills at the next open.

Stops and targets with ApplyStop#

ArgumentValues
typestopTypeLoss, stopTypeProfit, stopTypeTrailing
modestopModePercent, stopModePoint, stopModeDisable
amountA number, or an array (e.g. 2 × ATR)
exitAtStopTrue: exit intrabar at the level; False: check the close only
ApplyStop(stopTypeLoss,   stopModePercent, 0.5, True);
ApplyStop(stopTypeProfit, stopModePercent, 1.0, True);
ApplyStop(stopTypeLoss,   stopModePoint, 2 * ATR(14), True);
// freeze for plotting levels
atrAtEntry = ValueWhen(Buy, ATR(14));

A plotted line never exits a trade; only ApplyStop does, and it handles longs and shorts automatically. Trailing stops follow the best price since entry. Lock entry-time ATR with ValueWhen or the drawn levels wobble. Test every stop with and without it: too tight turns noise into a string of small losses.

Check yourself 2 questions
  1. Name the three ApplyStop types.

    Show answer

    stopTypeLoss, stopTypeProfit and stopTypeTrailing.

  2. What does exitAtStop = False do?

    Show answer

    Checks only the close, rather than exiting intrabar at the level.

Takeaway ApplyStop sets loss, profit and trailing stops in percent or points, and can take an ATR array.

Position sizing, costs and delays#

SetOption("InitialEquity", 1000000);
// 1 = % of value, 2 = flat per trade
SetOption("CommissionMode", 2);
SetOption("CommissionAmount", 20);
SetOption("AccountMargin", 100);  // 100 = fully funded, 20 = 5x
SetPositionSize(75, spsPercentOfEquity);
Mode (₹1,318 stock, ₹10 lakh equity)Size
spsShares, 100100 shares (₹1,31,800)
spsValue, 1,00,00075 shares
spsPercentOfEquity, 75569 shares, compounding

Test with fixed size first to see the bare edge; percent-of-equity compounding flatters weak edges. Always include realistic commissions, match AccountMargin to the instrument, and keep core assumptions in code because AFL settings override the dialog. SetTradeDelays(buy, sell, short, cover) is the engine's whole-bar delay.

Main card on position sizing: Risk management → Also in Technical · OV technicals · Futures · Options basics · Options strategies · Algo trading · Stock basics.

Check yourself 2 questions
  1. AccountMargin 20 means what leverage?

    Show answer

    5×.

  2. CommissionMode 2 means what?

    Show answer

    A flat amount per trade.

Takeaway Set equity, commission, margin, position size and trade delays in code, not just the dialog.

05Backtesting and optimisation

OpenAlgo Open Varsity · AmiBroker AFL · chapters 25–27 (first backtest, reading the report, optimisation)

Your first backtest#

  1. Analysis → New Analysis; pick the saved .afl.
  2. Set symbols, date range and a periodicity that matches the system (daily for swing, minutes for intraday).
  3. Put equity, commission, size and delays in code, not just the dialog.
  4. Press Backtest, then Report → Equity.
  • Read the curve's shape first: a steady climb is good; one jump then sideways is a lucky trade; a deep cliff is drawdown risk even if it ends higher.
  • Test multiple years across varied regimes; a few months proves little. A backtest is a simulation of the past, not a forecast: forward-test in OpenAlgo's analyzer mode next.
Check yourself 2 questions
  1. Why put equity and commission in code?

    Show answer

    So results don't depend on dialog settings someone can forget.

  2. What should you look at first in the report?

    Show answer

    The equity curve's shape.

Takeaway Pick the formula, symbols, dates and matching periodicity, set costs in code, then read the equity curve's shape first.

Reading the report#

MetricGoodPoorNote
CAR (annual return)> 10%< 0Use instead of net profit, which grows with test length
Max system drawdown0 to −10%Worse than −30%Could you sit through it?
CAR / MDD> 2 excellent, 1–2 respectable< 1Check it isn't curve-fit
RAR % (return per exposure)> 10< 0Judge with exposure %
Payoff ratio (avg win ÷ avg loss)> 2< 1Win rate means nothing without it
Profit factor> 2< 1> 1 is profitable
Expectancy, recovery factor> 0; > 2< 0; < 1Recovery = net profit ÷ worst drawdown
Sharpe; K-ratio> 1 (2 very good); ≥ 13+ is suspicious; < 1Ulcer index: lower is better
  • Check All / Long / Short separately: the edge may live on one side. Trend systems win rarely with big payoffs; mean reversion wins often with small ones.
  • Want 30–50 trades at minimum, ideally hundreds. Sort the trade list: is profit spread out, or carried by one giant winner? Remove it and re-check.
  • Benchmark against buy-and-hold. A smooth curve with a very high Sharpe on heavily optimised parameters is a curve-fitting warning; a good backtest is a hypothesis.
Check yourself 2 questions
  1. Why use CAR instead of net profit?

    Show answer

    Net profit grows with test length; CAR is annualised.

  2. CAR/MDD below 1: verdict?

    Show answer

    Weak; also check it isn't curve-fit.

Takeaway CAR beats net profit, max drawdown tests your nerves, CAR/MDD above 1 is respectable and above 2 excellent.

Optimisation and robustness#

// name, default, min, max, step
Fast = Optimize("Fast EMA", 10, 5, 30, 1);
Slow = Optimize("Slow EMA", 20, 10, 100, 5);
OptimizerSetEngine("cmae");  // smart search for 3+ dials
OptimizerSetOption("Runs", 5);
OptimizerSetOption("MaxEval", 5000);
  • Optimize returns the default except during an optimisation run (arrow beside Backtest → Optimize). Exhaustive search suits 2–3 dials; beyond that use CMA-ES (cmae), particle swarm (spso) or Tribes (trib), and budget ≈ 10× more tests per extra dial. Set on/off switches by hand.
  • Rank by CAR/MDD, not net profit, and check trade counts. On the 2D heatmap or 3D graph pick the centre of a broad plateau, never a lone spike.
  • Use few dials, sensible steps (not 0.1 on EMA periods), never optimise on all your data, and confirm with AmiBroker's walk-forward and then sandbox trading.
Check yourself 2 questions
  1. What does Optimize return outside an optimisation run?

    Show answer

    Its default value.

  2. Which engine suits three or more dials?

    Show answer

    A smart search engine such as CMA-ES ("cmae").

Takeaway Optimize sweeps parameter ranges; use smart engines for three or more dials and choose plateaus, not peaks.

Is this system ready for sandbox?#

A backtest you like
1Are signals shifted a bar, ExRem-cleaned, with one delay mechanism?
no
Fix repainting firstRef -1, ExRem pair, SetTradeDelays 0
yes
2Are commission, size and margin set explicitly in code?
no
Set costs and size in codezero-cost results flatter every system
yes
330 or more trades, CAR/MDD near 1 or better, and beating buy-and-hold?
no
Not enough evidencelonger history, more symbols, or a better idea
yes
4Do the parameters come from a broad plateau that held out of sample?
no
Re-pick from a plateauthen walk-forward before trusting it
yes
Forward-test in analyzer modethen the smallest live size
Check yourself 2 questions
  1. First check before sandbox?

    Show answer

    Signals shifted a bar, ExRem-cleaned, with one delay mechanism.

  2. Why must costs be set in code?

    Show answer

    Zero-cost results flatter every system.

Takeaway No repainting, costs and size in code, enough trades and robust parameters before sandbox trading.

06Strategy playbook

OpenAlgo Open Varsity · AmiBroker AFL · chapters 28–32 (EMA crossover, Supertrend, VWAP intraday, Donchian and ORB, RSI pullback)

Five systems at a glance#

SystemEntryExitKey parametersCharacter
EMA crossoverFast EMA crosses above slowCrosses back belowFast 10 (2–50), slow 20 (5–100), optional shortsWin rate under 50%, payoff above 1; whipsaws in chop
SupertrendClose breaks the prior upper bandClose breaks the prior lower bandFactor 3 (1–6, step 0.5), ATR period 10 (5–30)Band ratchets like a trailing stop; few big winners
VWAP intradayClose crosses above session VWAP, 09:30–15:00Cross below VWAP, or square off 15:155- or 15-minute bars; one-bar delay; next-open fillsPick trend (reclaim) or reversion (fade), not both
Donchian / opening rangeHigh crosses the prior N-bar high, or the opening-range highLow crosses the prior N-bar low; ORB squares off 15:15, no entries after 14:30Channel 20 (try 55); OR bars 3 on 5-minExpect false breaks; gap-safe fills
RSI pullbackClose above 200 EMA, RSI was < 40, RSI turning upRSI crosses 60, or close below the EMARSI 14, dip 40, trend EMA 200 (50–300)Wins 55–70%, payoff often below 1

The course reports no fixed backtest figures for these; generate your own with realistic costs. Shared plumbing: Ref(…, −1) signals with zero trade delays (or the engine delay with Open fills), ExRem, explicit sizing, and sandbox before live. "A breakout system that only works at zero cost is not a system."

Check yourself 2 questions
  1. Typical character of an EMA crossover system?

    Show answer

    Win rate under 50% with payoff above 1, and whipsaws in chop.

  2. Supertrend default factor?

    Show answer

    3.

Takeaway EMA crossover, Supertrend, VWAP, opening range and RSI pullback: each with entry, exit, key parameters and a character.

Supertrend needs a loop#

Factor = Optimize("Factor", 3, 1, 6, 0.5);
Pd     = Optimize("ATR period", 10, 5, 30, 1);
mid = (H + L) / 2;
up  = mid + Factor * ATR(Pd);
dn  = mid - Factor * ATR(Pd);
trend = Null;  trend[0] = 1;
lineUp = dn;   lineDn = up;               // raw bands as seeds
for (i = 1; i < BarCount; i++)
{
    if (Close[i] > lineDn[i-1])      trend[i] = 1;
    else if (Close[i] < lineUp[i-1]) trend[i] = -1;
    else                             trend[i] = trend[i-1];
    if (trend[i] == 1 AND trend[i-1] == 1)
        lineUp[i] = Max(dn[i], lineUp[i-1]);   // only tightens
    if (trend[i] == -1 AND trend[i-1] == -1)
        lineDn[i] = Min(up[i], lineDn[i-1]);
}
st = IIf(trend == 1, lineUp, lineDn);

Each bar depends on the previous bar's state, so this is a genuine loop case: seed bar 0, start at 1, reset to the raw band on a flip (here by keeping the seed), ratchet otherwise. A compact sketch in the course's spirit; signals are trend == 1 / == −1, cleaned with ExRem.

Check yourself 2 questions
  1. Why can't Supertrend be pure array maths?

    Show answer

    Each band value depends on the previous bar's band.

  2. How are the raw bands built?

    Show answer

    Mid-price ± factor × ATR.

Takeaway Supertrend's bands depend on their own previous values, so it needs a bar-by-bar loop.

Session-anchored VWAP and opening range#

newDay    = DateNum() != Ref(DateNum(), -1);
barsToday = 1 + BarsSince(newDay);
tp   = (H + L + C) / 3;
vwap = Sum(tp * V, barsToday) / Max(Sum(V, barsToday), 1);
tn   = TimeNum();
Buy  = Ref(Cross(C, vwap) AND tn >= 93000 AND tn < 150000, -1);
Sell = Ref(Cross(vwap, C), -1) OR tn >= 151500;

ORBars = Param("OR bars", 3, 1, 12, 1);  // 3 × 5-min = 15 min
orDone = barsToday == ORBars;
orHigh = ValueWhen(orDone, HighestSince(newDay, High));
orLow  = ValueWhen(orDone, LowestSince(newDay, Low));
up20   = Ref(HHV(High, 20), -1);  // Donchian, prior bar
BuyPrice = Max(Open, up20);                    // gap-safe fill

Reset VWAP every session ("yesterday's volume has no business in today's average"); Max(…, 1) guards zero-volume bars. Freeze the opening range with ValueWhen rather than recomputing it. Use intraday periodicity, and commodity session times for MCX.

Check yourself 2 questions
  1. Session VWAP formula?

    Show answer

    Sum(typical × volume, bars today) ÷ Sum(volume, bars today).

  2. Why guard the denominator with Max(…, 1)?

    Show answer

    To avoid dividing by zero volume.

Takeaway Anchor VWAP to the session with BarsSince(newDay), and restrict entries to a time window with forced exits later.

RSI pullback inside a trend#

trendMA = EMA(Close, Param("Trend EMA", 200, 50, 300, 10));
r       = RSI(Param("RSI length", 14, 2, 50, 1));
upTrend = Close > trendMA;
dipped  = Ref(r, -1) < Param("Dip level", 40, 10, 50, 1);
Buy  = upTrend AND dipped AND r > Ref(r, -1);
Sell = Cross(r, 60) OR Close < trendMA;
Buy  = ExRem(Buy, Sell);  Sell = ExRem(Sell, Buy);
SetTradeDelays(1, 1, 1, 1);  BuyPrice = SellPrice = Open;
expectancy = win% × avg win − loss% × avg loss62% × 1.4% − 38% × 1.6% ≈ +0.26% a trade

Without the trend gate it buys falling knives. A dip level of 30 rarely triggers in uptrends; if trades are scarce, shorten the EMA rather than deleting the filter. Judge by expectancy, never win rate alone.

Check yourself 2 questions
  1. What defines the uptrend in this system?

    Show answer

    Close above a long EMA (default 200).

  2. What triggers the entry?

    Show answer

    RSI dipped below the dip level and is now rising.

Takeaway Buy RSI dips that turn up while price is above a long EMA; exit on RSI strength or a trend break.

07Real-time, alerts and automation

OpenAlgo Open Varsity · AmiBroker AFL · chapters 33–36 (multiple time frames, alerts, OpenAlgo automation, what next)

Multiple time frames#

TimeFrameSet(inHourly);
    hrEMA = EMA(Close, 20);
TimeFrameRestore();                            // always pair them
// expandLast by default
hrEMAx  = TimeFrameExpand(hrEMA, inHourly);
Buy     = Cross(fast, slow) AND Close > hrEMAx;
prevDayClose = TimeFrameGetPrice("C", inDaily, -1);  // closed bar
Expand modeUse
expandLastValue appears after the higher bar closes: for trading
expandFirstAppears from the start of the higher bar: leaks the future
expandPointOne bar only

Lower timeframe gives the entry, higher gives permission. Expand before comparing or plotting; use offset −1 (closed) in signals, not 0 (still forming). Self-check: the expanded line should only change at completed higher-bar boundaries.

Check yourself 2 questions
  1. What must always follow TimeFrameSet?

    Show answer

    TimeFrameRestore().

  2. How do you get the previous day's closed price on intraday bars?

    Show answer

    TimeFrameGetPrice("C", inDaily, −1).

Takeaway TimeFrameSet computes on a higher timeframe, TimeFrameRestore returns, TimeFrameExpand aligns the result.

Alerts: log, voice, Telegram#

msg = "BUY " + Name() + " at " + NumToStr(Close, 1.2);
AlertIf(Buy, "", msg, 1);
RequestTimedRefresh(1, False);  // re-run about once a second
key = Name() + GetChartID() + Interval(2);
bar = StrFormat("%0.f", LastValue(BarIndex()));
if (LastValue(Buy) AND StaticVarGetText(key + "buyBar") != bar)
{
    StaticVarSetText(key + "buyBar", bar);     // once per bar
    Say("Buy signal");
    url = "https://api.telegram.org/bot" + token +
          "/sendMessage?chat_id=" + chat +
          "&text=Buy%20" + Name();
    ih = InternetOpenURL(url);
    if (ih) InternetClose(ih);
}

A plain if (Buy) Say(…) re-fires on every refresh: fingerprint the bar in a static variable (the course also keeps a flag and re-arms it when the signal clears). Alert on confirmed signals (Ref(Cross(…), −1), ExRem), URL-encode spaces, close internet handles, keep the bot token as a placeholder, and toggle each channel with ParamList.

Check yourself 2 questions
  1. Why store the last alerted bar in a static variable?

    Show answer

    To avoid sending the same alert repeatedly.

  2. What keeps the formula re-running live?

    Show answer

    RequestTimedRefresh.

Takeaway AlertIf logs and sounds alerts; static variables stop duplicate Telegram messages for the same bar.

Automating orders through OpenAlgo#

apikey = ParamStr("OpenAlgo API key", "PLACEHOLDER");
host   = ParamStr("Host", "http://127.0.0.1:5000");
algoOn = ParamList("Algo mode", "Disable|Enable", 0) == "Enable";   // off by default

function PlaceOrder(action, qty)
{
    body = "{\"apikey\":\"" + apikey + "\",\"strategy\":\"afl-ema\",\"symbol\":\"" + Name() +
           "\",\"action\":\"" + action + "\",\"exchange\":\"NSE\",\"pricetype\":\"MARKET\"," +
           "\"product\":\"MIS\",\"quantity\":\"" + NumToStr(qty, 1.0, False) + "\"}";
    InternetSetHeaders("Content-Type: application/json\r\n");
    ih = InternetPostRequest(host + "/api/v1/placeorder", body);
    if (ih) { while ((s = InternetReadString(ih)) != "") _TRACE(s); InternetClose(ih); }
}

if (algoOn AND LastValue(Buy) AND StaticVarGetText(key + "ordBar") != bar)
{
    StaticVarSetText(key + "ordBar", bar);     // one order per bar
    PlaceOrder("BUY", 1);
}
  • OpenAlgo runs locally and exposes one order API for any connected broker; AFL just posts JSON to it (placeorder; a closeposition endpoint backs a "close all" button; the course's SmartOrder chart module moves to a target position).
  • Three safety layers: OpenAlgo's analyzer mode on, an algo switch defaulting to Disable, and once-per-bar de-duplication. Prove the connection with chart buttons before automating signals, read every _TRACE response, and use different strategy names for sandbox and live.
  • Never paste a real API key into shared code. Go live with the smallest quantity and remove safety layers one at a time, only after each earns trust.
Check yourself 2 questions
  1. Why default algo mode to Disable?

    Show answer

    So orders are never sent by accident.

  2. Where does the AFL send orders?

    Show answer

    To the OpenAlgo host's API (e.g. 127.0.0.1:5000).

Takeaway AFL posts JSON orders to OpenAlgo's API, with algo mode off by default and the key as a parameter.

Where to go next#

  • Portfolio backtests: test a whole universe, rank candidates, allocate capital.
  • Custom backtester (CBT): custom sizing, exit priorities, portfolio rules.
  • Walk-forward analysis: optimise on one slice, test the next unseen slice, roll on.
  • Advanced GFX dashboards and exporting data for ML.
  • Pick by bottleneck: can't choose between candidates → portfolio backtests; fear the result is luck → walk-forward.
  • Habits: version-control .afl files, keep a strategy journal (idea, rules, numbers, why it should work), sandbox before every live run. "Never run untested code with real money."
Check yourself 2 questions
  1. What does the custom backtester (CBT) allow?

    Show answer

    Custom sizing, exit priorities and portfolio rules.

  2. What is walk-forward analysis?

    Show answer

    Optimise on one slice, test on the next unseen slice, and roll on.

Takeaway Portfolio backtests, the custom backtester, walk-forward analysis and GFX dashboards are the next steps.

08Checklists and quick reference

A skeleton to start every system from.

AFL system skeleton#

_SECTION_BEGIN("System");
SetOption("InitialEquity", 1000000);
SetOption("CommissionMode", 2);  SetOption("CommissionAmount", 20);
SetPositionSize(100, spsShares);                 // fixed size first
SetTradeDelays(0, 0, 0, 0);

fastLen = Optimize("Fast", 10, 5, 30, 1);
slowLen = Optimize("Slow", 20, 10, 100, 5);
Fast = EMA(Close, fastLen);  Slow = EMA(Close, slowLen);

Buy  = Ref(Cross(Fast, Slow), -1);  Sell = Ref(Cross(Slow, Fast), -1);
Buy  = ExRem(Buy, Sell);            Sell = ExRem(Sell, Buy);
BuyPrice = ValueWhen(Buy, Open);    SellPrice = ValueWhen(Sell, Open);
ApplyStop(stopTypeLoss, stopModePercent, 2, True);

Plot(C, "Close", colorDefault, styleNoTitle | GetPriceStyle());
Plot(Fast, "Fast", colorAqua);  Plot(Slow, "Slow", colorOrange);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone), colorGreen, 0, Low, -20);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0, High, -20);
_SECTION_END();
Check yourself 2 questions
  1. Why start with fixed size in the skeleton?

    Show answer

    To judge the signal before adding sizing complexity.

  2. What are the trade delays set to, and why?

    Show answer

    0, 0, 0, 0, because signals are already delayed with Ref(−1).

Takeaway Options, fixed size, zero trade delays, Optimize parameters, delayed and cleaned signals, realistic prices, then plots.

Pre-live checklist#

  1. Signals use only closed bars: Ref(…, −1), no positive Ref, channels shifted a bar.
  2. ExRem pair applied; exactly one delay mechanism.
  3. Equity, commission, size and margin set in code.
  4. Enough trades, CAR/MDD and expectancy checked against buy-and-hold.
  5. Parameters from a plateau, confirmed out of sample.
  6. Intraday: entry window and square-off time coded.
  7. Alerts and orders fire once per bar; API keys are placeholders.
  8. Analyzer mode run clean for weeks; then the smallest live size.
Check yourself 2 questions
  1. Name two signal hygiene checks.

    Show answer

    Any two of: Ref(…, −1), no positive Ref, channels shifted a bar, an ExRem pair, exactly one delay mechanism.

  2. Where should parameters come from?

    Show answer

    A plateau, confirmed out of sample.

Takeaway Closed-bar signals, ExRem pair, one delay mechanism, costs in code, enough trades, plateau parameters, sandbox first.

About this sheet#

This sheet condenses the free course AmiBroker AFL from OpenAlgo Open Varsity (36 chapters, 8 modules) into reference cards in our own words. Code snippets are short illustrative AFL in the course's style, not copies of its listings; confirm function details in the official AmiBroker guide. Each section links back to its chapters. Educational, not investment advice.

No cards match. Try fewer or different words, or press Esc to clear.