AmiBroker AFL to RealTest Syntax Translation Guide (Validated Code Migration)
Converting AmiBroker AFL to RealTest replaces imperative Buy/Sell arrays and CBT loops with declarative sections (Data, Library, Strategy). Translate Ref(C, -1) to C[1], IIf() to IF(), Foreign() to Extern($SYM, ...), PositionScore to SetupScore, ApplyStop() to price-based ExitStop, and AddToComposite() to standalone #Avg or #Sum breadth lines, while dropping ExRem() and SetTradeDelays(1,1,1,1) because RealTest handles both natively.
- RealTest eliminates AmiBroker's Custom Backtester (CBT) boilerplate for multi-strategy portfolios, dynamic allocation, and cross-strategy exposure caps by providing native Template, StatsGroup, StrategyScore, and Combined sections.
- Standard AmiBroker signal mechanics map one-to-one into RealTest, turning Ref(C, -1) into C[1], IIf() into IF(), Foreign("SPY", "C") into Extern($SPY, C), PositionScore into SetupScore, and SetOption("MaxOpenPositions", 10) into MaxPositions 10.
- You do not need ExRem(Buy, Sell) or SetTradeDelays(1, 1, 1, 1) in RealTest because MaxSameSym defaults to 1 per strategy and RealTest evaluates signals on the prior bar automatically before entering at NextOpen or Intraday.
- AmiBroker's ApplyStop(stopTypeLoss, stopModePercent, 8) must be converted into an explicit per-share price inside ExitStop (such as FillPrice * 0.92 placed in Library or Strategy, never in Data).
- RealTest can import an AmiBroker exported TradeList CSV directly using TradeList, TLDateFmt, and TLEndDate so you can reconcile equity curves and individual trade fills bar for bar during migration.
- Validated in RealTest 2.0 on Norgate historical S&P 500 data from 2010 through 2024, our ported AFL mean-reversion script executed 2,555 trades cleanly across active and delisted constituents such as MRO-202411.
Across 272 dedicated threads on the RealTest user forum, AmiBroker is the single most common platform systematic traders migrate from. The motivation is rarely speed alone. Traders usually move after spending weeks maintaining brittle Custom Backtester (CBT) loops in AFL just to combine three strategies, cap shared portfolio exposure, or generate daily Interactive Brokers orders.
The fastest way to break a migration is translating AFL line by line without respecting RealTest's declarative structure. Every syntax mapping and TradeList import rule below follows the official RealTest AmiBroker migration documentation, and the complete side-by-side ported script was parsed and executed in RealTest 2.0 on 15 years of historical Norgate S&P 500 data.
Complete AmiBroker AFL to RealTest 2.0 Syntax Translation Table
Keep this reference open beside your .afl file when rewriting portfolio strategies into .rts format.
| Trading Concept | AmiBroker AFL | Validated RealTest 2.0 | Critical Migration Difference |
|---|---|---|---|
| Prior bar reference | Ref(C, -1) |
C[1] |
Positive integer looks backward in RealTest; never use negative offsets |
| Conditional branch | IIf(cond, a, b) |
IF(cond, a, b) or Select(...)
|
Select(c1, v1, c2, v2, 1, def) replaces nested IIf chains cleanly |
| Moving average | MA(C, 200) |
Avg(C, 200) or MA(C, 200)
|
Both work in RealTest; EMA(C, 20) is also built in |
| 2-period RSI | RSI(2) |
RSI(2) |
One argument only (never RSI(C, 2)) |
| Benchmark symbol check | Foreign("SPY", "C") > MA(Foreign("SPY", "C"), 200) |
Extern($SPY, C > Avg(C, 200)) |
Use single $SPY for ETFs and double $$SPX for Norgate indices |
| Higher timeframe |
TimeFrameSet(inWeekly) / TimeFrameExpand()
|
Extern(~Weekly, expr) or BarSize: Weekly
|
RealTest evaluates completed weekly bars automatically with zero expand flags |
| Position priority ranking | PositionScore = 100 - RSI(2); |
SetupScore: 100 - rsi2 |
Highest score enters first; omit Legacy Mode EntryScore
|
| Position sizing | SetPositionSize(10, spsPercentOfEquity); |
Quantity: 10 + QtyType: Percent
|
Defaults to Shares if QtyType is omitted; sizes off S.Alloc
|
| Max concurrent holdings | SetOption("MaxOpenPositions", 10); |
MaxPositions: 10 |
Never write 100 / MaxPositions; divide by a Parameters item instead |
| Next-bar execution delay | SetTradeDelays(1, 1, 1, 1); |
Automatic default (EntryTime: NextOpen) |
Do NOT add [1] shifts manually on top of RealTest's default prior-bar evaluation |
| Remove duplicate signals | Buy = ExRem(Buy, Sell); |
Not needed (MaxSameSym: 1 default) |
RealTest never pyramids into an open symbol unless you raise MaxSameSym
|
| Stop loss / trailing stop | ApplyStop(stopTypeLoss, stopModePercent, 8, 1); |
ExitStop: FillPrice * 0.92 |
Must return a numeric price per share inside Library or Strategy
|
| Universe membership |
InWatchListName("S&P 500") / Norgate NorgateIndexConstituentTimeSeries()
|
InSPX, InNDX, InRUI, or InList("Name")
|
Built directly into RealTest when importing Norgate Current & Past watchlists |
| Cross-sectional breadth |
AddToComposite(...) + second scan pass |
#Avg, #Sum, #Count, #Rank
|
Single-pass standalone Data line; use IF(InSPX, x, NaN) to filter universe |
| Multi-strategy combining | Custom Backtester (SetCustomBacktestProc) |
Multiple Strategy blocks + StatsGroup + Combined
|
Zero low-level procedural loop required |
Four Execution Differences That Cause AFL vs RealTest Mismatches
Even when indicators match to the fourth decimal place, four structural differences between AmiBroker and RealTest frequently explain why a ported backtest initially shows slightly different trade counts.
1. Double-delaying signals. In AmiBroker, many scripts manually reference Ref(Buy, -1) or use SetTradeDelays(1, 1, 1, 1). RealTest evaluates EntrySetup, EntryLimit, ExitRule, and ExitStop on the bar prior to entry/exit automatically. Carrying an extra [1] shift over from AFL delays every entry by two full bars.
2. Data vs Library scoping for ApplyStop replacements. In AFL, ApplyStop runs inside the backtest engine alongside your array declarations. In RealTest, precomputed Data arrays run before the test starts and cannot read FillPrice or BarsHeld. Always place stop formulas inside Library or Strategy (covered in depth in our RealTest ExitStop and trailing stop guide).
3. Limit order timing and gap fills. In AFL, limit strategies often check Low < BuyPrice manually on the next bar with SetTradeDelays(0, 0, 0, 0) and Ref(signal, -1) (which can accidentally leak future bar prices if not careful). In RealTest, simply set EntryLimit: C * 0.98 with EntryTime: Intraday and add LimitExtra: 0.001 * C to match realistic order-book fill-through (see our RealTest EntryLimit and slippage guide).
4. NaN handling inside boolean filters. AmiBroker treats missing values (Null and IsNull) differently from RealTest's strict NaN propagation across and and or. Guard any Extern() benchmark with shorter history using IF(IsNaN(x), 1, cond) (detailed in our RealTest Extern and market breadth guide).
Side-by-Side Example (Original AmiBroker AFL vs Validated RealTest 2.0)
Consider a classic AmiBroker S&P 500 two-day pullback mean-reversion strategy with a 2 percent intraday buy limit, 8 percent stop loss, 6-bar max hold, and SPY 200-day trend filter.
// Typical AmiBroker AFL Portfolio Script (Reference Only)
SetOption("InitialEquity", 100000);
SetOption("MaxOpenPositions", 10);
SetPositionSize(10, spsPercentOfEquity);
SetTradeDelays(1, 1, 1, 1);
spyC = Foreign("SPY", "C");
spyTrend = spyC > MA(spyC, 200);
dollarVol = MA(C * V, 20);
downTwo = C < Ref(C, -1) AND Ref(C, -1) < Ref(C, -2);
Buy = NorgateIndexConstituentTimeSeries("$SPX")
AND C > 10 AND dollarVol > 20000000
AND spyTrend AND C > MA(C, 200) AND downTwo AND RSI(2) < 15;
BuyPrice = Ref(C, -1) * 0.98;
PositionScore = 100 - RSI(2);
Sell = C > Ref(H, -1) OR BarsSince(Buy) >= 6;
SellPrice = Open;
ApplyStop(stopTypeLoss, stopModePercent, 8, 1);
Now look at the clean, idiomatic RealTest 2.0 equivalent using Norgate Data historical constituents (InSPX). Every AFL quirk disappears into crisp declarative blocks with realistic IBKR commissions, LimitExtra fill-through, and day-1 BarsHeld >= 1 order consistency.
Notes:
Idiomatic RealTest port of a classic AmiBroker AFL portfolio
mean-reversion system (Ref -> [1], Foreign -> Extern, PositionScore
-> SetupScore, ApplyStop -> ExitStop, SetOption -> MaxPositions).
Import:
DataSource: Norgate
IncludeList: .S&P 500 Current & Past
IncludeList: SPY
StartDate: 2005-01-01
EndDate: Latest
SaveAs: spx_afl_port.rtd
Settings:
DataFile: spx_afl_port.rtd
StartDate: 2010-01-01
EndDate: 2024-12-31
AccountSize: 100000
BarSize: Daily
Parameters:
numPos: 10
rsiMax: 15
maxHold: 6
Data:
// AmiBroker Ref(C, -1) -> C[1]; Foreign("SPY","C") -> Extern($SPY, C)
atr14: ATR(14)
rsi2: RSI(2)
ma200: Avg(C, 200)
spyTrend: Extern($SPY, C > Avg(C, 200))
dollarVol: Avg(C * V, 20)
downTwo: C < C[1] and C[1] < C[2]
buySignal: InSPX and C > 10 and dollarVol > 20000000 and spyTrend and C > ma200 and downTwo and rsi2 < rsiMax
Library:
// Replaces AmiBroker ApplyStop(stopTypeLoss, stopModePercent, 8)
stopPx: FillPrice * 0.92
Strategy: afl_port_mean_reversion
Side: Long
EntrySetup: buySignal
EntryLimit: C * 0.98
EntryTime: Intraday
SetupScore: 100 - rsi2
Quantity: 100 / numPos
QtyType: Percent
MaxPositions: numPos
MaxExposure: 100
Commission: Max(1, Shares * 0.005)
LimitExtra: 0.001 * C
OpenSlip: 0.0005 * FillPrice
ExitStop: IF(BarsHeld >= 1, stopPx, 0)
ExitRule: C > H[1] or BarsHeld >= maxHold
ExitTime: NextOpen
Ambiguity: Stop
Charts:
MA200: ma200
Validated in RealTest 2.0 from 2010 through 2024 on historical Norgate S&P 500 data, this ported strategy executed 2,555 trades cleanly (2,360 exit rule, 191 exit stop, and 4 end-of-test exits across 2,296 intraday limit fills and 259 opening gap fills), winning 59.10 percent of trades with 27.55 percent average exposure and handling delisted constituents like MRO-202411 cleanly alongside active stocks like LLY and AMZN.

