Backtesting RealTest RealTest Code RealTest Syntax Reference Hub Systematic Trading

RealTest Code and Syntax Complete Reference Hub (58 Validated Guides)

Summary

Bookmark this complete RealTest 2.0 code and syntax hub organizing all 58 SetupAlpha validated guides across core syntax, strategy blueprints, portfolio engineering, breadth, fixed income, data feeds, IBKR automation, and migrations, plus our top 15 verified anti-hallucination fixes.

· 10 min read
RealTest 2.0 four-pane master reference workspace displaying multi-strategy equity curves, active script editor, custom correlation results table, and trade list
Key findings
  • Every one of the 58 linked RealTest guides in this hub has been parsed and executed live inside RealTest 2.0 with Exit Code 0 on real historical S&P 500, Russell 2000, ETF, bond, futures, or crypto datasets.
  • Fifteen recurring syntax hallucinations account for nearly all failed AI-generated RealTest scripts, including InfoDelist = 0 instead of 99991231, SaveResultsAs instead of SaveTestListAs, #PctRank instead of #PercentRank, 3-arg AEMA instead of 2-arg AEMA(expr, factor), and inline #Avg/#Sum expressions.
  • Always add Allocation S.Equity inside shared Templates when comparing strategies side by side, and reserve MinFreeCash for Combined account-level cash floors rather than individual sleeves inside mixed-margin scripts.
  • Individual US stock backtests require survivorship-free point-in-time Norgate Data (InSPX, InNDX, InRUI, InRUT) because excluding delisted companies via InfoDelist = 99991231 nearly triples apparent dip-buying net profit over 18 years.
  • Live Interactive Brokers execution aligns cleanly with RealTest when matching NextOpen to OpenSlip, NextClose to CloseSlip, pairing EntryStop with EntryLimit for gap-capped breakouts, keeping MarkToMarket True, and decoding CLI exit codes 0 through 8.
  • All 58 guides organize cleanly into six tracks covering core syntax, strategy blueprints, portfolio engineering, breadth and robustness, data feeds, live IBKR/CLI automation, and platform migrations.

This master directory indexes all 58 RealTest 2.0 code, syntax, portfolio engineering, breadth, fixed income, data, execution, and migration guides published by SetupAlpha. Every script across these 58 technical manuals was built strictly from official documentation and clean public textbook logic, parsed and executed live inside RealTest 2.0 with Exit Code 0, and audited against real historical S&P 500, Russell 2000, ETF, bond, futures, and crypto datasets.

Use the top-15 anti-hallucination reference table right below to eliminate the most common RealTest syntax bugs immediately, consult the official RealTest User Guide for full keyword specs, and jump straight to any topic across the six categorized directories below.

Top 15 Verified RealTest 2.0 Syntax Gotchas (AI-Hallucination Checklist)

General-purpose chatbots frequently invent nonexistent keywords from AmiBroker, Pine Script, or EasyLanguage when writing RealTest scripts. Every single trap below was caught and verified directly against the RealTest 2.0 parser.

