Range Filter [DW] in MQL5 — converted from Pine Script
The Range Filter [DW] indicator by DonovanWall, 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).
██████╗ ██╗ ██╗ ██╔══██╗██║ ██║ ██║ ██║██║ █╗ ██║ ██║ ██║██║███╗██║ ██████╔╝╚███╔███╔╝ ╚═════╝ ╚══╝╚══╝
Inputs
| Input | Default |
|---|---|
| Filter Type | "Type 1" |
| Movement Source | "Close" |
| Range Size | 2.618 |
| Range Scale | "Average Change" |
| Range Period (for ATR, Average Change, and Standard Deviation) | 14 |
| Smooth Range | true |
| Smoothing Period | 27 |
| Average Filter Changes | false |
| Number Of Changes To Average | 2 |
Plots
External Output - Trend Signal.
Converted MQL5
Save as 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: e6be6077e894 status: CLEAN
//| notes: 0 unsupported, 0 warn, 9 info
//| Review, compile and backtest before trading.
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Range Filter [DW]
//| 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 9
#property indicator_plots 6
#property indicator_label1 "High Band Fill"
#property indicator_type1 DRAW_FILLING
#property indicator_color1 clrDodgerBlue
#property indicator_width1 1
#property indicator_label2 "Low Band Fill"
#property indicator_type2 DRAW_FILLING
#property indicator_color2 clrDodgerBlue
#property indicator_width2 1
#property indicator_label3 "Filter"
#property indicator_type3 DRAW_COLOR_LINE
#property indicator_color3 clrDodgerBlue
#property indicator_width3 3
#property indicator_label4 "High Band"
#property indicator_type4 DRAW_LINE
#property indicator_color4 clrDodgerBlue
#property indicator_width4 1
#property indicator_label5 "Low Band"
#property indicator_type5 DRAW_LINE
#property indicator_color5 clrDodgerBlue
#property indicator_width5 1
#property indicator_label6 "External Output - Trend Signal"
#property indicator_type6 DRAW_NONE
#property indicator_color6 clrDodgerBlue
#property indicator_width6 1
#include "PineRuntime.mqh"
//--- plot buffers
double PineFill0[];
double PineFill1[];
double PineFill2[];
double PineFill3[];
double Buf4[];
double Buf5[];
double Buf6[];
double Buf7[];
double Buf8[];
color __pal2[64]; // the colours plot 2 has drawn so far; see pine_color_slot
int __paln2 = 0;
//--- 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 h_val = PINE_NA;
double l_val = PINE_NA;
double h_band = PINE_NA;
double l_band = PINE_NA;
double filt[];
double fdir = 0.0;
int upward = 0;
int downward = 0;
color filt_color = clrNONE;
color bar_color = clrNONE;
//--- live-tick rollback: the state each bar started from
double __sv_h_val;
double __si_h_val;
double __sv_l_val;
double __si_l_val;
double __sv_h_band;
double __si_h_band;
double __sv_l_band;
double __si_l_band;
double __sv_fdir;
double __si_fdir;
int __sv_upward;
int __si_upward;
int __sv_downward;
int __si_downward;
color __sv_filt_color;
color __si_filt_color;
color __sv_bar_color;
color __si_bar_color;
int __pineSnapBar = -1;
void __pineSaveState()
{
__sv_h_val = h_val;
__sv_l_val = l_val;
__sv_h_band = h_band;
__sv_l_band = l_band;
__sv_fdir = fdir;
__sv_upward = upward;
__sv_downward = downward;
__sv_filt_color = filt_color;
__sv_bar_color = bar_color;
pine_draw_mark();
__pineSaveGen++; // helpers' static arrays snapshot lazily
}
void __pineRestoreState()
{
h_val = __sv_h_val;
l_val = __sv_l_val;
h_band = __sv_h_band;
l_band = __sv_l_band;
fdir = __sv_fdir;
upward = __sv_upward;
downward = __sv_downward;
filt_color = __sv_filt_color;
bar_color = __sv_bar_color;
pine_draw_rollback();
__pineRestoreGen++;
__pineRestoreSaveGen = __pineSaveGen;
}
void __pineSaveInitial()
{
__si_h_val = h_val;
__si_l_val = l_val;
__si_h_band = h_band;
__si_l_band = l_band;
__si_fdir = fdir;
__si_upward = upward;
__si_downward = downward;
__si_filt_color = filt_color;
__si_bar_color = bar_color;
pine_draw_save_initial();
}
void __pineRestoreInitial()
{
h_val = __si_h_val;
l_val = __si_l_val;
h_band = __si_h_band;
l_band = __si_l_band;
fdir = __si_fdir;
upward = __si_upward;
downward = __si_downward;
filt_color = __si_filt_color;
bar_color = __si_bar_color;
pine_draw_reset();
__pineInitGen++;
}
string f_type = ""; // input the script modifies; reset each bar
string mov_src = ""; // input the script modifies; reset each bar
string rng_scale = ""; // input the script modifies; reset each bar
double __st0[]; // accumulator for one stateful call site
double __stb0[]; // secondary buffer (e.g. true range for ATR)
double __fl_rng_filt_rng_filt1[]; // history of `rng_filt1`, a local of rng_filt() the script reads with [n]
double __ti0[]; // materialised ta.* source: pine_div((h_val + l_val), 2)
//--- inputs
enum ENUM_F_TYPE_OPTS
{
f_type_opt0, // Type 1
f_type_opt1 // Type 2
};
string f_type_Labels[] = {"Type 1", "Type 2"};
input ENUM_F_TYPE_OPTS f_type_Input = f_type_opt0; // Filter Type
enum ENUM_MOV_SRC_OPTS
{
mov_src_opt0, // Wicks
mov_src_opt1 // Close
};
string mov_src_Labels[] = {"Wicks", "Close"};
input ENUM_MOV_SRC_OPTS mov_src_Input = mov_src_opt1; // Movement Source
input double rng_qty = 2.618; // Range Size
enum ENUM_RNG_SCALE_OPTS
{
rng_scale_opt0, // Points
rng_scale_opt1, // Pips
rng_scale_opt2, // Ticks
rng_scale_opt3, // % of Price
rng_scale_opt4, // ATR
rng_scale_opt5, // Average Change
rng_scale_opt6, // Standard Deviation
rng_scale_opt7 // Absolute
};
string rng_scale_Labels[] = {"Points", "Pips", "Ticks", "% of Price", "ATR", "Average Change", "Standard Deviation", "Absolute"};
input ENUM_RNG_SCALE_OPTS rng_scale_Input = rng_scale_opt5; // Range Scale
input int rng_per = 14; // Range Period (for ATR, Average Change, and Standard Deviation)
input bool smooth_range = true; // Smooth Range
input int smooth_per = 27; // Smoothing Period
input bool av_vals = false; // Average Filter Changes
input int av_samples = 2; // Number Of Changes To Average
//--- user functions
double Cond_EMA(const double x, const double cond, const int n, const int __pineBar)
{
static double val[];
static bool val__once = false;
static double val__sv[];
static bool val__once__sv = false;
static int val__sg = -1, val__rg = 0, val__ig = 0;
if(val__ig != __pineInitGen)
{
val__ig = __pineInitGen; val__rg = __pineRestoreGen; val__sg = -1;
ArrayFree(val); val__once = false;
}
if(val__rg != __pineRestoreGen)
{
val__rg = __pineRestoreGen;
if(val__sg == __pineRestoreSaveGen)
{
ArrayFree(val); ArrayCopy(val, val__sv); val__once = val__once__sv;
}
}
if(val__sg != __pineSaveGen)
{
val__sg = __pineSaveGen;
ArrayFree(val__sv); ArrayCopy(val__sv, val); val__once__sv = val__once;
}
if(!val__once)
{
val__once = true;
ArrayResize(val, (int)(0));
ArrayInitialize(val, PINE_NA); // Pine's default element is na
}
static double ema_val[];
static bool ema_val__once = false;
static double ema_val__sv[];
static bool ema_val__once__sv = false;
static int ema_val__sg = -1, ema_val__rg = 0, ema_val__ig = 0;
if(ema_val__ig != __pineInitGen)
{
ema_val__ig = __pineInitGen; ema_val__rg = __pineRestoreGen; ema_val__sg = -1;
ArrayFree(ema_val); ema_val__once = false;
}
if(ema_val__rg != __pineRestoreGen)
{
ema_val__rg = __pineRestoreGen;
if(ema_val__sg == __pineRestoreSaveGen)
{
ArrayFree(ema_val); ArrayCopy(ema_val, ema_val__sv); ema_val__once = ema_val__once__sv;
}
}
if(ema_val__sg != __pineSaveGen)
{
ema_val__sg = __pineSaveGen;
ArrayFree(ema_val__sv); ArrayCopy(ema_val__sv, ema_val); ema_val__once__sv = ema_val__once;
}
if(!ema_val__once)
{
ema_val__once = true;
ArrayResize(ema_val, (int)(1));
ArrayInitialize(ema_val, PINE_NA); // Pine's default element is na
}
if(pine_truthy(cond))
{
pine_arr_push(val, x);
if((pine_arr_size(val) > 1))
{
pine_arr_remove(val, (int)(0));
}
if(pine_na(ema_val[pine_idx(0)]))
{
pine_arr_fill(ema_val, val[pine_idx(0)]);
}
ema_val[pine_idx(0)] = (((val[pine_idx(0)] - ema_val[pine_idx(0)]) * pine_div(2, (n + 1))) + ema_val[pine_idx(0)]);
}
double EMA = ema_val[pine_idx(0)];
return EMA;
return PINE_NA;
}
double Cond_SMA(const double x, const int cond, const int n, const int __pineBar)
{
static double vals[];
static bool vals__once = false;
static double vals__sv[];
static bool vals__once__sv = false;
static int vals__sg = -1, vals__rg = 0, vals__ig = 0;
if(vals__ig != __pineInitGen)
{
vals__ig = __pineInitGen; vals__rg = __pineRestoreGen; vals__sg = -1;
ArrayFree(vals); vals__once = false;
}
if(vals__rg != __pineRestoreGen)
{
vals__rg = __pineRestoreGen;
if(vals__sg == __pineRestoreSaveGen)
{
ArrayFree(vals); ArrayCopy(vals, vals__sv); vals__once = vals__once__sv;
}
}
if(vals__sg != __pineSaveGen)
{
vals__sg = __pineSaveGen;
ArrayFree(vals__sv); ArrayCopy(vals__sv, vals); vals__once__sv = vals__once;
}
if(!vals__once)
{
vals__once = true;
ArrayResize(vals, (int)(0));
ArrayInitialize(vals, PINE_NA); // Pine's default element is na
}
if(pine_truthy(cond))
{
pine_arr_push(vals, x);
if((pine_arr_size(vals) > n))
{
pine_arr_remove(vals, (int)(0));
}
}
double SMA = pine_arr_avg(vals);
return SMA;
return PINE_NA;
}
double Stdev(const double x, const int n, const int __pineBar)
{
return MathSqrt((Cond_SMA(MathPow(x, 2), 1, n, __pineBar) - MathPow(Cond_SMA__site1(x, 1, n, __pineBar), 2)));
return PINE_NA;
}
double rng_size(const double &x[], const string scale, const double qty, const int n, const int __pineBar,
const double &open[], const double &high[], const double &low[],
const double &close[], const long &volume[], const datetime &time[])
{
double ATR = Cond_EMA(pine_tr_na(high, low, close, __pineBar, true), 1, n, __pineBar);
double AC = Cond_EMA__site1(MathAbs((x[__pineBar] - pine_hist(x, __pineBar, (int)(1)))), 1, n, __pineBar);
double SD = Stdev(x[__pineBar], n, __pineBar);
double rng_size = ((scale == "Pips") ? (qty * 1.0E-4) : ((scale == "Points") ? (qty * MarketInfo(Symbol(), MODE_TICKVALUE)) : ((scale == "% of Price") ? pine_div((close[__pineBar] * qty), 100) : ((scale == "ATR") ? (qty * ATR) : ((scale == "Average Change") ? (qty * AC) : ((scale == "Standard Deviation") ? (qty * SD) : ((scale == "Ticks") ? (qty * _Point) : qty)))))));
return rng_size;
return PINE_NA;
}
void rng_filt(const double h, const double l, const double rng_, const int n, const string type, const bool smooth, const int sn, const bool av_rf, const int av_n, const int __pineBar, double &__out0, double &__out1, double &__out2)
{
double rng_smooth = Cond_EMA__site2(rng_, 1, sn, __pineBar);
double r = (smooth ? rng_smooth : rng_);
static double rfilt[];
static bool rfilt__once = false;
static double rfilt__sv[];
static bool rfilt__once__sv = false;
static int rfilt__sg = -1, rfilt__rg = 0, rfilt__ig = 0;
if(rfilt__ig != __pineInitGen)
{
rfilt__ig = __pineInitGen; rfilt__rg = __pineRestoreGen; rfilt__sg = -1;
ArrayFree(rfilt); rfilt__once = false;
}
if(rfilt__rg != __pineRestoreGen)
{
rfilt__rg = __pineRestoreGen;
if(rfilt__sg == __pineRestoreSaveGen)
{
ArrayFree(rfilt); ArrayCopy(rfilt, rfilt__sv); rfilt__once = rfilt__once__sv;
}
}
if(rfilt__sg != __pineSaveGen)
{
rfilt__sg = __pineSaveGen;
ArrayFree(rfilt__sv); ArrayCopy(rfilt__sv, rfilt); rfilt__once__sv = rfilt__once;
}
if(!rfilt__once)
{
rfilt__once = true;
ArrayResize(rfilt, (int)(2));
ArrayInitialize(rfilt, pine_div((h + l), 2));
}
rfilt[pine_idx(1)] = rfilt[pine_idx(0)];
if((type == "Type 1"))
{
if(((h - r) > rfilt[pine_idx(1)]))
{
rfilt[pine_idx(0)] = (h - r);
}
if(((l + r) < rfilt[pine_idx(1)]))
{
rfilt[pine_idx(0)] = (l + r);
}
}
if((type == "Type 2"))
{
if((h >= (rfilt[pine_idx(1)] + r)))
{
rfilt[pine_idx(0)] = (rfilt[pine_idx(1)] + (MathFloor(pine_div(MathAbs((h - rfilt[pine_idx(1)])), r)) * r));
}
if((l <= (rfilt[pine_idx(1)] - r)))
{
rfilt[pine_idx(0)] = (rfilt[pine_idx(1)] - (MathFloor(pine_div(MathAbs((l - rfilt[pine_idx(1)])), r)) * r));
}
}
__fl_rng_filt_rng_filt1[__pineBar] = rfilt[pine_idx(0)];
double hi_band1 = (__fl_rng_filt_rng_filt1[__pineBar] + r);
double lo_band1 = (__fl_rng_filt_rng_filt1[__pineBar] - r);
double rng_filt2 = Cond_EMA__site3(__fl_rng_filt_rng_filt1[__pineBar], (__fl_rng_filt_rng_filt1[__pineBar] != pine_hist(__fl_rng_filt_rng_filt1, __pineBar, (int)(1))), av_n, __pineBar);
double hi_band2 = Cond_EMA__site4(hi_band1, (__fl_rng_filt_rng_filt1[__pineBar] != pine_hist(__fl_rng_filt_rng_filt1, __pineBar, (int)(1))), av_n, __pineBar);
double lo_band2 = Cond_EMA__site5(lo_band1, (__fl_rng_filt_rng_filt1[__pineBar] != pine_hist(__fl_rng_filt_rng_filt1, __pineBar, (int)(1))), av_n, __pineBar);
double rng_filt = (av_rf ? rng_filt2 : __fl_rng_filt_rng_filt1[__pineBar]);
double hi_band = (av_rf ? hi_band2 : hi_band1);
double lo_band = (av_rf ? lo_band2 : lo_band1);
__out0 = hi_band;
__out1 = lo_band;
__out2 = rng_filt;
return;
}
double Cond_EMA__site1(const double x, const double cond, const int n, const int __pineBar)
{
static double val[];
static bool val__once = false;
static double val__sv[];
static bool val__once__sv = false;
static int val__sg = -1, val__rg = 0, val__ig = 0;
if(val__ig != __pineInitGen)
{
val__ig = __pineInitGen; val__rg = __pineRestoreGen; val__sg = -1;
ArrayFree(val); val__once = false;
}
if(val__rg != __pineRestoreGen)
{
val__rg = __pineRestoreGen;
if(val__sg == __pineRestoreSaveGen)
{
ArrayFree(val); ArrayCopy(val, val__sv); val__once = val__once__sv;
}
}
if(val__sg != __pineSaveGen)
{
val__sg = __pineSaveGen;
ArrayFree(val__sv); ArrayCopy(val__sv, val); val__once__sv = val__once;
}
if(!val__once)
{
val__once = true;
ArrayResize(val, (int)(0));
ArrayInitialize(val, PINE_NA); // Pine's default element is na
}
static double ema_val[];
static bool ema_val__once = false;
static double ema_val__sv[];
static bool ema_val__once__sv = false;
static int ema_val__sg = -1, ema_val__rg = 0, ema_val__ig = 0;
if(ema_val__ig != __pineInitGen)
{
ema_val__ig = __pineInitGen; ema_val__rg = __pineRestoreGen; ema_val__sg = -1;
ArrayFree(ema_val); ema_val__once = false;
}
if(ema_val__rg != __pineRestoreGen)
{
ema_val__rg = __pineRestoreGen;
if(ema_val__sg == __pineRestoreSaveGen)
{
ArrayFree(ema_val); ArrayCopy(ema_val, ema_val__sv); ema_val__once = ema_val__once__sv;
}
}
if(ema_val__sg != __pineSaveGen)
{
ema_val__sg = __pineSaveGen;
ArrayFree(ema_val__sv); ArrayCopy(ema_val__sv, ema_val); ema_val__once__sv = ema_val__once;
}
if(!ema_val__once)
{
ema_val__once = true;
ArrayResize(ema_val, (int)(1));
ArrayInitialize(ema_val, PINE_NA); // Pine's default element is na
}
if(pine_truthy(cond))
{
pine_arr_push(val, x);
if((pine_arr_size(val) > 1))
{
pine_arr_remove(val, (int)(0));
}
if(pine_na(ema_val[pine_idx(0)]))
{
pine_arr_fill(ema_val, val[pine_idx(0)]);
}
ema_val[pine_idx(0)] = (((val[pine_idx(0)] - ema_val[pine_idx(0)]) * pine_div(2, (n + 1))) + ema_val[pine_idx(0)]);
}
double EMA = ema_val[pine_idx(0)];
return EMA;
return PINE_NA;
}
double Cond_EMA__site2(const double x, const double cond, const int n, const int __pineBar)
{
static double val[];
static bool val__once = false;
static double val__sv[];
static bool val__once__sv = false;
static int val__sg = -1, val__rg = 0, val__ig = 0;
if(val__ig != __pineInitGen)
{
val__ig = __pineInitGen; val__rg = __pineRestoreGen; val__sg = -1;
ArrayFree(val); val__once = false;
}
if(val__rg != __pineRestoreGen)
{
val__rg = __pineRestoreGen;
if(val__sg == __pineRestoreSaveGen)
{
ArrayFree(val); ArrayCopy(val, val__sv); val__once = val__once__sv;
}
}
if(val__sg != __pineSaveGen)
{
val__sg = __pineSaveGen;
ArrayFree(val__sv); ArrayCopy(val__sv, val); val__once__sv = val__once;
}
if(!val__once)
{
val__once = true;
ArrayResize(val, (int)(0));
ArrayInitialize(val, PINE_NA); // Pine's default element is na
}
static double ema_val[];
static bool ema_val__once = false;
static double ema_val__sv[];
static bool ema_val__once__sv = false;
static int ema_val__sg = -1, ema_val__rg = 0, ema_val__ig = 0;
if(ema_val__ig != __pineInitGen)
{
ema_val__ig = __pineInitGen; ema_val__rg = __pineRestoreGen; ema_val__sg = -1;
ArrayFree(ema_val); ema_val__once = false;
}
if(ema_val__rg != __pineRestoreGen)
{
ema_val__rg = __pineRestoreGen;
if(ema_val__sg == __pineRestoreSaveGen)
{
ArrayFree(ema_val); ArrayCopy(ema_val, ema_val__sv); ema_val__once = ema_val__once__sv;
}
}
if(ema_val__sg != __pineSaveGen)
{
ema_val__sg = __pineSaveGen;
ArrayFree(ema_val__sv); ArrayCopy(ema_val__sv, ema_val); ema_val__once__sv = ema_val__once;
}
if(!ema_val__once)
{
ema_val__once = true;
ArrayResize(ema_val, (int)(1));
ArrayInitialize(ema_val, PINE_NA); // Pine's default element is na
}
if(pine_truthy(cond))
{
pine_arr_push(val, x);
if((pine_arr_size(val) > 1))
{
pine_arr_remove(val, (int)(0));
}
if(pine_na(ema_val[pine_idx(0)]))
{
pine_arr_fill(ema_val, val[pine_idx(0)]);
}
ema_val[pine_idx(0)] = (((val[pine_idx(0)] - ema_val[pine_idx(0)]) * pine_div(2, (n + 1))) + ema_val[pine_idx(0)]);
}
double EMA = ema_val[pine_idx(0)];
return EMA;
return PINE_NA;
}
double Cond_EMA__site3(const double x, const double cond, const int n, const int __pineBar)
{
static double val[];
static bool val__once = false;
static double val__sv[];
static bool val__once__sv = false;
static int val__sg = -1, val__rg = 0, val__ig = 0;
if(val__ig != __pineInitGen)
{
val__ig = __pineInitGen; val__rg = __pineRestoreGen; val__sg = -1;
ArrayFree(val); val__once = false;
}
if(val__rg != __pineRestoreGen)
{
val__rg = __pineRestoreGen;
if(val__sg == __pineRestoreSaveGen)
{
ArrayFree(val); ArrayCopy(val, val__sv); val__once = val__once__sv;
}
}
if(val__sg != __pineSaveGen)
{
val__sg = __pineSaveGen;
ArrayFree(val__sv); ArrayCopy(val__sv, val); val__once__sv = val__once;
}
if(!val__once)
{
val__once = true;
ArrayResize(val, (int)(0));
ArrayInitialize(val, PINE_NA); // Pine's default element is na
}
static double ema_val[];
static bool ema_val__once = false;
static double ema_val__sv[];
static bool ema_val__once__sv = false;
static int ema_val__sg = -1, ema_val__rg = 0, ema_val__ig = 0;
if(ema_val__ig != __pineInitGen)
{
ema_val__ig = __pineInitGen; ema_val__rg = __pineRestoreGen; ema_val__sg = -1;
ArrayFree(ema_val); ema_val__once = false;
}
if(ema_val__rg != __pineRestoreGen)
{
ema_val__rg = __pineRestoreGen;
if(ema_val__sg == __pineRestoreSaveGen)
{
ArrayFree(ema_val); ArrayCopy(ema_val, ema_val__sv); ema_val__once = ema_val__once__sv;
}
}
if(ema_val__sg != __pineSaveGen)
{
ema_val__sg = __pineSaveGen;
ArrayFree(ema_val__sv); ArrayCopy(ema_val__sv, ema_val); ema_val__once__sv = ema_val__once;
}
if(!ema_val__once)
{
ema_val__once = true;
ArrayResize(ema_val, (int)(1));
ArrayInitialize(ema_val, PINE_NA); // Pine's default element is na
}
if(pine_truthy(cond))
{
pine_arr_push(val, x);
if((pine_arr_size(val) > 1))
{
pine_arr_remove(val, (int)(0));
}
if(pine_na(ema_val[pine_idx(0)]))
{
pine_arr_fill(ema_val, val[pine_idx(0)]);
}
ema_val[pine_idx(0)] = (((val[pine_idx(0)] - ema_val[pine_idx(0)]) * pine_div(2, (n + 1))) + ema_val[pine_idx(0)]);
}
double EMA = ema_val[pine_idx(0)];
return EMA;
return PINE_NA;
}
double Cond_EMA__site4(const double x, const double cond, const int n, const int __pineBar)
{
static double val[];
static bool val__once = false;
static double val__sv[];
static bool val__once__sv = false;
static int val__sg = -1, val__rg = 0, val__ig = 0;
if(val__ig != __pineInitGen)
{
val__ig = __pineInitGen; val__rg = __pineRestoreGen; val__sg = -1;
ArrayFree(val); val__once = false;
}
if(val__rg != __pineRestoreGen)
{
val__rg = __pineRestoreGen;
if(val__sg == __pineRestoreSaveGen)
{
ArrayFree(val); ArrayCopy(val, val__sv); val__once = val__once__sv;
}
}
if(val__sg != __pineSaveGen)
{
val__sg = __pineSaveGen;
ArrayFree(val__sv); ArrayCopy(val__sv, val); val__once__sv = val__once;
}
if(!val__once)
{
val__once = true;
ArrayResize(val, (int)(0));
ArrayInitialize(val, PINE_NA); // Pine's default element is na
}
static double ema_val[];
static bool ema_val__once = false;
static double ema_val__sv[];
static bool ema_val__once__sv = false;
static int ema_val__sg = -1, ema_val__rg = 0, ema_val__ig = 0;
if(ema_val__ig != __pineInitGen)
{
ema_val__ig = __pineInitGen; ema_val__rg = __pineRestoreGen; ema_val__sg = -1;
ArrayFree(ema_val); ema_val__once = false;
}
if(ema_val__rg != __pineRestoreGen)
{
ema_val__rg = __pineRestoreGen;
if(ema_val__sg == __pineRestoreSaveGen)
{
ArrayFree(ema_val); ArrayCopy(ema_val, ema_val__sv); ema_val__once = ema_val__once__sv;
}
}
if(ema_val__sg != __pineSaveGen)
{
ema_val__sg = __pineSaveGen;
ArrayFree(ema_val__sv); ArrayCopy(ema_val__sv, ema_val); ema_val__once__sv = ema_val__once;
}
if(!ema_val__once)
{
ema_val__once = true;
ArrayResize(ema_val, (int)(1));
ArrayInitialize(ema_val, PINE_NA); // Pine's default element is na
}
if(pine_truthy(cond))
{
pine_arr_push(val, x);
if((pine_arr_size(val) > 1))
{
pine_arr_remove(val, (int)(0));
}
if(pine_na(ema_val[pine_idx(0)]))
{
pine_arr_fill(ema_val, val[pine_idx(0)]);
}
ema_val[pine_idx(0)] = (((val[pine_idx(0)] - ema_val[pine_idx(0)]) * pine_div(2, (n + 1))) + ema_val[pine_idx(0)]);
}
double EMA = ema_val[pine_idx(0)];
return EMA;
return PINE_NA;
}
double Cond_EMA__site5(const double x, const double cond, const int n, const int __pineBar)
{
static double val[];
static bool val__once = false;
static double val__sv[];
static bool val__once__sv = false;
static int val__sg = -1, val__rg = 0, val__ig = 0;
if(val__ig != __pineInitGen)
{
val__ig = __pineInitGen; val__rg = __pineRestoreGen; val__sg = -1;
ArrayFree(val); val__once = false;
}
if(val__rg != __pineRestoreGen)
{
val__rg = __pineRestoreGen;
if(val__sg == __pineRestoreSaveGen)
{
ArrayFree(val); ArrayCopy(val, val__sv); val__once = val__once__sv;
}
}
if(val__sg != __pineSaveGen)
{
val__sg = __pineSaveGen;
ArrayFree(val__sv); ArrayCopy(val__sv, val); val__once__sv = val__once;
}
if(!val__once)
{
val__once = true;
ArrayResize(val, (int)(0));
ArrayInitialize(val, PINE_NA); // Pine's default element is na
}
static double ema_val[];
static bool ema_val__once = false;
static double ema_val__sv[];
static bool ema_val__once__sv = false;
static int ema_val__sg = -1, ema_val__rg = 0, ema_val__ig = 0;
if(ema_val__ig != __pineInitGen)
{
ema_val__ig = __pineInitGen; ema_val__rg = __pineRestoreGen; ema_val__sg = -1;
ArrayFree(ema_val); ema_val__once = false;
}
if(ema_val__rg != __pineRestoreGen)
{
ema_val__rg = __pineRestoreGen;
if(ema_val__sg == __pineRestoreSaveGen)
{
ArrayFree(ema_val); ArrayCopy(ema_val, ema_val__sv); ema_val__once = ema_val__once__sv;
}
}
if(ema_val__sg != __pineSaveGen)
{
ema_val__sg = __pineSaveGen;
ArrayFree(ema_val__sv); ArrayCopy(ema_val__sv, ema_val); ema_val__once__sv = ema_val__once;
}
if(!ema_val__once)
{
ema_val__once = true;
ArrayResize(ema_val, (int)(1));
ArrayInitialize(ema_val, PINE_NA); // Pine's default element is na
}
if(pine_truthy(cond))
{
pine_arr_push(val, x);
if((pine_arr_size(val) > 1))
{
pine_arr_remove(val, (int)(0));
}
if(pine_na(ema_val[pine_idx(0)]))
{
pine_arr_fill(ema_val, val[pine_idx(0)]);
}
ema_val[pine_idx(0)] = (((val[pine_idx(0)] - ema_val[pine_idx(0)]) * pine_div(2, (n + 1))) + ema_val[pine_idx(0)]);
}
double EMA = ema_val[pine_idx(0)];
return EMA;
return PINE_NA;
}
double Cond_SMA__site1(const double x, const int cond, const int n, const int __pineBar)
{
static double vals[];
static bool vals__once = false;
static double vals__sv[];
static bool vals__once__sv = false;
static int vals__sg = -1, vals__rg = 0, vals__ig = 0;
if(vals__ig != __pineInitGen)
{
vals__ig = __pineInitGen; vals__rg = __pineRestoreGen; vals__sg = -1;
ArrayFree(vals); vals__once = false;
}
if(vals__rg != __pineRestoreGen)
{
vals__rg = __pineRestoreGen;
if(vals__sg == __pineRestoreSaveGen)
{
ArrayFree(vals); ArrayCopy(vals, vals__sv); vals__once = vals__once__sv;
}
}
if(vals__sg != __pineSaveGen)
{
vals__sg = __pineSaveGen;
ArrayFree(vals__sv); ArrayCopy(vals__sv, vals); vals__once__sv = vals__once;
}
if(!vals__once)
{
vals__once = true;
ArrayResize(vals, (int)(0));
ArrayInitialize(vals, PINE_NA); // Pine's default element is na
}
if(pine_truthy(cond))
{
pine_arr_push(vals, x);
if((pine_arr_size(vals) > n))
{
pine_arr_remove(vals, (int)(0));
}
}
double SMA = pine_arr_avg(vals);
return SMA;
return PINE_NA;
}
int OnInit()
{
f_type = f_type_Labels[(int)f_type_Input];
mov_src = mov_src_Labels[(int)mov_src_Input];
rng_scale = rng_scale_Labels[(int)rng_scale_Input];
if(rng_qty < 1.0E-7) { Print("Range Size", " must be at least 1.0E-7"); return INIT_PARAMETERS_INCORRECT; }
if(rng_per < 1) { Print("Range Period (for ATR, Average Change, and Standard Deviation)", " must be at least 1"); return INIT_PARAMETERS_INCORRECT; }
if(smooth_per < 1) { Print("Smoothing Period", " must be at least 1"); return INIT_PARAMETERS_INCORRECT; }
if(av_samples < 1) { Print("Number Of Changes To Average", " must be at least 1"); return INIT_PARAMETERS_INCORRECT; }
upward = ((fdir == 1) ? 1 : 0);
downward = ((fdir == (-1)) ? 1 : 0);
SetIndexBuffer(0, PineFill0, INDICATOR_DATA);
SetIndexBuffer(1, PineFill1, INDICATOR_DATA);
SetIndexBuffer(2, PineFill2, INDICATOR_DATA);
SetIndexBuffer(3, PineFill3, INDICATOR_DATA);
SetIndexBuffer(4, Buf4, INDICATOR_DATA);
SetIndexBuffer(5, Buf5, INDICATOR_COLOR_INDEX);
SetIndexBuffer(6, Buf6, INDICATOR_DATA);
SetIndexBuffer(7, Buf7, INDICATOR_DATA);
SetIndexBuffer(8, Buf8, INDICATOR_DATA);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetDouble(3, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetDouble(4, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetDouble(5, PLOT_EMPTY_VALUE, EMPTY_VALUE);
PlotIndexSetInteger(0, PLOT_SHOW_DATA, false);
PlotIndexSetInteger(0, PLOT_LINE_COLOR, 0, C'0,179,107');
PlotIndexSetInteger(0, PLOT_LINE_COLOR, 1, C'0,179,107');
PlotIndexSetInteger(1, PLOT_SHOW_DATA, false);
PlotIndexSetInteger(1, PLOT_LINE_COLOR, 0, C'184,0,93');
PlotIndexSetInteger(1, PLOT_LINE_COLOR, 1, C'184,0,93');
PlotIndexSetInteger(3, PLOT_LINE_COLOR, C'5,255,155');
PlotIndexSetInteger(4, PLOT_LINE_COLOR, C'255,5,131');
PlotIndexSetInteger(5, PLOT_SHOW_DATA, false);
PlotIndexSetInteger(5, PLOT_DRAW_TYPE, DRAW_NONE);
IndicatorSetString(INDICATOR_SHORTNAME, "Range Filter [DW]");
__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[])
{
if(__pineBar > 0)
{
filt[__pineBar] = filt[__pineBar - 1];
}
f_type = f_type_Labels[(int)f_type_Input];
mov_src = mov_src_Labels[(int)mov_src_Input];
rng_scale = rng_scale_Labels[(int)rng_scale_Input];
h_val = ((mov_src == "Wicks") ? high[__pineBar] : close[__pineBar]);
l_val = ((mov_src == "Wicks") ? low[__pineBar] : close[__pineBar]);
double __tc0_0 = PINE_NA;
double __tc0_1 = PINE_NA;
double __tc0_2 = PINE_NA;
__ti0[__pineBar] = pine_div((h_val + l_val), 2);
rng_filt(h_val, l_val, rng_size(__ti0, rng_scale, rng_qty, rng_per, __pineBar, open, high, low, close, volume, time), rng_per, f_type, smooth_range, smooth_per, av_vals, av_samples, __pineBar, __tc0_0, __tc0_1, __tc0_2);
h_band = __tc0_0;
l_band = __tc0_1;
filt[__pineBar] = __tc0_2;
fdir = ((filt[__pineBar] > pine_hist(filt, __pineBar, (int)(1))) ? 1 : ((filt[__pineBar] < pine_hist(filt, __pineBar, (int)(1))) ? (-1) : fdir));
upward = ((fdir == 1) ? 1 : 0);
downward = ((fdir == (-1)) ? 1 : 0);
filt_color = (pine_truthy(upward) ? C'5,255,155' : (pine_truthy(downward) ? C'255,5,131' : C'204,204,204'));
bar_color = ((((pine_truthy(upward) ? 1 : 0) & ((close[__pineBar] > filt[__pineBar]) ? 1 : 0)) != 0) ? ((close[__pineBar] > pine_hist(close, __pineBar, (int)(1))) ? C'5,255,155' : C'0,179,107') : ((((pine_truthy(downward) ? 1 : 0) & ((close[__pineBar] < filt[__pineBar]) ? 1 : 0)) != 0) ? ((close[__pineBar] < pine_hist(close, __pineBar, (int)(1))) ? C'255,5,131' : C'184,0,93') : C'204,204,204'));
0 /* barcolor dropped: visual only */;
double __pinePlotValue2 = filt[__pineBar];
double __pinePlotColour2 = (double)(filt_color);
Buf4[__pineBar] = __pinePlotValue2;
Buf5[__pineBar] = pine_color_slot(2, pine_na(__pinePlotColour2) ? clrNONE : (color)__pinePlotColour2, __pal2, __paln2);
Buf6[__pineBar] = h_band;
Buf7[__pineBar] = l_band;
Buf8[__pineBar] = fdir;
PineFill0[__pineBar] = Buf6[__pineBar];
PineFill1[__pineBar] = Buf4[__pineBar];
PineFill2[__pineBar] = Buf7[__pineBar];
PineFill3[__pineBar] = Buf4[__pineBar];
}
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(__st0, rates_total);
ArrayResize(__stb0, rates_total);
ArrayResize(__fl_rng_filt_rng_filt1, rates_total);
ArrayResize(__ti0, rates_total);
if(prev_calculated == 0)
{
ArrayInitialize(filt, PINE_NA);
ArrayInitialize(__st0, PINE_NA);
ArrayInitialize(__stb0, PINE_NA);
ArrayInitialize(__fl_rng_filt_rng_filt1, PINE_NA);
ArrayInitialize(__ti0, 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;
}Original Pine Script
© DonovanWall — 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/
// © DonovanWall
//██████╗ ██╗ ██╗
//██╔══██╗██║ ██║
//██║ ██║██║ █╗ ██║
//██║ ██║██║███╗██║
//██████╔╝╚███╔███╔╝
//╚═════╝ ╚══╝╚══╝
//@version=4
study(title="Range Filter [DW]", shorttitle="RF [DW]", overlay=true)
//This is an experimental study designed to filter out minor price action for a clearer view of trends.
//Inspired by the QQE's volatility filter, this filter applies the process directly to price rather than to a smoothed RSI.
//First, a smooth average price range is calculated for the basis of the filter and multiplied by a specified amount.
//Next, the filter is calculated by gating price movements that do not exceed the specified range.
//Lastly the target ranges are plotted to display the prices that will trigger filter movement.
//Custom bar colors are included. The color scheme is based on the filtered price trend.
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Updates:
// -> Migrated to v4.
// -> Range Filter and the bands are now calculated in a singular function.
// -> There are now two different calculation methods for the filter. Select the type you want to use via the "Filter Type" input. Type 1 is the original formula.
// -> Multiple range sizing methods are now available. You can choose from the following scales:
// - Points
// - Pips (Works best with forex pairs, obviously)
// - Ticks
// - % of Price
// - ATR
// - Average Change (Default. This is the original sizing method.)
// - Standard Deviation
// - Absolute (Absolute numerical value)
// -> Range smoothing is now optional, and you can specify your smoothing length. Smoothing only affects dynamic scales (ATR, Average Change, and Standard Deviation).
// -> Filter movement can now be determined using wicks or close. This can be specified via the "Movement Source" input.
// -> Stability Fix: Added correction for NaN values to stabilize initial states.
// -> Reorganized the script structure.
// -> Revamped the color scheme.
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Updates:
// - The Range Filter functions have now been rebuilt using Pine's awesome new array functions.
// - Standard deviation calculation has been adjusted to calculate the same as TV's built in stdev() function.
// - Rewritten filter direction and bar color variables.
// - Included an external output variable for trend information that can easily be sent to other scripts without hardcoding.
// The output format is 1 for bullish, and -1 for bearish.
// To use this external variable with another script, simply select it from your other script's source dropdown tab.
// - Added the ability to average range filter values based on a user defined number of filter changes.
// This averaging method utilized the Conditional Sampling EMA function I introduced in my Resampling Filter Pack and only takes a new sample when the filter changes its value.
// This opens up a whole new world of possible filter outputs.
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Functions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Conditional Sampling EMA Function
Cond_EMA(x, cond, n)=>
var val = array.new_float(0)
var ema_val = array.new_float(1)
if cond
array.push(val, x)
if array.size(val) > 1
array.remove(val, 0)
if na(array.get(ema_val, 0))
array.fill(ema_val, array.get(val, 0))
array.set(ema_val, 0, (array.get(val, 0) - array.get(ema_val, 0))*(2/(n + 1)) + array.get(ema_val, 0))
EMA = array.get(ema_val, 0)
EMA
//Conditional Sampling SMA Function
Cond_SMA(x, cond, n)=>
var vals = array.new_float(0)
if cond
array.push(vals, x)
if array.size(vals) > n
array.remove(vals, 0)
SMA = array.avg(vals)
SMA
//Standard Deviation Function
Stdev(x, n)=>
sqrt(Cond_SMA(pow(x, 2), 1, n) - pow(Cond_SMA(x, 1, n), 2))
//Range Size Function
rng_size(x, scale, qty, n)=>
ATR = Cond_EMA(tr(true), 1, n)
AC = Cond_EMA(abs(x - x[1]), 1, n)
SD = Stdev(x, n)
rng_size = scale=="Pips" ? qty*0.0001 : scale=="Points" ? qty*syminfo.pointvalue : scale=="% of Price" ? close*qty/100 : scale=="ATR" ? qty*ATR :
scale=="Average Change" ? qty*AC : scale=="Standard Deviation" ? qty*SD : scale=="Ticks" ? qty*syminfo.mintick : qty
//Two Type Range Filter Function
rng_filt(h, l, rng_, n, type, smooth, sn, av_rf, av_n)=>
rng_smooth = Cond_EMA(rng_, 1, sn)
r = smooth ? rng_smooth : rng_
var rfilt = array.new_float(2, (h + l)/2)
array.set(rfilt, 1, array.get(rfilt, 0))
if type=="Type 1"
if h - r > array.get(rfilt, 1)
array.set(rfilt, 0, h - r)
if l + r < array.get(rfilt, 1)
array.set(rfilt, 0, l + r)
if type=="Type 2"
if h >= array.get(rfilt, 1) + r
array.set(rfilt, 0, array.get(rfilt, 1) + floor(abs(h - array.get(rfilt, 1))/r)*r)
if l <= array.get(rfilt, 1) - r
array.set(rfilt, 0, array.get(rfilt, 1) - floor(abs(l - array.get(rfilt, 1))/r)*r)
rng_filt1 = array.get(rfilt, 0)
hi_band1 = rng_filt1 + r
lo_band1 = rng_filt1 - r
rng_filt2 = Cond_EMA(rng_filt1, rng_filt1 != rng_filt1[1], av_n)
hi_band2 = Cond_EMA(hi_band1, rng_filt1 != rng_filt1[1], av_n)
lo_band2 = Cond_EMA(lo_band1, rng_filt1 != rng_filt1[1], av_n)
rng_filt = av_rf ? rng_filt2 : rng_filt1
hi_band = av_rf ? hi_band2 : hi_band1
lo_band = av_rf ? lo_band2 : lo_band1
[hi_band, lo_band, rng_filt]
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Inputs
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Filter Type
f_type = input(defval="Type 1", options=["Type 1", "Type 2"], title="Filter Type")
//Movement Source
mov_src = input(defval="Close", options=["Wicks", "Close"], title="Movement Source")
//Range Size Inputs
rng_qty = input(defval=2.618, minval=0.0000001, title="Range Size")
rng_scale = input(defval="Average Change", options=["Points", "Pips", "Ticks", "% of Price", "ATR", "Average Change", "Standard Deviation", "Absolute"], title="Range Scale")
//Range Period
rng_per = input(defval=14, minval=1, title="Range Period (for ATR, Average Change, and Standard Deviation)")
//Range Smoothing Inputs
smooth_range = input(defval=true, title="Smooth Range")
smooth_per = input(defval=27, minval=1, title="Smoothing Period")
//Filter Value Averaging Inputs
av_vals = input(defval=false, title="Average Filter Changes")
av_samples = input(defval=2, minval=1, title="Number Of Changes To Average")
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Definitions
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//High And Low Values
h_val = mov_src=="Wicks" ? high : close
l_val = mov_src=="Wicks" ? low : close
//Range Filter Values
[h_band, l_band, filt] = rng_filt(h_val, l_val, rng_size((h_val + l_val)/2, rng_scale, rng_qty, rng_per), rng_per, f_type, smooth_range, smooth_per, av_vals, av_samples)
//Direction Conditions
var fdir = 0.0
fdir := filt > filt[1] ? 1 : filt < filt[1] ? -1 : fdir
upward = fdir==1 ? 1 : 0
downward = fdir==-1 ? 1 : 0
//Colors
filt_color = upward ? #05ff9b : downward ? #ff0583 : #cccccc
bar_color = upward and (close > filt) ? (close > close[1] ? #05ff9b : #00b36b) :
downward and (close < filt) ? (close < close[1] ? #ff0583 : #b8005d) : #cccccc
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Outputs
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
//Filter Plot
filt_plot = plot(filt, color=filt_color, linewidth=3, transp=0, title="Filter")
//Band Plots
h_band_plot = plot(h_band, color=#05ff9b, transp=100, title="High Band")
l_band_plot = plot(l_band, color=#ff0583, transp=100, title="Low Band")
//Band Fills
fill(h_band_plot, filt_plot, color=#00b36b, transp=85, title="High Band Fill")
fill(l_band_plot, filt_plot, color=#b8005d, transp=85, title="Low Band Fill")
//Bar Color
barcolor(bar_color)
//External Trend Output
plot(fdir, transp=100, editable=false, display=display.none, title="External Output - Trend Signal")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 converterMore: all example conversions · how Pine Script maps to MQL5 · how the engine measures