MomentumPine Script v6

Commodity Channel Index Pine Script — Complete TradingView Guide

The Commodity Channel Index (CCI) is a momentum oscillator built into Pine Script v6 via ta.cci(source, length). The CCI measures how far price deviates from its statistical mean using the typical price (hlc3) over a lookback period, with readings above +100 signaling overbought conditions and below −100 signaling oversold conditions. The CCI default period is 20 bars — the same value Donald Lambert used when he published the indicator in 1980. Unlike bounded oscillators such as RSI, CCI is unbounded and can exceed ±200 or ±300 during strong trending moves. This guide covers the complete Pine Script v6 implementation using ta.cci(), all configurable parameters with recommended ranges, three concrete CCI trading strategies including overbought/oversold reversals and zero-line crossovers, plus a five-step guide to generating CCI scripts instantly with Pineify.

What Is the Commodity Channel Index?

The Commodity Channel Index (CCI) is a momentum oscillator that measures how far the current typical price has deviated from its statistical mean, used to identify overbought and oversold conditions, trend direction, and price cycle extremes. Unlike the Relative Strength Index (RSI), which is bounded between 0 and 100, the CCI is an unbounded oscillator — it can reach +200, +300, or beyond during powerful trending moves, and similarly deep negative values during sustained sell-offs.

Donald Lambert developed the Commodity Channel Index and published it in Commodities magazine in October 1980. Lambert originally designed the indicator to identify cyclical tops and bottoms in commodity futures markets — he believed commodities moved in natural cycles of 20 to 30 days, and the CCI was intended to mark the turning points of those cycles. The ±100 thresholds were chosen mathematically: Lambert selected the constant 0.015 in the denominator so that approximately 70–80% of CCI values would fall between −100 and +100 under normal market conditions. Values outside that range indicated an unusual price extreme — a potential cycle turn.

Core formula: CCI = (Typical Price − SMA of Typical Price) ÷ (0.015 × Mean Deviation), where Typical Price = (High + Low + Close) ÷ 3. The Mean Deviation is the average of the absolute differences between each bar's typical price and the SMA of typical price over the period. In Pine Script v6, the entire calculation is handled by ta.cci(hlc3, 20), where hlc3 is the built-in typical price series.

The CCI applies to all liquid asset classes: stocks, crypto, forex, and futures. It performs well in both trending markets — where extreme readings above +200 confirm strong momentum — and ranging markets, where the ±100 bands serve as reliable reversal zones. Best timeframes are 15m to Daily charts. On the daily chart, CCI 20 is the most common setting for swing trading. On intraday charts (5m–1H), CCI 14 is preferred for faster signal generation. On weekly charts, CCI 20 or CCI 40 can identify major cycle extremes in stocks and commodities.

Best Markets

Stocks · Crypto · Forex · Futures

Best Timeframes

15m, 1H, 4H, Daily

Overlay

No — separate oscillator panel

CCI Pine Script Code Example

The code below plots a 20-period CCI oscillator using Pine Script v6's built-in ta.cci(hlc3, 20) function, with dashed ±100 reference bands and a blue shaded background between them. To add it to TradingView, open the Pine Script editor with Alt+P, paste the code, and click Add to chart. The CCI will appear in a separate panel below the price chart. Change the 20 period to adjust sensitivity — lower values react faster, higher values are smoother.

Pine Script v6
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//@version=6
indicator(title="Commodity Channel Index", overlay=false, max_labels_count=500)

// CCI — measures price deviation from its statistical mean over a given period
p_ind_1 = ta.cci(hlc3, 20) // CCI with default period 20, source hlc3 (typical price)

// Plot the CCI line
plot(p_ind_1, "CCI", color.rgb(41, 98, 255, 0), 1)

