Indicators··8 min read

Spread Tracker: Related Futures Contracts

0 references, link-verified · inline [n] markersEditor of record: Shane CantyStandards review editorial standard · audit log

Spread tracking monitors the price difference between two correlated futures contracts, commonly used to identify relative value opportunities, hedging ratios, and temporal or product basis shifts. Traders and portfolio managers use spreads to isolate the relationship between contract months (calendar spreads), related products (intercommodity spreads such as crude oil and heating oil), or index futures (e.g., E-mini S&P 500 versus E-mini Nasdaq 100). This indicator calculates and visualizes the spread, baseline, and optional moving-average filters to support spread-relative decision-making.

//@version=6
indicator("Spread Tracker: Related Futures Contracts", overlay=false)

// Input: Two contract symbols and calculation parameters
string sym1 = input.string("ES1!", "Long Leg (e.g., ES1!)")
string sym2 = input.string("NQ1!", "Short Leg (e.g., NQ1!)")
string spreadType = input.string("Absolute", "Spread Type", options=["Absolute", "Percentage", "Ratio"])

// Smoothing and baseline
int smaLength = input.int(20, "SMA Length for Spread", minval=1)
bool showSMA = input.bool(true, "Show SMA of Spread")
float baselineLevel = input.float(0, "Baseline Level")

// Fetch prices from both symbols
float price1 = request.security(sym1, timeframe.period, close)
float price2 = request.security(sym2, timeframe.period, close)

// Calculate spread based on type selected
float spread = na
if spreadType == "Absolute"
    spread := price1 - price2
else if spreadType == "Percentage"
    spread := ((price1 - price2) / price2) * 100
else if spreadType == "Ratio"
    spread := price1 / price2

// Moving average of the spread for trend
float spreadSMA = ta.sma(spread, smaLength)

// Plot spread and baseline
plot(spread, "Spread", color=color.new(color.blue, 0), linewidth=2)
plot(showSMA ? spreadSMA : na, "Spread SMA", color=color.new(color.orange, 0), linewidth=1, style=plot.style_line)
hline(baselineLevel, "Baseline", color=color.gray, linestyle=hline.style_dashed, linewidth=1)

// Highlighting for extreme deviations (user-defined bands)
float upperBand = baselineLevel + input.float(5, "Upper Band Offset")
float lowerBand = baselineLevel - input.float(5, "Lower Band Offset")
hline(upperBand, "Upper Band", color=color.new(color.red, 50), linestyle=hline.style_dotted)
hline(lowerBand, "Lower Band", color=color.new(color.green, 50), linestyle=hline.style_dotted)

// Background coloring for band breaks
bgcolor(spread > upperBand ? color.new(color.red, 80) : spread < lowerBand ? color.new(color.green, 80) : na)

How the code works

The indicator calls request.security() to retrieve the closing price of both input symbols asynchronously without introducing lookahead bias, ensuring that prices are fetched at the current bar's timestamp only [1]. Users select two futures symbols (e.g., ES1! For E-mini S&P 500 and NQ1! For E-mini Nasdaq 100) and a spread calculation method: absolute (raw price difference), percentage (change relative to the short leg's price), or ratio (multiplicative relationship).

The spread is then smoothed using a simple moving average over a configurable lookback period. This SMA filters noise while preserving the underlying trend in the spread's behaviour. A user-defined baseline (typically zero for absolute spreads) and surrounding bands (upper and lower offsets) mark the normal trading range, with background colour fills highlighting when the spread breaks those bounds. This visual aid helps traders quickly identify when a spread moves beyond its historical range.

All inputs are fully parameterized, permitting rapid adjustment without recompiling the script. The indicator generates no alerts or orders; traders apply their own decision rules externally.

Reading it on a chart

Apply the indicator to any chart with a single contract symbol (preferably a rolled futures contract or continuous contract data series). Set the two input symbols to the contracts of interest. For calendar spreads between contract months (e.g., ES1! Versus ES2!), the spread typically oscillates around a small positive or negative value reflecting the term structure and carry cost; widening spreads may signal increased uncertainty or demand imbalances between maturities [2].

For intercommodity spreads such as crude oil (CL) and gasoline (RB) or crude and heating oil (HO), the spread reflects the relative value of refined products and is sensitive to refinery use, seasonal demand, and geopolitical supply shocks. A spread that crosses above the upper band suggests one contract is outpacing the other; traders may interpret this as a potential reversion candidate (if the spread is mean-reverting over the timeframe examined) or a trend break (if the relationship has shifted fundamentally).

