#Avg #Sum Market Breadth McClellan Oscillator RealTest RealTest Code

Market Breadth in RealTest Using #Avg, #Sum, McClellan Oscillator, and 52-Week NH-NL

Summary

Calculate survivorship-free market breadth natively inside RealTest's Data section with zero external breadth feeds using standalone cross-sectional lines (#Avg for percent above MA200, #Sum for Advance-Decline and 52-week New Highs minus New Lows, and EMA(netAdvDec, 19) - EMA(netAdvDec, 39) for the McClellan Oscillator).

· 5 min read
RealTest 2.0 native breadth workbench showing HPE +8.35 percent trade with PctAbove200 and McClellan lower panes left, #Avg and #Sum script top right, and equity curves bottom right
Key findings
  • Critical RealTest 2.0 parser rule confirmed live is that cross-sectional operators (#Avg, #Sum, #Count, #PercentRank) MUST start at the very beginning of a standalone Data item; writing 100 * #Avg inSpxAbove200 inline fails with Exit Code 5 ('expected an operator here').
  • Always wrap cross-sectional breadth items in IF(InSPX, condition, NaN) before calling #Avg or #Sum so breadth measures strictly point-in-time S&P 500 constituents rather than counting non-member tickers in your database.
  • Compute the classic Sherman McClellan Oscillator directly inside Data with zero external feeds via netAdvDec #Sum advIssue followed by mcClellan EMA(netAdvDec, 19) - EMA(netAdvDec, 39).
  • Compute 52-week New Highs minus New Lows natively via nhNlItem IF(InSPX, IF(C >= HHV(C, 252), 1, IF(C <= LLV(C, 252), -1, 0)), NaN) and netNhNl #Sum nhNlItem.
  • Validated in RealTest 2.0 on survivorship-free S&P 500 stocks (2015 through 2024, $100,000 start), unfiltered mr_no_breadth reached $276,484 but absorbed a steep -25.20 percent MaxDD across 6,002 trades.
  • Gating entries with native McClellan and 52-week NH-NL breadth (mr_mcclellan_nhnl_gate, 5,483 trades) slashed MaxDD by 35 percent down to -16.35 percent while preserving $220,404 in ending equity, outperforming a rigid 50 percent above-MA200 gate ($185,629, -17.54 percent MaxDD).

Coding Advance-Decline lines, percentage of stocks above their 200-day moving average, McClellan Oscillators, and 52-week New Highs minus New Lows without paying for extra breadth data feeds is a favorite technical topic on the RealTest user forum (52 posts across threads like Advance Decline, McClellan Summation Index, and Custom Cumulative Advance Decline Line). Almost every trader who tries cross-sectional breadth for the first time runs straight into a sneaky RealTest parser rule. Writing 100 * #Avg ... on one line throws an instant syntax error!

Every cross-sectional formula below matches the official RealTest Cross-Sectional Functions documentation and was verified live in RealTest 2.0 on historical S&P 500 constituents (InSPX) from 2015 through 2024.

Exact Cross-Sectional #Avg and #Sum Rules for Native Market Breadth

Because RealTest evaluates Data across every stock on every date in parallel, computing point-in-time breadth takes two tiny rules that prevent syntax errors and universe leakage.

Native Breadth Indicator Broken Syntax Trap Validated RealTest 2.0 Syntax
% of S&P 500 stocks above MA200 pct: 100 * #Avg (C > ma200) (Exit Code 5!) inSpxAbove200: IF(InSPX, C > ma200, NaN) -> rawAbove200: #Avg inSpxAbove200 -> pctAbove200: 100 * rawAbove200
Net Advancing minus Declining issues Counting non-index symbols in .rtd advIssue: IF(InSPX, IF(C > C[1], 1, IF(C < C[1], -1, 0)), NaN) -> netAdvDec: #Sum advIssue
McClellan Oscillator (19 vs 39 EMA) Trying to nest EMA(#Sum ..., 19) inline Compute netAdvDec: #Sum advIssue first, then mcClellan: EMA(netAdvDec, 19) - EMA(netAdvDec, 39)
52-Week New Highs minus New Lows Paying for separate $NYHL feed nhNlItem: IF(InSPX, IF(C >= HHV(C, 252), 1, IF(C <= LLV(C, 252), -1, 0)), NaN) -> netNhNl: #Sum nhNlItem

Memorize that golden RealTest rule. Cross-sectional operators (#Avg, #Sum, #Count, #Rank, #PercentRank) MUST always sit at the start of their own dedicated Data line, and any arithmetic or EMA smoothing happens on the NEXT line! Also notice that wrapping each stock expression in IF(InSPX, ..., NaN) excludes non-constituents cleanly because RealTest ignores NaN values inside cross-sectional aggregations (see our Extern() market regime filter guide and our sector breadth and InfoTRBC guide).

Complete Validated RealTest Script (PctAbove200 + McClellan Oscillator + 52-Week NH-NL)

Copy and run this complete RealTest 2.0 script on survivorship-free S&P 500 data to plot live PctAbove200 and McClellan panes right underneath any chart while testing both breadth regime gates against an unfiltered baseline.

Notes:
	Native cross-sectional market breadth in RealTest 2.0 using #Avg, #Sum,
	McClellan Oscillator, and 52-week New Highs minus New Lows on historical
	S&P 500 constituents (InSPX) with zero external breadth subscriptions.

Settings:
	DataFile:	C:\RealTest\Data\SPY_Tickers.rtd
	StartDate:	2015-01-01
	EndDate:	2024-12-31
	AccountSize:	100000
	BarSize:	Daily

Parameters:
	numPos:	10

Data:
	ma200:	Avg(C, 200)
	rsi2:	RSI(2)
	atr14:	ATR(14)
	liquid:	C > 10 and Avg(C * V, 20) > 25000000
	// Native cross-sectional S&P 500 breadth computed strictly across historical InSPX members
	// Note: cross-sectional #Avg and #Sum must lead a standalone Data item!
	inSpxAbove200:	IF(InSPX, C > ma200, NaN)
	rawAbove200:	#Avg inSpxAbove200
	pctAbove200:	100 * rawAbove200
	// Advance - Decline net issues & classic McClellan Oscillator (19-EMA minus 39-EMA)
	advIssue:	IF(InSPX, IF(C > C[1], 1, IF(C < C[1], -1, 0)), NaN)
	netAdvDec:	#Sum advIssue
	mcClellan:	EMA(netAdvDec, 19) - EMA(netAdvDec, 39)
	// 52-Week New Highs minus New Lows
	nhNlItem:	IF(InSPX, IF(C >= HHV(C, 252), 1, IF(C <= LLV(C, 252), -1, 0)), NaN)
	netNhNl:	#Sum nhNlItem

Template: br_base
	Side:	Long
	Allocation:	S.Equity
	SetupScore:	100 - rsi2
	QtyType:	Percent
	Quantity:	100 / numPos
	MaxPositions:	numPos
	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

// 1. Unfiltered S&P 500 RSI(2) baseline (no market breadth regime gate)
Strategy: mr_no_breadth
	Using:	br_base
	EntrySetup:	InSPX and liquid and C > ma200 and rsi2 < 10

// 2. Breadth-gated: enters only when >= 50% of historical S&P 500 stocks trade above MA200
Strategy: mr_pct_above200_gate
	Using:	br_base
	EntrySetup:	InSPX and liquid and C > ma200 and rsi2 < 10 and pctAbove200 >= 50

// 3. Breadth thrust + positive NH-NL confirmation (McClellan > -30 and netNhNl >= -20)
Strategy: mr_mcclellan_nhnl_gate
	Using:	br_base
	EntrySetup:	InSPX and liquid and C > ma200 and rsi2 < 10 and mcClellan > -30 and netNhNl >= -20

Charts:
	MA200:	ma200
	PctAbove200:	pctAbove200 {|}
	McClellan:	mcClellan {|}

Validated 2015 to 2024 Breadth-Filter Comparison (InSPX)

Filtering S&P 500 mean-reversion entries through native cross-sectional breadth slashes crash drawdowns dramatically while keeping strong compounding intact.

Breadth Regime Gate (2015 to 2024, InSPX) Completed Trades Ending Equity ($100k start) Max Drawdown Risk-Adjusted Benefit
mr_no_breadth (No Breadth Filter) 6,002 $276,484 -25.20% Absorbs full bear-market cascades in 2020 and 2022
mr_mcclellan_nhnl_gate (McClellan > -30 & NH-NL >= -20) 5,483 $220,404 -16.35% Cuts MaxDD by 35% while keeping 80% of raw equity
mr_pct_above200_gate (PctAbove200 >= 50) 4,814 $185,629 -17.54% Slowest to re-enter after V-shaped bear-market bottoms
RealTest 2.0 chart displaying native cross-sectional S&P 500 PctAbove200 breadth and McClellan Oscillator lower subpanes computed via #Avg and #Sum
RealTest 2.0 HPE trade (+8.35%) displaying 100% natively computed S&P 500 PctAbove200 (75.05%, green) and McClellan Oscillator (+22.61, dark red) subpanes with zero external breadth data subscriptions.

Notice why the fast McClellan + NH-NL gate beat the slower PctAbove200 >= 50 gate on BOTH return ($220,404 vs $185,629) AND MaxDD (-16.35 percent vs -17.54 percent)! Because PctAbove200 lags major market bottoms by months while stocks claw back above their 200-day averages, it misses lucrative post-crash rebounds, whereas the McClellan Oscillator turns positive within days of a real breadth thrust.

Build Custom Equal-Weighted Indices and Low-Drawdown Breadth Portfolios

Want to construct custom equal-weighted composite indices and market-breadth benchmarks natively inside RealTest 2.0? Grab our ready-to-run Custom Equal Weighted Index Builder for RealTest.

For complete low-drawdown production strategies and portfolios already protected by proven regime filters, explore our RealTest Low Drawdown Nasdaq Mean Reversion Strategy and our All-Weather Low-Drawdown Portfolio.

Key terms

Cross-Sectional #Avg and #Sum
RealTest Data operators aggregating a numeric expression across all active non-NaN symbols on each bar date, requiring their own standalone Data line.
Native McClellan Oscillator
A fast market-breadth momentum oscillator computed natively in RealTest as EMA(netAdvDec, 19) - EMA(netAdvDec, 39) from historical index constituents.
Percent Above MA200 Breadth
The point-in-time percentage of historical index constituents trading above their 200-day moving average, computed via 100 * #Avg of IF(InSPX, C > ma200, NaN).
52-Week NH-NL Breadth
Daily count of index stocks hitting 252-day closing highs minus stocks hitting 252-day closing lows, aggregated via #Sum.
NaN Universe Masking
Returning NaN for non-index tickers inside IF(InSPX, ..., NaN) so cross-sectional breadth calculations ignore irrelevant or delisted symbols.

Frequently asked questions

Why does 100 * #Avg inSpxAbove200 throw a syntax error in RealTest?

In RealTest, cross-sectional operators (#Avg, #Sum, #Count, #Rank, #PercentRank) must appear at the very start of a standalone Data item. Define rawAbove200 as #Avg inSpxAbove200 on one line, then multiply pctAbove200 as 100 * rawAbove200 on the next line.

How do you code the McClellan Oscillator in RealTest without external breadth data?

Define advIssue as IF(InSPX, IF(C > C[1], 1, IF(C < C[1], -1, 0)), NaN), aggregate daily net advancing issues with netAdvDec = #Sum advIssue, and smooth on the next line via mcClellan = EMA(netAdvDec, 19) - EMA(netAdvDec, 39).

Why must you wrap breadth conditions in IF(InSPX, ..., NaN) before using #Avg or #Sum?

RealTest databases often hold historical delisted stocks, ETFs, and non-index tickers alongside current members. Returning NaN whenever InSPX is false guarantees #Avg and #Sum measure strictly the historical S&P 500 constituents alive on each bar date.

How do you calculate 52-week New Highs minus New Lows natively in RealTest?

Flag each stock via nhNlItem = IF(InSPX, IF(C >= HHV(C, 252), 1, IF(C <= LLV(C, 252), -1, 0)), NaN) and sum across the index on the next Data line with netNhNl = #Sum nhNlItem.

Why did McClellan plus NH-NL outperform Percent Above MA200 as a breadth gate?

In our 2015 through 2024 S&P 500 test, McClellan > -30 and netNhNl >= -20 reacted far faster after crash bottoms than slow 200-day moving average breadth, earning $220,404 vs $185,629 while achieving an even lower MaxDD (-16.35 percent vs -17.54 percent).

Can you build a cumulative Advance-Decline Line inside RealTest Data?

Yes. Once netAdvDec = #Sum advIssue is computed, accumulate it cleanly via cumAD = Sum(netAdvDec, BarNum) or track its slope with EMA(netAdvDec, 50) to spot bearish market divergences ahead of index peaks.

Related strategies

Custom Equal Weighted Index Builder for RealTest
Build custom equal-weighted stock indices and breadth benchmarks natively inside RealTest 2.0.
View →
RealTest Low Drawdown Nasdaq Mean Reversion Strategy
Disciplined Nasdaq-100 mean-reversion system engineered with strict regime protection for shallow drawdowns.
View →
All-Weather Low-Drawdown Portfolio
Multi-strategy RealTest portfolio engineered to weather breadth collapses smoothly across market cycles.
View →
← Back to Learn

#1 RealTest Backtests

Supercharge Your Trading Now

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

Browse RealTest Strategies