Squeeze Momentum: TradingView (Pine Script) to MT5 (MQL5)

Short answer

The squeeze is on while the Bollinger Bands sit inside the Keltner Channel; the momentum histogram is a linear regression of price relative to a mid-range anchor. Every part is a finite window, so a careful MQL5 port matches TradingView once the windows are full, apart from the cross-style dots.

Squeeze Momentum combines two things in one pane: a squeeze flag that is on while the Bollinger Bands sit inside the Keltner Channel, and a momentum histogram that is a linear regression of price relative to a mid-range anchor. All of its parts are finite windows (SMA, standard deviation, highest, lowest, regression), so a careful MQL5 port reproduces TradingView's values exactly once the windows are full. The only approximation worth knowing about is cosmetic: MetaTrader has no cross-style plot for the squeeze dots.

How Squeeze Momentum is calculated

Defaults: Bollinger length 20 and multiplier 2.0, Keltner length 20 and multiplier 1.5, Keltner width from the true range.

  • Bollinger Bands: bbMid = SMA(close, 20), bbUp/bbDn = bbMid ± 2.0 × stdev(close, 20). The standard deviation is the population form (divide by n), which is what ta.stdev computes.
  • Keltner Channel: kcMid = SMA(close, 20), kcUp/kcDn = kcMid ± 1.5 × SMA(range, 20) where range is the true range (or high - low if the option is off). Note the SMA of the range, not an EMA or ATR; that is what keeps this indicator free of seeding differences.
  • Squeeze on: bbDn > kcDn and bbUp < kcUp. Squeeze off: bbDn < kcDn and bbUp > kcUp. Neither: the bands straddle the channel.
  • Momentum: anchor = avg(avg(highest(high, 20), lowest(low, 20)), SMA(close, 20)), then mom = linreg(close - anchor, 20, 0), the value of the least-squares line through the last 20 differences at the current bar.
  • Colour: lime when mom > 0 and rising, green when positive and falling, red when negative and falling, maroon when negative and rising. The squeeze dot is black when on, gray when off, blue otherwise.

Pine Script v6 version

The script computes each component with the basic ta.* windows. ta.tr(true) makes the first bar's range high - low instead of na.

//@version=6
indicator("Squeeze Momentum, written out", "SQZ", overlay = false)

bbLen  = input.int(20, "Bollinger length", minval = 1)
bbMult = input.float(2.0, "Bollinger multiplier", minval = 0.1, step = 0.1)
kcLen  = input.int(20, "Keltner length", minval = 1)
kcMult = input.float(1.5, "Keltner multiplier", minval = 0.1, step = 0.1)
useTR  = input.bool(true, "Keltner width from true range")

// Bollinger Bands: SMA +/- k * population standard deviation
float bbMid = ta.sma(close, bbLen)
float bbDev = bbMult * ta.stdev(close, bbLen)
float bbUp  = bbMid + bbDev
float bbDn  = bbMid - bbDev

// Keltner Channel: SMA +/- k * SMA(range)
float kcMid = ta.sma(close, kcLen)
float rng   = useTR ? ta.tr(true) : high - low
float kcDev = kcMult * ta.sma(rng, kcLen)
float kcUp  = kcMid + kcDev
float kcDn  = kcMid - kcDev

bool squeezeOn  = bbDn > kcDn and bbUp < kcUp   // Bollinger inside Keltner
bool squeezeOff = bbDn < kcDn and bbUp > kcUp   // Bollinger outside Keltner

// Momentum: linear regression of price minus the midpoint of
// (Donchian middle, SMA)
float donchMid = math.avg(ta.highest(high, kcLen), ta.lowest(low, kcLen))
float anchor   = math.avg(donchMid, kcMid)
float mom      = ta.linreg(close - anchor, kcLen, 0)

color momColor = mom > 0 ? (mom > mom[1] ? color.lime : color.green) :
                           (mom < mom[1] ? color.red : color.maroon)
