Twin Range Filter in MQL5 — converted from Pine Script

The Twin Range Filter indicator by colinmck, published on TradingView under the Mozilla Public License 2.0, converted to MetaTrader 5 by the Stratlate engine. The conversion was executed against the original on 500 synthetic bars and compared value by value: equivalent (fidelity 1.000).

Direction
Pine Script → MQL5
Kind
indicator, drawn on the price chart
Verdict
EQUIVALENT on 500 bars
Engine
pinec 0.6.46
Conversion notes
5 informational
Source
125 lines of Pine v4

Inputs

InputDefault
Sourceclose
Fast period27
Fast range1.6
Slow period55
Slow range2

Converted MQL5

Save as twin-range-filter.mq5 next to PineRuntime.mqh (included with every conversion), compile in MetaEditor, then review and backtest before trading. Output of the engine alone; the AI review available after sign-in may improve it further.

//+------------------------------------------------------------------+
//| pine-transpiler 0.6.46 (pinec) - generated code
//| source sha256: ca2d542653e1   status: CLEAN
//| notes: 0 unsupported, 0 warn, 5 info
//| Review, compile and backtest before trading.
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Twin Range Filter
//| Converted from Pine Script by pine-transpiler.
//| Review before trading: see the accompanying report for every
//| construct that was approximated or could not be converted.
//+------------------------------------------------------------------+
#property copyright "Converted by pine-transpiler"
#property version   "1.00"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   2
#property indicator_label1  "Long"
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrDodgerBlue
#property indicator_width1  1
#property indicator_label2  "Short"
#property indicator_type2   DRAW_ARROW
#property indicator_color2  clrDodgerBlue
#property indicator_width2  1

#include "PineRuntime.mqh"

//--- plot buffers
double Buf0[];
double Buf1[];

//--- script-level state
// The newest bar's index: `last_bar_index` and `barstate.islast`.
int    __pineLastBar = 0;
// Series-valued names are arrays because their history is read;
// the rest stay scalars.
double smrng1 = PINE_NA;
double smrng2 = PINE_NA;
double smrng = PINE_NA;
double filt[];
double upward[];
double downward[];
double hband = PINE_NA;
double lband = PINE_NA;
bool longCond = false;
bool shortCond = false;
double CondIni[];
bool long_ = false;
bool short_ = false;

//--- live-tick rollback: the state each bar started from
double __sv_smrng1;
double __si_smrng1;
double __sv_smrng2;
double __si_smrng2;
double __sv_smrng;
double __si_smrng;
double __sv_hband;
double __si_hband;
double __sv_lband;
double __si_lband;
bool __sv_longCond;
bool __si_longCond;
bool __sv_shortCond;
bool __si_shortCond;
bool __sv_long_;
bool __si_long_;
bool __sv_short_;
bool __si_short_;
int __pineSnapBar = -1;
void __pineSaveState()
{
   __sv_smrng1 = smrng1;
   __sv_smrng2 = smrng2;
   __sv_smrng = smrng;
   __sv_hband = hband;
   __sv_lband = lband;
   __sv_longCond = longCond;
   __sv_shortCond = shortCond;
   __sv_long_ = long_;
   __sv_short_ = short_;
   pine_draw_mark();
   __pineSaveGen++;   // helpers' static arrays snapshot lazily
}
void __pineRestoreState()
{
   smrng1 = __sv_smrng1;
   smrng2 = __sv_smrng2;
   smrng = __sv_smrng;
   hband = __sv_hband;
   lband = __sv_lband;
   longCond = __sv_longCond;
   shortCond = __sv_shortCond;
   long_ = __sv_long_;
   short_ = __sv_short_;
   pine_draw_rollback();
   __pineRestoreGen++;
   __pineRestoreSaveGen = __pineSaveGen;
}
void __pineSaveInitial()
{
   __si_smrng1 = smrng1;
   __si_smrng2 = smrng2;
   __si_smrng = smrng;
   __si_hband = hband;
   __si_lband = lband;
   __si_longCond = longCond;
   __si_shortCond = shortCond;
   __si_long_ = long_;
   __si_short_ = short_;
   pine_draw_save_initial();
}
void __pineRestoreInitial()
{
   smrng1 = __si_smrng1;
   smrng2 = __si_smrng2;
   smrng = __si_smrng;
   hband = __si_hband;
   lband = __si_lband;
   longCond = __si_longCond;
   shortCond = __si_shortCond;
   long_ = __si_long_;
   short_ = __si_short_;
   pine_draw_reset();
   __pineInitGen++;
}

