Band Based Trend Filter for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
DEBMdQB.png

Creator Message:

Concept
On contrary to reversal mindset, we define trend when price hits either side of the band. If close price hits upper band then it is considered as bullish and if close price hits lower band, then it is considered bearish . Further, trend strength is measured in terms of how many times the price hits one side of the band without hitting other side. Hit is counted only if price has touched middle line in between the touches. This way price walks on the bands are considered as just one hit.

CODE:

CSS:
#/@version=5
#https://www.tradingview.com/script/5egLveLn-Relative-Bandwidth-Filter/
#indicator("Band Based Trend Filter") by HeWhoMustNotBeNamed
#Converted and mod by Sam4COK @ Samer800 - 01/2023

declare lower;
input BarColor = no;
input useChartTimeframe = yes;
input HigherTimeframe = AggregationPeriod.FIFTEEN_MIN;
input bandType = {default BB, KC, DC};
#input BandSource = close;
input BandMovAvg = {default SMA, EMA, HMA, RMA, WMA, VWMA, SWMA, Linreg, Median};
input BandLength = 20;
input BandMultiplier = 3.0;
input KCTrueRange = yes;      # "Use True Range (KC)"
input DCAlternateSource = no; # "Use Alternate Source (DC)"
input sticky = yes;            # "Sticky"
input trendConfirmationCount = 3;

def na = Double.NaN;
script nz {
    input data = close;
    input replacement  = 0;
    def ret_val = if !IsNaN(data) then data else replacement;
    plot return = ret_val;
}

def ctf;def htf; def ltf; def vtf;def ctf1;
if useChartTimeframe {
    ctf = close;
    ctf1 = close[1];
    htf = high;
    ltf = low;
    vtf = volume;
    } else {
    ctf = nz(close(Period=HigherTimeframe), close);
    ctf1 = nz(close(Period=HigherTimeframe)[1], close[1]);
    htf = nz(high(Period=HigherTimeframe), high);
    ltf = nz(low(Period=HigherTimeframe), low);
    vtf = nz(volume(Period=HigherTimeframe), volume);
}
def isrealtime = isNaN(ctf) and !isNaN(ctf1);
def indexHighTF = if isrealtime then ctf1 else ctf;
script indexCurrTF {
input data = close;
input ctf = close;
       def isrealtime = isNaN(ctf) and !isNaN(ctf[1]);
       def indexCurrTF = if isrealtime then data else data[1];
       plot return = indexCurrTF;
}
#swma(source)
script swma {
    input x = close;
    def swma = x[3] * 1 / 6 + x[2] * 2 / 6 + x[1] * 2 / 6 + x[0] * 1 / 6;
    plot return = swma;
}
#ma(type, source, length) =>
script ma {
    input type   = "SMA";
    input source = close;
    input length = 20;
    input vtf    = volume;
    def VWMA = SimpleMovingAvg(source * vtf, length) / SimpleMovingAvg(vtf, length);
    def ma;
    ma = if type == "SMA" then SimpleMovingAvg(source, length) else
     if type == "EMA" then ExpAverage(source, length) else
     if type == "HMA" then HullMovingAvg(source, length) else
     if type == "RMA" then WildersAverage(source, length) else
     if type == "WMA" then WMA(source, length) else
     if type == "VWMA" then VWMA else
     if type == "SWMA" then SWMA(source) else
     if type == "Linreg" then Inertia(source, length) else
     if type == "Median" then Median(source, length) else Double.NaN;
    plot result = ma;
}
#getStickyRange(highsource, lowsource, upper, lower, sticky=false)=>
script getStickyRange {
    input highsource = high;
    input lowsource = low;
    input upper = high;
    input lower = low;
    input sticky = no;
    def newUpper;
    def newLower;
    newUpper = if isNaN(newUpper[1]) then upper else
        if highsource[1] >= newUpper[1] or lowsource[1] <= newLower[1] or !sticky
           then upper else nz(newUpper[1], upper);
    newLower = if isNaN(newLower[1]) then lower else
        if highsource[1] >= newUpper[1] or lowsource[1] <= newLower[1] or !sticky
           then lower else nz(newLower[1], lower);
    plot UpBand = newUpper;
    plot LoBand = newLower;
}
#### BB
def sDev = stdev(indexHighTF,BandLength);
def BBMid = ma(BandMovAvg, indexHighTF, BandLength, vtf);
def BBup = BBMid + BandMultiplier * sDev;
def BBlo = BBMid - BandMultiplier * sDev;
def BBupper = getStickyRange(htf, ltf, BBup, BBlo, sticky).Upband;
def Blower = getStickyRange(htf, ltf, BBup, BBlo, sticky).Loband;
def Bupper = Bupper;
def BBlower = Blower;
def BBmiddle = BBMid;

