AI in Trading Backtesting ChatGPT Claude Code RealTest RealTest Code

Using ChatGPT and Claude to Write Valid RealTest Code Without Syntax Hallucinations

Summary

ChatGPT and Claude regularly hallucinate Pine Script, AmiBroker, or Python syntax when writing RealTest scripts, omitting InSPX survivorship filters, passing two arguments to RSI(C, 2), putting FillPrice in Data, or injecting ThisClose lookahead bias. Supplying a strict syntax guardrail block and looping outputs through realtest.exe -parse and batchlog.txt eliminates hallucinations completely.

· 8 min read
RealTest 2.0 workbench showing AI-validated survivorship-free S&P 500 RSI(2) script, NVR trade chart with StopLine and bounce_exit, and 4,268 Trade List rows
Key findings
  • General-purpose LLMs frequently forget Norgate point-in-time index membership filters like InSPX even when explicitly asked for a survivorship-bias-free S&P 500 backtest.
  • Ten recurring syntax hallucinations account for nearly every failed AI-generated RealTest script, led by RSI(C, 2), boolean conditions inside ExitStop, FillPrice inside Data, Quantity 100 / MaxPositions, and EntryTime ThisClose lookahead bias.
  • RealTest 2.0 ships with both headless CLI validation (realtest.exe -parse and -test writing exact line/column diagnostics to batchlog.txt) and a local HTTP Automation API (-api) built specifically for agentic AI loops.
  • Giving Claude or ChatGPT a concise 12-rule RealTest syntax contract plus your exact DataFile symbols cuts broken draft iterations dramatically.
  • Validated in RealTest 2.0 on Norgate historical S&P 500 constituents from 2010 to 2024, the corrected RSI(2) mean-reversion script executed 4,268 trades cleanly across 3,263 bounce_exit, 621 time_stop, and 373 exit stop closures.

Across nearly 200 discussions on the RealTest user forum, systematic traders report the exact same experience with ChatGPT and Claude. The model writes clean-looking indentation, invents sensible-sounding variable names, and hands back a .rts file that either crashes on line 18 or silently produces an invalid backtest with hidden survivorship bias and lookahead fills.

The cause is simple. RealTest's primary forum sits behind a member login, so public training data contains a tiny fraction of RealTest code compared to Python, Pine Script, or AmiBroker AFL. When an LLM hits an uncertain RealTest directive, it blends AmiBroker and Pine Script conventions into the script. Worse, RealTest also provides an official Automation API and CLI mode that few systematic traders ever wire into their AI workflow. Below is the exact hallucination audit, reusable AI prompt contract, and CLI validation loop we use internally to produce zero-error RealTest code.

The 10 RealTest Hallucinations ChatGPT and Claude Repeat Every Time

Every entry in this table was observed repeatedly in real AI-generated drafts and verified directly against RealTest 2.0.

