Range Filtered Trend Signals for Thinkorswim

chewie76

Well-known member
VIP
VIP Enthusiast
This is my conversion of the Range Filtered Trend Signals that gives entry signals and profit target levels. Perfect fit for people who want to maximize their profits. It also offers band levels that you can set stop losses that are still profitable. This is a trend indicator where green candles are an uptrend and red candles are a downtrend. Any gray area is a ranging market and should not be traded. The indicator plots a cyan or magenta dot when a trend breakout takes place. That is your entry. The far white bands are max profit. Take your profits when price hits the far bands if not sooner. Note that price can extend past the white lines in massive moves, especially at lower timeframes. There are other inside bands that also could be used for support/resistance. Below is a 1 hour chart of /NQ. Notice the circled areas of entries and exits. Breakout alerts are available if you remove the #s in the alert section at the bottom of the code.

I found this indicator from watching this video.
This is the original code. https://www.tradingview.com/script/6uzoUSV9-Range-Filtered-Trend-Signals-AlgoAlpha/

1756904821151.png

Code:
## Range Filtered Trend Signals [AlgoAlpha] – (ThinkScript Conversion)
## Kalman via CompoundValue
#Assembled by Chewie 9/3/25

declare upper;

#------------------------------
# Inputs
#------------------------------
input bands = yes;
input kalmanAlpha = 0.01;   # smoothing factor (like Pine alpha)
input kalmanBeta  = 0.1;    # trend sensitivity term
input kalmanPeriod = 77;    # period used in beta term
input dev = 1.2;            # deviation multiplier for range bands
input supertrendFactor = 0.7;
input supertrendAtrPeriod = 7;



#------------------------------
# Recursive Kalman (simulated)
#------------------------------
def src = close;

rec kalmanV1 =
    CompoundValue(1,
        kalmanV1[1] + kalmanAlpha * (src - kalmanV1[1]),
        src
    );

# variance / process term (kept for parity; not used directly)
rec kalmanVar =
    CompoundValue(1,
        (1 - kalmanAlpha) * kalmanVar[1] + kalmanBeta / kalmanPeriod,
        1
    );

plot kalman = kalmanV1;
kalman.setdefaultColor(color.white);
kalman.setlineWeight(2);

#------------------------------
# Supertrend (ATR envelope + direction)
#------------------------------
def atr = Average(TrueRange(high, close, low), supertrendAtrPeriod);
def upperBand = kalman + atr * supertrendFactor;
def lowerBand = kalman - atr * supertrendFactor;

rec supertrendDir =
    CompoundValue(1,
        if IsNaN(supertrendDir[1]) then 1
        else if close > upperBand[1] then 1
        else if close < lowerBand[1] then -1
        else supertrendDir[1],
        1
    );

def supertrend = if supertrendDir == 1 then lowerBand else upperBand;

#------------------------------
# Volatility bands around Kalman
#------------------------------
def vola  = WMA(high - low, 200);
def upper = kalman + vola * dev;
def lower = kalman - vola * dev;
def midbody1 = (open + close) / 2;

#------------------------------
# Trend states
#------------------------------
def trend  = if close > upper then 1 else if close < lower then -1 else 0;
def ktrend = if supertrendDir < 0 then 1 else -1;  # Pine maps -1/+1 to long/short bias
def ktimes = ktrend * trend;

#------------------------------
# Plots (lines/points)
#------------------------------
plot KalmanLine = if ktimes == 1 then kalman else Double.NaN;
KalmanLine.SetDefaultColor(Color.gray);
KalmanLine.SetLineWeight(3);

plot MidBody = midbody1;    # helper (hidden)
MidBody.SetDefaultColor(Color.GRAY);
MidBody.Hide();


plot UpperBandPlot = if trend == 0 or ktimes == 1 then upper else Double.NaN;
UpperBandPlot.SetPaintingStrategy(PaintingStrategy.POINTS);
UpperBandPlot.SetLineWeight(2);
UpperBandPlot.AssignValueColor(
    if ktimes == -1 then color.red
    else if ktrend == 0 then color.gray
    else color.gray);
plot UpperBandPlot2 = if trend == -1 or ktimes == 1 then upper else Double.NaN;
UpperBandPlot2.SetPaintingStrategy(PaintingStrategy.POINTS);
UpperBandPlot2.SetLineWeight(2);
UpperBandPlot2.AssignValueColor(
    if ktimes == -1 then color.red
    else if ktrend == 0 then color.gray
    else color.gray);


plot LowerBandPlot = if trend == 0 or ktimes == 1 then lower else Double.NaN;
LowerBandPlot.SetPaintingStrategy(PaintingStrategy.POINTS);
LowerBandPlot.SetLineWeight(2);
LowerBandPlot.AssignValueColor(
    if ktimes == 1 then color.green
    else if ktrend == -1 then color.gray
    else color.gray);

plot LowerBandPlot2 = if trend == 1 or ktimes == 1 then lower else Double.NaN;
LowerBandPlot2.SetPaintingStrategy(PaintingStrategy.POINTS);
LowerBandPlot2.SetLineWeight(2);
LowerBandPlot2.AssignValueColor(
if ktimes == 1 then color.green
else if ktrend == -1 then color.green
else color.gray);


# Signal marker: Pine used crossover(ktrend*trend, 0) and plotted at k (kalman here)
def crossTrendingUp   = ktimes crosses above 0;
def crossTrendingDown = ktimes crosses below 0;