color sqzColor = squeezeOn ? color.black : squeezeOff ? color.gray : color.blue

plot(mom, "Momentum", momColor, 4, plot.style_histogram)
plot(0, "Squeeze", sqzColor, 2, plot.style_cross)
alertcondition(squeezeOff and squeezeOn[1], "Squeeze released", "Bollinger Bands left the Keltner Channel")

The mom > mom[1] test is false on the first bar with a value (mom[1] is na), so that bar is green or maroon rather than lime or red. The MQL5 code keeps the same rule.

MQL5 version

The indicator runs in a separate window with two plots: a DRAW_COLOR_HISTOGRAM with four colours and a DRAW_COLOR_ARROW at zero with three colours for the squeeze state. The window functions are written once over oldest-first arrays. Linreg() counts x as bars back (0 = current bar), so the intercept is the fitted value on the current bar, which is ta.linreg(..., 0).

//+------------------------------------------------------------------+
//| SqueezeMomentum_TV.mq5 - Bollinger-in-Keltner squeeze + momentum |
//+------------------------------------------------------------------+
#property indicator_separate_window
#property indicator_buffers 6
#property indicator_plots   2
#property indicator_label1  "Momentum"
#property indicator_type1   DRAW_COLOR_HISTOGRAM
#property indicator_color1  clrLime, clrGreen, clrRed, clrMaroon
#property indicator_width1  4
#property indicator_label2  "Squeeze"
#property indicator_type2   DRAW_COLOR_ARROW
#property indicator_color2  clrOrange, clrGray, clrBlue
#property indicator_width2  2
#property indicator_level1  0.0

input int    InpBbLen  = 20;    // Bollinger length
input double InpBbMult = 2.0;   // Bollinger multiplier
input int    InpKcLen  = 20;    // Keltner length
input double InpKcMult = 1.5;   // Keltner multiplier
input bool   InpUseTR  = true;  // Keltner width from true range

double Mom[], MomColor[], Sqz[], SqzColor[];   // drawn
double Rng[], Diff[];                          // per-bar state: range, close - anchor