double __st0[];    // accumulator for one stateful call site
double __stb0[];   // secondary buffer (e.g. true range for ATR)
double __st1[];    // accumulator for one stateful call site
double __stb1[];   // secondary buffer (e.g. true range for ATR)
double __st2[];    // accumulator for one stateful call site
double __stb2[];   // secondary buffer (e.g. true range for ATR)
double __st3[];    // accumulator for one stateful call site
double __stb3[];   // secondary buffer (e.g. true range for ATR)
double __source[];   // Pine's `source` as a real series, filled per bar
double __fl_rngfilt_rngfilt[];   // history of `rngfilt`, a local of rngfilt() the script reads with [n]

//--- inputs
input ENUM_APPLIED_PRICE source = PRICE_CLOSE;   // Source
input int per1 = 27;   // Fast period
input double mult1 = 1.6;   // Fast range
input int per2 = 55;   // Slow period
input int mult2 = 2;   // Slow range

//--- user functions
double smoothrng(const double &x[], const int t, const double m, const int __pineBar)
{
   double wper = ((t * 2) - 1);
   double avrng = pine_ema_step(MathAbs((x[__pineBar] - pine_hist(x, __pineBar, (int)(1)))), __st0, __stb0, __pineBar, (int)(t));
   double smoothrng = (pine_ema_step(avrng, __st1, __stb1, __pineBar, (int)(wper)) * m);
   return smoothrng;
   return PINE_NA;
}

double rngfilt(const double x, const double r, const int __pineBar)
{
   __fl_rngfilt_rngfilt[__pineBar] = x;
   __fl_rngfilt_rngfilt[__pineBar] = ((x > pine_nz(pine_hist(__fl_rngfilt_rngfilt, __pineBar, (int)(1)))) ? (((x - r) < pine_nz(pine_hist(__fl_rngfilt_rngfilt, __pineBar, (int)(1)))) ? pine_nz(pine_hist(__fl_rngfilt_rngfilt, __pineBar, (int)(1))) : (x - r)) : (((x + r) > pine_nz(pine_hist(__fl_rngfilt_rngfilt, __pineBar, (int)(1)))) ? pine_nz(pine_hist(__fl_rngfilt_rngfilt, __pineBar, (int)(1))) : (x + r)));
   return __fl_rngfilt_rngfilt[__pineBar];
   return PINE_NA;
}

double smoothrng__site1(const double &x[], const int t, const double m, const int __pineBar)
{
   double wper = ((t * 2) - 1);
   double avrng = pine_ema_step(MathAbs((x[__pineBar] - pine_hist(x, __pineBar, (int)(1)))), __st2, __stb2, __pineBar, (int)(t));
   double smoothrng = (pine_ema_step(avrng, __st3, __stb3, __pineBar, (int)(wper)) * m);
   return smoothrng;
   return PINE_NA;
}