def Long = if lowerbandplot2 then kalman else double.nan;
def short = if upperbandplot2 then kalman else double.nan;
def LongTrigger = isNaN(Long[1]) and !isNaN(Long);
def ShortTrigger = isNaN(Short[1]) and !isNaN(Short);

plot LongDot = if LongTrigger then kalman else Double.NaN;
LongDot.SetPaintingStrategy(PaintingStrategy.POINTS);
LongDot.AssignValueColor(Color.cyan);
LongDot.SetLineWeight(5);
LongDot.HideBubble();
LongDot.HideTitle();

plot ShortDot = if ShortTrigger then kalman else Double.NaN;
ShortDot.SetPaintingStrategy(PaintingStrategy.POINTS);
ShortDot.AssignValueColor(Color.magenta);
ShortDot.SetLineWeight(5);
ShortDot.HideBubble();
ShortDot.HideTitle();

# ------------------------------
# Ranging flag and mutually-exclusive clouds
# ------------------------------
# Define ranging explicitly: either ktimes == -1 (Pine's 'range' condition) OR no short-term trend (trend == 0)
def isRanging = (ktimes == 1) or (trend == 0);

# 1) Cloud between Kalman and MidBody (bull only when trending up)
plot KM_Bull_Top = if (trend == 1) and !isRanging then kalman else Double.NaN;
plot KM_Bull_Bot = if (trend == 1) and !isRanging then midbody else Double.NaN;
KM_Bull_Top.Hide(); KM_Bull_Bot.Hide();
AddCloud(KM_Bull_Top, KM_Bull_Bot, color.cyan, color.cyan);

# 2) Cloud between Kalman and MidBody (bear only when trending down)
plot KM_Bear_Top = if (trend == -1) and !isRanging then kalman else Double.NaN;
plot KM_Bear_Bot = if (trend == -1) and !isRanging then midbody else Double.NaN;
KM_Bear_Top.Hide(); KM_Bear_Bot.Hide();
AddCloud(KM_Bear_Top, KM_Bear_Bot, color.magenta, color.magenta);

# 3) Cloud between Upper/Lower bands when TRENDING UP (and not ranging)
plot Range_Up_Top = if (trend == 1) and !isRanging then upper else Double.NaN;
plot Range_Up_Bot = if (trend == 1) and !isRanging then kalman else Double.NaN;
Range_Up_Top.Hide(); Range_Up_Bot.Hide();
AddCloud(Range_Up_Top, Range_Up_Bot, color.cyan, color.cyan);

# 4) Cloud between Upper/Lower bands when TRENDING DOWN (and not ranging)
plot Range_Dn_Top = if (trend == -1) and !isRanging then kalman else Double.NaN;
plot Range_Dn_Bot = if (trend == -1) and !isRanging then lower else Double.NaN;
Range_Dn_Top.Hide(); Range_Dn_Bot.Hide();
AddCloud(Range_Dn_Top, Range_Dn_Bot, color.magenta, color.magenta);

# 5) Cloud between Upper/Lower bands when RANGING (only this one uses neutralGray)
plot Range_Neut_Top = if isRanging then upper else Double.NaN;
plot Range_Neut_Bot = if isRanging then lower else Double.NaN;
Range_Neut_Top.Hide(); Range_Neut_Bot.Hide();
AddCloud(Range_Neut_Top, Range_Neut_Bot, color.gray, color.gray);

#------------------------------
# Bar colors
#------------------------------
AssignPriceColor(
    if (trend == 1) and !isRanging then color.green else if (trend == -1) and !isRanging then color.red
    else if trend == 1 then color.gray
    else color.gray);


#Bands

input atrMultiplier1 = 2;
input atrMultiplier2 = 4;
input atrMultiplier3 = 8;
input atrLength = 200;
def source = FundamentalType.CLOSE;
def ATRb = atr(Length = ATRlength);

def emaup    = kalman + (ATRb*atrMultiplier1);
def emadw    = kalman - (ATRb*atrMultiplier1);
def emaup2   = kalman + (ATRb*atrMultiplier2);
def emadw2   = kalman - (ATRb*atrMultiplier2);
def emaup3   = kalman + (ATRb*atrMultiplier3);
def emadw3   = kalman - (ATRb*atrMultiplier3);

plot Up = if bands then emaup else Double.NaN;
plot Dn = if bands then emadw else Double.NaN;
plot Up2 = if bands then emaup2 else Double.NaN;
plot Dn2 = if bands then emadw2 else Double.NaN;
plot Up3 = if bands then emaup3 else Double.NaN;
plot Dn3 = if bands then emadw3 else Double.NaN;


up.setdefaultColor(color.dark_orange);
up2.setdefaultColor(color.magenta);
up3.setdefaultColor(color.white);
dn.setdefaultColor(color.light_green);
dn2.setdefaultColor(color.cyan);
dn3.setdefaultColor(color.white);


#------------------------------
# Alerts
#------------------------------
#Alert(crossTrendingUp,   "Market Trending", Alert.BAR, Sound.Ring);
#Alert(crossTrendingDown, "Market Ranging",  Alert.BAR, Sound.Bell);

#Alert(trend crosses above 0, "Market Short Term Bullish", Alert.BAR, Sound.Chimes);
#Alert(trend crosses below 0, "Market Short Term Bearish", Alert.BAR, Sound.Chimes);

#Alert(ktrend crosses above 0, "Market Long Term Bullish", Alert.BAR, Sound.Ding);
#Alert(ktrend crosses below 0, "Market Long Term Bearish", Alert.BAR, Sound.Ding);
 
Last edited:

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
424 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