Backtesting Debugging RealTest RealTest Code Syntax Errors Systematic Trading

Why Your RealTest Script Takes No Trades (Complete Debugging and Error Reference)

Summary

When a RealTest script parses cleanly yet takes zero trades, the usual culprits are position variables placed in Data instead of Library, an unguarded NaN inside an or/and expression before an ETF launch date, missing Symbol filters, or capacity constraints skipping every setup. Set KeepTrades to All and inspect DebugEntry plus TestData to pinpoint the exact failing bar.

· 9 min read
RealTest 2.0 debugging workbench showing Data, Library, TestData, TestScan script, SPY trade chart with StopLine, and Trade List KeepTrades All skip reasons
Key findings
  • Data section arrays calculate across all symbols before the backtest starts, so placing FillPrice, BarsHeld, or Shares inside Data silently returns 0 or NaN instead of open-position values.
  • RealTest does not short-circuit NaN inside boolean or/and expressions, meaning a single pre-inception ETF reference like Extern($HYG, mom) <= 0 can wipe out every trade prior to that ETF's launch date.
  • Setting KeepTrades to All exposes hidden setup rejections directly in the Trade List Reason column, including max positions, max exposure, max same symbol, and zero quantity.
  • Built-in functions such as RSI(2) accept only one argument (length) rather than RSI(C, 2), and breadth operators like #Avg or #Rank must occupy their own standalone Data line.
  • Command-line RealTest runs write exact line and column diagnostics into batchlog.txt with structured exit codes (0 success, 5 syntax error, 6 import failure, 7 data issue).
  • TestData combined with Extern(@strategy_name, ...) and TestScan lets you export bar-by-bar open position states and stop prices to CSV without modifying your backtest logic.

RealTest runs backtests in fractions of a second, which also means a silent logic bug finishes cleanly with exit code 0 and an empty results row. Traders coming from Python, Pine Script, or AmiBroker routinely stare at zero trades or a cryptic parser message pointing at a line that looks completely valid.

Every error message, exit code, and diagnostic workflow below comes directly from the official RealTest User Guide, the RealTest debugging reference, and real failures reproduced in RealTest 2.0.

Data vs Library vs TestData vs StratData (Where Most Silent Bugs Begin)

The single largest source of broken RealTest scripts is placing a formula in the wrong script section. RealTest evaluates four distinct calculation scopes at different moments in the engine lifecycle, and each scope sees different variables.