##### KC
def tr = TrueRange(htf,ctf,ltf);
def mid = ma(BandMovAvg, indexHighTF, BandLength, vtf);
def span =  if KCTrueRange then tr else (htf - ltf);
def KCrange = ma(BandMovAvg, span, BandLength);
def KCUp = mid + KCrange * BandMultiplier;
def KClo = mid - KCrange * BandMultiplier;
def KCnewUpper = getStickyRange(htf, ltf, KCUp, KClo, sticky).Upband;
def KCnewLower = getStickyRange(htf, ltf, KCUp, KClo, sticky).Loband;
def KCupper  = KCnewUpper;
def KClower  = KCnewLower;
def KCmiddle = mid;

##### DC
def highSource = if DCAlternateSource then ctf else htf;
def lowSource  = if DCAlternateSource then ctf else ltf;
def DCupp = Highest(highSource, BandLength);
def DClow = Lowest(lowSource, BandLength);
def DCnewUpper = getStickyRange(highSource, lowSource, DCupp, DClow, sticky).UpBand;
def DCnewLower = getStickyRange(highSource, lowSource, DCupp, DClow, sticky).LoBand;
def DCmid = (DCnewUpper + DCnewLower) / 2;
def DCupper  = DCnewUpper;
def DClower  = DCnewLower;
def DCmiddle = DCmid;

### Bands
def upper;
def lower;
def middle;
if bandType == bandType.BB
then {
    upper  = indexCurrTF(BBupper, ctf);
    lower  = indexCurrTF(BBlower, ctf);
    middle = indexCurrTF(BBmiddle, ctf);
} else
if bandType == bandType.KC
then {
    upper  = indexCurrTF(KCupper, ctf);
    lower  = indexCurrTF(KClower, ctf);
    middle = indexCurrTF(KCmiddle, ctf);
} else
if bandType == bandType.DC
then {
    upper  = indexCurrTF(DCupper, ctf);
    lower  = indexCurrTF(DClower, ctf);
    middle = indexCurrTF(DCmiddle, ctf);
} else
{
    upper  = na;
    lower  = na;
    middle = na;
}
def CrossUp = ctf > middle;
def Up = if CrossUp then nz(Up[1]) + 1 else 0;
def CrossDn = ctf < middle;
def Dn = if CrossDn then nz(Dn[1]) + 1 else 0;
def flag;
flag = nz(flag[1],1) or Up==1 or Dn==1;

def uptrendCount;
def downtrendCount;

def closeAboveTop    = ctf >= upper;
def closeBelowBottom = ctf <= lower;
if(flag) {
    if(closeAboveTop) {
        downtrendCount = 0;
        uptrendCount = nz(uptrendCount[1]) + 1;
    } else
    if(closeBelowBottom) {
        uptrendCount = 0;
        downtrendCount = nz(downtrendCount[1]) + 1;
    } else {
        downtrendCount = nz(downtrendCount[1]);
        uptrendCount   = nz(uptrendCount[1]);}
    } else {
        downtrendCount = nz(downtrendCount[1]);
        uptrendCount   = nz(uptrendCount[1]);
}
def trend = if uptrendCount >= trendConfirmationCount then 1 else
            if downtrendCount >= trendConfirmationCount then -1 else 0;

plot uptrend =  if isNaN(close) then na else uptrendCount;     # "uptrend"
uptrend.SetDefaultColor(Color.GREEN);
plot downtrend = if isNaN(close) then na else downtrendCount; # "downtrend"
downtrend.SetDefaultColor(Color.RED);


AddCloud(uptrend, downtrend, Color.DARK_GREEN, COLOR.DARK_RED);

AssignPriceColor(if BarColor then if trend > 0 then Color.GREEN else
                 if trend < 0 then Color.RED else color.GRAY else Color.CURRENT);


##### END
 
Last edited by a moderator:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
196 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top