ta.stoch in MQL5: raw %K vs iStochastic's slowing and %D

Short answer

Compute the raw %K yourself from the highest high and lowest low of the window, then apply the same ta.sma calls the Pine script does. iStochastic returns a slowed %K and %D whose slowing sums values instead of taking an SMA, so it won't match.

ta.stoch(source, high, low, length) returns the raw stochastic: where source sits inside the highest-high to lowest-low range of the last length bars, as a percentage. It is one number, not a %K/%D pair. MetaTrader's iStochastic returns a slowed %K and a %D, and its slowing is not a moving average of the raw value. To match TradingView's Stochastic indicator in MQL5, compute the raw value yourself and apply the two ta.sma calls the Pine script applies.

What ta.stoch computes

100 * (source - lowest(low, length)) / (highest(high, length) - lowest(low, length)). The highest and lowest are taken over the bars 0..length-1 back from the current one, so the first value appears on bar index length - 1; before that it is na. If the window is flat (highest equals lowest) the division has a zero denominator and the result is na. The high and low arguments are ordinary series: TradingView's Stochastic passes the bar high and low, but you can pass a smoothed high or a different symbol's data. The usual indicator then takes k = ta.sma(ta.stoch(close, high, low, 14), 3) and d = ta.sma(k, 3).

The MQL5 equivalent

//@version=6
indicator("Stoch ref")
k = ta.sma(ta.stoch(close, high, low, 14), 3)
d = ta.sma(k, 3)
plot(k, "%K")
plot(d, "%D")

The MQL5 version keeps the raw %K in a calculation buffer, averages it into %K and averages %K into %D. The helper SmaNa treats EMPTY_VALUE as Pine treats na: one missing value inside the window makes the average missing. A flat window stores EMPTY_VALUE rather than 100.

//+------------------------------------------------------------------+
//| Stochastic as TradingView computes it: ta.stoch, then two SMAs    |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_plots   2
#property indicator_label1  "%K"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_label2  "%D"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrOrange
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_level1  20
#property indicator_level2  80

input int InpLength  = 14;   // %K length
input int InpSmoothK = 3;    // %K smoothing
input int InpSmoothD = 3;    // %D smoothing

double KBuf[], DBuf[], RawBuf[];

int OnInit()
{
   SetIndexBuffer(0, KBuf,   INDICATOR_DATA);
   SetIndexBuffer(1, DBuf,   INDICATOR_DATA);
   SetIndexBuffer(2, RawBuf, INDICATOR_CALCULATIONS);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   return INIT_SUCCEEDED;
}

// ta.sma over a buffer that may hold EMPTY_VALUE (na): one na in the
// window makes the mean na, as in Pine.
double SmaNa(const double &src[], const int i, const int len)
{
   if(i < len - 1) return EMPTY_VALUE;
   double sum = 0.0;
   for(int k = 0; k < len; k++)
   {
      if(src[i - k] == EMPTY_VALUE) return EMPTY_VALUE;
      sum += src[i - k];
   }
   return sum / len;
}

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[])
{
   int start = prev_calculated > 1 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      // raw %K = ta.stoch(close, high, low, length)
      if(i < InpLength - 1) RawBuf[i] = EMPTY_VALUE;
      else
      {
         double hh = high[i], ll = low[i];
         for(int k = 1; k < InpLength; k++)
         {
            if(high[i - k] > hh) hh = high[i - k];
            if(low[i - k]  < ll) ll = low[i - k];
         }
         RawBuf[i] = hh == ll ? EMPTY_VALUE : 100.0 * (close[i] - ll) / (hh - ll);
      }
      KBuf[i] = SmaNa(RawBuf, i, InpSmoothK);   // %K = ta.sma(raw, smoothK)
      DBuf[i] = SmaNa(KBuf,   i, InpSmoothD);   // %D = ta.sma(%K, smoothD)
   }
   return rates_total;
}

