Spread Tracker
The spread tracker monitors the price difference between two related futures contracts, displayed as a single line on the chart. This metric shows the relative valuation between contracts at different expirations (calendar spread), different contract types in the same commodity (intercommodity spread), or between functionally linked instruments. Portfolio managers, spread traders and risk analysts use spread trackers to identify periods when contracts move out of typical relationship, signal potential reversion patterns, or confirm relative strength or weakness before entering paired positions [1].
//@version=6
indicator("Spread Tracker", overlay=false, precision=2)
// Inputs
symbolA = input.symbol("ES1!", title="Contract A")
symbolB = input.symbol("NQ1!", title="Contract B")
spreadType = input.string("Absolute", title="Spread Type", options=["Absolute", "Ratio", "Percent"])
showMA = input.bool(true, title="Show Moving Average")
maLength = input.int(20, title="MA Length", minval=1)
useClose = input.bool(true, title="Use Close (unchecked = use OHLC)")
// Request data for both contracts
priceA = request.security(symbolA, timeframe.period, useClose ? close : ohlc4)
priceB = request.security(symbolB, timeframe.period, useClose ? close : ohlc4)
// Calculate spread
spread = switch spreadType
"Absolute" => priceA - priceB
"Ratio" => priceB != 0 ? priceA / priceB : na
"Percent" => priceB != 0 ? ((priceA - priceB) / priceB) * 100 : na
=> na
// Moving average of spread
spreadMA = ta.sma(spread, maLength)
// Plotting
plot(spread, title="Spread", color=color.blue, linewidth=2)
plot(showMA ? spreadMA : na, title="Spread MA", color=color.orange, linewidth=1, linestyle=linestyle.dashed)
// Zero line for reference
hline(0, color=color.gray, linestyle=linestyle.dotted, linewidth=1)
// Coloring for visual clarity
spreadColor = spread >= 0 ? color.new(color.green, 80) : color.new(color.red, 80)
bgcolor(spreadColor, title="Spread Direction Background")
How the code works
The indicator fetches the price of two user-selected contracts via request.security(), which retrieves data for each symbol at the chart's timeframe [2]. The spread calculation supports three common methods: absolute difference (Contract A price minus Contract B price), ratio (Contract A divided by Contract B), and percentage difference. The ratio and percent modes normalize the spread relative to one contract's magnitude, useful when comparing instruments with significantly different price scales.
The moving average computation uses a simple average of the spread values over a configurable period, typically revealing the mean-reversion band around which a spread oscillates. The indicator plots both the raw spread and its MA, allowing traders to see both instantaneous deviation and the underlying trend. The background color signals direction: green when the spread is positive (Contract A stronger), red when negative (Contract B stronger). The zero reference line marks neutral spread position, aiding visual interpretation.
Reading it on a chart
A calendar spread tracker typically shows predictable oscillation within a band. When applied to ES (E-mini S&P 500) and NQ (E-mini Nasdaq), the ratio spread reflects whether equities tech exposure (Nasdaq weight) is gaining or losing ground relative to the broader market. If the ratio rises, Nasdaq is outperforming; if it falls, the S&P 500 components outside tech are strengthening.
Practical traders watch for spread extremes relative to the moving average. When the raw spread diverges far above the MA, contracts may be reversing (the spread may tighten). Conversely, a tightening spread after a period of widening can signal consolidation before a directional break. Note that seasonal factors, volatility regime changes and structural shifts in the markets' relationship can cause the MA to drift, so historical levels are not guaranteed anchors [1].
The choice between absolute and ratio modes depends on the contract pair. For intercommodity spreads like crude oil and heating oil, absolute difference in dollars per barrel is standard. For index futures or currency pairs, ratio or percent modes often reveal the proportional relationship more clearly.
Limitations
The spread tracker is a tool for observation and analysis only; it does not generate trading signals or predict price action. Several structural limits constrain its use. First, the two contracts must trade with matching or easily compared resolutions; if one contract has lower liquidity or wider bid-ask spread than the other, the tracked spread may reflect transaction cost rather than market consensus [1]. Second, commission and slippage costs on each leg of a spread trade reduce profitability, and these costs are invisible in the indicator itself [3]. Third, the relationship between contracts can shift structurally due to supply-demand changes, policy shifts or technological disruption; a spread that historically mean-reverted may not in the future. Fourth, if one contract rolls from front to back month while the other does not, the indicator will show a discontinuity that is not a market signal but a calendar transition. Fifth, use of close versus OHLC for the price basis can produce different spread values; overnight gaps in one contract relative to another will distort intraday spread readings. Finally, the indicator does not account for transaction timing, margin requirements or cash-flow implications of running a spread position, all of which are material to real execution.
Key definitions
Calendar spread: a position holding two contracts of the same commodity at different expiration dates, intended to profit from convergence in their prices as the near contract expires.
Intercommodity spread: a position between two different but related contracts (such as crude oil and natural gas), designed to capture the relative valuation or co-movement between different commodities.
Ratio: the quotient of one price divided by another, normalized to show relative magnitude when prices trade at different absolute levels.
Mean reversion: the observed tendency of a value (such as a spread) to gravitate toward a historical average after moving away from it; statistical tendency, not a guarantee.
Bid-ask spread: the difference between the highest price a buyer will pay (bid) and the lowest price a seller will accept (ask); wider spreads indicate lower liquidity.
OHLC4: the simple average of open, high, low and close prices for a period; used as an alternative to close price alone.
References
[1] CME Group, "Understanding Futures Spreads", CME Group Education (year not specified). Accessed at CME's educational archive on calendar and intercommodity spread mechanics.
[2] TradingView, "request.security()", TradingView Pine Script Reference (2024). Documents the syntax and behavior of fetching external symbol data within a Pine indicator.
[3] CME Group, "Futures Contract Specifications and Fee Schedule", CME Group Rulebook (current). Lists standard trading costs and transaction requirements for spread positions.
Educational research on historical data only. Not investment advice, not a signal, and never a performance promise. Past results do not predict future performance. Every reference is link-verified before publication and every paper is re-audited weekly against the library's editorial standard.
Last reviewed by the PropLedger research pipeline: 2026-11-15. Educational research on historical data, not financial advice.
Keep reading
Swing Structure: BOS & CHoCH
Free open-source Pine Script indicator: swing high/low structure marker (BOS and CHoCH labels). Full code and a plain-English walkthrough.
New High/New Low Breadth Proxy
Free open-source Pine Script indicator: new high/new low breadth proxy for a symbol basket. Full code and a plain-English walkthrough.
Consecutive Close Counter
Free open-source Pine Script indicator: consecutive close counter with streak statistics table. Full code and a plain-English walkthrough.