TradingView indicator comparisons

CCI vs Stochastic: Deviation vs Range Location

CCI measures typical price relative to its recent mean and average absolute deviation. Stochastic measures where the close lies within the recent high-low range. Use CCI for a deviation rule and Stochastic for a range-position rule. Neither establishes that an extreme must reverse. In the same-bar example below, CCI reaches +166.67 while raw Stochastic is only 55: price is unusual relative to recent typical prices but still near the middle of the high-low range.

See the decision guide

The denominator determines the question

For N bars, typical price TP = (high + low + close) / 3. Let M be the N-bar SMA of TP and MAD = sum(|TP_i - M|) / N over that same window. CCI = (TP - M) / (0.015 × MAD). Every deviation uses the current window mean. Substituting standard deviation or averaging deviations from different historical means changes the indicator.

  • The 0.015 factor scales CCI; it is not a probability calibration. CCI +100 and K 80 do not identify the same price condition.
  • Select HLC3 explicitly for the built-in CCI. TradingView documents typical price in its formula but lists Close in its Source settings. The script here fixes HLC3.
  • K smoothing 1 gives raw K; larger values average range positions. D is another average of K, not another high-low normalization. A K/D crossing tests a different rule from a K threshold.
MeasurementCCIStochastic
BaselineCurrent N-bar mean of typical priceLowest low and highest high of N bars
CalculationDeviation / (0.015 × mean absolute deviation)Raw K = 100 × (close - lowest low) / (highest high - lowest low)
SmoothingSMA and MAD are part of CCI; no extra signal line hereK = SMA(raw K, smoothK); D = SMA(K, lengthD)
Common zone referencesAbove +100 or below -100Above 80 or below 20
Undefined denominatorMAD = 0Highest high = lowest low

Reproduce a range counterexample on identical bars

This constructed fixture is arithmetic evidence, not market history. Use N = 5, K smoothing = 1 and D smoothing = 3. Every bar has high 110, low 90 and open equal to close. Bars 0 to 10 close at 99, 99, 99, 99, 101, 102, 101, 100, 99, 98, 99. Both indicators evaluate the same completed bar, including that bar in the five-bar window.

  • At bar 4, four typical prices equal 299/3 and the newest equals 301/3. Their mean is 99.8. The absolute deviations sum to 16/15, so MAD = 16/75. CCI = (8/15) / (0.015 × 16/75) = 166.67. Raw K = 100 × (101 - 90) / 20 = 55.
  • The broad intrabar range stays unchanged while typical prices cluster tightly. A small move relative to that cluster produces high CCI without a high range position. This is why the page does not translate +100 into 80.
  • D first appears at bar 6: (55 + 60 + 55) / 3 = 56.67. With K smoothing 3 instead, K first appears at bar 6 with 56.67 and D first appears at bar 8 with 53.89. Values are calculated before rounding.
BarCloseTP meanMADCCIKD
410199.80000.213333166.6755Not ready
5102100.00000.400000111.1160Not ready
6101100.13330.37333335.715556.67
7100100.20000.293333-45.455055.00
899100.20000.293333-121.214550.00
998100.00000.400000-111.114045.00
109999.80000.293333-30.304543.33

Test states and entries at the same confirmation time

For the fixture, an upper state means CCI > 100 or K > 80. A lower state means CCI < -100 or K < 20. An upper entry requires the preceding value at or below its upper threshold and the current value strictly above it; lower entry reverses those inequalities. Require both current and preceding comparison bars to be valid. Evaluate all conditions only at bar close.

  • A filter selecting upper-zone bars keeps two CCI observations and no K observations. A filter selecting lower-zone bars also disagrees. These are selection counts, not returns.
  • The first valid observation may already be extreme. Do not label it a crossing when the prior value is missing. Equality at the threshold is also distinct from a strict state above or below it.
  • After arithmetic checks, fix a symbol, exchange feed, session, standard candle type, timeframe and date range. Record accepted and rejected timestamps for each filter. Match entries, exits, costs and execution timing before comparing any subsequent strategy performance.
Test over bars 4 to 10CCI resultK result
Upper stateBars 4 and 5None
Lower stateBars 8 and 9None
Upper entryNone: bar 4 has no valid predecessorNone
Lower entryBar 8None

A persistent trend can keep both indicators extreme

Consider a second synthetic sequence with close = 100 + bar number, high = close, low = close - 2 and open = close - 1. With N = 5, the latest typical price is two units above its window mean and MAD is 1.2. CCI therefore stays at 111.11 after warm-up. Each close is also the window high, so raw K stays at 100. Fully warmed SMA smoothing leaves that constant K unchanged.

  • K cannot report how far the latest high has advanced once it is at 100. CCI is not capped at +100, but this constant-slope trend also gives a constant CCI reading. Neither flat oscillator line means price stopped advancing.
  • Selling each upper-zone reading opposes every later rising close in this constructed path. The range fixture above gives the opposite warning: a CCI extreme need not mean price is near a range edge. Neither example determines a profitable trading rule.
  • CCI is commonly called unbounded because it has no fixed universal endpoints like Stochastic. For this exact finite-window formula with positive MAD, there is a length-dependent bound: |CCI| ≤ N / 0.03. The absolute deviations sum to at least twice any individual deviation. At N = 5 the bound is 166.67, reached by bar 4 of the first fixture.

Run a confirmed-bar Pine Script v6 comparison