If you only need the shape of a standard stochastic and can accept small differences, the built-in handle is one line:

// iStochastic(symbol, timeframe, %K length, %D length, slowing, MA method, price field)
// Buffer 0 = %K (already slowed), buffer 1 = %D.
int stoHandle = iStochastic(_Symbol, _Period, 14, 3, 3, MODE_SMA, STO_LOWHIGH);

Where the two differ

AspectPine ta.stochMQL5 iStochastic
OutputRaw %K, one seriesSlowed %K (buffer 0) and %D (buffer 1)
SlowingDone by the script: ta.sma of the ratioSum of (close - LL) over slowing bars divided by sum of (HH - LL); a ratio of sums, not an average of ratios
Flat windowna100
SourceAny series, and any high/low seriesclose against high/low (STO_LOWHIGH) or close against close (STO_CLOSECLOSE)
First valuesna until length - 1 bars exist, plus the SMA windows0 written on the warm-up bars
%D methodWhatever the script uses, usually ta.smaMODE_SMA, MODE_EMA, MODE_SMMA or MODE_LWMA parameter

The slowing row is the one that surprises people. With slowing 3, MetaTrader computes 100 * (n1 + n2 + n3) / (d1 + d2 + d3), where n is close - LL and d is HH - LL for each of the last three bars. TradingView computes (100 * n1/d1 + 100 * n2/d2 + 100 * n3/d3) / 3. The two agree exactly only when the three ranges are equal. On quiet bars they are within a point or two of each other; after a range expansion they can differ by five or more points for a few bars, and 20/80 crosses land on different bars.

What the Stratlate converter emits

The converter maps ta.stoch to its runtime helper pine_stoch(src, high, low, bar, length), which takes pine_highest and pine_lowest over the window, returns na before the window is full or when any value in it is na, and returns na for a flat window through pine_div. It does not use iStochastic, so the slowing stays whatever the Pine script wrote: in the test script above, the raw value is materialised into a buffer and the two ta.sma calls become pine_sma over it. The result is reported as exact (CLEAN). Compile and backtest the output; the differential verifier described on the quality page runs it against the original on the same bars.

Pitfalls

  • Treating iStochastic buffer 0 as ta.stoch. It is already slowed; applying the script's ta.sma on top smooths twice and the line lags TradingView by a bar or two.
  • Setting slowing to 1 to get the raw value, then expecting %K to match after your own ta.sma. The raw value does match, but a flat window yields 100 on MT5 and na in Pine, so a few bars after a doji-only stretch differ.
  • Using the bar's high/low when the Pine script passes something else, such as ta.stoch(rsi, rsi, rsi, 14) in a Stochastic RSI. Build the window from the same series the script does.
  • Looping only over high[i - k] for k < length while the window is still short, which reads index -1 and raises "array out of range". Guard i < length - 1 first.
  • Averaging EMPTY_VALUE as a number. EMPTY_VALUE is DBL_MAX; one in the window turns the SMA into a huge number and the plot into a vertical spike.

FAQ

Which iStochastic parameters give TradingView's default Stochastic (14, 3, 3)?

%K length 14, %D length 3, slowing 3, MODE_SMA and STO_LOWHIGH. The lines are close to TradingView's but not identical, because MetaTrader slows %K as a ratio of sums and treats a flat window as 100. For a bar-for-bar match use the hand-written version.

How do I get the unsmoothed %K from iStochastic?

Set slowing to 1; buffer 0 is then the raw stochastic on every bar whose window is not flat. It is usually simpler to compute the raw value directly, which also lets you use any source, as ta.stoch does.

Why does my MQL5 %D start later than TradingView's?

Each averaging stage needs a full window. With length 14 and two SMAs of 3, Pine's first %D value appears on bar index 17. If your MQL5 code writes 0 instead of EMPTY_VALUE on earlier bars the plot draws a line from 0, which looks like a late start or a spike; use EMPTY_VALUE and PLOT_EMPTY_VALUE.

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

Related