ta.cci in MQL5: iCCI, mean deviation and the 0.015 constant
Short answer
Use iCCI with the matching PRICE_* constant: it uses the same formula, including the 0.015 constant, so the two agree once the window is full. The differences are the flat-window case and that iCCI accepts prices only.
ta.cci(source, length) is the Commodity Channel Index: how far the source is from its own simple moving average, measured in units of the window's mean absolute deviation and divided by Lambert's constant 0.015. MetaTrader 5's iCCI(symbol, timeframe, length, applied_price) uses the identical formula, so for a price source the two agree on every bar once the window is full. The only differences are the flat-window case and the fact that iCCI accepts prices only.
What ta.cci computes
With m = ta.sma(source, length) and dev = (1 / length) * sum(|source[k] - m|, k = 0..length-1), the index is (source - m) / (0.015 * dev). Note that the deviation is the mean absolute deviation from the window's mean, not the standard deviation ta.dev or ta.stdev would give; using ta.stdev produces values about 20% smaller. The constant 0.015 scales the result so that roughly three quarters of values fall between -100 and +100. The first value appears on bar index length - 1; before that, and whenever a value in the window is na, the result is na. A window of identical values has zero deviation and the result is na as well. TradingView's CCI indicator passes hlc3 as the source with length 20.
The MQL5 equivalent
//@version=6
indicator("CCI ref")
c = ta.cci(hlc3, 20)
plot(c, "CCI")For a price source the complete MQL5 indicator is a handle and a copy. PRICE_TYPICAL is hlc3; PRICE_MEDIAN is hl2, PRICE_WEIGHTED is ohlc4 and PRICE_CLOSE is close. The loop at the end blanks the warm-up bars, where iCCI writes 0 and Pine shows na.
//+------------------------------------------------------------------+
//| ta.cci(hlc3, 20) through the built-in iCCI |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_label1 "CCI"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
#property indicator_level1 -100
#property indicator_level2 100
input int InpLength = 20; // Length
double CciBuf[];
int cciHandle = INVALID_HANDLE;
int OnInit()
{
SetIndexBuffer(0, CciBuf, INDICATOR_DATA);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
// PRICE_TYPICAL is (high + low + close) / 3, Pine's hlc3
cciHandle = iCCI(_Symbol, _Period, InpLength, PRICE_TYPICAL);
if(cciHandle == INVALID_HANDLE) return INIT_FAILED;
return INIT_SUCCEEDED;
}
int OnCalculate(const int rates_total, const int prev_calculated,
const datetime &time[], const double &open[],
const double &high[], const double &low[], const double &close[],
const long &tick_volume[], const long &volume[], const int &spread[])
{
if(BarsCalculated(cciHandle) < rates_total) return 0; // not ready yet
// Copy only what changed: the whole history once, then the newest bar(s).
const int toCopy = prev_calculated == 0 ? rates_total : rates_total - prev_calculated + 1;
if(CopyBuffer(cciHandle, 0, 0, toCopy, CciBuf) != toCopy) return 0;
// iCCI writes 0 for the first len-1 bars; ta.cci is na there.
if(prev_calculated == 0)
for(int i = 0; i < InpLength - 1 && i < rates_total; i++) CciBuf[i] = EMPTY_VALUE;
return rates_total;
}When the source is a computed series (a CCI of an RSI, of a spread, of a smoothed price), compute it into a buffer and apply the formula directly. The function below is the formula from the first section with Pine's na behaviour kept:
// ta.cci(src, len) for any series held in an oldest-first buffer.
double CciOf(const double &src[], const int i, const int len)
{
if(i < len - 1) return EMPTY_VALUE; // na until the window is full
double mean = 0.0;
for(int k = 0; k < len; k++) mean += src[i - k];
mean /= len;
double dev = 0.0; // mean absolute deviation
for(int k = 0; k < len; k++) dev += MathAbs(src[i - k] - mean);
dev /= len;
if(dev == 0.0) return EMPTY_VALUE; // Pine: division by zero is na
return (src[i] - mean) / (0.015 * dev);
}Where the two differ
| Aspect | Pine ta.cci | MQL5 iCCI |
|---|---|---|
| Formula | (src - SMA) / (0.015 * mean abs. deviation) | Identical |
| Source | Any series | ENUM_APPLIED_PRICE constant; default in the terminal UI is Typical |
| Warm-up bars | na for the first length - 1 bars | 0 written, hidden by the plot's draw-begin |
| Flat window | na (zero deviation) | 0 |
| Missing values in the window | na | Not applicable; prices are never missing |
| Realtime bar | Recalculated each tick | Recalculated each tick; last element of the copied buffer |
Because the CCI has no recursion, there is no seeding problem and no slow convergence: unlike RSI or MACD, a correct CCI matches TradingView from its very first value, provided the input candles are the same. Any persistent difference therefore points at the data (bid versus mid prices, a different session calendar) or at the source constant, not at the formula.
What the Stratlate converter emits
The converter treats ta.cci as a windowed indicator and emits its runtime helper pine_cci(src, bar, length): the source is materialised into an oldest-first array when it is not already one, the helper computes the SMA and the mean absolute deviation over the last length values, returns na while the window is short, when any value in it is na, and when the deviation is zero. It does not use iCCI on the chart timeframe. Inside request.security(...) a CCI of a price on another timeframe becomes an iCCI handle with the matching PRICE_* constant. The chart-timeframe mapping is reported as exact; the test script above converts CLEAN. Compile and backtest the output.
Pitfalls
- Using the standard deviation instead of the mean absolute deviation. The CCI is compressed by about a fifth, so +100/-100 crossings happen less often than on TradingView.
- Dividing the deviation sum by
length - 1, the sample convention. Values are too small by(length - 1) / length; with length 20 that is 5%. - Passing
PRICE_CLOSEfor a script that uses the defaulthlc3. The lines have the same shape but cross the zero line on different bars. - Reading the whole
iCCIbuffer withCopyBufferon every tick. It works, but on a chart with a hundred thousand bars it costs a full copy per tick; copy only the bars that changed. - Plotting 0 on the warm-up bars. The line appears to come from zero on the left edge; use
EMPTY_VALUEorPLOT_DRAW_BEGIN. - Integer arithmetic in
0.015 * devis safe, butmean /= lenwith anintaccumulator is not. Keep every accumulator adouble.
FAQ
Is iCCI the same as ta.cci?
Yes for any applied-price source, from the first full window on. Both divide the distance from the simple moving average by 0.015 times the mean absolute deviation. They differ only on a window of identical prices, where iCCI gives 0 and ta.cci gives na.
Which applied price corresponds to Pine's hlc3?
PRICE_TYPICAL. hl2 is PRICE_MEDIAN, ohlc4 is PRICE_WEIGHTED, and open, high, low and close are PRICE_OPEN, PRICE_HIGH, PRICE_LOW and PRICE_CLOSE. There is no constant for a custom source such as an EMA; compute that into a buffer and apply the formula yourself.
Why does my converted CCI differ from TradingView by a few points on some bars?
Almost always the input candles. The CCI cancels a constant price offset, so a bid-versus-mid feed does not shift it; what remains are bars whose high, low or close differ between the two feeds, and session boundaries that put a different set of bars in the window. A formula error shows up over the whole chart as a scale factor or a shape change, not on isolated bars.
Convert the whole script
Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.
Open the converter