int OnInit()
{
   if(InpBbLen < 1 || InpKcLen < 1)
      return INIT_PARAMETERS_INCORRECT;
   SetIndexBuffer(0, Mom,      INDICATOR_DATA);
   SetIndexBuffer(1, MomColor, INDICATOR_COLOR_INDEX);
   SetIndexBuffer(2, Sqz,      INDICATOR_DATA);
   SetIndexBuffer(3, SqzColor, INDICATOR_COLOR_INDEX);
   SetIndexBuffer(4, Rng,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(5, Diff, INDICATOR_CALCULATIONS);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(1, PLOT_ARROW, 159);   // small dot on the zero line
   IndicatorSetString(INDICATOR_SHORTNAME, "Squeeze(" + (string)InpBbLen + "," + (string)InpKcLen + ")");
   return INIT_SUCCEEDED;
}

// Window helpers over oldest-first arrays; EMPTY_VALUE until the window is full
double Sma(const double &a[], const int i, const int len)
{
   if(i < len - 1) return EMPTY_VALUE;
   double s = 0.0;
   for(int k = 0; k < len; k++) { if(a[i - k] == EMPTY_VALUE) return EMPTY_VALUE; s += a[i - k]; }
   return s / len;
}
double Stdev(const double &a[], const int i, const int len)   // population, like ta.stdev
{
   double m = Sma(a, i, len);
   if(m == EMPTY_VALUE) return EMPTY_VALUE;
   double acc = 0.0;
   for(int k = 0; k < len; k++) { double d = a[i - k] - m; acc += d * d; }
   return MathSqrt(acc / len);
}
double Highest(const double &a[], const int i, const int len)
{
   if(i < len - 1) return EMPTY_VALUE;
   double best = a[i];
   for(int k = 1; k < len; k++) if(a[i - k] > best) best = a[i - k];
   return best;
}
double Lowest(const double &a[], const int i, const int len)
{
   if(i < len - 1) return EMPTY_VALUE;
   double best = a[i];
   for(int k = 1; k < len; k++) if(a[i - k] < best) best = a[i - k];
   return best;
}
// Least-squares line through the last len values, evaluated at the current bar
// (ta.linreg with offset 0). x counts bars back: 0 = this bar.
double Linreg(const double &a[], const int i, const int len)
{
   if(len < 2 || i < len - 1) return EMPTY_VALUE;
   double sx = 0, sy = 0, sxy = 0, sxx = 0;
   for(int k = 0; k < len; k++)
   {
      if(a[i - k] == EMPTY_VALUE) return EMPTY_VALUE;
      sx += k; sy += a[i - k]; sxy += k * a[i - k]; sxx += (double)k * k;
   }
   double den = len * sxx - sx * sx;
   if(den == 0.0) return EMPTY_VALUE;
   double slope = (len * sxy - sx * sy) / den;
   return (sy - slope * sx) / len;          // intercept = value at x = 0
}

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 > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      // Bollinger Bands on close
      double bbMid = Sma(close, i, InpBbLen);
      double bbDev = Stdev(close, i, InpBbLen);
      // Keltner Channel: SMA of close +/- mult * SMA(range)
      Rng[i] = (!InpUseTR || i == 0) ? high[i] - low[i]
             : MathMax(high[i] - low[i], MathMax(MathAbs(high[i] - close[i - 1]), MathAbs(low[i] - close[i - 1])));
      double kcMid = Sma(close, i, InpKcLen);
      double kcDev = Sma(Rng, i, InpKcLen);
      // Momentum: regression of close minus the average of Donchian middle and SMA
      double hh = Highest(high, i, InpKcLen), ll = Lowest(low, i, InpKcLen);
      Diff[i] = (hh == EMPTY_VALUE || kcMid == EMPTY_VALUE) ? EMPTY_VALUE
              : close[i] - ((hh + ll) / 2.0 + kcMid) / 2.0;
      Mom[i] = Linreg(Diff, i, InpKcLen);

      if(bbMid == EMPTY_VALUE || kcDev == EMPTY_VALUE || Mom[i] == EMPTY_VALUE)
      {
         Mom[i] = EMPTY_VALUE; MomColor[i] = 0; Sqz[i] = EMPTY_VALUE; SqzColor[i] = 2;
         continue;
      }
      double bbUp = bbMid + InpBbMult * bbDev, bbDn = bbMid - InpBbMult * bbDev;
      double kcUp = kcMid + InpKcMult * kcDev, kcDn = kcMid - InpKcMult * kcDev;
      bool squeezeOn  = (bbDn > kcDn && bbUp < kcUp);
      bool squeezeOff = (bbDn < kcDn && bbUp > kcUp);

      // Compare with the previous bar; with no previous value (mom[1] is na in
      // Pine) the "rising"/"falling" test is false, as it is on TradingView
      bool havePrev = (i > 0 && Mom[i - 1] != EMPTY_VALUE);
      if(Mom[i] > 0) MomColor[i] = (havePrev && Mom[i] > Mom[i - 1]) ? 0 : 1;   // lime rising, green fading
      else           MomColor[i] = (havePrev && Mom[i] < Mom[i - 1]) ? 2 : 3;   // red falling, maroon fading
      Sqz[i] = 0.0;
      SqzColor[i] = squeezeOn ? 0 : (squeezeOff ? 1 : 2);
   }
   return rates_total;
}

Diff holds close - anchor per bar because the regression needs the last 20 of them; this is the MQL5 equivalent of Pine quietly keeping a history for the expression close - anchor. The histogram width of 4 approximates Pine's linewidth = 4.

Differences you will see on the chart