// Overbought / oversold reference bands
p_ind_1_band1 = hline(100, "CCI - Upper Band", color=#787B86, linestyle=hline.style_dashed)
hline(0, "CCI - Middle Band", color=color.new(#787B86, 50))
p_ind_1_band0 = hline(-100, "CCI - Lower Band", color=#787B86, linestyle=hline.style_dashed)
fill(p_ind_1_band1, p_ind_1_band0, color=color.rgb(33, 150, 243, 90), title="CCI - Background")

Chart Preview

Commodity Channel Index indicator Pine Script code example in TradingView — CCI 20 with overbought/oversold bands

CCI Parameters

ParameterDefault ValueDescriptionRecommended Range
sourcehlc3The price series used for the calculation. The default hlc3 is the typical price: (high + low + close) / 3. Can be changed to close, hl2, or any numeric series.hlc3 (recommended), close, hl2
length20The lookback period in bars. Controls how many bars are used to calculate the SMA and mean deviation. Smaller values produce a more sensitive, faster- reacting CCI with more signals; larger values produce a smoother oscillator with fewer, higher-quality signals.10–50 (most common: 14, 20)
Upper Band+100The overbought reference level. CCI crossing above +100 signals that price is unusually high relative to its statistical mean. Some traders use +200 as an extreme overbought level during strong trends.+100 (standard), +200 (extreme)
Lower Band−100The oversold reference level. CCI crossing below −100 signals that price is unusually low relative to its statistical mean. Some traders use −200 as an extreme oversold level during strong downtrends.−100 (standard), −200 (extreme)

Tuning Guide by Trading Style

  • Scalping (5m–15m charts): CCI 10–14 — fast oscillator for quick overbought/oversold entries; expect frequent signals and more noise
  • Day trading (15m–1H charts): CCI 14–20 — balanced responsiveness for intraday cycle identification with ±100 reversal triggers
  • Swing trading (4H–Daily charts): CCI 20 — Lambert's original period; best for identifying multi-day price cycle extremes
  • Position trading (Daily–Weekly charts): CCI 40–50 — smoother oscillator for major cycle turns in commodities, indices, and sector ETFs

CCI Trading Strategies

The CCI is most effective as an overbought/oversold reversal detector in ranging markets and as a momentum confirmation tool in trending markets. Below are three concrete strategies with specific entry and exit conditions.

Strategy 1 — CCI Overbought/Oversold Reversal

Market environment: ranging and mean-reverting markets · Best timeframe: Daily, 4H

The classic CCI reversal strategy enters long when CCI returns above −100 (oversold recovery) and short when CCI falls back below +100 (overbought rejection). Combine with RSI(14) below 40 to confirm genuine oversold conditions and reduce false entries.

  1. Calculate CCI: cci = ta.cci(hlc3, 20)
  2. Add RSI confirmation: rsi = ta.rsi(close, 14)
  3. Long entry: ta.crossover(cci, -100) AND rsi < 45 — CCI exits oversold zone with RSI confirming weakness
  4. Short entry: ta.crossunder(cci, 100) AND rsi > 55 — CCI exits overbought zone with RSI confirming strength
  5. Exit: CCI returns to the zero line (take profit at mean reversion) or CCI crosses back into the opposite extreme band (stop loss)

Strategy 2 — CCI Zero-Line Crossover Trend Follow

Market environment: trending markets · Best timeframe: 1H, Daily

The CCI zero-line crossover uses the 0 level as a trend-direction signal. When CCI crosses above 0, bulls are in control of the current period; below 0, bears are. Use SMA 200 on the daily chart as a macro filter to avoid counter-trend trades.

  1. Calculate macro trend filter: sma200 = ta.sma(close, 200)
  2. Calculate CCI: cci = ta.cci(hlc3, 20)
  3. Long entry: ta.crossover(cci, 0) AND close > sma200 — CCI turns bullish in a bull market
  4. Avoid: zero-line crossovers when price is below SMA 200 — these are counter-trend longs in a bear market and have lower win rates
  5. Exit: ta.crossunder(cci, 0) — CCI crosses back below zero, momentum has shifted

Strategy 3 — CCI Divergence + Bollinger Bands Confirmation

Market environment: trending markets approaching exhaustion · Best timeframe: 4H, Daily

CCI divergence — price making new highs while CCI makes lower highs — is one of the earliest reversal warnings. Pair with Bollinger Bands(20, 2.0): price touching the upper band while CCI diverges confirms the overextended move. In Pine Script v6: [bbMid, bbUpper, bbLower] = ta.bb(close, 20, 2.0).

  1. Calculate Bollinger Bands: [_, bbUpper, bbLower] = ta.bb(close, 20, 2.0)
  2. Calculate CCI: cci = ta.cci(hlc3, 20)
  3. Bearish divergence signal: price makes a higher high AND closes at or above bbUpper AND CCI makes a lower high compared to the prior swing — momentum is weakening
  4. Bullish divergence signal: price makes a lower low AND closes at or below bbLower AND CCI makes a higher low — selling pressure is exhausting
  5. Entry: wait for CCI to cross back above −100 (for bull divergence) or below +100 (for bear divergence) to confirm the reversal before entering

Disclaimer: The strategies above are for educational purposes only and do not constitute investment advice. Past performance does not guarantee future results. Always apply proper risk management and position sizing.

How to Generate the CCI Indicator in Pineify

  1. 1

    Open Pineify

    Go to pineify.app and sign in — a free account is sufficient to generate CCI indicators.

  2. 2

    Click "New Indicator"

    Select "Indicator" as the script type from the creation menu on the dashboard.

  3. 3

    Describe the CCI configuration you want

    Type a prompt such as: "Plot a 20-period Commodity Channel Index using ta.cci(hlc3, 20) with ±100 overbought/oversold bands." Pineify's AI Coding Agent generates the complete Pine Script v6 code in seconds.

  4. 4

    Copy to TradingView

    Click "Copy to TradingView" to copy the generated code, then open the TradingView Pine Script editor (Alt+P), paste the code, and click "Add to chart".

  5. 5

    Adjust the length parameter

    In the TradingView indicator settings panel, change the CCI length (e.g., from 20 to 14 for faster signals or 40 for smoother readings) to match your trading style — no code editing required.

Frequently Asked Questions

Build Your CCI Indicator in Seconds

Skip the manual coding. Pineify's AI Coding Agent generates complete, ready-to-use Pine Script indicators — including CCI overbought/oversold strategies with RSI and Bollinger Bands confirmation — instantly for free.

Try Pineify Free