The SMA smooths intraday noise, helping traders distinguish between short-term reversals and genuine regime changes. The baseline and bands serve as reference points; they do not automatically imply support, resistance, or trading signals, but rather anchor visual analysis. Traders must examine the spread's historical distribution, the correlation between the two contracts, and the economic drivers of the relationship before acting on band crossings.

Limitations

Spread analysis rests on the assumption that two contracts maintain a stable or predictable relationship, but this assumption frequently breaks down:

  1. Contract roll-over risk: Futures contracts approach expiration and are rolled to later months. At roll dates, the spread may spike sharply not because of a fundamental change in the underlying relationship but because of liquidity migration between contract months [3]. Continuous or back-adjusted contract series mitigate this but introduce their own distortions. The indicator does not automatically handle rolls; the user must manage contract switching manually.

  2. Basis and arbitrage bounds: The spread between related contracts is constrained by arbitrage and carry costs, but those bounds are wider and more volatile than casual analysis suggests. For example, the spread between crude oil futures and refined product futures can widen significantly during supply disruptions even when arbitrage relationships remain intact. The fixed upper and lower bands in this indicator cannot adapt to these shifting boundaries.

  3. Non-stationary relationships: Many spreads are not mean-reverting or stationary, meaning the spread does not oscillate around a fixed level or return to historical averages with statistical regularity. Fundamental shifts in supply, demand, regulatory policy, or market structure can cause permanent or long-lasting shifts in the spread [4]. An SMA of a non-stationary series provides little predictive value and may mislead traders into false fade trades.

  4. Correlation and causality confusion: Two related futures contracts may be correlated without one being a reliable hedge or relative-value trade for the other. Correlation measures co-movement; it does not ensure that trading one contract to offset the other will reduce risk as intended. This is particularly important when constructing hedges with the spread.

  5. Tick size and precision: Futures contracts have different tick sizes and precision (e.g., crude oil in cents per barrel, equity index futures in quarter-points). Small rounding or contract specification differences can compound into spreads that appear wider or narrower than they are when prices are normalized differently. The percentage and ratio calculation options mitigate this somewhat, but users must verify the data carefully.

  6. Intraday liquidity gaps: The indicator plots spread changes at every bar, but during illiquid market hours (e.g., overnight in US equity index futures), one or both legs may trade few or no contracts. Spreads during those periods may not reflect the true economic relationship and can whipsaw the bands shown on the chart.

This indicator is a visualization tool; it does not forecast spreads, confirm reversals, or identify profit opportunities. Spread trading requires understanding the fundamentals driving both contracts, the statistical properties of the spread over the trader's intended holding period, and the costs and risks of entry, exit, and hold. No chart display alone can substitute for that analysis.

Key definitions

Calendar spread: The price difference between two futures contracts of the same underlying commodity or index but different expiration months.

Intercommodity spread: The price difference between futures contracts on related but distinct products, such as crude oil and refined petroleum products.

Basis: The difference between the spot price (immediate delivery) of a commodity and the price of its corresponding futures contract.

Continuous contract series: A synthetic price history created by chaining successive futures contracts (e.g., the front month through roll dates), adjusted to smooth discontinuities.

Mean reversion: The tendency of a price or price difference to return to its historical average over time; spreads are not guaranteed to be mean-reverting.

Arbitrage: The simultaneous purchase of one contract and sale of another to exploit temporary price differences, subject to transaction costs and carry charges.

References

  1. TradingView, "Pine Script v6 Reference, request.security()," TradingView Help Center. Https://www.tradingview.com/pine-script-reference/v5/#fun_request.security

  2. CME Group, "E-mini S&P 500 Futures Contract Specifications," CME Group. Https://www.cmegroup.com/markets/equity/sp-500/es.html

  3. CME Equity Index Futures User Guide, "Understanding Contract Rolls," CME Group. Https://www.cmegroup.com/education/

  4. Schwarz, G., et al., "Mean Reversion in Commodity Futures," working paper, NBER (2016). Https://doi.org/10.3386/w22965


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-09-13. Educational research on historical data, not financial advice.

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. Found an error? Email support@prop-ledger.org and the paper is corrected or withdrawn.