Reconciling Your AmiBroker Backtest Inside RealTest via TradeList Playback
RealTest includes native TradeList playback specifically designed to audit migrations from AmiBroker or combine legacy AmiBroker strategies with new RealTest systems in a single portfolio. Export your AmiBroker backtest trade list as CSV, point a RealTest strategy at it with TradeList, and specify your date string format with TLDateFmt if AmiBroker exports non-US date strings.
Strategy: amibroker_csv_audit
TradeList: C:\RealTest\Imports\amibroker_trades.csv
TLDateFmt: DMY
// Optional cutoff if hybridizing with RealTest formula trades after migration date
TLEndDate: 2024-12-31
Commission: Max(1, Shares * 0.005)
Running your exported AmiBroker TradeList alongside your new native RealTest strategy in one script lets you overlay both equity curves in a single RealTest Stats Graph and verify every single trade difference before retiring AmiBroker. Once verified, you can even stack multiple ported strategies under one portfolio using our RealTest multi-strategy combining guide or connect directly to Interactive Brokers using our RealTest OrderSettings and OrderClerk guide.
Migrating Your AmiBroker Library to RealTest Faster
Most AmiBroker traders discover that a 180-line AFL + CBT file shrinks to 55 clean lines of declarative RealTest code once the syntax differences click. To inspect idiomatic RealTest templates right away, download our free RealTest strategy and code library or grab the Free Mean-Reversion Strategy for RealTest and Python.
If you want complete, production-tested multi-strategy RealTest systems to study idiomatic architecture across complementary market styles, browse the RealTest Portfolios collection. If you use AI assistants to convert legacy AFL scripts, read our guide to writing valid RealTest code with ChatGPT and Claude or see the Build RealTest Strategies with Claude Code AI course. And if you want your existing AmiBroker systems converted and trade-by-trade verified without burning weekends on syntax quirks, our RealTest Strategy Development service handles full AFL-to-RealTest migrations.
Migrating strategies from TradingView or Python instead of AmiBroker? Use our TradingView Pine Script v5 to RealTest translation guide and our Python Pandas and Backtrader to RealTest code guide.
Porting TradeStation EasyLanguage scripts alongside AmiBroker? Check our TradeStation EasyLanguage to RealTest conversion guide.
Key terms
- SetupScore
- RealTest's equivalent of AmiBroker PositionScore, ranking competing qualifying setups highest-first whenever setups exceed MaxPositions or MaxExposure.
- TradeList Playback
- A RealTest Strategy mode that replays historical trades from an external CSV file (such as an AmiBroker export) inside RealTest's portfolio analytics and Combined engine.
- TLDateFmt
- A RealTest Strategy element defining the date column order (such as DMY or MDY) when importing external AmiBroker or broker CSV trade lists.
- Declarative Strategy Sections
- RealTest's structured script layout (Import, Settings, Parameters, Data, Library, Strategy, StatsGroup, Combined) replacing procedural AFL loops and Custom Backtester code.
- InSPX
- RealTest's built-in Norgate historical S&P 500 membership array, replacing AmiBroker's NorgateIndexConstituentTimeSeries("$SPX") call.
Frequently asked questions
What is the RealTest equivalent of AmiBroker Ref(C, -1)?
Write C[1] in RealTest. Positive bracket offsets look backward in RealTest (C[1] is yesterday's close, C[2] is two bars ago), whereas negative offsets look forward and should never be used in strategy signals.
How do you translate AmiBroker Foreign() to RealTest?
Replace Foreign("SPY", "C") with Extern($SPY, C), or evaluate the entire condition inside Extern($SPY, C > Avg(C, 200)). For Norgate index tickers that start with $, use double dollar signs like Extern($$SPX, C).
Do I need ExRem(Buy, Sell) or SetTradeDelays(1, 1, 1, 1) in RealTest?
No. RealTest automatically prevents duplicate entries in the same symbol via MaxSameSym 1 (default) and evaluates signals on the prior bar automatically before executing at NextOpen or Intraday. Adding extra [1] shifts from AFL delays signals by an unintended extra bar.
How do you convert AmiBroker PositionScore and MaxOpenPositions to RealTest?
Replace PositionScore with SetupScore (highest score enters first in top-down mode) and SetOption("MaxOpenPositions", 10) with MaxPositions 10 inside your Strategy block. For equal-weight sizing, define numPos 10 in Parameters and set Quantity to 100 / numPos with QtyType Percent.
How do you translate AmiBroker ApplyStop to RealTest?
Replace ApplyStop with a price-per-share ExitStop formula inside Library or Strategy (never Data). For an 8 percent long stop loss, write ExitStop as FillPrice * 0.92. For a trailing stop, use HHV(H - 3 * atr14, BarsHeld + 1).
Can RealTest import an AmiBroker backtest trade list for comparison?
Yes. RealTest supports direct CSV playback via the TradeList strategy element (plus TLDateFmt for DMY/MDY formatting and TLEndDate for hybrid cutoffs), allowing you to plot your AmiBroker equity curve directly alongside your newly ported RealTest strategy in one Stats Graph.