int OnInit()
{
   if(per1 < 1) { Print("Fast period", " must be at least 1"); return INIT_PARAMETERS_INCORRECT; }
   if(mult1 < 0.1) { Print("Fast range", " must be at least 0.1"); return INIT_PARAMETERS_INCORRECT; }
   if(per2 < 1) { Print("Slow period", " must be at least 1"); return INIT_PARAMETERS_INCORRECT; }
   if(mult2 < 0.1) { Print("Slow range", " must be at least 0.1"); return INIT_PARAMETERS_INCORRECT; }
   longCond = (bool)(PINE_NA);
   shortCond = (bool)(PINE_NA);
   SetIndexBuffer(0, Buf0, INDICATOR_DATA);
   SetIndexBuffer(1, Buf1, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(0, PLOT_LINE_COLOR, C'0,230,118');
   PlotIndexSetInteger(1, PLOT_LINE_COLOR, C'242,54,69');
   PlotIndexSetInteger(0, PLOT_DRAW_TYPE, DRAW_ARROW);
   PlotIndexSetInteger(0, PLOT_ARROW, 241);
   PlotIndexSetInteger(0, PLOT_ARROW_SHIFT, 16);
   PlotIndexSetInteger(1, PLOT_DRAW_TYPE, DRAW_ARROW);
   PlotIndexSetInteger(1, PLOT_ARROW, 242);
   PlotIndexSetInteger(1, PLOT_ARROW_SHIFT, -16);
   IndicatorSetString(INDICATOR_SHORTNAME, "Twin Range Filter");
   __pineSaveInitial();
   return INIT_SUCCEEDED;
}

//--- one bar == one evaluation of the original Pine script
void PineBar(const int __pineBar,
             const double   &open[],  const double &high[],
             const double   &low[],   const double &close[],
             const long     &volume[],
             const datetime &time[])
{
   __source[__pineBar] = pine_source(source, open, high, low, close, __pineBar);
   if(__pineBar > 0)
   {
      filt[__pineBar] = filt[__pineBar - 1];
      upward[__pineBar] = upward[__pineBar - 1];
      downward[__pineBar] = downward[__pineBar - 1];
      CondIni[__pineBar] = CondIni[__pineBar - 1];
   }
   smrng1 = smoothrng(__source, per1, mult1, __pineBar);
   smrng2 = smoothrng__site1(__source, per2, mult2, __pineBar);
   smrng = pine_div((smrng1 + smrng2), 2);
   filt[__pineBar] = rngfilt(pine_source(source, open, high, low, close, __pineBar), smrng, __pineBar);
   upward[__pineBar] = 0.0;
   upward[__pineBar] = ((filt[__pineBar] > pine_hist(filt, __pineBar, (int)(1))) ? (pine_nz(pine_hist(upward, __pineBar, (int)(1))) + 1) : ((filt[__pineBar] < pine_hist(filt, __pineBar, (int)(1))) ? 0 : pine_nz(pine_hist(upward, __pineBar, (int)(1)))));
   downward[__pineBar] = 0.0;
   downward[__pineBar] = ((filt[__pineBar] < pine_hist(filt, __pineBar, (int)(1))) ? (pine_nz(pine_hist(downward, __pineBar, (int)(1))) + 1) : ((filt[__pineBar] > pine_hist(filt, __pineBar, (int)(1))) ? 0 : pine_nz(pine_hist(downward, __pineBar, (int)(1)))));
   hband = (filt[__pineBar] + smrng);
   lband = (filt[__pineBar] - smrng);
   longCond = (bool)(PINE_NA);
   shortCond = (bool)(PINE_NA);
   longCond = ((((((((((pine_source(source, open, high, low, close, __pineBar) > filt[__pineBar]) ? 1 : 0) & ((pine_source(source, open, high, low, close, __pineBar) > pine_hist(__source, __pineBar, (int)(1))) ? 1 : 0)) != 0) ? 1 : 0) & ((upward[__pineBar] > 0) ? 1 : 0)) != 0) ? 1 : 0) | ((((((((pine_source(source, open, high, low, close, __pineBar) > filt[__pineBar]) ? 1 : 0) & ((pine_source(source, open, high, low, close, __pineBar) < pine_hist(__source, __pineBar, (int)(1))) ? 1 : 0)) != 0) ? 1 : 0) & ((upward[__pineBar] > 0) ? 1 : 0)) != 0) ? 1 : 0)) != 0);
   shortCond = ((((((((((pine_source(source, open, high, low, close, __pineBar) < filt[__pineBar]) ? 1 : 0) & ((pine_source(source, open, high, low, close, __pineBar) < pine_hist(__source, __pineBar, (int)(1))) ? 1 : 0)) != 0) ? 1 : 0) & ((downward[__pineBar] > 0) ? 1 : 0)) != 0) ? 1 : 0) | ((((((((pine_source(source, open, high, low, close, __pineBar) < filt[__pineBar]) ? 1 : 0) & ((pine_source(source, open, high, low, close, __pineBar) > pine_hist(__source, __pineBar, (int)(1))) ? 1 : 0)) != 0) ? 1 : 0) & ((downward[__pineBar] > 0) ? 1 : 0)) != 0) ? 1 : 0)) != 0);
   CondIni[__pineBar] = 0;
   CondIni[__pineBar] = (longCond ? 1 : (shortCond ? (-1) : pine_hist(CondIni, __pineBar, (int)(1))));
   long_ = (((longCond ? 1 : 0) & ((pine_hist(CondIni, __pineBar, (int)(1)) == (-1)) ? 1 : 0)) != 0);
   short_ = (((shortCond ? 1 : 0) & ((pine_hist(CondIni, __pineBar, (int)(1)) == 1) ? 1 : 0)) != 0);
   pine_alertcond(long_, "Long", 489427271, __pineBar, __pineLastBar);
   pine_alertcond(short_, "Short", 1922745637, __pineBar, __pineLastBar);
   Buf0[__pineBar] = long_ ? low[__pineBar] : EMPTY_VALUE;
   pine_shape_text("0", __pineBar, Buf0[__pineBar], "Long", C'0,230,118', false);
   Buf1[__pineBar] = short_ ? high[__pineBar] : EMPTY_VALUE;
   pine_shape_text("1", __pineBar, Buf1[__pineBar], "Short", C'242,54,69', true);
}

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[])
{
   // Pine evaluates oldest-to-newest. MQL4 hands OnCalculate
   // SERIES-indexed arrays (0 == newest) while MQL5 hands over
   // oldest-first, so the direction is forced explicitly rather
   // than relying on either default. `x[n]` is then index i - n
   // in both dialects, and the generated logic is identical.
   ArraySetAsSeries(open,  false);
   ArraySetAsSeries(high,  false);
   ArraySetAsSeries(low,   false);
   ArraySetAsSeries(close, false);
   ArraySetAsSeries(tick_volume, false);
   ArraySetAsSeries(volume, false);
   ArraySetAsSeries(time,  false);
   ArrayResize(filt, rates_total);
   ArrayResize(upward, rates_total);
   ArrayResize(downward, rates_total);
   ArrayResize(CondIni, rates_total);
   ArrayResize(__st0, rates_total);
   ArrayResize(__stb0, rates_total);
   ArrayResize(__st1, rates_total);
   ArrayResize(__stb1, rates_total);
   ArrayResize(__st2, rates_total);
   ArrayResize(__stb2, rates_total);
   ArrayResize(__st3, rates_total);
   ArrayResize(__stb3, rates_total);
   ArrayResize(__source, rates_total);
   ArrayResize(__fl_rngfilt_rngfilt, rates_total);
   if(prev_calculated == 0)
   {
      ArrayInitialize(filt, PINE_NA);
      ArrayInitialize(upward, PINE_NA);
      ArrayInitialize(downward, PINE_NA);
      ArrayInitialize(CondIni, PINE_NA);
      ArrayInitialize(__st0, PINE_NA);
      ArrayInitialize(__stb0, PINE_NA);
      ArrayInitialize(__st1, PINE_NA);
      ArrayInitialize(__stb1, PINE_NA);
      ArrayInitialize(__st2, PINE_NA);
      ArrayInitialize(__stb2, PINE_NA);
      ArrayInitialize(__st3, PINE_NA);
      ArrayInitialize(__stb3, PINE_NA);
      ArrayInitialize(__source, PINE_NA);
      ArrayInitialize(__fl_rngfilt_rngfilt, PINE_NA);
   }

   __pineLastBar = rates_total - 1;
   const int start = (prev_calculated > 1) ? prev_calculated - 1 : 0;
   static bool __pineRealVolume = false;
   if(start == 0)
   {
      __pineRestoreInitial();
      __pineSnapBar = -1;
      __pineRealVolume = rates_total > 0 && volume[rates_total - 1] > 0;
   }
   __pineRealtime = prev_calculated > 0;
   for(int __pineBar = start; __pineBar < rates_total; __pineBar++)
   {
      if(__pineBar == __pineSnapBar)
         __pineRestoreState();   // a re-run of this bar: back to its start
      else if(__pineBar == __pineLastBar)
      {
         __pineSaveState();      // the forming bar: remember the state it starts from
         __pineSnapBar = __pineBar;
      }
      if(__pineRealVolume) PineBar(__pineBar, open, high, low, close, volume, time);
      else PineBar(__pineBar, open, high, low, close, tick_volume, time);
   }

   return rates_total;
}

