Concept 09 / 52·Momentum·Unbounded oscillators
‹ Chandelier ExitDay-of-Week Effects ›

Commodity Channel Index (CCI) in Pine Script

CCI · commodity channel index · Lambert's CCI · CCI 20

An unbounded oscillator that measures how far typical price sits from its moving average in units of mean deviation, scaled so that most readings fall between −100 and +100.

Reads best on: Futures and commodities, which it was built for, plus liquid stocks and indices on 15-minute to daily charts. The regime decides between the reversion and the trend read.
On this page: the Pine v6 script, checked, drawn on real NVDA bars. Backtest it free, costs charged, every trade on the chart.
01

Definition

The Commodity Channel Index (CCI) is an unbounded momentum oscillator. It takes the typical price of each bar, subtracts a simple moving average of typical price, and divides by the average distance of typical price from that average over the same window. The result says how unusual the current distance from the mean is compared with the recent norm. A constant of 0.015 scales it so that roughly three quarters of readings fall between −100 and +100. Unlike RSI or the stochastic, nothing caps it: in a strong move CCI can reach 300 or beyond.

What CCI measures is a standardised deviation from the mean, close to a z-score but using mean absolute deviation instead of standard deviation. That is why it sits in the same family as MACD and rate of change: its scale depends on the instrument's recent behaviour rather than on a fixed range. A reading of +100 means the typical price is one and a half mean deviations above its average. That can mean a stretched market about to revert, or a trend that has just begun. The two ways of reading CCI come from that ambiguity.

Donald Lambert published CCI in 1980 for commodity cycles, hence the name, and suggested a length of about a third of the dominant cycle. His original rule was trend-following: long when CCI rises above +100 and exit when it drops back below, with the mirror for shorts below −100. The more common modern use is the reverse, treating +100 and −100 as overbought and oversold and trading the return inside them. Platforms default to 20 bars, with 14 as the second most common setting.

On the chart CCI spends most bars between the lines and breaks out of them in bursts. The moves beyond the lines come in clusters during trends and as single spikes during ranges, so the same reading can be the start of a leg or the end of one. The zero line is the moving average itself: CCI above zero means typical price is above its 20-bar average. The library's script takes the reversion read. It marks Long when CCI climbs back above −100 and Short when it drops back below +100, and colours the line red above the upper level and green below the lower one.

02

Reading the chart

Read the regime first, because the same CCI reading is a reversal setup in a range and a continuation setup in a trend.

  1. Add a 20-period CCI in a pane with lines at +100, −100 and 0. Check the source: the classic calculation uses typical price, the average of high, low and close, not the close alone.
  2. Note the regime the oscillator is in. Long stretches above +100 with shallow dips to zero say the market is trending up; a sequence of spikes past both lines with a return to zero each time says it is ranging.
  3. Decide which read applies. In a range, a spike beyond a line and the cross back inside is a reversion signal. In a trend, the first move beyond the line in the trend's direction is a continuation entry, which was Lambert's rule.
  4. Watch the cross back inside the lines. The library's script marks the cross above −100 as Long and the cross below +100 as Short; that is the reversion read, and it fits ranges and pullbacks with the trend.
  5. Use the zero line for the trend. CCI holding above zero keeps typical price above its average; a drop through zero after a run above +100 is often the first sign the leg is done.
  6. Check for divergence at the spikes. A higher price high with a lower CCI peak says the move is stretching less against its own norm, which often precedes the return to zero.
03

The maths

CCI standardises the distance between typical price and its moving average by the mean absolute deviation over the same window.

TPt=Ht+Lt+Ct3\mathrm{TP}_t = \frac{H_t + L_t + C_t}{3}
MAt=1n∑i=t−n+1tTPi\mathrm{MA}_t = \frac{1}{n} \sum_{i=t-n+1}^{t} \mathrm{TP}_i
MDt=1n∑i=t−n+1t∣TPi−MAt∣\mathrm{MD}_t = \frac{1}{n} \sum_{i=t-n+1}^{t} \lvert \mathrm{TP}_i - \mathrm{MA}_t \rvert
CCIt=TPt−MAt0.015 MDt\mathrm{CCI}_t = \frac{\mathrm{TP}_t - \mathrm{MA}_t}{0.015 \, \mathrm{MD}_t}
HtH_thigh of bar t
LtL_tlow of bar t
CtC_tclose of bar t
TPt\mathrm{TP}_ttypical price of bar t
MAt\mathrm{MA}_tsimple moving average of typical price over the last n bars
MDt\mathrm{MD}_tmean absolute deviation of typical price from MA_t over the same n bars
nnthe CCI length, 20 by default
0.0150.015Lambert's scaling constant
CCIt\mathrm{CCI}_tthe index at bar t, unbounded

Mean deviation is the average of absolute distances from the window's own average, not the standard deviation; it is smaller and less affected by one outlier bar.

Lambert chose 0.015 so that about 70 to 80 percent of values land between −100 and +100; without it the natural range would be roughly −1.5 to +1.5.

Because the scale is set by the instrument's own recent deviation, CCI readings are comparable across markets even though the index is unbounded.

Some platforms let you replace typical price with the close; that makes the line jumpier on bars with long wicks.

04

Inputs that matter