Common Bug or AI Hallucination What Fails in RealTest 2.0 Verified Working RealTest 2.0 Syntax
InfoDelist = 0 or IsNan(InfoDelist) Silently returns 0 trades on Norgate stocks InfoDelist = 99991231 (active stocks use Dec 31, 9999 sentinel!)
SaveResultsAs: results.csv Exit Code 5 (unrecognized setting name) SaveTestListAs: results.csv (plus SaveStatsAs, SaveTradesAs)
DayOfMonth <= 5 Parse error (function does not exist) Day <= 5 (and DayOfWeek has Monday = 1 through Friday = 5)
Floor(S.Alloc / C) Parse error (no Floor function) QtyRound: 1 for whole shares/contracts or QtyRound: 0 for fractional
EventList: events.csv Parse error in Import section EventListFile: events.csv queried via Event(1) and Event(1, 1)
Omitting Allocation: S.Equity in A/B tests Cross-contaminates sizing via Combined(S.Equity) Add Allocation: S.Equity inside shared Template for isolated comparisons
MinFreeCash inside one sleeve of margin test Reads Combined S.Cash and starves cash sleeve Use MaxInvested: 0.85 * S.Equity per sleeve; put MinFreeCash in Combined
InfoFloat < 20000000 in multi-year backtest Severe lookahead (current float applied to past) Import dated float snapshots via EventListFile and read Event(2, 1)
HHV(H - 3 * atr, 20) trailing stop Uses highs from BEFORE trade entry IF(BarsHeld >= 1, HHV(H - 3 * atr, BarsHeld + 1), 0)
ExitTime: ThisClose on close-based rule Same-bar close lookahead (misses 15:50 ET MOC) EntryTime: NextOpen or NextClose paired with OpenSlip / CloseSlip
MaxEntries: 2 in default Top-Down mode LegacyMode-only directive (incompatible with Top-Down) MaxNewPos: 2 + SetupSkip (frees rejected slot to next rank)
MaxPctVol: 2 for small-cap volume cap AmiBroker hallucination (unrecognized keyword!) QtyType: Shares + Quantity: Min((S.Alloc / numPos) / C, 0.02 * Avg(V, 20))
AEMA(C, 20, kaufER) for adaptive KAMA Exit Code 5 (wrong number of arguments!) AEMA(expr, factor) takes strictly 2 args (compute kaufSC first)
#PctRank rsRaw for IBD RS Rating Parse error (function does not exist) rsRating: #PercentRank rsRaw on its own standalone Data line
100 * #Avg ... or #Sum inside Quantity Exit Code 5 (cross-sectional operator scope!) Put #Avg / #Sum at the start of a standalone Data line first

Minimal Production-Grade RealTest 2.0 Script Skeleton

Start every new strategy from this verified RealTest 2.0 skeleton so point-in-time filtering, realistic commissions, slippage, entry-anchored stops, and clean CSV exports are wired from bar one.

Settings:
	DataFile:	C:\RealTest\Data\SPY_Tickers.rtd
	StartDate:	2015-01-01
	EndDate:	2024-12-31
	AccountSize:	100000
	BarSize:	Daily
	CashIntPct:	3.5
	MarginIntPct:	6.5
	SaveStatsAs:	C:\RealTest\Output\daily_stats.csv
	SaveTestListAs:	C:\RealTest\Output\summary_results.csv

Data:
	ma200:	Avg(C, 200)
	rsi2:	RSI(2)
	atr14:	ATR(14)
	spyUp:	Extern($SPY, C > Avg(C, 200))
	liquid:	C > 10 and Avg(C * V, 20) > 25000000

Strategy: clean_spx_template
	Side:	Long
	Allocation:	S.Equity
	EntrySetup:	InSPX and liquid and spyUp and C > ma200 and rsi2 < 10
	EntryLimit:	C - 0.35 * atr14
	EntryTime:	Intraday
	LimitExtra:	0.001 * C
	SetupScore:	100 - rsi2
	QtyType:	Percent
	Quantity:	10
	MaxPositions:	10
	MaxExposure:	100
	Commission:	Max(1, Shares * 0.005)
	OpenSlip:	0.0005 * FillPrice
	ExitStop:	IF(BarsHeld >= 1, FillPrice - 3 * atr14[BarsHeld], 0)
	ExitRule:	C > H[1] or BarsHeld >= 7
	ExitTime:	NextOpen
	Ambiguity:	Stop

Core RealTest Syntax and Execution Rules (11 Guides)

RealTest 2.0 Code Guide Verified Syntax and Empirical Scope
Trailing Stops and ExitStop Syntax Entry-anchored BarsHeld trailing stops, ATR stops, and Ambiguity Stop protection
Profit Targets (ExitLimit), Breakeven Stops, and Time Stops Entry-anchored ExitLimit targets, breakeven stop movers, BarsHeld timing, and Ambiguity Stop
ATR and Volatility Position Sizing QtyType Percent vs Value, volatility-parity share sizing, and risk caps
Combining Multiple Strategies in One Script Template inheritance, shared cash pools, Combined section, and multi-sleeve setup
Cross-Sectional Ranking with SetupScore and #Rank Ranking ties, top-N monthly rotation, and NaN filtering before #Rank
Extern() Market Regime and Breadth Filters Referencing $SPY, #Avg breadth, and avoiding lookahead across symbols
EntryLimit, Fill Timing, Slippage, and Lookahead Bias NextOpen vs Intraday vs ThisClose, LimitExtra realism, and zero-lookahead audits
Debugging Zero Trades and Common Parse Errors Systematic troubleshooting checklist for silent 0-trade scripts and syntax errors
Orders Mode, OrderClerk, and IBKR Syntax Generating daily live broker orders via realtest.exe -orders cleanly
MaxNewPos, SetupSkip, and Top-Down Order Priority Why MaxEntries only works in LegacyMode, MaxNewPos pacing, and SetupSkip slot recycling
EntryStop, Stop-Limit Breakouts, and Gap Fills Native EntryStop plus EntryLimit gap caps, StopSlip vs LimitSlip, and NextOpen vs intraday stops

