iStochastic in Pine Script: slowing is not ta.sma of ta.stoch

Short answer

MetaTrader's slowing is not ta.sma of ta.stoch: it sums numerator and denominator separately. The exact port is %K = math.sum(close - LL, slowing) / math.sum(HH - LL, slowing) * 100, then %D = ta.sma(%K, Dperiod).

iStochastic returns a handle to MetaTrader's Stochastic Oscillator with two buffers, MAIN_LINE (%K) and SIGNAL_LINE (%D). Pine's ta.stoch gives the raw %K only, and TradingView's usual "slow" stochastic smooths that ratio with ta.sma. MetaTrader's slowing is different: it sums the numerator and the denominator separately over the slowing period and divides afterwards. The exact Pine port is math.sum(close − LL, slowing) / math.sum(HH − LL, slowing) · 100, then ta.sma of that for %D.

What iStochastic computes

The signature is iStochastic(symbol, timeframe, Kperiod, Dperiod, slowing, ma_method, price_field). With price_field = STO_LOWHIGH the stock indicator (Indicators\Examples\Stochastic.mq5) finds, for each bar, the highest high HH and lowest low LL of the last Kperiod bars. The main line is then Σ(close − LL) / Σ(HH − LL) · 100, both sums taken over the last slowing bars; if the denominator sum is zero the line is set to 100. The signal line is a moving average of the main line over Dperiod bars using ma_method (SMA by default). STO_CLOSECLOSE replaces HH and LL with the highest and lowest close. Cells before Kperiod + slowing − 2 hold 0.0 for %K, and %D holds 0.0 for its first Dperiod − 1 bars. With slowing = 1 the main line is the plain fast %K.

The Pine Script equivalent

ta.stoch(close, high, low, Kperiod) is the unslowed %K. To reproduce MetaTrader's slowing, sum the two parts over the slowing window and divide; ta.sma of the numerator and denominator works equally well because the two 1/slowing factors cancel. For STO_CLOSECLOSE replace high and low with close in the ta.highest/ta.lowest calls; for a non-SMA ma_method replace ta.sma in the %D line with ta.ema, ta.rma (SMMA) or ta.wma.

//@version=6
indicator("iStochastic port", overlay = false)
kLen    = input.int(5, "%K period", minval = 1)
dLen    = input.int(3, "%D period", minval = 1)
slowing = input.int(3, "Slowing", minval = 1)

hh = ta.highest(high, kLen)
ll = ta.lowest(low, kLen)
// MetaTrader slows the numerator and the denominator separately, then divides.
num = math.sum(close - ll, slowing)
den = math.sum(hh - ll, slowing)
k   = den == 0 ? 100.0 : num / den * 100
d   = ta.sma(k, dLen)

plot(k, "%K (MAIN_LINE)", color.rgb(30, 144, 255))
plot(d, "%D (SIGNAL_LINE)", color.red)
hline(80, "Upper", color.gray)
hline(20, "Lower", color.gray)

The MQL5 indicator this replaces, with the inputs that iStochastic takes:

#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_level1  20
#property indicator_level2  80
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrRed

input int            InpK       = 5;           // Kperiod
input int            InpD       = 3;           // Dperiod
input int            InpSlowing = 3;           // slowing
input ENUM_MA_METHOD InpMethod  = MODE_SMA;    // ma_method for %D
input ENUM_STO_PRICE InpField   = STO_LOWHIGH; // price_field

double KBuffer[];
double DBuffer[];
int    stoHandle;

int OnInit()
  {
   SetIndexBuffer(0, KBuffer, INDICATOR_DATA);
   SetIndexBuffer(1, DBuffer, INDICATOR_DATA);
   stoHandle = iStochastic(_Symbol, _Period, InpK, InpD, InpSlowing, InpMethod, InpField);
   if(stoHandle == 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(stoHandle) < rates_total)
      return(0);
   int to_copy = (prev_calculated == 0) ? rates_total : rates_total - prev_calculated + 1;
   if(CopyBuffer(stoHandle, MAIN_LINE,   0, to_copy, KBuffer) <= 0) return(0);
   if(CopyBuffer(stoHandle, SIGNAL_LINE, 0, to_copy, DBuffer) <= 0) return(0);
   return(rates_total);
  }

Where the two differ

TopicMQL5 iStochasticTradingView "Stochastic" (ta.sma of ta.stoch)Pine above
SlowingSum of numerators over sum of denominatorsAverage of per-bar ratiosSame as MT5
Zero range%K = 100na (0/0) for that bar100, same as MT5
%D methodAny ENUM_MA_METHODSMASMA; swap the function for other methods
Price fieldSTO_LOWHIGH or STO_CLOSECLOSEHigh/low only in ta.stoch(close, high, low, n); pass close three times for close/closeHigh/low as written
Warm-up0.0 until Kperiod + slowing − 2nana
Values when the range is steadyIdentical; the two slowing definitions only differ when HH − LL changes inside the slowing window

What the Stratlate converter emits

The MQL5 → Pine engine emits MetaTrader's form, not ta.stoch: its iStochastic entry expands MAIN_LINE to ta.sma(close − ta.lowest(low, K), slowing) / ta.sma(ta.highest(high, K) − ta.lowest(low, K), slowing) · 100 and SIGNAL_LINE to ta.sma of that over Dperiod; the catalog comment records that the ratio-of-averages form measured far from parity on a test indicator before this change. In the handle form the line is chosen from the CopyBuffer buffer index, reported as an approximation (MQLW0501). The ma_method and price_field arguments are not modelled: the emitted %D is always an SMA, the range is always high/low, and our probe logged STO_LOWHIGH as an identifier with no Pine mapping (MQLW0512). Check both lines against the MT5 chart after compiling.

Pitfalls

  • Porting %K as ta.sma(ta.stoch(close, high, low, K), slowing). The lines look alike and cross on different bars whenever the trading range expands or contracts within the slowing window.
  • Using ta.stoch with slowing > 1 and no smoothing at all. The MetaTrader line is slower; signals arrive earlier in Pine and overbought readings are more frequent.
  • Dividing by zero on a flat window. The hand-written version returns 100 like MetaTrader; ta.stoch returns na, and a crossover test against na is silently false.
  • Reading MetaTrader's 0.0 warm-up values as oversold. For the first Kperiod + slowing − 2 bars the buffer is 0.0, not a real reading.
  • Forgetting that ma_method applies to %D only. The slowing of %K is always a sum in MetaTrader regardless of the method chosen.

FAQ

Is MetaTrader's Stochastic the same as TradingView's built-in?

Not exactly. Both are slow stochastics with the same periods, but MetaTrader slows the numerator and denominator before dividing and TradingView averages the already-divided %K. They coincide when the high–low range is constant over the slowing window and differ otherwise.

How do I port STO_CLOSECLOSE?

Use ta.highest(close, K) and ta.lowest(close, K) in place of the high and low versions. Everything else in the formula stays the same.

What does slowing = 1 give?

The fast stochastic. The sums collapse to a single bar and %K equals ta.stoch(close, high, low, K) exactly, so in that case the built-in Pine function is a correct port.

Convert the whole program

Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 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