InputTypicalWhat changing it does
Length20Shorter lengths make CCI cross the lines on most swings and suit intraday reversion; longer lengths hold it near zero and reserve the lines for moves that stand out over weeks.
Level100Raising it to 150 or 200 waits for larger deviations before a signal, which cuts whipsaws in trends; lowering it towards 50 gives earlier and more frequent signals.
Sourcetypical price (hlc3)Using the close instead responds faster to the last print and adds noise on bars with long wicks.
05

In practice

  • As a reversion oscillator: the rule fades the spike, going long on the cross back above −100 and short on the cross back below +100, which is what the library's script marks as Long and Short on confirmed bars.
  • As Lambert's trend trigger: the rule enters long when CCI first rises above +100 and exits when it drops back below it, with the mirror for shorts. That read suits trending futures and fails in ranges.
  • As a pullback tool in a trend: with the trend set by a moving average, the rule goes long on the cross back above −100 in an uptrend and ignores the overbought readings, which are the trend expressing itself.
  • As a zero-line trend filter: CCI above zero means typical price is above its average; requiring that before a long breakout removes the entries taken against the local mean.
  • As a stretch gauge across markets: because the deviation is standardised, a CCI of +250 on gold and on a stock index say the same thing about each market's own norm. That helps when scanning a watchlist.
  • As a divergence detector at spikes: a series of higher price highs with lower CCI peaks says each push is smaller against its own norm, a common precursor to the return to zero.
06

Where it goes wrong

  • Mixing the two reads. Fading +100 in a trend and going long at +100 in a range both lose; decide from the chart which regime you are in before choosing the rule.
  • Treating +100 as a ceiling. CCI is unbounded and 300 is common in a strong move; there is no level at which it must turn.
  • Using the close instead of typical price without knowing it. Platforms differ; a close-based CCI is noisier and its signals do not line up with a typical-price one.
  • Reading a 20-period CCI on a timeframe that does not match the swing. On 1-minute bars it covers 20 minutes; lengthen it or move up a timeframe.
07

Compared with

RSI. RSI is bounded from 0 to 100 and reads how one-sided the closes have been. CCI is unbounded and reads how far price sits from its own average in the instrument's normal units. RSI saturates in a trend; CCI keeps growing, which makes CCI the better trend read and RSI the better range read.

Bollinger Bands. Bollinger Bands put a standard-deviation envelope around a 20-bar average on the price chart; CCI does almost the same sum in a pane, using mean absolute deviation and typical price. A close at the upper band and a CCI near +100 to +150 describe the same stretch. The bands show the level; CCI shows the number.

Stochastic Oscillator. The stochastic asks where the close sits inside the recent high-low range, so it is capped at 100 and swings edge to edge in a range. CCI asks how far price is from its mean, so it can run without limit. The stochastic times entries inside a range; CCI measures the size of a departure from the mean.

Rate of Change. Rate of change is the raw percentage change over n bars with no normalisation, so its scale differs from market to market. CCI divides by the instrument's own deviation, which is why the 100 lines mean the same thing everywhere. ROC reads speed; CCI reads distance from the mean in normal units.

08

Build it in Quant

Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.

Open Commodity Channel Index (CCI) on the workbench chart
Drawn on real data; then audit, backtest and refine in conversation.
Open in Quant →
09

Questions

  • What does the 0.015 constant do?

    It scales the ratio of deviation to mean deviation so that most readings fall between −100 and +100. Without it a typical reading would sit between −1.5 and +1.5, which is awkward to chart. Lambert chose the number so that about 70 to 80 percent of values land inside the lines, leaving the excursions beyond them rare enough to mean something. It is a display choice, not a statistical threshold.

  • Is CCI overbought at +100?

    Only in a range. +100 means typical price sits one and a half mean deviations above its average, which a trend produces routinely and holds for many bars. In a range that distance is stretched and the cross back below +100 is a short trigger. In a trend the first cross above +100 is a continuation entry, which was Lambert's original rule. Read the regime first.

  • Why can CCI go above 300?

    Because the index is unbounded. It divides the distance from the mean by the average distance over the window, and during a breakout the current distance can be many times the recent norm. RSI cannot do this because its formula caps at 100. Extreme CCI readings say the move is exceptional for the instrument, not that it must reverse.

  • What length should I use for CCI?

    20 is the default on most platforms and reads the same swing as a 20-bar moving average. 14 is faster and common on intraday charts. Lambert suggested a third of the dominant cycle length, so a 60-bar cycle gives 20. Longer settings such as 50 keep CCI close to zero and reserve the lines for large, slow deviations.

  • What does the library's CCI script do?

    It calculates a 20-period CCI on typical price and plots it with dashed lines at +100 and −100 and a dotted zero line. The line is red above the upper level and green below the lower one. It marks Long when CCI crosses back above −100 and Short when it crosses back below +100, on confirmed bars, with an optional alert on each. The level is one input, so 150 or 200 is a single change.

  • How is CCI different from a z-score?

    A z-score divides the distance from the mean by the standard deviation; CCI divides by the mean absolute deviation and multiplies by a constant. Mean deviation is smaller and less sensitive to a single outlier bar, so CCI reacts a little more to moderate moves. In practice they draw similar shapes, and the 100 lines sit 1.5 mean deviations out, roughly 1.2 standard deviations on data that is close to normal.