What ChatGPT or Claude Writes Why It Fails in RealTest Validated RealTest 2.0 Syntax
RSI(C, 2) < 10 wrong number of arguments because RSI(n) takes 1 argument only. RSI(2) < 10
S&P 500 script with no InSPX filter Trades delisted and non-member symbols on dates they were outside the index, breaking survivorship accuracy. Import .S&P 500 Current & Past and require InSPX inside EntrySetup.
ExitStop: C < LLV(L, 20) Evaluates to 0 or 1 (a 1-dollar stop price) instead of the 20-bar low. ExitStop: LLV(L, 20) (always pass a price).
FillPrice or BarsHeld in Data Data calculates before the test starts, so position variables silently return 0 or NaN. Put position-aware formulas in Library or Strategy.
Quantity: 100 / MaxPositions unrecognized syntax element because MaxPositions is not readable inside Quantity. Define numPos: 10 in Parameters and write Quantity: 100 / numPos.
EntryTime: ThisClose on close signal Same-bar close lookahead bias (you cannot know today's close triggers the setup before the bell). Use EntryTime: NextOpen, NextClose, or Intraday with EntryLimit.
atr: ATR(14) or rsi: RSI(2) reserved syntax elements cannot be used as item names. Rename to atrN: ATR(14) and rsiVal: RSI(2).
Extern($SPX, ...) or Extern($$SPY, ...) unrecognized symbol (Norgate indices need double $$, ETFs need single $). Extern($$SPX, ...) for index, Extern($SPY, ...) for ETF.
mom - (#Avg mom) on one line expected an operator here because breadth tags cannot be nested inside expressions. Put avgMom: #Avg mom on its own Data line first.
Slippage: 0.01 inside Settings unrecognized setting name because cost settings belong at strategy level. Move Commission and Slippage into Strategy or Template.

For deep dives into each of those subsystems, bookmark our validated references on RealTest ExitStop and trailing stops, RealTest position sizing, RealTest #Rank and rotation, RealTest Extern() and breadth filters, RealTest EntryLimit and lookahead control, RealTest multi-strategy combining, AmiBroker AFL to RealTest migration, and RealTest zero-trade debugging.

Copy-Paste RealTest Guardrail Prompt for ChatGPT and Claude

Paste this exact constraint block above your strategy idea before asking Claude or ChatGPT to generate a .rts script. Every bullet targets a verified failure mode.

Write a RealTest 2.0 (.rts) script following these strict rules.
1. Use tab indentation inside sections and Windows backslashes in all file paths.
2. Never shadow built-in names (use atrN, rsiVal, numPos, PriceC instead of atr, rsi, positions, close).
3. Built-in RSI(n) takes ONE argument only (never RSI(C, n)).
4. Put FillPrice, BarsHeld, Shares, and PrevExitStop in Library or Strategy, NEVER in Data.
5. ExitStop and ExitLimit must return a numeric PRICE per share, never a boolean condition.
6. Never write Quantity: 100 / MaxPositions; divide by a Parameters item like 100 / numPos.
7. Put breadth operators (#Avg, #Sum, #Rank) at the start of their own standalone Data line.
8. Use $SPY for ETFs and $$SPX for Norgate indices inside Extern(); guard pre-inception NaN with IF(IsNaN(x), 0, cond).
9. Never use EntryTime: ThisClose or negative offsets like [-1] on price-dependent signals (avoid lookahead bias).
10. Include historical constituent filters (InSPX / InNDX / InRUI) plus realistic Commission and Slippage inside Strategy.
11. Never write Slippage or Commission in Settings.
12. Do not invent functions like Top(expr, N) for ranking or Ref(C, -1); use C[1] and #Rank.

Quick Syntax Mapping When Porting AmiBroker, Pine Script, or Python via AI

One of the fastest ways to use Claude or ChatGPT is converting an existing AmiBroker AFL, TradingView Pine Script, or Python prototype into RealTest. Include this translation table in your prompt so the model stops carrying foreign idioms over.

Concept AmiBroker AFL TradingView Pine Script Validated RealTest 2.0
Prior bar close Ref(C, -1) close[1] C[1]
20-bar highest high (prior) Ref(HHV(H, 20), -1) ta.highest(high, 20)[1] HHV(H, 20)[1]
2-period RSI RSI(2) ta.rsi(close, 2) RSI(2)
External benchmark filter Foreign("SPY", "C") request.security("SPY", ...) Extern($SPY, C > Avg(C, 200))
Rank competing setups PositionScore = ... Not native (single symbol) SetupScore: ...
Trailing stop price ApplyStop(...) strategy.exit(trail_points=...) ExitStop: HHV(H - 3 * atrN, BarsHeld + 1)
Max concurrent positions SetOption("MaxOpenPositions", 10) Not native MaxPositions: 10

The Automated CLI Parse-and-Test Feedback Loop

Never trust an AI-generated .rts file by visual inspection alone. If you use Claude Code or a local terminal workflow, run RealTest's command-line parser immediately after every edit and feed batchlog.txt back to the model whenever exit code 5 appears.

# 1. Syntax check only (exit code 0 = clean, 5 = syntax error)
$p = Start-Process 'C:\RealTest\realtest.exe' -ArgumentList '-parse','C:\RealTest\Scripts\my_strategy.rts' -Wait -PassThru
Get-Content 'C:\RealTest\batchlog.txt' -Tail 20

# 2. Run full backtest and verify trade list + exit reasons
$p = Start-Process 'C:\RealTest\realtest.exe' -ArgumentList '-test','C:\RealTest\Scripts\my_strategy.rts' -Wait -PassThru
Get-Content 'C:\RealTest\batchlog.txt' -Tail 20

Complete AI-Validated RealTest Script (Survivorship-Free S&P 500 RSI(2))

Below is a complete S&P 500 mean-reversion script generated under the exact 12-rule contract above and verified directly in RealTest 2.0 on Norgate Data historical constituents (InSPX). Every single hallucination trap from the table above is resolved cleanly.

Notes:
	Validated survivorship-bias-free S&P 500 RSI(2) mean-reversion script
	demonstrating every guardrail required when generating RealTest code with
	ChatGPT or Claude.

Import:
	DataSource:	Norgate
	IncludeList:	.S&P 500 Current & Past
	IncludeList:	SPY
	StartDate:	2005-01-01
	EndDate:	Latest
	SaveAs:	spx_rsi2_ai.rtd

Settings:
	DataFile:	spx_rsi2_ai.rtd
	StartDate:	2010-01-01
	EndDate:	2024-12-31
	AccountSize:	100000
	BarSize:	Daily

Parameters:
	numPos:	10
	rsiLen:	2
	rsiMax:	10
	atrLen:	14
	dropMult:	0.5
	maxHold:	7

Data:
	atrN:	ATR(atrLen)
	rsiVal:	RSI(rsiLen)
	ma200:	Avg(C, 200)
	spyUp:	Extern($SPY, C > Avg(C, 200))
	liquid:	C > 5 and Avg(C * V, 20) > 20000000
	entrySig:	InSPX and liquid and spyUp and C > ma200 and rsiVal < rsiMax
	entryLim:	C - dropMult * atrN

Library:
	stopPx:	FillPrice - 3 * atrN[BarsHeld]

Strategy: spx_rsi2_ai_validated
	Side:	Long
	EntrySetup:	entrySig
	EntryLimit:	entryLim
	EntryTime:	Intraday
	SetupScore:	100 - rsiVal
	Quantity:	100 / numPos
	QtyType:	Percent
	MaxPositions:	numPos
	MinFreeCash:	0.02 * S.Equity
	Commission:	Max(1, Shares * 0.005)
	Slippage:	0.01
	ExitStop:	IF(BarsHeld >= 1, stopPx, 0)
	ExitRule:	Select(C > H[1], "bounce_exit", BarsHeld >= maxHold, "time_stop")
	ExitTime:	NextOpen
	Ambiguity:	Stop

TestData:
	recordedStop:	Extern(@spx_rsi2_ai_validated, IF(Shares <> 0, stopPx, NaN))

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

Parsed and executed in RealTest 2.0 across 2010 to 2024 on Norgate historical S&P 500 constituents, this script produced 4,268 trades cleanly (3,263 bounce_exit, 621 time_stop, 373 exit stop, and 11 end-of-data or end-of-test closures, including delisted constituents like JNPR-202507) with zero parser warnings and zero lookahead fills.

RealTest 2.0 trade chart on NVR showing validated survivorship-free S&P 500 RSI(2) limit entry, StopLine, and bounce_exit
RealTest 2.0 trade chart on NVR (November 19 to November 21, 2024) confirming intraday EntryLimit fill at 8,753.58, day-1 protective StopLine underneath price, and NextOpen bounce_exit at 9,044.99 (+3.32%).

Turn Claude Code Into a RealTest Research Engine

Using AI safely for systematic research means pairing strict language guardrails with real Norgate data, CLI validation, and out-of-sample discipline rather than accepting single-shot scripts at face value. If you want a complete working script to test inside your own workflow right away, start with our free RealTest strategy and code library or grab the Free Mean-Reversion Strategy for RealTest and Python.

If you want our complete production setup for wiring Claude Code directly into RealTest (including official syntax reference files, automated -parse and -test error loops, walk-forward validation gates, and zero-hallucination research templates), see our Build RealTest Strategies with Claude Code AI course. For traders comparing platforms before migrating existing code, read our RealTest vs Pine Script vs Python comparison, or use our RealTest Strategy Development service if you prefer an audited custom build.

To validate AI-generated scripts against overfitting with native OptimizeSettings walk-forward testing and reproducible EntrySkip Monte Carlo stress runs, see our RealTest Walk-Forward Optimization and Monte Carlo guide. If you want to test 5-minute intraday Opening Range Breakouts via CSV workarounds, read our RealTest intraday 5-minute ORB CSV guide.

Key terms

RealTest CLI Parse Mode
Running realtest.exe -parse script.rts to validate syntax headlessly, returning exit code 0 on success or exit code 5 with line and column diagnostics in batchlog.txt.
RealTest Automation API
RealTest 2.0's local HTTP and JSON interface (launched with realtest.exe -api) enabling scripts and AI agents to run tests, inspect results CSVs, and capture charts programmatically.
InSPX
A Norgate point-in-time index constituency flag inside RealTest returning true only on dates when a stock was an active member of the S&P 500, preventing survivorship bias.
Lookahead Bias
A backtesting error where a strategy formula uses future bar information not available at order submission time, such as EntryTime ThisClose on a close-price signal or negative bar offsets.
Syntax Guardrail Prompt
A structured list of platform-specific constraints supplied to ChatGPT or Claude to prevent cross-language hallucinations when generating RealTest code.

Frequently asked questions

Can ChatGPT or Claude write working RealTest scripts?

Yes, provided you supply a strict RealTest syntax guardrail prompt and validate every output with realtest.exe -parse and -test. Without explicit rules, general LLMs frequently hallucinate AmiBroker or Pine Script syntax such as RSI(C, 2), boolean conditions in ExitStop, FillPrice inside Data, and missing InSPX survivorship filters.

Why does ChatGPT forget survivorship bias in RealTest S&P 500 scripts?

Because RealTest's Norgate historical constituency flags (InSPX, InNDX, InRUI) are rare in public LLM training data, ChatGPT often imports a static list or omits InSPX from EntrySetup. Always specify .S&P 500 Current & Past in Import and require InSPX inside EntrySetup.

How do you validate AI-generated RealTest code automatically from the command line?

Run realtest.exe -parse script.rts via PowerShell Start-Process -Wait -PassThru and inspect batchlog.txt in your RealTest installation folder. Exit code 0 confirms clean syntax, while exit code 5 reports the exact line number, column number, and offending item to feed back to Claude or ChatGPT.

Does RealTest have an API for Claude Code or AI agents?

Yes. RealTest 2.0 includes a local HTTP and JSON Automation API launched with realtest.exe -api (default 127.0.0.1 port 7827) that allows local scripts and AI coding agents to parse scripts, run backtests, read structured results and trade lists, and capture screenshots programmatically.

How do you convert AmiBroker AFL or Pine Script to RealTest with AI?

Give the AI a direct mapping table alongside your source code so Ref(C, -1) becomes C[1], PositionScore becomes SetupScore, Foreign becomes Extern($SYM, ...), ApplyStop becomes a price-based ExitStop, and ta.rsi(close, 2) becomes RSI(2), then verify the converted script with realtest.exe -parse and -test.

What is the biggest silent lookahead bug in AI-generated RealTest code?

Setting EntryTime or ExitTime to ThisClose on a signal that inspects today's Close, High, or Low. Because you cannot know today's final close before the market closes, switch price-dependent setups to EntryTime NextOpen, NextClose, or Intraday with EntryLimit.

Related strategies

Build RealTest Strategies with Claude Code AI
Complete system for connecting Claude Code directly to RealTest with official syntax guardrails, automated CLI parse/test loops, and validation gates.
View →
Free Mean-Reversion Strategy for RealTest & Python
Free working RealTest and Python script pair so you can inspect clean, bias-free code side by side before running your own AI experiments.
View →
RealTest Short Term Mean Reversion Strategy
Production-grade short-term equity mean-reversion strategy built on Norgate historical constituents with full transparent RealTest code.
View →
← Back to Learn

#1 RealTest Backtests

Supercharge Your Trading Now

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

Browse RealTest Strategies