Paste the indicator into Pine Editor and add it to a standard candle chart. The Pane scale input displays CCI or Stochastic without visually mixing their scales; all values remain available in the Data Window. C and K mark entries into the corresponding extreme zones. The script uses chart OHLC, not the synthetic fixture, and places no orders. Its shared readiness gate compares CCI with K; D is displayed but does not gate the threshold tests.

  • All displayed observations and event markers wait for barstate.isconfirmed. There are no higher-timeframe requests; chart close confirmation alone would not settle an unfinished higher-timeframe bar.
  • The strict average deliberately propagates missing values. A missing OHLC observation invalidates the whole lookback. Zero MAD makes CCI na; zero range makes raw K na. Missing results are not filled with zero or carried forward.
  • For uninterrupted valid data and nonzero denominators, CCI and raw K first become available on bar N - 1. K needs N + smoothK - 1 observations and D needs N + smoothK + lengthD - 2. A missing raw K restarts the consecutive smoothing requirement.
  • The first paired valid bar can show a state but cannot show an entry. Inspect each indicator value and the 1/0 state fields in the Data Window before interpreting the C/K markers. Syntax validation is not a backtest or evidence of profitability.
Complete Pine v6 indicator. Default lookback 5, K smoothing 1 and D smoothing 3 match the calculation fixture; market-chart readings depend on the chart data.pine
//@version=6
indicator("CCI vs Stochastic: matched bars", overlay = false, max_bars_back = 500)
length = input.int(5, "Shared lookback", minval = 2, maxval = 200)
smoothK = input.int(1, "K smoothing", minval = 1, maxval = 200)
lengthD = input.int(3, "D smoothing", minval = 1, maxval = 200)
pane = input.string("CCI", "Pane scale", options = ["CCI", "Stochastic"])

// Require consecutive observations; an na input invalidates the average.
strictSma(float source, int count) =>
    float total = 0.0
    for i = 0 to count - 1
        total += source[i]
    total / count

typical = hlc3
mean = strictSma(typical, length)
float deviationSum = 0.0
bool fullWindow = bar_index >= length - 1
for i = 0 to length - 1
    deviationSum += math.abs(typical[i] - mean)
    fullWindow := fullWindow and not na(high[i]) and not na(low[i]) and not na(close[i])
meanDeviation = deviationSum / length
cci = fullWindow and meanDeviation > 0 ? (typical - mean) / (0.015 * meanDeviation) : na
windowHigh = ta.highest(high, length)
windowLow = ta.lowest(low, length)
priceRange = windowHigh - windowLow
rawK = fullWindow and priceRange > 0 ? 100 * (close - windowLow) / priceRange : na
k = strictSma(rawK, smoothK)
d = strictSma(k, lengthD)
ready = not na(cci) and not na(k)
confirmed = barstate.isconfirmed
cciUpper = ready and cci > 100
stochUpper = ready and k > 80
cciLower = ready and cci < -100
stochLower = ready and k < 20
cciEnterUpper = confirmed and ready and ready[1] and cciUpper and cci[1] <= 100
stochEnterUpper = confirmed and ready and ready[1] and stochUpper and k[1] <= 80
cciEnterLower = confirmed and ready and ready[1] and cciLower and cci[1] >= -100
stochEnterLower = confirmed and ready and ready[1] and stochLower and k[1] >= 20

plot(confirmed and pane == "CCI" ? cci : na, "CCI pane", color.blue)
plot(confirmed and pane == "Stochastic" ? k : na, "K pane", color.orange)
plot(confirmed and pane == "Stochastic" ? d : na, "D pane", color.teal)
plot(confirmed ? cci : na, "CCI value", display = display.data_window)
plot(confirmed ? rawK : na, "Raw K value", display = display.data_window)
plot(confirmed ? k : na, "K value", display = display.data_window)
plot(confirmed ? d : na, "D value", display = display.data_window)
plot(confirmed ? mean : na, "Typical price SMA", display = display.data_window)
plot(confirmed ? meanDeviation : na, "Mean absolute deviation", display = display.data_window)
plot(confirmed and ready ? (cciUpper ? 1 : 0) : na, "CCI above 100", display = display.data_window)
plot(confirmed and ready ? (stochUpper ? 1 : 0) : na, "K above 80", display = display.data_window)
plot(confirmed and ready ? (cciLower ? 1 : 0) : na, "CCI below -100", display = display.data_window)
plot(confirmed and ready ? (stochLower ? 1 : 0) : na, "K below 20", display = display.data_window)
plotchar(cciEnterUpper, "CCI enters upper zone", "C", location.top, color.blue)
plotchar(stochEnterUpper, "K enters upper zone", "K", location.top, color.orange)
plotchar(cciEnterLower, "CCI enters lower zone", "C", location.bottom, color.blue)
plotchar(stochEnterLower, "K enters lower zone", "K", location.bottom, color.orange)

Specify the rule before asking the Coding Agent to extend it

The Pine Script AI Coding Agent can draft and edit code from a stated rule. Give it the same OHLC source, lookback, K and D smoothing, strict threshold inequalities, close confirmation and missing-value policy used here. Ask for a timestamped comparison of selected bars before adding orders. Explicitly request syntax checking, then review the result against the numerical fixture.

  • If the intended question is distance from recent typical prices, retain the CCI definition. If it is location inside a recent range, retain K and name the smoothing. Requiring both is a third filter with a different set of selected bars.
  • For a trading experiment, define a measurable outcome and reserve a later test period before selecting thresholds. Agreement between two price-based filters is not independent evidence that a reversal will occur.
Where Pineify fits

Pine Script AI Coding Agent

Draft or edit a CCI and Stochastic comparison with explicit inputs, confirmation and invalid-value handling. Request syntax validation and inspect the values before testing trades.

Draft a comparison script

Frequently asked questions

Educational comparison, not investment advice. Prices and filter counts are synthetic calculation fixtures, not market observations or backtested returns. Indicator extremes and generated code do not guarantee reversals or profitable trades.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.