Futures Contract Roll and Expiry Week Shading
An indicator that highlights the periods when a futures contract is entering its expiry week and has passed expiry (post-roll period). Traders use this to stay aware of contract viability and avoid the technical distortions, liquidity changes and wider spreads that often occur near expiry. Most useful for active futures traders managing roll risk and position timing.
//@version=6
indicator("Contract Roll & Expiry Week Shading", overlay=true)
// Configuration inputs
expiryDayOfMonth = input(15, "Expiry Day of Month", minval=1, maxval=31,
tooltip="Day of month on which the contract typically expires")
daysBeforeExpiry = input(5, "Shade Days Before Expiry", minval=0, maxval=20,
tooltip="How many days before expiry day to start shading expiry week")
daysAfterExpiry = input(3, "Shade Days After Expiry (Roll Period)", minval=0, maxval=10,
tooltip="Days after expiry to shade as roll/transition period")
expiryWeekColor = input(color.new(color.red, 85), "Expiry Week Color")
rollPeriodColor = input(color.new(color.orange, 85), "Roll Period Color")
showLabels = input(true, "Show Day Counter Labels")
// Calculate days until/since expiry
currentDay = dayofmonth(time)
daysUntilExpiry = expiryDayOfMonth - currentDay
// Determine shading regions
isExpiryWeek = daysUntilExpiry >= -daysBeforeExpiry and daysUntilExpiry <= 0
isRollPeriod = daysUntilExpiry < 0 and daysUntilExpiry >= -daysAfterExpiry
// Apply background shading
shadingColor = isExpiryWeek ? expiryWeekColor : isRollPeriod ? rollPeriodColor : na
bgcolor(shadingColor)
// Display countdown label on last bar
if barstate.islast and showLabels
displayText = daysUntilExpiry >= 0 ?
"Expiry in " + str.tostring(daysUntilExpiry) + " days" :
str.tostring(-daysUntilExpiry) + " days post-expiry"
label.new(bar_index, high * 1.005, displayText,
color=isExpiryWeek ? expiryWeekColor : rollPeriodColor,
style=label.style_label_bottom,
textcolor=color.white,
textsize=size.small)
// Alert when contract expires
alertexpr = daysUntilExpiry == 0 and barstate.isconfirmed
alert(alertexpr, "Futures contract expiry day", alert.freq_once_per_bar_close)
How the code works
The indicator calculates how many days remain until the contract's expiry day by subtracting the current day of the month from the user-defined expiry day. This difference drives two shading regions.
When daysUntilExpiry is zero or negative but within the threshold set by daysBeforeExpiry, the indicator shades the background in red (expiry week color). This highlights the period when the contract is approaching maturity and liquidity may begin to migrate to the next contract month.
After the expiry day passes, shading switches to orange (roll period color) for the number of days specified by daysAfterExpiry. This marks the transition window where the old contract is no longer viable for new positions and traders have migrated to the next contract month.
The bar-by-bar counter on the last bar shows how many days remain until expiry (if positive) or how long ago the contract expired (if negative), updated in real time. An alert fires once on the expiry day itself.
Reading it on a chart
Look for the red band approaching from the right side of the chart as the bar count descends to zero. This is the signal that the current contract is becoming less useful for new entries; existing positions should be rolled to the next month. The orange band that appears afterward shows the immediate post-expiry period where volume and liquidity are transitioning, this is the highest-risk zone for slippage if any positions are still held in the expiring contract.
On a daily chart of a contract with mid-month expiry (e.g., crude oil CL), you will see red shading appear around day 10, intensifying as the contract ages. Once expiry day arrives, orange shading marks the 3-5 day period when the next month's contract becomes the focus.
Limitations
This indicator makes a critical simplifying assumption: that all contracts expire on the same day of every month. In reality, futures expiry dates are precise, often tied to the third Friday, a specific day, or a calendar-based rule that varies by contract. A US Treasury note futures contract (ZT) expires on the last business day of the delivery month; Eurodollar futures (GE) expire on the second London banking day before the third Wednesday. This indicator cannot capture those rules without manual updates per contract.
If the expiry day of month is set to 15 but the actual contract expires on the 14th, all shading will be off by one day. Conversely, if you use a continuous futures contract symbol (e.g., one that auto-rolls), the day-of-month will drift across actual expiry boundaries; the shading becomes meaningless after a roll occurs.
The indicator repaint: as the day changes, dayofmonth() updates, so historical bars will exhibit different coloring if viewed on a later date. This is inherent to day-of-month logic and cannot be eliminated without hardcoding contract expiry dates into the script.
The label countdown and alert are calculated on each chart update, so they may fire early or late if the chart is not updated in real time, and the alert can only fire once per bar close.
Users must manually set the correct expiry day for each contract they monitor. There is no automatic detection of contract month from the ticker symbol, so contracts from different months on the same underlying (e.g., CLZ24 vs. CLF25) will use the same expiry day unless the input is changed.
Key definitions
Futures contract expiry: The date on which a futures contract ceases to exist and all open positions must be closed or rolled to the next contract month. No new trades are permitted on an expired contract.
Contract roll: The process of closing a position in an expiring contract month and simultaneously opening the same position in the next contract month to maintain exposure without physical delivery.
Delivery month: The calendar month in which a futures contract matures and is subject to physical or cash settlement; expiry occurs at a specified day within this month.
Liquidity migration: The shift in trading volume and open interest from an expiring contract month to the next contract month, typically accelerating in the week before expiry.
Continuous futures (roll-adjusted): A synthetic price series that automatically splices together contracts across multiple months to create an unbroken historical chart; the splicing introduces gaps or adjustments that do not reflect actual trading.
Slippage: The difference between expected execution price and actual fill price, often widening near contract expiry due to reduced liquidity and wider bid-ask spreads.
References
- CME Group, "Futures Product Specifications: Crude Oil", CME (2024). URL: https://www.cmegroup.com/markets/energy/crude-oil.contractSpecs.html
- CME Group, "Understanding Futures Expiration", CME Education (2024). URL: https://www.cmegroup.com/education/articles/understanding-futures-expiration.html
- Nasdaq, "Futures Contract Specifications and Codes", Nasdaq (2024). URL: https://www.nasdaq.com/market-activity/futures
- CFTC, "Derivatives Markets: An Introduction", Commodity Futures Trading Commission (2013). URL: https://www.cftc.gov/sites/default/files/idc/groups/public/@newsroom/documents/file/oce_derivativesmarkets.pdf
- Pine Script Documentation, "Built-in Functions", TradingView (2025). URL: https://www.tradingview.com/pine-script-reference/v5/
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-08. 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.