Script Section When RealTest Calculates It Sees OHLCV & Breadth Tags Sees FillPrice, BarsHeld & Shares Best Use Case
Data Once per symbol before the backtest starts Yes (#Avg, #Rank, #Sum) No (silently 0 or NaN) Indicators, moving averages, liquidity filters, cross-sectional ranks
Library Inline on demand wherever referenced Yes (no breadth tags) Yes Trailing stops, breakeven levels, shared position-aware formulas
TestData Once per symbol at the end of each test date Yes Yes (via Extern(@strat, ...)) Recording live daily stops or open states for Charts and TestScan
StratData Once per strategy per test date Only via Extern($SYM, ...) Strategy stats (S.Equity, S.DDPct) Custom equity-curve indicators for Results and Graphs

If your script calculates a trailing stop or holding-period rule inside Data, move it to Library immediately. If you want to plot or export that open-position value after the test, wrap it inside TestData using Extern(@your_strategy, ...) because TestData runs per symbol without an implicit strategy context even in a single-strategy script.

The 12 Most Common RealTest Parser and Zero-Trade Errors

Match the exact symptom or error string from RealTest or batchlog.txt against this lookup table before rewriting your strategy logic.

Error Message or Symptom Root Cause in RealTest Validated Fix
wrong number of arguments on RSI(C, 2) Built-in RSI(n) takes one argument and always uses Close. Write RSI(2) instead of RSI(C, 2).
reserved syntax elements cannot be used as item names A Data, Parameters, or Scan name shadows a built-in like atr, rsi, close, open, rank, score, or positions. Rename to neutral identifiers like atrN, rsiVal, numPos, or PriceC.
unrecognized symbol on $SYM or $$SPX Symbol is missing from the .rtd file, or index prefix lacks double $$ ($SPX in IncludeList, $$SPX in Extern). Add the symbol to IncludeList and re-run -import; use $SPY for ETFs and $$SPX for Norgate indices.
unrecognized syntax element on $BTC-USD RealTest parses the hyphen inside a ticker as a subtraction operator. Use SymRef("BTC-USD") or assign a named list like IncludeList: BTC-USD {"Crypto"} and filter with InList("Crypto").
expected an operator here on #Avg or #Rank Breadth tags must start the entire Data line and cannot sit inside parentheses or arithmetic. Compute numUp: #Sum above200 on its own line, then divide in a second Data item.
Zero trades prior to an ETF launch date NaN inside any branch of or or and turns the entire boolean expression into NaN (false). Guard pre-inception series with IF(IsNaN(x), 0, cond) before combining with or.
unrecognized setting name on Slippage or Commission Cost directives belong inside Strategy or Template, never inside Settings. Move Commission and Slippage into your Strategy block.
unrecognized syntax element on Quantity: 100 / MaxPositions MaxPositions is a constraint keyword rather than a numeric variable inside Quantity. Define numPos: 10 in Parameters and write Quantity: 100 / numPos.
Dynamic-sizing strategy cannot specify Side DynamicSizing: True infers direction from the sign of Quantity and disallows Side, EntryTime, and ExitTime. Remove Side and timing directives when using DynamicSizing: True.
Parse error inside Notes section A prose line begins with a section name plus colon (such as Data:) or contains operator characters like arrows. Write plain prose inside Notes without leading section keywords or arrow symbols.
BarNum = 1 benchmark takes 0 trades BarNum counts from the data file's first date rather than the test window's StartDate. Use EntrySetup: Symbol = $SPY with MaxPositions: 1 and no exit rule.
Limit strategy fills 100% at open with tiny exposure Inherited or explicit EntryTime: NextOpen turns EntryLimit into a limit-on-open order rather than an intraday limit. Set EntryTime: Intraday (or omit EntryTime) for intraday limit entries.

If your bug specifically involves stop losses or trailing exits failing to fire, check our dedicated RealTest ExitStop and trailing stop code guide. For sizing and capacity skips, review our RealTest position sizing and ATR risk guide.

Why NaN Poisons Boolean Conditions (And How to Guard It)

In Python or JavaScript, True or NaN short-circuits to True. In RealTest, boolean operators propagate NaN across the whole expression. Suppose you test a multi-asset regime filter starting in 2000 that checks Extern($SPY, C > Avg(C, 200)) or Extern($TLT, ROC(C, 60) > 0). Because TLT launched in July 2002, Extern($TLT, ...) returns NaN on every bar from 2000 through late 2002, forcing the entire or expression to evaluate false and silently wiping out two years of trades.

Data:
	tltMom:	Extern($TLT, ROC(C, 60))
	// Safe pre-inception guard prevents NaN from poisoning boolean filters
	tltSafe:	IF(IsNaN(tltMom), 0, tltMom > -10)
	above200:	C > Avg(C, 200)
	// Breadth operator MUST sit on its own Data line
	mktBreadth:	#Avg above200

Finding Skipped Setups With KeepTrades All, DebugEntry, and TestScan

Whenever a strategy takes fewer trades than expected (or zero trades), turn on KeepTrades: All inside Settings. RealTest then logs every rejected setup straight into the Trade List with Skip Long or Skip Short and the exact reason it was dropped (max positions, max exposure, max same symbol, or zero quantity).

To inspect exact indicator values at the moment an order triggers, add a DebugEntry line using Format() and enable Debug output in Test Output. To dump open-position states to a clean CSV file at the end of a backtest, pair TestData with TestScan.

Notes:
	Validated RealTest debugging template demonstrating Data vs Library vs TestData,
	NaN-safe Extern filters, standalone breadth operators, KeepTrades All,
	DebugEntry, and TestScan auditing.

Settings:
	DataFile:	MainETF.rtd
	StartDate:	2010-01-01
	EndDate:	2024-12-31
	AccountSize:	100000
	BarSize:	Daily
	KeepTrades:	All
	SaveScanAs:	C:\RealTest\Output\debug_scan.csv

Parameters:
	numPos:	4
	rsiLen:	2
	rsiMax:	15
	maxHold:	7

Data:
	atrN:	ATR(14)
	rsiVal:	RSI(rsiLen)
	ma200:	Avg(C, 200)
	above200:	C > ma200
	mktBreadth:	#Avg above200
	tltMom:	Extern($TLT, ROC(C, 60))
	tltSafe:	IF(IsNaN(tltMom), 0, tltMom > -10)
	entrySig:	above200 and rsiVal < rsiMax and mktBreadth > 0.50 and tltSafe

Library:
	stopLevel:	FillPrice - 2.5 * atrN[BarsHeld]
	holdDone:	BarsHeld >= maxHold

Strategy: etf_mr_debuggable
	Side:	Long
	EntrySetup:	entrySig
	SetupScore:	100 - rsiVal
	Quantity:	100 / numPos
	QtyType:	Percent
	MaxPositions:	numPos
	MaxExposure:	100
	Commission:	Max(1, Shares * 0.005)
	Slippage:	0.01
	ExitStop:	stopLevel
	ExitRule:	C > H[1] or holdDone
	ExitTime:	NextOpen
	DebugEntry:	IF(IsOrder, Format("rsi={#1} breadth={%0} qty={#0}", rsiVal, mktBreadth, Shares), "")

TestData:
	openStop:	Extern(@etf_mr_debuggable, IF(Shares <> 0, stopLevel, 0))
	openBars:	Extern(@etf_mr_debuggable, IF(Shares <> 0, BarsHeld, 0))

TestScan:
	Filter:	Extern(@etf_mr_debuggable, Shares <> 0)
	PriceC:	C
	RsiNow:	rsiVal
	StopPx:	openStop
	HeldBars:	openBars

Charts:
	MA200:	ma200
	StopLine:	IF(BarDate > T.DateIn and BarDate <= T.DateOut, openStop[1], NaN)

When we ran this exact script in RealTest 2.0 on ETF data from 2010 to 2024, KeepTrades: All expanded the Trade List to 3,277 total records, making every hidden constraint immediately visible. Alongside 1,491 executed trades (1,280 exit rule and 211 exit stop), the Trade List exposed 855 setups skipped for max positions, 783 skipped for max same symbol, and 148 skipped for max exposure.

RealTest 2.0 trade chart on SPY with StopLine overlay from TestData and KeepTrades All debugging workflow
RealTest 2.0 trade chart on SPY (July 25 to August 1, 2024) plotting the TestData openStop value directly below entry price (StopLine = 526.2) while the trade exits cleanly on ExitRule (+2.06%).

Command-Line Parsing and batchlog.txt Exit Codes

When running RealTest from PowerShell or automated workflows, stderr does not print to the console because RealTest is a Windows GUI binary. Always run with -parse first and read C:\RealTest\batchlog.txt for exact line and column errors.

RealTest Exit Code Meaning First File or Fix to Check
0 Success Check results.csv and trades.csv for silent 0-trade logic issues.
5 Syntax or parse error Open batchlog.txt for exact line number, column number, and offending item name.
6 Data import failure Verify Norgate Data Updater is running or check CSV paths use backslashes.
7 Data problem during test Confirm DataFile exists, symbols were imported, and date range overlaps available bars.

Note one command-line path rule inside .rts files. Always use Windows backslashes (\) in Include, DataFile, and SaveTradesAs paths, because forward slashes can break RealTest's parser. Also pass multiple preprocessor flags individually (-define research -define oos) rather than comma-separated.

Stop Fighting Syntax and Start Testing Clean Systems

Once you understand RealTest's four calculation scopes and how to inspect skipped trades, most broken scripts take five minutes to diagnose instead of an afternoon. If you want a clean, pre-validated starting script to compare against your own file, start with our free RealTest strategy and code library or download the Free Mean-Reversion Strategy for RealTest and Python.

If you are using AI tools to draft or debug RealTest scripts, read our guide to writing valid RealTest code with ChatGPT and Claude or check the full Build RealTest Strategies with Claude Code AI course. And if you have a stubborn broken script or a strategy from another platform you want turned into clean, audited code, our RealTest Strategy Development service handles full script repair and validation. You can also explore RealTest Orders mode and OrderClerk syntax once your backtest matches live assumptions.

If your data problem stems from custom CSV imports, missing Extra columns, or external TradeList positions staying open until end of test, read our RealTest CSV import, Extra column, and TradeList playback guide and our RealTest dividends, TotalReturn adjustment, and CashInOut accounting guide.

Key terms

KeepTrades
A RealTest Settings option (Trades, Skipped, or All) controlling whether skipped setups appear in the Trade List with their exact skip reason.
TestData
A RealTest script section calculated per symbol on each test date while the backtest runs, capable of storing strategy open-position values via Extern(@strat, ...).
TestScan
A RealTest scan section that runs automatically at the end of a backtest with full access to open positions and TestData arrays.
DebugEntry
A RealTest Strategy formula evaluated for every setup prior to entry processing that writes formatted diagnostic text to the Test Debug log when non-blank.
SymRef
A RealTest function that resolves a symbol string containing special characters like hyphens (for example SymRef("BTC-USD")) into its internal symbol reference.
batchlog.txt
The log file written in the RealTest installation folder recording command-line run status, exit codes, and exact line/column syntax errors.

Frequently asked questions

Why does my RealTest script parse with no errors but take zero trades?

Check four items in order. First, turn on KeepTrades All in Settings to see whether setups are being skipped by MaxPositions, MaxExposure, or zero quantity. Second, check whether any Extern() series returns NaN before an ETF launch date inside an or/and expression. Third, confirm FillPrice or BarsHeld are not inside the Data section. Fourth, verify your StartDate overlaps imported bars and IncludeList contains the symbols referenced in EntrySetup.

What is the difference between Data, Library, and TestData in RealTest?

Data runs once across all symbols before the backtest starts and cannot read open-position variables like FillPrice or BarsHeld. Library substitutes formulas inline during strategy evaluation and can read open-position state. TestData runs per symbol at the end of each test date inside the backtest loop and can store position-dependent values via Extern(@strategy_name, ...) for Charts and TestScan.

Why does RSI(C, 2) fail with wrong number of arguments in RealTest?

Unlike Avg(C, n) or ROC(C, n), RealTest's built-in RSI(n) function accepts only one argument (the lookback period) and implicitly operates on Close. Change RSI(C, 2) to RSI(2).

How do you fix reserved syntax elements cannot be used as item names in RealTest?

Rename any Data, Parameters, Results, or Scan column that matches or shadows a RealTest keyword such as atr, rsi, open, close, volume, symbol, rank, score, or positions. Neutral names like atrN, rsiVal, PriceC, and numPos parse cleanly.

How do you reference a ticker with a hyphen like BTC-USD in RealTest?

RealTest treats the hyphen in $BTC-USD as a minus sign. Use Symbol = SymRef("BTC-USD") or Extern(SymRef("BTC-USD"), ...), or group symbols in a named IncludeList and filter with InList("Crypto").

Where do RealTest command-line parse errors appear?

RealTest is a Windows GUI application and does not print errors to terminal stderr. After running realtest.exe -parse script.rts, open C:\RealTest\batchlog.txt to read the exact file, line number, column number, and error description.

Related strategies

Free Mean-Reversion Strategy for RealTest & Python
Download a clean, error-free RealTest script template to compare section layout, data filters, and cost syntax against your own code.
View →
Build RealTest Strategies with Claude Code AI
Learn the exact structured workflow for generating, parsing, debugging, and validating RealTest strategies with Claude Code without syntax hallucinations.
View →
RealTest Mean Reversion Trading Strategy
Full production-grade Norgate S&P 500 RealTest script demonstrating survivorship-free filters, realistic IBKR costs, and clean execution logic.
View →
← Back to Learn

#1 RealTest Backtests

Supercharge Your Trading Now

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

Browse RealTest Strategies