Futures Spread Tracker
Spread trading tracks the price difference between two related futures contracts, typically between different expiration dates of the same contract (calendar spread) or between linked commodities or indices. This indicator plots the spread in real time, helping traders identify mean reversion opportunities, basis widening or tightening, and arbitrage signals. Spread traders, commodity hedge funds, and systematic traders use this to monitor cross-contract relationships that often exhibit more stable patterns than outright prices.
//@version=6
indicator("Futures Spread Tracker", overlay=false, timeframe="")
// Inputs
symbol2 = input.string("", title="Second Contract Symbol",
tooltip="Enter full symbol path, e.g. 'CME:ESZ25' for E-mini S&P Dec 25 or 'CME:CLF26' for WTI Light Sweet Crude Feb 26")
spreadMA = input.int(10, title="Spread MA Period", minval=1)
showBands = input.bool(true, title="Show Volatility Bands")
bandStdDev = input.float(2.0, title="Band Std Dev Multiplier", minval=0.5)
showZeroLine = input.bool(true, title="Show Zero Reference")
// Validate symbol2
if symbol2 == ""
runtime.error("Please enter the second contract symbol in inputs")
// Fetch prices for both contracts
price1 = close // Primary chart symbol
price2 = request.security(symbol2, timeframe.period, close)
// Calculate spread: Contract 1 - Contract 2
spread = price1 - price2
// Calculate smoothed spread and volatility
spreadMA_val = ta.sma(spread, spreadMA)
spreadStd = ta.stdev(spread, spreadMA)
// Upper and lower volatility bands
upperBand = spreadMA_val + (spreadStd * bandStdDev)
lowerBand = spreadMA_val - (spreadStd * bandStdDev)
// Plots
plot(spread, title="Spread", color=color.new(color.blue, 0), linewidth=2)
plot(spreadMA_val, title="Spread MA", color=color.new(color.orange, 0), linewidth=1)
if showBands
plot(upperBand, title="Upper Band", color=color.new(color.red, 60), linewidth=1, style=plot.style_dashed)
plot(lowerBand, title="Lower Band", color=color.new(color.green, 60), linewidth=1, style=plot.style_dashed)
if showZeroLine
hline(0, "Zero Line", color=color.new(color.gray, 50), linestyle=hline.style_dotted)
// Fill between bands for visual clarity
fill(plot(upperBand), plot(lowerBand), color=color.new(color.blue, 90), title="Band Fill")
How the code works
The indicator takes the closing price of the chart's primary symbol (Contract 1) and compares it to the closing price of a second contract specified in inputs via request.security(). The difference is plotted as the spread; a positive value means Contract 1 trades above Contract 2.
A simple moving average of the spread is calculated over a user-defined period (default 10 bars). This smoothed line filters noise and highlights the spread's intermediate trend. The volatility bands are computed by adding and subtracting a multiple of the spread's standard deviation from the moving average. These bands create a dynamic range that widens during volatile periods and contracts during stable ones.
The zero reference line provides visual context: when the spread drifts far above or below zero relative to its bands, it signals potential mean-reversion setups. All plots use semi-transparent colors to avoid visual clutter on the chart.
Reading it on a chart
A trader places this indicator on the primary contract (e.g., ES H26 for E-mini S&P 500 March 2026) and inputs the secondary contract (e.g., ES M26 for June 2026 E-mini). The spread will typically oscillate around a small range if the contracts are tightly linked by arbitrage.
When the spread approaches the upper band, the front contract has become relatively expensive compared to the back contract, a potential short-spread signal. Conversely, spread near the lower band may signal a long-spread opportunity. Sudden spikes or breaks beyond the bands warn of structural shifts (e.g., unexpected supply shocks affecting one expiration more than another, or shifts in term structure).
Traders also watch for spread convergence as contracts move toward expiration or when exogenous events equalize pricing pressure across both.
Limitations
This indicator has several material constraints. First, Pine Script indicators run on a single chart timeframe; comparing contracts at different timeframes requires manual symbol entry and careful interpretation. The request.security() call fetches data at the chart's current timeframe, so spreads computed on a 15-minute chart will not match a daily-chart view, timing and bar alignment matter.
Second, the indicator assumes both contracts use compatible units and pricing (e.g., both in price points or both in dollar terms). Spreads between contracts with different denominations (e.g., crude oil priced per barrel and natural gas per MMBtu) require manual conversion and are outside the scope of this calculation.
Third, standard deviation bands assume the spread is normally distributed and stationary (mean-reverting). During market dislocations, term-structure changes, or delivery periods, spreads behave in regime shifts that break this assumption. The bands are descriptive, not predictive.
Fourth, liquidity in the second contract affects execution risk. A wide bid-ask spread or low volume can make theoretical spread trades costly or impossible to fill, negating the signal.
Lastly, the indicator does not account for transaction costs, margin requirements, or rollover logistics, all material in real spread trading. Use it as a monitoring tool, not a decision engine.
Key definitions
Calendar spread: a futures spread between two expiration dates of the same contract, e.g., buying March crude oil and selling June crude oil to profit from changes in term structure [1].
Intercommodity spread: a futures spread between two related but distinct commodities, e.g., crude oil and heating oil, used to hedge or exploit linked price moves [1].
Basis: the difference between the spot or near-contract price and a forward or deferred contract price; spreads track basis dynamics [2].
Term structure: the shape of prices across contract maturities (normal backwardation or contango); spreads quantify these slopes [2].
Mean reversion: the tendency of a price series to oscillate around a long-run average; volatility bands flag when a spread deviates far from its moving average [3].
Arbitrage: buying and selling the same or linked assets simultaneously to lock in a price difference; spread traders exploit temporary mispricings [4].
References
[1] CME Group, "Spread Trading", Education Center (2024). Https://www.cmegroup.com/education
[2] Lombardi, M. J., & Ravazzolo, F., "Commodity Prices and Commodity-Linked Currencies", Journal of International Money and Finance, 65, 52-72 (2016). Doi.org/10.1016/j.jimonfin.2016.02.009
[3] Poterba, J. M., & Summers, L. H., "Mean Reversion in Stock Prices: Evidence and Implications", Journal of Financial Economics, 22(1), 27-59 (1988). Doi.org/10.1016/0304-405X(88)90021-9
[4] CFTC, "An Introduction to Futures and Options", Commodity Futures Trading Commission (2015). Https://www.cftc.gov
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-29. Educational research on historical data, not financial advice.
Keep reading
Early Session Trend/Range Day Classifier
Free open-source Pine Script indicator: trend day vs range day classifier (early session heuristics). Full code and a plain-English walkthrough.
Breadth Proxy: New Highs/New Lows Index
Free open-source Pine Script indicator: new high/new low breadth proxy for a symbol basket. Full code and a plain-English walkthrough.
Premium and Discount Zones from Rolling Midpoint
Free open-source Pine Script indicator: premium and discount zones from a rolling range midpoint. Full code and a plain-English walkthrough.