Complete Validated Strategy Blueprints and Book Systems (16 Guides)

RealTest 2.0 Code Guide Verified Syntax and Empirical Scope
S&P 500 Mean Reversion with RSI(2) and IBS Survivorship-free InSPX dip-buying rules with catastrophe stops
Bollinger Bands (BBBot), Keltner (KBBot), and Z-Score MR Native one-pass volatility envelopes and statistical Z-Score stretch mean reversion
Dual Momentum ETF Rotation Code Relative plus absolute momentum rotation with cash shield
Fixed-Income Bond Rotation and Credit-Spread Switching 20-year bond dual momentum plus High-Yield vs Treasury risk-on ratio
Ray Dalio All-Weather, 60/40, and Drift-Band Rebalancing One-line +/- 5% drift bands cutting rebalance turnover by 96%
Donchian Turtle Breakout and Pyramiding MaxSameSym scaling-in, ATR unit sizing, and breakout exits
Parabolic Short Selling and Borrow Fees Side Short syntax, FeesInOut borrow drag, and squeeze stop limits
Long-Short Equity Portfolios and MaxNetExp Hedging Unified Long plus Short scripts bounded by Combined MaxNetExp and MinNetExp
Weekly Trend Following (Clenow and Nick Radge) BarSize Weekly momentum, R-squared slope ranking, and stepped MAs
Multi-Timeframe Weekly Strategies Inside BarSize Daily EndOfWeek plus HolidayList us_auto weekly entries paired with daily ATR ExitStops
IBD Relative Strength (#PercentRank) and Minervini Stage 2 Native 1-99 RS Rating via #PercentRank and 8-point Stage 2 Trend Template
VIX Regime Position Sizing and Hedging Scaling exposure dynamically via $$VIX and volatility regimes
Intraday 5-Minute ORB and VWAP CSV Code Importing 5-minute intraday bars and coding Opening Range Breakouts
Volatility Targeting, Risk Parity, and VAA/DAA Inverse-volatility #Sum weighting inside DynamicSizing and canary assets
Bensdorp, Connors Double 7s, and Radge Book Systems Pure public textbook sleeves with Template inheritance and Allocation S.Equity
Gold/SPY/TLT Rotation and Synthetic 3x TQQQ Modeling Defensive gold rotation plus daily-resetting 3x ETF proxy with expense drag

Portfolio Architecture, Breadth, Indicators, and Robustness (14 Guides)

RealTest 2.0 Code Guide Verified Syntax and Empirical Scope
Sector and Industry Exposure Caps (InfoTRBC / GICS) Top(InfoTRBC, 2), MaxSameCat, MaxCatExp, and #ByEcon sector ranking
Native Market Breadth, McClellan Oscillator, and 52-Week NH-NL Zero-feed cross-sectional #Avg and #Sum breadth gating on historical InSPX
Equity Curve Trading with StratData Shadow strategy pattern so paused systems still track recovery cleanly
Walk-Forward Optimization and Monte Carlo OptimizeSettings, OptWalkForward, SkipTestIf, and random() permutation tests
Out-of-Sample Robustness, Plateaus, and Random EntrySkip Visualizing parameter plateaus and 20% random EntrySkip anti-overfitting stress tests
Custom Results Metrics and Benchmarks Custom CAGR, Sortino, Ulcer Index, equal-weight #Avg index, and Benchmark section
Partial Exits and Scaling Out (ExitQty vs FillQty) Selling half at 1R with FillQty / 2, ExitNum latch, and trailing stops
Scaling In, Averaging Down, and Pyramiding (MaxSameSym) MaxSameSym 3, MaxSymExp 15, Shares > 0 ATR lot spacing, and single-lot benchmarks
Margin, Reg-T, Portfolio Margin, MaxInvested, and MinFreeCash Modeling 85% cash reserve vs 150% Reg-T vs 200% PM with MarginIntPct
StatsGroup, Capital Pooling, and Correlation Matrix Group MaxExposure caps plus live Correl(Extern(@a, S.NetPct), ...) matrix
Modular Include/Library Architecture and Tax Drag Simulation Reusable Library modules plus 0.10% FTT and 30% annual capital gains tax proof
Scan, TestScan, and Daily Watchlist Exports Live holdings via Extern(@strat, Shares <> 0), ScanSettings, and SaveScanAs
SuperTrend, MACD, VCP, and R-Squared Formulas Native indicator syntax, volatility contraction scans, and squeeze triggers
Wilder ADX, PDI/MDI, Kaufman ER, and Adaptive AEMA (KAMA) 2-argument AEMA(expr, factor) KAMA plus Low-ADX vs High-ADX empirical proof

Data Engineering, Liquidity, Survivorship Bias, Events, Futures, and Crypto (7 Guides)

RealTest 2.0 Code Guide Verified Syntax and Empirical Scope
CSV Import, Fundamentals, and TradeList Playback CSVFields Extra columns, SymInfoFile, InList, and TLFields Shares rule
Dividends, Splits, Multi-Currency FX, and CashInOut TotalReturn vs Capital adjustments, SymChangeList, NetFX, and S.TWEQ
Futures PointValue, Margin, and CSI Rollovers SymInfoFile PointValue, FuturesMargin InfoMargin, RollCost, and QtyRound 1
24/7 Crypto Backtesting and Fractional Shares QtyRound 0, SymRef('BTC-USD'), CalendarSym BTC-USD, and Padding None
EventListFile, Earnings Skipping, and InfoFloat Traps Import EventListFile, Event(1) cooldowns, Event(1, 1), and static float warnings
Norgate Survivorship Bias Proof (InSPX and InfoDelist) 18-year empirical proof plus the critical InfoDelist = 99991231 discovery
Small-Cap and Russell 2000 Liquidity, Volume Caps, and Slippage InRUT 25 bps slippage proof, Avg(C * V, 20), 2% ADV cap, and IBKR Error 201 fixes

IBKR Live Execution, CLI Automation, Speed, and Calendar Edges (5 Guides)

RealTest 2.0 Code Guide Verified Syntax and Empirical Scope
Task Scheduler Batch Automation and IBKR Drift Automated -import to -orders scripts, HolidayList us_auto, and IBKR Error 201
IBKR MOC, CloseSlip, OpenSlip, and MarkToMarket False 15:50 ET MOC cutoffs, auction slippage calibration, and live NLV sync
CLI Batch, Python Subprocess, Exit Code 6, and SaveStatsAs Exit codes 0 to 8, SaveTestListAs vs SaveResultsAs, and -api HTTP server
Mac Parallels, VPS, Memory, and Speed Tuning Keeping .rtd files lean, RAM limits, and sub-second S&P 500 runtimes
Overnight Gaps, Turnaround Tuesday, and Calendar Edges DayOfWeek (Monday = 1), Day (never DayOfMonth), and backward-only Month checks

Platform Migrations and AI Coding Workflows (5 Guides)

RealTest 2.0 Code Guide Verified Syntax and Empirical Scope
AmiBroker AFL to RealTest Translation Guide Side-by-side mapping of Foreign, PositionScore, ExRem, and SetOption
Using ChatGPT and Claude to Write Valid RealTest Code Eliminating LLM syntax hallucinations with verified RealTest validation loops
TradingView Pine Script to RealTest Migration Moving from single-chart ta.* calls to true multi-stock portfolio backtesting
Python, Pandas, and Backtrader to RealTest Guide Replacing slow Python loops with declarative millisecond portfolio code
TradeStation EasyLanguage to RealTest Conversion Translating Next Bar Stop/Limit, MarketPosition, and BarsSinceEntry cleanly

Turn Validated RealTest Knowledge into Live Systematic Portfolios

Ready to apply these validated building blocks immediately on your own machine? Start free with our Free RealTest Codes & Sample Strategies collection, or compare performance metrics across every production system on our RealTest Strategy Backtest Comparison page.

When you are ready to deploy complete, low-drawdown multi-strategy portfolios or automate daily trading end to end, explore our RealTest Portfolios collection, test custom combinations in our RealTest Strategy Combiner & Portfolio Builder, wire hands-free IBKR execution through our RealTest, OrderClerk, and IBKR Course, accelerate strategy engineering with our Build RealTest Strategies with Claude Code AI Course, or commission custom code via our RealTest Strategy Coding Service.

Key terms

RealTest Declarative Script
A structured plain-text .rts file divided into Import, Settings, Parameters, Data, Template, Strategy, StatsGroup, Combined, and Results sections executed natively in C++.
RealTest Anti-Hallucination Audit
The discipline of parsing and executing every RealTest script against realtest.exe with Exit Code 0 while checking for lookahead bias, survivorship bias, and exact keyword spelling.
Multi-Strategy Portfolio Script
A single RealTest file combining uncorrelated strategies (trend, mean reversion, defensive gold/bonds) over one shared capital pool with StatsGroup exposure limits.
Point-in-Time Backtesting
Historical simulation restricted strictly to securities, index memberships, and event values publicly known on each historical bar date.
RealTest 2.0 Automation Stack
Combining RealTest's CLI (-import, -test, -orders), CSV exports (SaveStatsAs, SaveTestListAs), OrderClerk IBKR routing, and local -api workflows.

Frequently asked questions

Where should a beginner start inside this 58-guide RealTest reference hub?

Start with the Core Syntax track (specifically trailing stops, ExitLimit profit targets, ATR position sizing, fill timing and lookahead prevention, MaxNewPos order priority, and debugging zero-trade scripts), then run one complete Strategy Blueprint such as S&P 500 RSI(2) mean reversion or dual-momentum ETF rotation.

Why do ChatGPT and Claude often generate RealTest code that fails with Exit Code 5?

General LLMs mix AmiBroker, Pine Script, and EasyLanguage keywords into RealTest scripts, inventing nonexistent directives like SaveResultsAs, DayOfMonth, Floor(), MaxPctVol, #PctRank, or 3-argument AEMA. Using our verified RealTest 2.0 checklist and running realtest.exe -parse eliminates syntax hallucinations immediately.

Are the RealTest scripts in these 58 guides tested in RealTest 2.0?

Yes. Every script published across all 58 SetupAlpha technical guides was compiled and backtested directly inside RealTest 2.0 with realistic commissions, slippage, and zero-lookahead fills, and accompanied by genuine RealTest screenshots and reported numbers.

Which guides cover connecting RealTest to Interactive Brokers and OrderClerk?

Read the three execution guides in Group 1 and Group 5 covering Orders mode syntax, IBKR MOC and CloseSlip timing with MarkToMarket rules, and fully automated Windows Task Scheduler batch scripts plus CLI exit code 0 through 8 diagnostics.

Which data provider is recommended for testing the stock strategies in this hub?

Use Norgate Data Platinum (for historical S&P 500 InSPX and Nasdaq-100 InNDX constituency plus delisted stocks) or Diamond (for Russell 1000 and 2000). Free Yahoo Finance works well for major ETFs like SPY, QQQ, GLD, and TLT, but lacks delisted equity history.

Can I migrate existing AmiBroker, TradingView, Python, or TradeStation strategies into RealTest?

Yes. Group 6 provides dedicated side-by-side syntax translation tables and validated RealTest 2.0 scripts for converting AmiBroker AFL, TradingView Pine Script, Python Pandas/Backtrader, and TradeStation EasyLanguage systems cleanly.

Related strategies

Free Mean-Reversion Strategy for RealTest & Python
Start immediately with our free open-source mean-reversion code validated for both RealTest 2.0 and Python.
View →
All-Weather Low-Drawdown Portfolio
Turnkey multi-strategy RealTest portfolio engineered around uncorrelated sleeves and strict drawdown control.
View →
Build RealTest Strategies with Claude Code AI
Learn our exact Claude Code AI workflow for writing, testing, and validating error-free RealTest strategies rapidly.
View →
← Back to Learn

#1 RealTest Backtests

Supercharge Your Trading Now

Reduce drawdown, build diversification, or speed up your development time.

Browse RealTest Strategies