You added a CCI to a TradingView chart, saw a line swinging between roughly minus 200 and plus 200, and now you want it in your own script with the length, the levels and the alerts set the way you like. Or you pasted a CCI from somewhere and it draws fine but you cannot tell what any number in it means. Either way the Commodity Channel Index is one of the shorter indicators to understand, and in Pine Script v6 it is one function call. The interesting part is what that call computes, how the zone levels behave, and how to turn a crossing into something you can alert on without it firing on the wrong bar.
This guide builds the indicator from the one-line version up. You will see the formula written out by hand so the built-in stops being a black box, add zone shading and level inputs, mark zone entries and exits, wire up alerts, and combine CCI with a trend filter. It describes what the code draws. It does not tell you which readings to trade, and nothing here is a forecast.
What the CCI measures
Donald Lambert introduced the Commodity Channel Index in 1980. Despite the name it is applied to any market. The idea is to measure how far the current price sits from its recent average, scaled by how far price usually sits from that average. A reading of zero means price equals its moving average. A positive reading means price is above it, and a negative reading means it is below. The scaling is what makes the number comparable across symbols and timeframes: a move of the same size is a bigger reading in a quiet market than in a noisy one.
The formula has three parts. The input is the typical price, which is the average of the high, low and close of each bar (Pine calls this hlc3). Take a simple moving average of the typical price over the lookback length, and take the mean deviation, which is the average absolute distance of each typical price in that window from the moving average. The index is the typical price minus its average, divided by 0.015 times the mean deviation.
The constant 0.015 is a scaling choice. It is commonly described as chosen so that most readings, roughly 70 to 80 percent, land between minus 100 and plus 100. That is why those two levels became the default reference lines, and why a reading beyond them is read as price stretched further from its average than usual. The index is not bounded. It can print 300 or minus 400 in a violent move, which is one of the practical differences from an oscillator like RSI that is capped between 0 and 100. If you want the arithmetic on a single bar, the CCI calculator walks through it with your own numbers.
The one-line version in Pine Script v6
Pine Script v6 has a built-in, ta.cci(source, length). The default on TradingView's own CCI is hlc3 with a length of 20. Here is a complete indicator with those defaults exposed as inputs, a plot, the two reference levels, and a shaded band between them.
//@version=6
indicator("CCI", overlay=false)
length = input.int(20, "Length", minval=1)
src = input.source(hlc3, "Source")
cciValue = ta.cci(src, length)
plot(cciValue, "CCI", color=color.blue)
upper = hline(100, "Upper", color=color.gray)
lower = hline(-100, "Lower", color=color.gray)
hline(0, "Zero", color=color.silver, linestyle=hline.style_dotted)
fill(upper, lower, color=color.new(color.blue, 92), title="Normal range")A few details are worth noticing. The indicator() call uses overlay=false because the CCI has its own scale and would flatten the price chart if drawn on top of it. The hline() function draws fixed horizontal lines and returns a handle, and fill() takes two of those handles to shade the space between them. The hline levels must be constants, which matters later: if you want the zone level to be an input, you plot it as a series instead of using hline. Finally, input.source lets you swap hlc3 for close from the settings dialog, which changes the character of the line noticeably, because the close alone is noisier than the average of high, low and close.
Build it by hand to see what ta.cci does
Calling a built-in is fine until it behaves in a way you did not expect. Writing the formula out takes four lines and makes the behavior legible, and it is also the shortest route to modifying it later, for instance to use a different moving average. The script below plots the manual version next to the built-in and then plots their difference.
//@version=6
indicator("CCI by hand", overlay=false)
length = input.int(20, "Length", minval=1)
src = hlc3
average = ta.sma(src, length)
meanDev = ta.dev(src, length)
manual = (src - average) / (0.015 * meanDev)
builtIn = ta.cci(src, length)
plot(manual, "By hand", color=color.orange, linewidth=2)
plot(builtIn, "ta.cci", color=color.blue)
plot(manual - builtIn, "Difference", color=color.red)ta.dev is the function that computes the mean absolute deviation, which is the denominator ingredient that trips people up. It is not the standard deviation. Standard deviation squares the distances before averaging and so weights large departures more heavily, while mean deviation treats every unit of distance the same. If you swap ta.stdev into the formula you get a different indicator that no longer matches the CCI everyone else is looking at. The ta.stdev guide covers the difference between the two measures in detail.
When you add this to a chart the orange and blue lines should sit on top of each other and the red difference line should stay at zero. If you can reproduce the built-in this way you understand it, and you also have a template for variants. Replace ta.sma with ta.ema and the line reacts faster but stops matching the standard definition, so it should carry a different name on your chart.
Choosing the length
The default of 20 is a convention, not a law. A shorter length such as 10 makes the average and the deviation track recent bars closely, so the line swings more often and crosses the plus and minus 100 levels more frequently. A longer length such as 50 smooths both, and readings beyond 100 become rarer. Because the scaling adapts to the window, changing the length does not just stretch the line in time. It changes how often the line reaches the reference levels, which means a threshold that suited length 20 may not suit length 14 or length 40.
The practical advice is to decide the length first, then look at how often each level is reached on the symbol and timeframe you care about, rather than copying levels from a tutorial. Inside PineScripter's chart you can run the indicator on real market data from 308 crypto spot markets across 14 timeframes, up to 5,000 bars per run, and flip between timeframes to see how the same length behaves at 15 minutes versus 4 hours. The chart covers crypto spot markets only, so check any stock or futures symbol you care about in TradingView itself.
Marking zone entries and exits
The most common way to read the CCI is by the plus and minus 100 levels. A cross above plus 100 means the line has entered the upper zone. A cross back below plus 100 means it has left it. The same two events exist at minus 100 on the way down. These are four different events with different meanings, and a lot of buggy CCI scripts conflate them, so it pays to name each one in code.
//@version=6
indicator("CCI zone crosses", overlay=false)
length = input.int(20, "Length", minval=1)
level = input.int(100, "Zone level", minval=1)
cciValue = ta.cci(hlc3, length)
enterUpper = ta.crossover(cciValue, level) and barstate.isconfirmed
exitUpper = ta.crossunder(cciValue, level) and barstate.isconfirmed
enterLower = ta.crossunder(cciValue, -level) and barstate.isconfirmed
exitLower = ta.crossover(cciValue, -level) and barstate.isconfirmed
plot(cciValue, "CCI", color=color.blue)
plot(level, "Upper", color=color.gray)
plot(-level, "Lower", color=color.gray)
plot(0, "Zero", color=color.silver)
plotshape(exitUpper, "Left upper zone", style=shape.triangledown, location=location.top, color=color.red, size=size.tiny)
plotshape(exitLower, "Left lower zone", style=shape.triangleup, location=location.bottom, color=color.teal, size=size.tiny)
plotshape(enterUpper, "Entered upper zone", style=shape.circle, location=location.top, color=color.gray, size=size.tiny)
plotshape(enterLower, "Entered lower zone", style=shape.circle, location=location.bottom, color=color.gray, size=size.tiny)
alertcondition(exitUpper, "CCI left upper zone", "CCI crossed back below the upper level")
alertcondition(exitLower, "CCI left lower zone", "CCI crossed back above the lower level")This version plots the levels as series rather than with hline, which is what lets the zone level be an input. It uses ta.crossover and ta.crossunder, which return true on the single bar where the line crosses; the crossover and crossunder guide explains their exact semantics. Every condition is joined with barstate.isconfirmed, so on a live bar nothing is marked until the bar has closed. Without that guard, the CCI on a live bar moves with every tick and can cross a level and cross back inside one bar, leaving markers on the chart that were never true at the close. The barstate.isconfirmed explainer covers why this works and what it costs in latency.
The alerts at the bottom use alertcondition. When you create the alert in TradingView, choose the option that fires once per bar close to match the guard in the code. If an alert seems to fire a bar early or late, the wrong-bar alert guide walks through the usual causes, and the alertcondition versus alert() comparison helps you decide whether you want the dynamic message version.
Combining CCI with a trend filter
The CCI says how stretched price is relative to its average. It says nothing about direction of the larger trend, and this is where it is usually combined with something slower. A common pairing is to look at CCI dips below minus 100 only while price is above a long moving average, on the idea that a pullback inside an uptrend is a different event from a drop in a downtrend. Whether that idea holds for your market is something you have to test yourself. The code below just marks where the condition is true so you can inspect it.
//@version=6
indicator("CCI pullback marker with trend filter", overlay=true)
length = input.int(20, "CCI length", minval=1)
emaLength = input.int(200, "Trend EMA length", minval=1)
level = input.int(100, "Zone level", minval=1)
cciValue = ta.cci(hlc3, length)
trendEma = ta.ema(close, emaLength)
aboveTrend = close > trendEma
recovered = ta.crossover(cciValue, -level) and aboveTrend and barstate.isconfirmed
plot(trendEma, "Trend EMA", color=color.orange)
plotshape(recovered, "CCI back above lower level", style=shape.triangleup, location=location.belowbar, color=color.teal, size=size.small)This one is drawn on the price chart (overlay=true), so the CCI itself is not visible; only the moment it climbs back above the lower level while price is above the 200 EMA is marked. That is deliberate. A marker on the price chart is easier to scan across hundreds of bars than a separate pane. For more on the slow filter itself, see the 200 EMA trend filter guide, and if you want to compare CCI with other bounded momentum measures, the stochastic oscillator and Williams %R posts use the same structure.
Common mistakes with CCI in Pine Script
The first mistake is treating plus 100 as a sell line and minus 100 as a buy line. The index is unbounded, and in a strong trend it can sit above plus 100 for dozens of bars. A reading beyond the level means price is far from its average relative to its usual spread, not that anything is about to reverse. That is why the code above marks exits from the zone rather than entries into it, and why neither is an instruction.
The second is comparing numbers across different lengths or sources without noticing. A CCI of 150 on length 14 with close is not the same statement as a CCI of 150 on length 20 with hlc3. When you share a script or read someone else's, check both settings before you check the level.
The third is using ta.stdev in place of ta.dev when writing the formula by hand, which produces a line that looks plausible and is quietly different. The fourth is forgetting that ta.cci returns na until enough bars exist for the window. On a fresh symbol with little history you will see a gap at the start, and any logic that compares the value to a level will simply be false there, which is the safe behavior.
The fifth is repainting. A CCI computed from closed bars does not repaint, because the inputs of a closed bar never change. The line on the live bar does move, and a cross detected there can disappear before the bar closes. The barstate.isconfirmed guard fixes the markers, and the repainting guide lists the other kinds you should know about. If you add a higher-timeframe CCI through request.security, use the patterns in the multi-timeframe guide instead of calling it bare.
Checking it on real data before you trust it
After the code compiles, the next question is whether the markers fire where you think they do. In PineScripter you can run the script on the chart and use Replay, which steps through the run one bar at a time, to watch the exact bar where a zone exit appears and confirm it only appears after the close. Indicator Analysis then measures what the triggers already did on past data: how they cluster, which sessions or hours they fall in, and how price moved 1, 5, 10 and 20 bars after each one. That is a description of the past on the data you ran. It is not a forecast and it is not a test of whether the idea is worth trading. PineScripter does not simulate trades or report returns, so for a strategy backtest you use TradingView's Strategy Tester, covered in the indicator to strategy guide.
Adapting it to your own rules
The scripts above are starting points, and the useful work begins when you change them: a different exit condition, a volume filter, markers only during a session, an alert text that matches what another tool expects. In PineScripter you describe the change in plain English, for example "only mark the zone exit when price is above the 50 EMA and the bar closed above its open", and the AI edits just the affected lines instead of rewriting the script. The Code Changes view shows line by line what moved, and the built-in linting engine checks the result the same way TradingView does, so the AI sees and fixes compile errors itself. The script is yours to copy into TradingView and keep.
If you are earlier in the process and want to understand a single value first, the free CCI calculator needs no account and shows the Pine Script that computes the same number.
This article is educational content about Pine Script code. PineScripter is a coding tool, not a financial advisor, and nothing here is a recommendation to buy or sell anything or a promise of any result.
Frequently asked questions
What is the default CCI length in Pine Script?
TradingView's own CCI uses a length of 20 on hlc3. In your own script you pass both to ta.cci(source, length), and exposing them with input.int and input.source lets you change them from the settings dialog.
What is the CCI formula?
The typical price (hlc3) minus its simple moving average over the length, divided by 0.015 times the mean absolute deviation of the typical price over the same window. In Pine, ta.sma and ta.dev give the two pieces.
Is CCI bounded between plus and minus 100?
No. The plus and minus 100 lines are reference levels, not limits. The index is unbounded and can stay beyond them for many bars in a strong move.
Does CCI repaint in Pine Script?
On closed bars it does not, because the inputs of a closed bar never change. The live bar's value moves with each tick, so gate markers and alerts with barstate.isconfirmed or use alerts that fire once per bar close.
Why does my hand-written CCI not match ta.cci?
The usual cause is using ta.stdev instead of ta.dev. The standard CCI divides by the mean absolute deviation, not the standard deviation, so swapping them gives a different line.
Describe your indicator in plain English and get Pine Script that compiles →
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.