TopicTradingViewMetaTrader 5
Warm-upHistogram starts on bar 19 (20-bar windows); the squeeze dot is drawn blue from bar 0 because the band comparisons are false while the bands are na.Histogram starts on bar 19; the dots also start on bar 19 (EMPTY_VALUE before).
ValuesIdentical after warm-up. There is no EMA or RMA anywhere, so the loaded history depth does not matter.
Squeeze markerplot.style_cross at zero.A Wingdings dot (code 159) via DRAW_COLOR_ARROW; the squeeze-on colour is orange instead of black so it is visible on a dark chart. Change indicator_color2 if you prefer black.
Zero lineImplied by the histogram base.Drawn by indicator_level1 0.0.
Realtime barLast histogram bar and dot recalculate every tick.Same.

No part of the indicator repaints closed bars.

What the Stratlate converter does with this script

Converted with the Stratlate engine, the script above is graded APPROXIMATED, not CLEAN, for one reason the report names: warning PM295, "plot.style_cross is drawn as a line; the requested plot style is not preserved". The squeeze dots become a DRAW_COLOR_LINE at zero whose colour changes with the squeeze state, which carries the same information in a different shape. Everything else is exact: ta.sma, ta.stdev, ta.highest and ta.lowest map to the pine_sma, pine_stdev, pine_highest and pine_lowest helpers; the computed sources rng and close - anchor are materialised into per-call-site series so that pine_sma and pine_linreg can read their windows; plot.style_histogram with a per-bar colour becomes a DRAW_COLOR_HISTOGRAM; and the pane goes to indicator_separate_window because the script declares overlay = false. Compile and backtest the output as usual.

Using it in MetaTrader 5

  1. Save as SqueezeMomentum_TV.mq5 in MQL5\Indicators, compile with F7 (no warnings) and attach it; it opens its own subwindow.
  2. Keep both lengths at 20 and the multipliers at 2.0 and 1.5 to match the common TradingView settings; switch Keltner width from true range off if the Pine script you are matching uses high - low.
  3. From an EA, iCustom(_Symbol, _Period, "SqueezeMomentum_TV", 20, 2.0, 20, 1.5, true); buffer 0 is the momentum, buffer 1 its colour index (0 lime, 1 green, 2 red, 3 maroon), buffer 3 the squeeze colour index (0 on, 1 off, 2 neither). A "squeeze released" event is buffer 3 going from 0 to 1 between two closed bars.
  4. To alert on the release, compare SqzColor[rates_total - 2] with SqzColor[rates_total - 3] when a new bar opens.

Pitfalls

  • Taking the Keltner width from iATR. The width here is a plain SMA of the true range, which no standard MetaTrader indicator provides; with iATR the channel is a different width and the squeeze turns on and off on different bars.
  • Sample standard deviation. Dividing by n - 1 widens the bands by about 2.5% at n = 20, enough to flip borderline squeeze bars.
  • Regression x-axis direction. Fitting with x = 0 at the oldest bar and reading the intercept returns the fitted value 19 bars ago. Either count x backwards as above or evaluate the line at x = n - 1.
  • Histogram colour from a sign only. The four-colour rule needs the previous momentum; a two-colour port loses the "fading" states traders read for exits.
  • Black squeeze dots. On MetaTrader's default black background they are invisible; pick a visible colour or set a chart background.

FAQ

Why does the MQL5 histogram match TradingView exactly when other indicators drift?

Every component is a fixed-length window over raw prices, with no recursive average. Given the same 20 bars both platforms produce the same number, so the only thing that can differ is the bar data itself.

Can I draw a real cross for the squeeze state in MetaTrader?

Use DRAW_COLOR_ARROW with a Wingdings code that looks like a cross (for example 251 or 252) instead of the dot used above. There is no line style that draws crosses, which is why the converter reports plot.style_cross as an approximation.

Is the momentum the same as ta.linreg(close - anchor, 20, 0) in Pine?

Yes. ta.linreg with offset 0 returns the least-squares line evaluated at the current bar, and Linreg() above computes the same intercept with bars counted backwards from the current one.

Convert your own version

Have a variant of this indicator, or any other TradingView script? Paste it and get MQL5 that is checked against the original on the same price history, with every construct that could not be carried over reported.

Open the converter

Related