Spread Tracker: Dual-Contract Price Differential
A spread tracker displays the price difference between two related futures contracts on a single chart [3], helping traders identify relative value and convergence patterns. This is essential for spread traders, hedgers, and relative-value strategists who monitor contracts that should move together but diverge due to supply shocks, carry costs [5], seasonality, or market dislocations.
//@version=6
indicator(title="Spread Tracker", shorttitle="Spread", overlay=false,
max_boxes_count=500, max_labels_count=500)
// ===== INPUTS =====
symbol1 = input.symbol(defval="NYMEX:CL1!", title="First Contract")
symbol2 = input.symbol(defval="NYMEX:BZ1!", title="Second Contract")
maLen = input.int(defval=9, title="MA Period", minval=1)
showMa = input.bool(defval=true, title="Show Moving Average")
showBands = input.bool(defval=true, title="Show Bands (±1 Std Dev)")
// ===== FETCH PRICES =====
close1 = request.security(symbol1, timeframe.period, close)
close2 = request.security(symbol2, timeframe.period, close)
// ===== CALCULATE SPREAD =====
spread = close1 - close2
// ===== SPREAD STATISTICS =====
spreadMa = ta.sma(spread, maLen)
spreadStd = ta.stdev(spread, maLen)
upperBand = spreadMa + spreadStd
lowerBand = spreadMa - spreadStd
// ===== PLOTS =====
plot(spread, title="Spread", color=color.new(color.blue, 0), linewidth=2)
plot(showMa ? spreadMa : na, title="MA", color=color.new(color.orange, 0), linewidth=1)
plot(showBands ? upperBand : na, title="Upper Band", color=color.new(color.gray, 50), linewidth=1, linestyle=line.dotted)
plot(showBands ? lowerBand : na, title="Lower Band", color=color.new(color.gray, 50), linewidth=1, linestyle=line.dotted)
hline(0, title="Zero Line", color=color.gray, linestyle=hline.dashed, linewidth=1)
// ===== TABLE DISPLAY =====
if barstate.islast
tbl = table.new(position=position.top_right, columns=2, rows=3, border_color=color.gray, border_width=1)
table.cell(tbl, 0, 0, str.tostring(symbol1), text_size=size.small)
table.cell(tbl, 1, 0, str.tostring(symbol2), text_size=size.small)
table.cell(tbl, 0, 1, str.format("{0:.2f}", close1), text_size=size.small)
table.cell(tbl, 1, 1, str.format("{0:.2f}", close2), text_size=size.small)
table.cell(tbl, 0, 2, str.format("Spread: {0:.4f}", spread), text_size=size.small, bgcolor=spread > spreadMa ? color.new(color.green, 80) : color.new(color.red, 80))
How the code works
The script fetches closing prices from two user-selected futures contracts using request.security() [6], which pulls data without introducing lookahead bias [6]. The difference between the first contract's close and the second contract's close is computed on every bar as the spread value.
A simple moving average of the spread, calculated over a configurable period (default 9 bars), establishes a baseline trend. Standard deviation around that moving average is computed using ta.stdev() [6], then added and subtracted to create upper and lower bands; these mark typical historical variation, helping traders spot extremes.
The plot layer displays the spread as a blue line, optional moving average in orange, and optional ±1 standard-deviation bands in dotted gray. A zero line marks where the two contracts are equal in price. A summary table in the top-right corner shows the current prices of both contracts and the live spread value, color-coded green when the spread is above its moving average and red below.
No historical data is requested beyond the current timeframe; the indicator repaints only when the current bar closes [6], making it safe for live trading analysis.
Reading it on a chart
A rising spread line indicates the first contract is strengthening relative to the second [3]. A falling spread indicates weakness. When the spread is at the upper band, it is trading at an extreme relative to recent history [3]; similarly, at the lower band it represents an outsized discount.
Mean reversion traders may look for spreads that exceed the bands and reverse toward the moving average [3]. Trend followers might trade the direction of the spread itself or monitor when it breaks above or below its moving average. Hedgers verify that their long and short legs remain correlated; a widening or unexpected spread movement may signal new risk.
Convergence is the most common trade: if the spread is historically 5.00 but temporarily 8.00, betting on a return to 5.00 (by buying contract 2, selling contract 1, or unwinding both legs at different speeds) is a classic relative-value position [3]. The moving average and bands give context for what is "normal" versus what is an outlier.
Limitations
Multi-instrument data requires availability: Not all charting platforms or time periods support simultaneous data from two arbitrary futures contracts [6]. Some exchanges or brokers may not offer historical data for both legs, or data misalignment (different session hours, holidays, or contract roll dates) can distort the spread. Always verify that both instruments have complete, aligned data for the period studied.
Spread is not risk-adjusted: A 10-unit absolute spread from contract 1 minus contract 2 does not reflect the relative volatility or notional size of each position [3]. If contract 1 is worth $100,000 per point and contract 2 is worth $50,000 per point, a raw spread hides the true exposure. Traders must manually adjust position sizing to hedge the spread, or define the spread as a ratio or percentage.
Carry, storage, and financing costs are invisible: Futures spreads often reflect interest rates, storage, convenience yields, and time decay [5]. A crude oil spread may widen or narrow not because of supply shocks but because financing rates changed or seasonal storage demand shifted [5]. The indicator shows the symptom but not the cause; fundamental analysis is still required.
Contract roll risk: Most liquid futures have front-month and deferred contracts [1]; this indicator does not automatically handle rolls. When the front contract expires or liquidity shifts, the spread can gap sharply even if the underlying supply/demand picture is stable. Users must select rolling contracts manually or switch symbols as needed.
Bands assume stationarity: Standard deviation bands assume the spread's distribution is stable over the lookback period [3]. In markets with regime shifts (e.g., geopolitical crisis, policy change), bands calculated from the last 9 bars may be too narrow or wide. They are a rough guide, not a guarantee.
No causal link to profitability: A narrow spread does not mean a trade will be profitable; a wide spread does not guarantee convergence. Spreads can widen indefinitely if supply/demand fundamentals shift, or remain wide for years if structural factors persist. The indicator identifies the spread's state, not whether trading it is sound.
Key definitions
Futures spread: The difference in price between two related futures contracts, typically the same commodity or asset at different expiration dates or on different exchanges [3].
Mean reversion: A trading premise that prices or differences that move away from a historical average tend to return to it over time [3].
Standard deviation: A measure of the dispersion or volatility of a data series around its mean [3]; used here to quantify typical spread fluctuation.
Request.security(): A Pine Script function that fetches OHLC data from a specified symbol and timeframe without introducing lookahead bias [6].
Carry: The cost of holding a physical commodity (storage, insurance, financing) or the benefit received from holding it (convenience yield) [5], reflected in the price difference between near and deferred contracts.
Repainting: Behavior in which an indicator changes its value on past bars after new data arrives; avoided here by using only closed bar data [6].
References
- CME Group, "Crude Oil Futures Specification", CME Group Education, https://www.cmegroup.com/trading/energy/crude-oil.html (primary)
- U.S. Commodity Futures Trading Commission, "Regulation of Futures Markets Under the Commodity Exchange Act", CFTC Rulebook, https://www.cftc.gov/ (primary)
- Hull, J., "Options, Futures, and Other Derivatives", Pearson Finance Textbooks (2021).
- Whaley, R. E., "Understanding the VIX", Journal of Portfolio Management, 2009, (link no longer resolves)
- Brennan, M. J., "The Supply of Storage", American Economic Review, 1958, Vol. 48, No. 1.
- TradingView, "request.security() Function Reference", Pine Script Documentation, https://www.tradingview.com/pine-script-reference/
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
Consecutive Close Counter
Free open-source Pine Script indicator: consecutive close counter with streak statistics table. Full code and a plain-English walkthrough.
Swing Structure & Break of Structure (BOS) / Change of Character (CHoCH) Marker
Free open-source Pine Script indicator: swing high/low structure marker (BOS and CHoCH labels). Full code and a plain-English walkthrough.
Prior Day High Low Settlement
Free open-source Pine Script indicator: prior day high, low, and settlement levels. Full code and a plain-English walkthrough.