#// This source code is subject to the terms of the Mozilla Public License 2.0
#// © colinmck
#study(title="Twin Range Filter", overlay=true)
# Converted and mod by Sam4Cok@Samer800 - 10/2022 - request from https://usethinkscript.com/ memeber
input signalStyle = {Default Arrows, Bubbles};
input source = close;#(defval=close, title="Source")
input ShowBand = no;
#// Smooth Average Range
input FastPeriod = 27; # "Fast period"
input FastRange = 1.6; # "Fast range"
input SlowPeriod = 55; # "Slow period"
input SlowRange = 2; # "Slow range"
def na = Double.NaN;
def arrow = signalStyle==signalStyle.Arrows;
#script nz {
# input data = close;
# input repl = 0;
# def ret_val = if isNaN(data) then repl else data;
# plot return = ret_val;
#}
#smoothrng(x, t, m) =>
script smoothrng {
input x = close;
input t = 20;
input m = 1;
def wper = t * 2 - 1;
def avrng = ExpAverage(AbsValue(x - x[1]), t);
def smoothrng = ExpAverage(avrng, wper) * m;
plot return = smoothrng;
}
def smrng1 = smoothrng(source, FastPeriod, FastRange);
def smrng2 = smoothrng(source, SlowPeriod, SlowRange);
def smrng = (smrng1 + smrng2) / 2;
#// Range Filter
#rngfilt(x, r) =>
script rngfilt {
input x = close;
input r = 0;
def rngfilt;
rngfilt = if x > rngfilt[1] then
CompoundValue(1, if x - r < rngfilt[1] then rngfilt[1] else x - r, x)
else if x + r > rngfilt[1] then rngfilt[1] else x + r;
plot return = rngfilt;
}
def filt = rngfilt(source, smrng);
#--------------------------------
def longCond; def shortCond; def CondIni;
def upward = if filt > filt[1] then upward[1] + 1 else if filt < filt[1] then 0 else upward[1];
def downward = if filt < filt[1] then downward[1] + 1 else if filt > filt[1] then 0 else downward[1];
def hband = filt + smrng;
def lband = filt - smrng;
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 = if longCond then 1 else if shortCond then -1 else CondIni[1];
def long = longCond and CondIni[1] == -1;
def short = shortCond and CondIni[1] == 1;
#// Plotting
plot UpperBand = hband;
UpperBand.SetDefaultColor(Color.DARK_RED);
UpperBand.SetHiding(!ShowBand);
plot LowerBand = lband;
LowerBand.SetDefaultColor(Color.DARK_GREEN);
LowerBand.SetHiding(!ShowBand);
plot SigUp = if arrow and long then low else na;
plot SigDn = if arrow and short then high else na;
SigUp.SetPaintingStrategy(paintingStrategy.BOOLEAN_ARROW_Up);
SigDn.SetPaintingStrategy(paintingStrategy.BOOLEAN_ARROW_Down);
SigUp.SetDefaultColor(Color.CYAN);
SigDn.SetDefaultColor(Color.MAGENTA);
AddChartBubble(!arrow and long, low, "Long", Color.CYAN, no);
AddChartBubble(!arrow and short, high, "Short", Color.MAGENTA, yes);
#---END Code