void OnDeinit(const int reason)
{
   ObjectsDeleteAll(0, "pine_");
}

Original Pine Script

© colinmck — Mozilla Public License 2.0. Reproduced for attribution and comparison; the converted code above is a derivative work offered under the same licence.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// © colinmck



//@version=4



study(title="Twin Range Filter", overlay=true)



source = input(defval=close, title="Source")



// Smooth Average Range



per1 = input(defval=27, minval=1, title="Fast period")

mult1 = input(defval=1.6, minval=0.1, title="Fast range")



per2 = input(defval=55, minval=1, title="Slow period")

mult2 = input(defval=2, minval=0.1, title="Slow range")



smoothrng(x, t, m) =>

    wper = t * 2 - 1

    avrng = ema(abs(x - x[1]), t)

    smoothrng = ema(avrng, wper) * m

    smoothrng

smrng1 = smoothrng(source, per1, mult1)

smrng2 = smoothrng(source, per2, mult2)

smrng = (smrng1 + smrng2) / 2



// Range Filter



rngfilt(x, r) =>

    rngfilt = x

    rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r : 

       x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r

    rngfilt

filt = rngfilt(source, smrng)



upward = 0.0

upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])

downward = 0.0

downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])



hband = filt + smrng

lband = filt - smrng



longCond = bool(na)

shortCond = bool(na)

longCond := source > filt and source > source[1] and upward > 0 or source > filt and source < source[1] and upward > 0

shortCond := source < filt and source < source[1] and downward > 0 or source < filt and source > source[1] and downward > 0



CondIni = 0

CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]



long = longCond and CondIni[1] == -1

short = shortCond and CondIni[1] == 1



// Plotting



plotshape(long, title="Long", text="Long", style=shape.labelup, textcolor=color.black, size=size.tiny, location=location.belowbar, color=color.lime, transp=0)

plotshape(short, title="Short", text="Short", style=shape.labeldown, textcolor=color.white, size=size.tiny, location=location.abovebar, color=color.red, transp=0)



// Alerts



alertcondition(long, title="Long", message="Long")

alertcondition(short, title="Short", message="Short")

Convert your own Pine Script to MQL5

Your first conversion is free, in either direction. Paste a TradingView indicator or strategy and get MQL5 or MQL4 source, with every construct the engine could not map flagged by line.

Open the converter

More: all example conversions · how Pine Script maps to MQL5 · how the engine measures