Repaints Chewie's Super Trend, Hull Average, Donchian Trend Ribbon Trading System for ThinkorSwim

Repaints

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

Thanks for getting back to me. Would you mind being a little more specific at to what to change? I'm new with scripting.
On Mobile, you have to go to studies, then click the gear icon next to the indicator name. Scroll down to MA_Min and MA_Max and click on them. Change the line of "Draw as" into a square or triangle. That's it.
 
Greetings all. I like the overall approach of Chewie's script, but, to be honest, the original version presented in the original post is a bit "busy" to me. There are also a few things that I consider glitches - primarily the way the entry lines and target lines didn't align. So, I wanted to offer an updated script that kept the spirit of Chewie's method but simplified the presentation some.

I've made the following changes to the code:
1) Added Donchian Trend Channel code. Item 2.2 in Chewie's OP says the Donchian Trend Ribbon should be red or green in the direction of your trade. I had already created code that generated a summary value of the DTR to use in an upper study, so I move that to this script. There are several inputs associated with this code:
  • Donchian_Channel_Period = 20; #length to calculate main trend - regular input from the lower study
  • secondary_colors = { default yellow , green_red } - regular input from the lower study
  • DTC_Trend_Cutoff = 20 - the summary code adds up the color values of each of the DTR lengths. This value is the limit of that summation used to determine if the trend is green, yellow (neutral) or red. A value of 20 means the entire trend ribbon has to be the same color. Lower values allow some yellow values to be included. Experiment with the values to see what works for you.
  • plotDTCResult = yes - turns the plot of the summary line on or off. Mostly used for debugging my code. If you're looking for the cleanest chart, set to "No".
2) Added constraints to drawing target lines based on HMA, Supertrend and DTC. Per Chewie's OP, all three of these indicators should be in buy or sell mode before entering the trade. So, I made it so that the entry and target lines won't appear unless that's true.
3) Added ability to remove drawing the Dyno lines and cloud (label and price bar coloring remain). The Dyno lines didn't seem to be used in determining buy/sell conditions, so I just added an input to allow you to turn off the plot of the lines/cloud to clean up the chart.
4) Commented out some code that didn't appear to be doing anything. Looks like it might have been left over from a previous iteration of the code (leaving in for Chewie to evaluate if it's actually needed - see lines 36-37, 54-58 and 150).
5) Made entry and target lines all start/end at the same place. Just some cleanup to the code so that all of these lines appear consistently.
6) Some general cleanup and rearranging (no effect to output)

Here's the updated script:
Code:
#Hull_SuperTrend_Trading_System
# assembled by Chewie 4/10/2022
# many thanks to all the other noted contributors to this system.
# SuperTrend Yahoo Finance Replica - Modified from Modius SuperTrend
# Modified Modius ver. by RConner7
# Modified by Barbaros to replicate look from TradingView version
# Modified by Barbaros to add EMA cross for bubbles and alerts
# Modified by Barbaros to update bar color painting
# v3.3
# Modified by Zetta_wow:
# - Add Donchian Trend Channel code to provide summary value of DTC and include in target lines
# - Added constraints to drawing target lines based on HMA, Supertrend and DTC
# - Added ability to remove drawing the Dyno lines and cloud (label and price bar coloring remain)
# - Commented out some code that didn't appear to be doing anything (leaving in for Chewie to evaluate need)
# - Made entry and target lines all start/end at the same place
# - Some general cleanup and rearranging (no effect to output)
# From the useThinkScript thread introducing Chewie's strategy:
#2. SETUP: You must see three things to define an entry position.
#  1. A top or bottom reversal signal of the Hull Moving Avg plotted with a white square (top) or white triangle (bottom).
#  2. Lower Donchian Trend Ribbon either green or red in the color of the direction you are entering the trade. (Shout out to @halcyonguy who converted this into TOS. Much appreciated, you are awesome!!!)
#  3. Break of the Super Trend indicator. (Default setting is 2.75. Feel free to adjust this if you want in the settings)
#
# HMA signal indicated by Hull_is_buy and Hull_is_sell variables
# Donchian Trend Ribbon signal indicated by DTC_is_buy and DTC_is_sell
# Supertrend signal indicated by Long and Short variables (plots)
# Don't draw entry/1x/2x/3x/4x lines unless all three match signals (buy/long or sell/short)
input Target_Bubbles = no;
input Entry_SL_Bubbles = no;
input Targetlines = yes;
input Labels = yes;
input alertON = yes;
input Bands = yes;
input AvgType = AverageType.HULL;
input STAtrMult = 2.75;
input nATR = 12;
#======== Calculate the Supertrend =====================================================
def ATR = ATR("length" = nATR, "average type" = AvgType);
def UP_Band_Basic = HL2 + (STAtrMult * ATR);
def LW_Band_Basic = HL2 + (-STAtrMult * ATR);
def UP_Band = if ((UP_Band_Basic < UP_Band[1]) or (close[1] > UP_Band[1])) then UP_Band_Basic else UP_Band[1];
def LW_Band = if ((LW_Band_Basic > LW_Band[1]) or (close[1] < LW_Band[1])) then LW_Band_Basic else LW_Band[1];
def ST = if ((ST[1] == UP_Band[1]) and (close < UP_Band)) then UP_Band
else if ((ST[1] == UP_Band[1]) and (close > Up_Band)) then LW_Band
else if ((ST[1] == LW_Band[1]) and (close > LW_Band)) then LW_Band
else if ((ST[1] == LW_Band) and (close < LW_Band)) then UP_Band
else LW_Band;
plot Long = if close > ST then ST else Double.NaN;
Long.AssignValueColor(Color.cyan);
Long.SetLineWeight(3);
plot Short = if close < ST then ST else Double.NaN;
Short.AssignValueColor(Color.magenta);
Short.SetLineWeight(3);
def LongTrigger = isNaN(Long[1]) and !isNaN(Long);
def ShortTrigger = isNaN(Short[1]) and !isNaN(Short);
plot LongDot = if LongTrigger then ST else Double.NaN;
LongDot.SetPaintingStrategy(PaintingStrategy.POINTS);
LongDot.AssignValueColor(Color.cyan);
LongDot.SetLineWeight(4);
plot ShortDot = if ShortTrigger then ST else Double.NaN;
ShortDot.SetPaintingStrategy(PaintingStrategy.POINTS);
ShortDot.AssignValueColor(Color.magenta);
ShortDot.SetLineWeight(4);
AddChartBubble(Entry_SL_Bubbles and LongTrigger, ST, "BUY", Color.GREEN, no);
AddChartBubble(Entry_SL_Bubbles and ShortTrigger, ST, "SELL", Color.RED, yes);
#Super Trend Labels
AddLabel(yes and labels and Long, "ST:LONG", color.CYAN);
AddLabel(yes and labels and Short, "ST:SHORT", color.magenta);
#======== End of Supertrend calcs =====================================================
# =====================================================================================
# Hull Moving Average Concavity and Turning Points
#
# Author: Seth Urion (Mahsume)
# Version: 2020-05-01 V4
#
# Now with support for ToS Mobile
#
declare upper;
input HMA_Length = 60;
input lookback = 3;
input arrows = no;
def price = HL2;
plot HMA = HullMovingAvg(price = price, length = HMA_Length);
def delta = HMA[1] - HMA[lookback + 1];
def delta_per_bar = delta / lookback;
def next_bar = HMA[1] + delta_per_bar;
def concavity = if HMA > next_bar then 1 else -1;
HMA.AssignValueColor(color = if concavity[1] == -1 then
    if HMA > HMA[1] then color.dark_orange else color.red else
    if HMA < HMA[1] then color.dark_green else color.green);
HMA.SetLineWeight(3);
#Define turning point where concavity switches directiion
plot turning_point = if concavity[1] != concavity then HMA else double.nan;
turning_point.SetLineWeight(2);
turning_point.SetPaintingStrategy(paintingStrategy = PaintingStrategy.POINTS);
turning_point.SetDefaultColor(color.white);
#Plot maximum/minimum points of HMA
# Note: the HMA[-1] term will cause repainting at the end of the chart (looks forward 1 bar)
plot MA_Max = if HMA[-1] < HMA and HMA > HMA[1] then HMA else Double.NaN;
MA_Max.SetDefaultColor(Color.WHITE);
MA_Max.SetPaintingStrategy(PaintingStrategy.SQUARES);
MA_Max.SetLineWeight(5);
plot MA_Min = if HMA[-1] > HMA and HMA < HMA[1] then HMA else Double.Nan;
MA_Min.SetDefaultColor(Color.WHITE);
MA_Min.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
MA_Min.SetLineWeight(5);
#Define conditions for HMA-based alerts (see end of code)
def BuySetup = HMA > HMA[1] and HMA[1] < HMA[2];
def SellSetup =  HMA < HMA[1] and HMA[1] > HMA[2];
#Plot buy/sell arrows based on HMA
# Up arrow if at a turning point and concavity is "up"
# Down arrow if at a turning point and concavity is "down"
plot sell = if arrows and turning_point and concavity == -1 then high else double.nan;
sell.SetDefaultColor(Color.DARK_ORANGE);
sell.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
sell.SetLineWeight(3);
plot buy = if arrows and turning_point and concavity == 1 then low else double.nan;
buy.SetDefaultColor(Color.CYAN);
buy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
buy.SetLineWeight(3);
###################
#
# 2020-05-01
#
# MOBILE TOS SUPPORT
#
# Each color of the HMA needs to be a separate plot as ToS Mobile
# lacks the ability to assign colors the way ToS Desktop does.
# I recommend a plain colored HMA behind the line
# Set the line color of the HMA above to gray or some neutral
#
# CCD_D -> ConCave Down and Decreasing
# CCD_I -> ConCave Down and Increasing
# CCU_D -> ConCave Up and Decreasing
# CCU_I -> ConCave Up and Increasing
#
###################
plot CCD_D = if concavity == -1 and HMA < HMA[1] then HMA else double.nan;
CCD_D.SetDefaultColor(Color.RED);
CCD_D.SetLineWeight(1);
plot CCD_I = if concavity == -1 and HMA >= HMA[1] then HMA else double.nan;
CCD_I.SetDefaultColor(Color.DARK_ORANGE);
CCD_I.SetLineWeight(1);
plot CCU_D = if concavity == 1 and HMA <= HMA[1] then HMA else double.nan;
CCU_D.SetDefaultColor(COLOR.DARK_GREEN);
CCU_D.SetLineWeight(1);
plot CCU_I = if concavity == 1 and HMA > HMA[1] then HMA else double.nan;
CCU_I.SetDefaultColor(COLOR.GREEN);
CCU_I.SetLineWeight(1);
#======= End of mobile HMA coloring support =============================
#Hull Label
AddLabel(yes and labels and CCD_D, "HULL:SELL", color.RED);
AddLabel(yes and labels and CCU_I, "HULL:BUY", color.green);
AddLabel(yes and labels and CCU_D, "HULL:WEAK SELL", color.dark_green);
AddLabel(yes and labels and CCD_I, "HULL:WEAK BUY", color.DARK_ORANGE);
def Hull_is_buy = !IsNaN(CCD_I) or !IsNaN(CCU_I);
def Hull_is_sell = !IsNaN(CCD_D) or !IsNaN(CCU_D);
#======= End of Hull Moving Avg Calcs =================================
#============ Create Donchian Trend Ribbon values =======================================
# Donchian Trend Channel parameters
input Donchian_Channel_Period = 20; #length to calculate main trend
input DTC_Trend_Cutoff = 20; #value of sum of all trends to exceed to use for buy/sell signal
input plotDTCResult = yes;
input secondary_colors = { default yellow , green_red };
#=======================================================================
# Donchian Trend Channel calcs
# all plots have been removed leaving only the value calculations
# How it works ?
# - it calculates main trend direction by using the length that is user-defined. so you can change it as you wish
# - then it calculates trend direction for each 9 lower lengths. if you set the length = 20 then the lengths are 19, 18,...11
# - and it checks if the trend directions that came from lower lengths is same or not with main trend direction.
# - it changes the trend color of the ribbon.
# -----------------------------
def dlen = if Donchian_Channel_Period < 10 then 10 else Donchian_Channel_Period;
def na = Double.NaN;
script dchannel {
    input len = 0;
    def hh = Highest(high, len);
    def ll = Lowest(low, len);
    def trend = if BarNumber() == 1 then 0 else if close > hh[1] then 1 else if close < ll[1] then -1 else trend[1];
    plot z = trend;
}
script dchannelalt {
    input len = 0;
    input maintrend = 0;
    def hh = Highest(high, len);
    def ll = Lowest(low, len);
    def trend = if BarNumber() == 1 then 0 else if close > hh[1] then 1 else if close < ll[1] then -1 else trend[1];
    def maincolor =
  if maintrend == 1 then if trend == 1 then 2 else 1
  else if maintrend == -1 then if trend == -1 then -2 else -1
  else 0;
    plot color = maincolor;
}
def maintrend = dchannel(dlen);
# ---------------------------------
def c01 = dchannelalt(dlen - 0, maintrend);
def c02 = dchannelalt(dlen - 1, maintrend);
def c03 = dchannelalt(dlen - 2, maintrend);
def c04 = dchannelalt(dlen - 3, maintrend);
def c05 = dchannelalt(dlen - 4, maintrend);
def c06 = dchannelalt(dlen - 5, maintrend);
def c07 = dchannelalt(dlen - 6, maintrend);
def c08 = dchannelalt(dlen - 7, maintrend);
def c09 = dchannelalt(dlen - 8, maintrend);
def c10 = dchannelalt(dlen - 9, maintrend);
# -----------------------------
# add up color numbers, to come up with a 'trend' number , 20 to -20
def colorsum = ( c01 + c02 + c03 + c04 + c05 + c06 + c07 + c08 + c09 + c10 );
# colors 
# 2 - up trend - green
# 1 - up trend - dark green
# 0 no trend
# -1 - down trend - dark red
# -2 - down trend - red
def DTC_Result = if colorsum >= DTC_Trend_Cutoff then 1
else if colorsum <= -DTC_Trend_Cutoff then -1
else 0;
def seccolor;
switch (secondary_colors) {
case yellow:
    seccolor = 1;
case green_red:
    seccolor = 2;
}
#   colors 
# 2 - up trend - green
# 1 - up trend - dark green
# 0 no trend
# -1 - down trend - dark red
# -2 - down trend - red
plot DTC_Trend = if (plotDTCResult) then (0.995 * low) else na;
DTC_Trend.SetPaintingStrategy(PaintingStrategy.LINE);
DTC_Trend.SetLineWeight(3);
DTC_Trend.DefineColor("up2", Color.GREEN);
DTC_Trend.DefineColor("up1", Color.DARK_GREEN);
DTC_Trend.DefineColor("none", Color.DARK_GRAY);
DTC_Trend.DefineColor("dwn1", Color.DARK_RED);
DTC_Trend.DefineColor("dwn2", Color.RED);
DTC_Trend.DefineColor("alt1", Color.YELLOW);
DTC_Trend.AssignValueColor( if colorsum >= DTC_Trend_Cutoff then DTC_Trend.Color("up2")
else if (colorsum > 0 and colorsum < DTC_Trend_Cutoff) and seccolor == 1 then DTC_Trend.Color("alt1") else if (colorsum > 0 and colorsum < DTC_Trend_Cutoff) and seccolor == 2 then DTC_Trend.Color("up1")
else if colorsum <= -DTC_Trend_Cutoff then DTC_Trend.Color("dwn2")
else if (colorsum < 0 and colorsum > -DTC_Trend_Cutoff) and seccolor == 1 then DTC_Trend.Color("alt1") else if (colorsum < 0 and colorsum > -DTC_Trend_Cutoff) and seccolor == 2 then DTC_Trend.Color("dwn1")
else Color.GRAY);
DTC_Trend.SetHiding(!plotDTCResult);
def DTC_is_buy = if colorsum >= DTC_Trend_Cutoff then yes else no;
def DTC_is_sell = if colorsum <= -DTC_Trend_Cutoff then yes else no;
# === End of Donchian Trend Channel code ===
#Target lines
# created by chewie
#=========== Determine long stoploss, entry point, and target lines =====================
#Stop Loss = minimum point of Hull MA
def line = if IsNaN(MA_Min) then line[1] else MA_Min[0];
plot L_stoploss = if IsNaN(MA_Min) and Hull_is_buy and Long and DTC_is_buy then line else double.nan;
L_stoploss.setpaintingStrategy(paintingStrategy.LINE);
L_stoploss.setlineWeight(3);
L_stoploss.setdefaultColor(color.dark_green);
L_stoploss.hideBubble();
def LSL = (if isNaN(L_stoploss[1]) then L_stoploss else Double.NaN);
#Long Entry = final value of previous Supertrend (short)
def line4 = if IsNaN(short) then line4[1] else short[0];
plot L_Entry = if IsNaN(short) and Hull_is_buy and DTC_is_buy then line4 else double.nan;
L_Entry.setpaintingStrategy(paintingStrategy.LINE);
L_Entry.setlineWeight(3);
L_Entry.setdefaultColor(color.green);
L_Entry.hideBubble();
def LE = (if isNaN(L_Entry[1]) then L_Entry else Double.NaN);
addchartBubble(Entry_SL_Bubbles and L_stoploss, LSL,"L/SL (" + AsDollars(L_stoploss) + " : " + AsPercent((L_stoploss - L_Entry)/L_Entry) + ")",color.DARK_GREEN);
addchartBubble(Entry_SL_Bubbles and L_Entry, LE,"L/E (" + AsDollars(L_Entry) + ")",color.GREEN);
#HalfX Long
plot x1a_Long = if Targetlines and L_Entry then (L_Entry + (L_Entry - L_Stoploss)/2) else double.nan;
x1a_Long.setpaintingStrategy(paintingStrategy.dashes);
x1a_Long.setlineWeight(1);
x1a_Long.setdefaultColor(color.magenta);
x1a_Long.hideBubble();
def x1aL = (if isNaN(x1a_Long[1]) then x1a_Long else Double.NaN);
addchartBubble(Target_Bubbles and x1a_Long, x1aL,"1/2xL (" + AsDollars(x1a_Long) + " : " + AsPercent((x1a_Long - L_Entry)/L_Entry) + ")",color.magenta);
#OneX Long
plot x1_Long = if Targetlines and x1a_Long > line4 then (L_Entry +(L_Entry - L_Stoploss)) else double.nan;
x1_Long.setpaintingStrategy(paintingStrategy.dashes);
x1_Long.setlineWeight(1);
x1_Long.setdefaultColor(color.yellow);
def X1L = (if isNaN(x1_Long[1]) then x1_Long else Double.NaN);
addchartBubble(Target_Bubbles and x1_Long, x1L,"1xL (" + AsDollars(x1_Long) + " : " + AsPercent((x1_Long - L_Entry)/L_Entry) + ")",color.yellow);
#TwoX Long
plot x2_Long = if Targetlines then x1_Long + (L_Entry - L_Stoploss) else double.nan;
x2_Long.setpaintingStrategy(paintingStrategy.dashes);
x2_Long.setlineWeight(2);
x2_Long.setdefaultColor(color.light_red);
def X2L = (if isNaN(x2_Long[1]) then x2_Long else Double.NaN);
addchartBubble(Target_Bubbles and x2_Long, x2L,"2xL (" + AsDollars(x2_Long) + " : " + AsPercent((x2_Long - L_Entry)/L_Entry) + ")",color.light_red);
#ThreeX Long
plot x3_Long = if Targetlines then x2_Long + (L_Entry - L_Stoploss) else double.nan;
x3_Long.setpaintingStrategy(paintingStrategy.dashes);
x3_Long.setlineWeight(1);
x3_Long.setdefaultColor(color.cyan);
def X3L = (if isNaN(x3_Long[1]) then x3_Long else Double.NaN);
addchartBubble(Target_Bubbles and x3_Long, x3L,"3xL (" + AsDollars(x3_Long) + " : " + AsPercent((x3_Long - L_Entry)/L_Entry) + ")",color.cyan);
#FourX Long
plot x4_Long = if Targetlines then x3_Long + (L_Entry - L_Stoploss) else double.nan;
x4_Long.setpaintingStrategy(paintingStrategy.dashes);
x4_Long.setlineWeight(1);
x4_Long.setdefaultColor(color.white);
def X4L = (if isNaN(x4_Long[1]) then x4_Long else Double.NaN);
addchartBubble(Target_Bubbles and x4_Long, x4L,"4xL (" + AsDollars(x4_Long) + " : " + AsPercent((x4_Long - L_Entry)/L_Entry) + ")",color.white);
#=========== Determine short stoploss, entry point, and target lines =====================
rec line2 = if IsNaN(MA_Max) then line2[1] else MA_Max[0];
plot S_stoploss = if IsNaN(MA_MAX) and Short and Hull_is_sell and DTC_is_sell then line2 else double.nan;
S_stoploss.setpaintingStrategy(paintingStrategy.LINE);
S_stoploss.setlineWeight(3);
S_stoploss.setdefaultColor(color.dark_red);
S_stoploss.hideBubble();
def SSL = (if isNaN(S_stoploss[1]) then S_stoploss else Double.NaN);
#Short Entry
rec line3 = if IsNaN(long) then line3[1] else long[0];
plot S_Entry = if IsNaN(long) and Hull_is_sell and DTC_is_sell then line3 else double.nan;
S_Entry.setpaintingStrategy(paintingStrategy.LINE);
S_Entry.setlineWeight(3);
S_Entry.setdefaultColor(color.red);
S_Entry.hideBubble();
def SE = (if isNaN(S_Entry[1]) then S_Entry else Double.NaN);
addchartBubble(Entry_SL_Bubbles and S_stoploss, SSL,"S/SL (" + AsDollars(S_stoploss) + " : " + AsPercent((S_stoploss - S_Entry)/S_Entry) + ")",color.DARK_RED);
addchartBubble(Entry_SL_Bubbles and S_Entry, SE,"S/E (" + AsDollars(S_Entry) + ")",color.RED);
#HalfX Short
plot x1a_Short = if Targetlines and S_Entry then (S_Entry - (S_Stoploss - S_Entry)/2) else double.nan;
x1a_Short.setpaintingStrategy(paintingStrategy.dashes);
x1a_Short.setlineWeight(1);
x1a_Short.setdefaultColor(color.magenta);
x1a_Short.hideBubble();
def x1a = (if isNaN(x1a_Short[1]) then x1a_Short else Double.NaN);
addchartBubble(Target_Bubbles and x1a_Short, x1a,"1/2xS (" + AsDollars(x1a_Short) + " : " + AsPercent((x1a_Short - S_Entry)/S_Entry) + ")",color.magenta);
#OneX Short
plot x1_Short = if Targetlines and x1a_short < line3 then (S_Entry -(S_Stoploss - S_Entry)) else double.nan;
x1_Short.setpaintingStrategy(paintingStrategy.dashes);
x1_Short.setlineWeight(1);
x1_Short.setdefaultColor(color.yellow);
def X1S = (if isNaN(x1_Short[1]) then x1_Short else Double.NaN);
addchartBubble(Target_Bubbles and x1_Short, x1S,"1xS (" + AsDollars(x1_Short) + " : " + AsPercent((x1_Short - S_Entry)/S_Entry) + ")",color.yellow);
#TwoX Short
plot x2_Short = if Targetlines then x1_Short - (S_Stoploss - S_Entry) else double.nan;
x2_Short.setpaintingStrategy(paintingStrategy.dashes);
x2_Short.setlineWeight(2);
x2_Short.setdefaultColor(color.light_green);
def X2S = (if isNaN(x2_Short[1]) then x2_Short else Double.NaN);
addchartBubble(Target_Bubbles and x2_Short, x2S,"2xS (" + AsDollars(x2_Short) + " : " + AsPercent((x2_Short - S_Entry)/S_Entry) + ")",color.light_green);
#ThreeX Short
plot x3_Short = if Targetlines then x2_Short - (S_Stoploss - S_Entry) else double.nan;
x3_Short.setpaintingStrategy(paintingStrategy.dashes);
x3_Short.setlineWeight(1);
x3_Short.setdefaultColor(color.cyan);
def X3S = (if isNaN(x3_Short[1]) then x3_Short else Double.NaN);
addchartBubble(Target_Bubbles and x3_Short, x3S,"3xS (" + AsDollars(x3_Short) + " : " + AsPercent((x3_Short - S_Entry)/S_Entry) + ")",color.cyan);
#FourX Short
plot x4_Short = if Targetlines then x3_Short - (S_Stoploss - S_Entry) else double.nan;
x4_Short.setpaintingStrategy(paintingStrategy.dashes);
x4_Short.setlineWeight(1);
x4_Short.setdefaultColor(color.white);
def X4S = (if isNaN(x4_Short[1]) then x4_Short else Double.NaN);
addchartBubble(Target_Bubbles and x4_Short, x4S,"4xS (" + AsDollars(x4_Short) + " : " + AsPercent((x4_Short - S_Entry)/S_Entry) + ")",color.white);
#=================================================================
#LinearRegCh100 RegressionDivergence - Trigger Lines - Trend Cross
# From Lizard Indicators Link: https://www.lizardindicators.com/trigger-lines-cross-vs-thrust/
# Line #1 - Fast = LinReg (80)
# Line #2 - Slow = EXPEMA[LinReg (80)]
input LinRegLength = 80;
input EMAlength = 20;
input ColorOn = yes;  #Color price bars based on linear reg
input ShowDynoLines = yes;
#Definitions
def price1 = close;
def displace = 0;
def LinReg = Inertia(price1[-displace], LinRegLength);
def EMA_LR = ExpAverage(LinReg[-displace], EMAlength);
def Body = (open + close)/2;
# Defining Long/Short Filters (these instructions determine entries / exits)
# Entry Requirements
def Long_Entry = close > LinReg and close > EMA_LR and body > LinReg and body > EMA_LR and close > high[1] and body > body[1];
# LinReg > LinReg[1] and
def Long_Stay_In = close > LinReg and close > EMA_LR;
def Long_Exit = (close < LinReg or close < EMA_LR) or Long_Stay_In == 0;
def Long_State = If Long_Entry then 1 else if Long_Exit then 0 else Long_State[1];
def Long1 = Long_State;
# Exit Requirements
def Short_Entry = close < LinReg and close < EMA_LR and body < LinReg and body < EMA_LR and close < low[1] and body < body[1];
# LinReg < LinReg[1] and
def Short_Stay_In = close < LinReg and close < EMA_LR;
def Short_Exit = (close > LinReg or close > EMA_LR) or Short_Stay_In == 0;
def Short_State = If Short_Entry then 1 else if Short_Exit then 0 else Short_State[1];
def Short1 = Short_State;
#Adding plot lines for Linear Regression averages
plot LR = if ShowDynoLines then LinReg else double.NaN;
LR.SetDefaultColor(CreateColor(0, 130, 255));
LR.setlineweight(1);
plot EMA_LinReg = if ShowDynoLines then EMA_LR else double.NaN;
EMA_LinReg.SetDefaultColor(CreateColor(255, 215,0));
EMA_LinReg.setlineweight(2);
#Add cloud between linear reg and EMA of lin reg lines
DefineGlobalColor("Bullish", Color.dark_Green);
DefineGlobalColor("Bearish", Color.dark_Red);
AddCloud(EMA_LinReg, LR, GlobalColor("Bearish"), GlobalColor("Bullish"));
#DYNO Label
AddLabel(yes and labels and Short1, "DYNO:BEARISH", color.RED);
AddLabel(yes and labels and Long1, "DYNO:BULLISH", color.green);
AddLabel(yes and labels and Long1 == Short1, "DYNO:NEUTRAL", color.YELLOW);
#Regression Bands
input deviations = 1.618;  #set your deviation units here.
input length = 500; #set your channel lookback period here.
def stdDeviation = StDevAll(price, length);
plot HighBand = if Bands then EMA_LinReg + deviations * stdDeviation else double.nan;
HighBand.SetDefaultColor(Color.red);
plot LowBand = if Bands then EMA_LinReg - deviations * stdDeviation else double.nan;
LowBand.SetDefaultColor(Color.green);
DefineGlobalColor("Bullish", Color.light_green);
DefineGlobalColor("Bearish", Color.light_RED);
# Coloring Bars
AssignPriceColor(if ColorON and Long_State then Color.GREEN else if ColorON and Short_State then Color.RED else Color.Yellow);
#==========End Dyno / Lin Reg Section ============================
#========= Plot Long Moving Average ==============================
input lengthAvgEXP = 200;
plot AvgExp = ExpAverage(price[-displace], lengthAvgExp);
AvgExp.SetDefaultColor(Color.white);
AvgExp.setlineweight(2);
#========== End Long Moving Average =============================
###################
#
# ALERTS
#
###################
Alert(alertON and LongTrigger, "Long Entry", Alert.BAR, Sound.Ding);
Alert(alertON and ShortTrigger, "Short Entry", Alert.BAR, Sound.Ding);
Alert(alertON and Buysetup, "HULL Buy", Alert.BAR, Sound.Bell);
Alert(alertON and Sellsetup, "HULL Sell", Alert.BAR, Sound.Bell);
Alert(alertON and high > highband, "Short Band", Alert.BAR, Sound.Ding);
Alert(alertON and low < lowband, "Long Band", Alert.BAR, Sound.Ding);


EDITS:
8/18/22 - original version posted
8/23/22 - code updated to add price level and % change (relative to entry price) for the stop loss and target lines
 
Last edited:
Greetings all. I like the overall approach of Chewie's script, but, to be honest, the original version presented in the original post is a bit "busy" to me. There are also a few things that I consider glitches - primarily the way the entry lines and target lines didn't align. So, I wanted to offer an updated script that kept the spirit of Chewie's method but simplified the presentation some.

I've made the following changes to the code:
1) Added Donchian Trend Channel code. Item 2.2 in Chewie's OP says the Donchian Trend Ribbon should be red or green in the direction of your trade. I had already created code that generated a summary value of the DTR to use in an upper study, so I move that to this script. There are several inputs associated with this code:
  • Donchian_Channel_Period = 20; #length to calculate main trend - regular input from the lower study
  • secondary_colors = { default yellow , green_red } - regular input from the lower study
  • DTC_Trend_Cutoff = 20 - the summary code adds up the color values of each of the DTR lengths. This value is the limit of that summation used to determine if the trend is green, yellow (neutral) or red. A value of 20 means the entire trend ribbon has to be the same color. Lower values allow some yellow values to be included. Experiment with the values to see what works for you.
  • plotDTCResult = yes - turns the plot of the summary line on or off. Mostly used for debugging my code. If you're looking for the cleanest chart, set to "No".
2) Added constraints to drawing target lines based on HMA, Supertrend and DTC. Per Chewie's OP, all three of these indicators should be in buy or sell mode before entering the trade. So, I made it so that the entry and target lines won't appear unless that's true.
3) Added ability to remove drawing the Dyno lines and cloud (label and price bar coloring remain). The Dyno lines didn't seem to be used in determining buy/sell conditions, so I just added an input to allow you to turn off the plot of the lines/cloud to clean up the chart.
4) Commented out some code that didn't appear to be doing anything. Looks like it might have been left over from a previous iteration of the code (leaving in for Chewie to evaluate if it's actually needed - see lines 36-37, 54-58 and 150).
5) Made entry and target lines all start/end at the same place. Just some cleanup to the code so that all of these lines appear consistently.
6) Some general cleanup and rearranging (no effect to output)

Here's the updated script:
Code:
#Hull_SuperTrend_Trading_System
# assembled by Chewie 4/10/2022
# many thanks to all the other noted contributors to this system.

# SuperTrend Yahoo Finance Replica - Modified from Modius SuperTrend
# Modified Modius ver. by RConner7
# Modified by Barbaros to replicate look from TradingView version
# Modified by Barbaros to add EMA cross for bubbles and alerts
# Modified by Barbaros to update bar color painting
# v3.3
# Modified by Zetta_wow:
# - Add Donchian Trend Channel code to provide summary value of DTC and include in target lines
# - Added constraints to drawing target lines based on HMA, Supertrend and DTC
# - Added ability to remove drawing the Dyno lines and cloud (label and price bar coloring remain)
# - Commented out some code that didn't appear to be doing anything (leaving in for Chewie to evaluate need)
# - Made entry and target lines all start/end at the same place
# - Some general cleanup and rearranging (no effect to output)

# From the useThinkScript thread introducing Chewie's strategy:
#2. SETUP: You must see three things to define an entry position.
#  1. A top or bottom reversal signal of the Hull Moving Avg plotted with a white square (top) or white triangle (bottom).
#  2. Lower Donchian Trend Ribbon either green or red in the color of the direction you are entering the trade. (Shout out to @halcyonguy who converted this into TOS. Much appreciated, you are awesome!!!)
#  3. Break of the Super Trend indicator. (Default setting is 2.75. Feel free to adjust this if you want in the settings)
#
# HMA signal indicated by Hull_is_buy and Hull_is_sell variables
# Donchian Trend Ribbon signal indicated by DTC_is_buy and DTC_is_sell
# Supertrend signal indicated by Long and Short variables (plots)
# Don't draw entry/1x/2x/3x/4x lines unless all three match signals (buy/long or sell/short)

input Target_Bubbles = no;
input Entry_SL_Bubbles = no;
input Targetlines = yes;
input Labels = yes;
input alertON = yes;
input Bands = yes;
#input EMA1 = 10;  #Inputs for unused code below
#input EMA2 = 20;  #Inputs for unused code below
input AvgType = AverageType.HULL;
input STAtrMult = 2.75;
input nATR = 12;

#======== Calculate the Supertrend =====================================================
def ATR = ATR("length" = nATR, "average type" = AvgType);
def UP_Band_Basic = HL2 + (STAtrMult * ATR);
def LW_Band_Basic = HL2 + (-STAtrMult * ATR);
def UP_Band = if ((UP_Band_Basic < UP_Band[1]) or (close[1] > UP_Band[1])) then UP_Band_Basic else UP_Band[1];
def LW_Band = if ((LW_Band_Basic > LW_Band[1]) or (close[1] < LW_Band[1])) then LW_Band_Basic else LW_Band[1];

def ST = if ((ST[1] == UP_Band[1]) and (close < UP_Band)) then UP_Band
else if ((ST[1] == UP_Band[1]) and (close > Up_Band)) then LW_Band
else if ((ST[1] == LW_Band[1]) and (close > LW_Band)) then LW_Band
else if ((ST[1] == LW_Band) and (close < LW_Band)) then UP_Band
else LW_Band;
#======== This code doesn't do anything that gets used elsewhere ========================
#def EMA1Val = MovAvgExponential(close, EMA1);
#def EMA2Val = MovAvgExponential(close, EMA2);
#def EMADirection = if EMA1Val > EMA2Val then 1 else if EMA1Val < EMA2Val then -1 else 0;
#=======================================================================================
plot Long = if close > ST then ST else Double.NaN;
Long.AssignValueColor(Color.cyan);
Long.SetLineWeight(3);

plot Short = if close < ST then ST else Double.NaN;
Short.AssignValueColor(Color.magenta);
Short.SetLineWeight(3);

def LongTrigger = isNaN(Long[1]) and !isNaN(Long);
def ShortTrigger = isNaN(Short[1]) and !isNaN(Short);

plot LongDot = if LongTrigger then ST else Double.NaN;
LongDot.SetPaintingStrategy(PaintingStrategy.POINTS);
LongDot.AssignValueColor(Color.cyan);
LongDot.SetLineWeight(4);

plot ShortDot = if ShortTrigger then ST else Double.NaN;
ShortDot.SetPaintingStrategy(PaintingStrategy.POINTS);
ShortDot.AssignValueColor(Color.magenta);
ShortDot.SetLineWeight(4);

AddChartBubble(Entry_SL_Bubbles and LongTrigger, ST, "BUY", Color.GREEN, no);
AddChartBubble(Entry_SL_Bubbles and ShortTrigger, ST, "SELL", Color.RED, yes);

#Super Trend Labels

AddLabel(yes and labels and Long, "ST:LONG", color.CYAN);
AddLabel(yes and labels and Short, "ST:SHORT", color.magenta);
#======== End of Supertrend calcs =====================================================

# =====================================================================================
# Hull Moving Average Concavity and Turning Points
#
# Author: Seth Urion (Mahsume)
# Version: 2020-05-01 V4
#
# Now with support for ToS Mobile
#
declare upper;

input HMA_Length = 60;
input lookback = 3;
input arrows = no;

def price = HL2;
plot HMA = HullMovingAvg(price = price, length = HMA_Length);
def delta = HMA[1] - HMA[lookback + 1];
def delta_per_bar = delta / lookback;
def next_bar = HMA[1] + delta_per_bar;
def concavity = if HMA > next_bar then 1 else -1;

HMA.AssignValueColor(color = if concavity[1] == -1 then
    if HMA > HMA[1] then color.dark_orange else color.red else
    if HMA < HMA[1] then color.dark_green else color.green);
HMA.SetLineWeight(3);

#Define turning point where concavity switches directiion
plot turning_point = if concavity[1] != concavity then HMA else double.nan;
turning_point.SetLineWeight(2);
turning_point.SetPaintingStrategy(paintingStrategy = PaintingStrategy.POINTS);
turning_point.SetDefaultColor(color.white);

#Plot maximum/minimum points of HMA
# Note: the HMA[-1] term will cause repainting at the end of the chart (looks forward 1 bar)
plot MA_Max = if HMA[-1] < HMA and HMA > HMA[1] then HMA else Double.NaN;
MA_Max.SetDefaultColor(Color.WHITE);
MA_Max.SetPaintingStrategy(PaintingStrategy.SQUARES);
MA_Max.SetLineWeight(5);

plot MA_Min = if HMA[-1] > HMA and HMA < HMA[1] then HMA else Double.Nan;
MA_Min.SetDefaultColor(Color.WHITE);
MA_Min.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
MA_Min.SetLineWeight(5);

#Define conditions for HMA-based alerts (see end of code)
def BuySetup = HMA > HMA[1] and HMA[1] < HMA[2];
def SellSetup =  HMA < HMA[1] and HMA[1] > HMA[2];

#Plot buy/sell arrows based on HMA
# Up arrow if at a turning point and concavity is "up"
# Down arrow if at a turning point and concavity is "down"
plot sell = if arrows and turning_point and concavity == -1 then high else double.nan;
sell.SetDefaultColor(Color.DARK_ORANGE);
sell.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
sell.SetLineWeight(3);

plot buy = if arrows and turning_point and concavity == 1 then low else double.nan;
buy.SetDefaultColor(Color.CYAN);
buy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
buy.SetLineWeight(3);

#def divergence = HMA - next_bar;  #this term isn't used anywhere else

###################
#
# 2020-05-01
#
# MOBILE TOS SUPPORT
#
# Each color of the HMA needs to be a separate plot as ToS Mobile
# lacks the ability to assign colors the way ToS Desktop does.
# I recommend a plain colored HMA behind the line
# Set the line color of the HMA above to gray or some neutral
#
# CCD_D -> ConCave Down and Decreasing
# CCD_I -> ConCave Down and Increasing
# CCU_D -> ConCave Up and Decreasing
# CCU_I -> ConCave Up and Increasing
#
###################
plot CCD_D = if concavity == -1 and HMA < HMA[1] then HMA else double.nan;
CCD_D.SetDefaultColor(Color.RED);
CCD_D.SetLineWeight(1);

plot CCD_I = if concavity == -1 and HMA >= HMA[1] then HMA else double.nan;
CCD_I.SetDefaultColor(Color.DARK_ORANGE);
CCD_I.SetLineWeight(1);

plot CCU_D = if concavity == 1 and HMA <= HMA[1] then HMA else double.nan;
CCU_D.SetDefaultColor(COLOR.DARK_GREEN);
CCU_D.SetLineWeight(1);

plot CCU_I = if concavity == 1 and HMA > HMA[1] then HMA else double.nan;
CCU_I.SetDefaultColor(COLOR.GREEN);
CCU_I.SetLineWeight(1);
#======= End of mobile HMA coloring support =============================

#Hull Label
AddLabel(yes and labels and CCD_D, "HULL:SELL", color.RED);
AddLabel(yes and labels and CCU_I, "HULL:BUY", color.green);
AddLabel(yes and labels and CCU_D, "HULL:WEAK SELL", color.dark_green);
AddLabel(yes and labels and CCD_I, "HULL:WEAK BUY", color.DARK_ORANGE);

def Hull_is_buy = !IsNaN(CCD_I) or !IsNaN(CCU_I);
def Hull_is_sell = !IsNaN(CCD_D) or !IsNaN(CCU_D);

#============ Create Donchian Trend Ribbon values =======================================
# Donchian Trend Channel parameters
input Donchian_Channel_Period = 20; #length to calculate main trend
input DTC_Trend_Cutoff = 20; #value of sum of all trends to exceed to use for buy/sell signal
input plotDTCResult = yes;
input secondary_colors = { default yellow , green_red };

#=======================================================================
# Donchian Trend Channel calcs
# all plots have been removed leaving only the value calculations

# How it works ?
# - it calculates main trend direction by using the length that is user-defined. so you can change it as you wish
# - then it calculates trend direction for each 9 lower lengths. if you set the length = 20 then the lengths are 19, 18,...11
# - and it checks if the trend directions that came from lower lengths is same or not with main trend direction.
# - it changes the trend color of the ribbon.
# -----------------------------

def dlen = if Donchian_Channel_Period < 10 then 10 else Donchian_Channel_Period;
def na = Double.NaN;

script dchannel {
    input len = 0;
    def hh = Highest(high, len);
    def ll = Lowest(low, len);
    def trend = if BarNumber() == 1 then 0 else if close > hh[1] then 1 else if close < ll[1] then -1 else trend[1];
    plot z = trend;
}

script dchannelalt {
    input len = 0;
    input maintrend = 0;
    def hh = Highest(high, len);
    def ll = Lowest(low, len);
    def trend = if BarNumber() == 1 then 0 else if close > hh[1] then 1 else if close < ll[1] then -1 else trend[1];

    def maincolor =
  if maintrend == 1 then if trend == 1 then 2 else 1
  else if maintrend == -1 then if trend == -1 then -2 else -1
  else 0;

    plot color = maincolor;
}

def maintrend = dchannel(dlen);

# ---------------------------------
def c01 = dchannelalt(dlen - 0, maintrend);

def c02 = dchannelalt(dlen - 1, maintrend);

def c03 = dchannelalt(dlen - 2, maintrend);

def c04 = dchannelalt(dlen - 3, maintrend);

def c05 = dchannelalt(dlen - 4, maintrend);

def c06 = dchannelalt(dlen - 5, maintrend);

def c07 = dchannelalt(dlen - 6, maintrend);

def c08 = dchannelalt(dlen - 7, maintrend);

def c09 = dchannelalt(dlen - 8, maintrend);

def c10 = dchannelalt(dlen - 9, maintrend);

# -----------------------------
# add up color numbers, to come up with a 'trend' number , 20 to -20
def colorsum = ( c01 + c02 + c03 + c04 + c05 + c06 + c07 + c08 + c09 + c10 );

# colors  
# 2 - up trend - green
# 1 - up trend - dark green
# 0 no trend
# -1 - down trend - dark red
# -2 - down trend - red

def DTC_Result = if colorsum >= DTC_Trend_Cutoff then 1
else if colorsum <= -DTC_Trend_Cutoff then -1
else 0;

def seccolor;
switch (secondary_colors) {
case yellow:
    seccolor = 1;
case green_red:
    seccolor = 2;
}

#   colors  
# 2 - up trend - green
# 1 - up trend - dark green
# 0 no trend
# -1 - down trend - dark red
# -2 - down trend - red

plot DTC_Trend = if (plotDTCResult) then (0.995 * low) else na;
DTC_Trend.SetPaintingStrategy(PaintingStrategy.LINE);
DTC_Trend.SetLineWeight(3);
DTC_Trend.DefineColor("up2", Color.GREEN);
DTC_Trend.DefineColor("up1", Color.DARK_GREEN);
DTC_Trend.DefineColor("none", Color.DARK_GRAY);
DTC_Trend.DefineColor("dwn1", Color.DARK_RED);
DTC_Trend.DefineColor("dwn2", Color.RED);
DTC_Trend.DefineColor("alt1", Color.YELLOW);

DTC_Trend.AssignValueColor( if colorsum >= DTC_Trend_Cutoff then DTC_Trend.Color("up2")
else if (colorsum > 0 and colorsum < DTC_Trend_Cutoff) and seccolor == 1 then DTC_Trend.Color("alt1") else if (colorsum > 0 and colorsum < DTC_Trend_Cutoff) and seccolor == 2 then DTC_Trend.Color("up1")
else if colorsum <= -DTC_Trend_Cutoff then DTC_Trend.Color("dwn2")
else if (colorsum < 0 and colorsum > -DTC_Trend_Cutoff) and seccolor == 1 then DTC_Trend.Color("alt1") else if (colorsum < 0 and colorsum > -DTC_Trend_Cutoff) and seccolor == 2 then DTC_Trend.Color("dwn1")
else Color.GRAY);
DTC_Trend.SetHiding(!plotDTCResult);

def DTC_is_buy = if colorsum >= DTC_Trend_Cutoff then yes else no;
def DTC_is_sell = if colorsum <= -DTC_Trend_Cutoff then yes else no;
# === End of Donchian Trend Channel code ===

#Target lines
# created by chewie
#=========== Determine long stoploss, entry point, and target lines =====================
#Stop Loss = minimum point of Hull MA
def line = if IsNaN(MA_Min) then line[1] else MA_Min[0];
plot L_stoploss = if IsNaN(MA_Min) and Hull_is_buy and Long and DTC_is_buy then line else double.nan;
L_stoploss.setpaintingStrategy(paintingStrategy.LINE);
L_stoploss.setlineWeight(3);
L_stoploss.setdefaultColor(color.dark_green);
L_stoploss.hideBubble();
def LSL = (if isNaN(L_stoploss[1]) then L_stoploss else Double.NaN);
addchartBubble(Entry_SL_Bubbles and L_stoploss, LSL,"L/SL",color.DARK_GREEN);

#Long Entry = final value of previous Supertrend (short)
def line4 = if IsNaN(short) then line4[1] else short[0];
plot L_Entry = if IsNaN(short) and Hull_is_buy and DTC_is_buy then line4 else double.nan;
L_Entry.setpaintingStrategy(paintingStrategy.LINE);
L_Entry.setlineWeight(3);
L_Entry.setdefaultColor(color.green);
L_Entry.hideBubble();
def LE = (if isNaN(L_Entry[1]) then L_Entry else Double.NaN);
addchartBubble(Entry_SL_Bubbles and L_Entry, LE,"L/E",color.GREEN);

#HalfX Long
plot x1a_Long = if Targetlines and L_Entry then (L_Entry + (L_Entry - L_Stoploss)/2) else double.nan;
x1a_Long.setpaintingStrategy(paintingStrategy.dashes);
x1a_Long.setlineWeight(1);
x1a_Long.setdefaultColor(color.magenta);
x1a_Long.hideBubble();
def x1aL = (if isNaN(x1a_Long[1]) then x1a_Long else Double.NaN);
addchartBubble(Target_Bubbles and x1a_Long, x1aL,"1/2xL",color.magenta);

#OneX Long
plot x1_Long = if Targetlines and x1a_Long > line4 then (L_Entry +(L_Entry - L_Stoploss)) else double.nan;
x1_Long.setpaintingStrategy(paintingStrategy.dashes);
x1_Long.setlineWeight(1);
x1_Long.setdefaultColor(color.yellow);
def X1L = (if isNaN(x1_Long[1]) then x1_Long else Double.NaN);
addchartBubble(Target_Bubbles and x1_Long, x1L,"1xL",color.yellow);

#TwoX Long
plot x2_Long = if Targetlines then x1_Long + (L_Entry - L_Stoploss) else double.nan;
x2_Long.setpaintingStrategy(paintingStrategy.dashes);
x2_Long.setlineWeight(2);
x2_Long.setdefaultColor(color.light_red);
def X2L = (if isNaN(x2_Long[1]) then x2_Long else Double.NaN);
addchartBubble(Target_Bubbles and x2_Long, x2L,"2xL",color.light_red);

#ThreeX Long
plot x3_Long = if Targetlines then x2_Long + (L_Entry - L_Stoploss) else double.nan;
x3_Long.setpaintingStrategy(paintingStrategy.dashes);
x3_Long.setlineWeight(1);
x3_Long.setdefaultColor(color.cyan);
def X3L = (if isNaN(x3_Long[1]) then x3_Long else Double.NaN);
addchartBubble(Target_Bubbles and x3_Long, x3L,"3xL",color.cyan);

#FourX Long
plot x4_Long = if Targetlines then x3_Long + (L_Entry - L_Stoploss) else double.nan;
x4_Long.setpaintingStrategy(paintingStrategy.dashes);
x4_Long.setlineWeight(1);
x4_Long.setdefaultColor(color.white);
def X4L = (if isNaN(x4_Long[1]) then x4_Long else Double.NaN);
addchartBubble(Target_Bubbles and x4_Long, x4L,"4xL",color.white);

#=========== Determine short stoploss, entry point, and target lines =====================
rec line2 = if IsNaN(MA_Max) then line2[1] else MA_Max[0];
plot S_stoploss = if IsNaN(MA_MAX) and Short and Hull_is_sell and DTC_is_sell then line2 else double.nan;
S_stoploss.setpaintingStrategy(paintingStrategy.LINE);
S_stoploss.setlineWeight(3);
S_stoploss.setdefaultColor(color.dark_red);
S_stoploss.hideBubble();
def SSL = (if isNaN(S_stoploss[1]) then S_stoploss else Double.NaN);
addchartBubble(Entry_SL_Bubbles and S_stoploss, SSL,"S/SL",color.DARK_RED);

#Short Entry
rec line3 = if IsNaN(long) then line3[1] else long[0];
plot S_Entry = if IsNaN(long) and Hull_is_sell and DTC_is_sell then line3 else double.nan;
S_Entry.setpaintingStrategy(paintingStrategy.LINE);
S_Entry.setlineWeight(3);
S_Entry.setdefaultColor(color.red);
S_Entry.hideBubble();
def SE = (if isNaN(S_Entry[1]) then S_Entry else Double.NaN);
addchartBubble(Entry_SL_Bubbles and S_Entry, SE,"S/E",color.RED);

#HalfX Short
plot x1a_Short = if Targetlines and S_Entry then (S_Entry - (S_Stoploss - S_Entry)/2) else double.nan;
x1a_Short.setpaintingStrategy(paintingStrategy.dashes);
x1a_Short.setlineWeight(1);
x1a_Short.setdefaultColor(color.magenta);
x1a_Short.hideBubble();
def x1a = (if isNaN(x1a_Short[1]) then x1a_Short else Double.NaN);
addchartBubble(Target_Bubbles and x1a_Short, x1a,"1/2xS",color.magenta);

#OneX Short
plot x1_Short = if Targetlines and x1a_short < line3 then (S_Entry -(S_Stoploss - S_Entry)) else double.nan;
x1_Short.setpaintingStrategy(paintingStrategy.dashes);
x1_Short.setlineWeight(1);
x1_Short.setdefaultColor(color.yellow);
def X1S = (if isNaN(x1_Short[1]) then x1_Short else Double.NaN);
addchartBubble(Target_Bubbles and x1_Short, x1S,"1xS",color.yellow);

#TwoX Short
plot x2_Short = if Targetlines then x1_Short - (S_Stoploss - S_Entry) else double.nan;
x2_Short.setpaintingStrategy(paintingStrategy.dashes);
x2_Short.setlineWeight(2);
x2_Short.setdefaultColor(color.light_green);
def X2S = (if isNaN(x2_Short[1]) then x2_Short else Double.NaN);
addchartBubble(Target_Bubbles and x2_Short, x2S,"2xS",color.light_green);

#ThreeX Short
plot x3_Short = if Targetlines then x2_Short - (S_Stoploss - S_Entry) else double.nan;
x3_Short.setpaintingStrategy(paintingStrategy.dashes);
x3_Short.setlineWeight(1);
x3_Short.setdefaultColor(color.cyan);
def X3S = (if isNaN(x3_Short[1]) then x3_Short else Double.NaN);
addchartBubble(Target_Bubbles and x3_Short, x3S,"3xS",color.cyan);

#FourX Short
plot x4_Short = if Targetlines then x3_Short - (S_Stoploss - S_Entry) else double.nan;
x4_Short.setpaintingStrategy(paintingStrategy.dashes);
x4_Short.setlineWeight(1);
x4_Short.setdefaultColor(color.white);
def X4S = (if isNaN(x4_Short[1]) then x4_Short else Double.NaN);
addchartBubble(Target_Bubbles and x4_Short, x4S,"4xS",color.white);

#=================================================================
#LinearRegCh100 RegressionDivergence - Trigger Lines - Trend Cross
# From Lizard Indicators Link: https://www.lizardindicators.com/trigger-lines-cross-vs-thrust/
# Line #1 - Fast = LinReg (80)
# Line #2 - Slow = EXPEMA[LinReg (80)]

input LinRegLength = 80;
input EMAlength = 20;
input ColorOn = yes;  #Color price bars based on linear reg
input ShowDynoLines = yes;

#Definitions
def price1 = close;
def displace = 0;
def LinReg = Inertia(price1[-displace], LinRegLength);
def EMA_LR = ExpAverage(LinReg[-displace], EMAlength);
def Body = (open + close)/2;

# Defining Long/Short Filters (these instructions determine entries / exits)
# Entry Requirements
def Long_Entry = close > LinReg and close > EMA_LR and body > LinReg and body > EMA_LR and close > high[1] and body > body[1];
# LinReg > LinReg[1] and
def Long_Stay_In = close > LinReg and close > EMA_LR;
def Long_Exit = (close < LinReg or close < EMA_LR) or Long_Stay_In == 0;
def Long_State = If Long_Entry then 1 else if Long_Exit then 0 else Long_State[1];
def Long1 = Long_State;

# Exit Requirements
def Short_Entry = close < LinReg and close < EMA_LR and body < LinReg and body < EMA_LR and close < low[1] and body < body[1];
# LinReg < LinReg[1] and
def Short_Stay_In = close < LinReg and close < EMA_LR;
def Short_Exit = (close > LinReg or close > EMA_LR) or Short_Stay_In == 0;
def Short_State = If Short_Entry then 1 else if Short_Exit then 0 else Short_State[1];
def Short1 = Short_State;

#Adding plot lines for Linear Regression averages
plot LR = if ShowDynoLines then LinReg else double.NaN;
LR.SetDefaultColor(CreateColor(0, 130, 255));
LR.setlineweight(1);
plot EMA_LinReg = if ShowDynoLines then EMA_LR else double.NaN;
EMA_LinReg.SetDefaultColor(CreateColor(255, 215,0));
EMA_LinReg.setlineweight(2);
#Add cloud between linear reg and EMA of lin reg lines
DefineGlobalColor("Bullish", Color.dark_Green);
DefineGlobalColor("Bearish", Color.dark_Red);
AddCloud(EMA_LinReg, LR, GlobalColor("Bearish"), GlobalColor("Bullish"));

#DYNO Label

AddLabel(yes and labels and Short1, "DYNO:BEARISH", color.RED);
AddLabel(yes and labels and Long1, "DYNO:BULLISH", color.green);
AddLabel(yes and labels and Long1 == Short1, "DYNO:NEUTRAL", color.YELLOW);

#Regression Bands

input deviations = 1.618;  #set your deviation units here.
input length = 500; #set your channel lookback period here.

def stdDeviation = StDevAll(price, length);
plot HighBand = if Bands then EMA_LinReg + deviations * stdDeviation else double.nan;
HighBand.SetDefaultColor(Color.red);
plot LowBand = if Bands then EMA_LinReg - deviations * stdDeviation else double.nan;
LowBand.SetDefaultColor(Color.green);
DefineGlobalColor("Bullish", Color.light_green);
DefineGlobalColor("Bearish", Color.light_RED);

# Coloring Bars
AssignPriceColor(if ColorON and Long_State then Color.GREEN else if ColorON and Short_State then Color.RED else Color.Yellow);
#==========End Dyno / Lin Reg Section ============================

#========= Plot Long Moving Average ==============================
input lengthAvgEXP = 200;

plot AvgExp = ExpAverage(price[-displace], lengthAvgExp);
AvgExp.SetDefaultColor(Color.white);
AvgExp.setlineweight(2);
#========== End Long Moving Average =============================

###################
#
# ALERTS
#
###################

Alert(alertON and LongTrigger, "Long Entry", Alert.BAR, Sound.Ding);

Alert(alertON and ShortTrigger, "Short Entry", Alert.BAR, Sound.Ding);

Alert(alertON and Buysetup, "HULL Buy", Alert.BAR, Sound.Bell);

Alert(alertON and Sellsetup, "HULL Sell", Alert.BAR, Sound.Bell);

Alert(alertON and high > highband, "Short Band", Alert.BAR, Sound.Ding);

Alert(alertON and low < lowband, "Long Band", Alert.BAR, Sound.Ding);
Looks GREAT!! Question: I use the DTC set at 10. Is there a way to make your line turn yellow when the shaded areas go below 40? I added a blue line at 40 on lower indicator. It indicates when trend is weak and could reverse, as in these examples.
 
Looks GREAT!! Question: I use the DTC set at 10. Is there a way to make your line turn yellow when the shaded areas go below 40? I added a blue line at 40 on lower indicator. It indicates when trend is weak and could reverse, as in these examples.
1) If you change the value of the "dtc trend cutoff" in the inputs, I think it will mostly get you what you're looking for. Example below shows the same timeframe as yours with a trend cutoff value of 19. You can try lower values to adjust the sensitivity. The result isn't explicitly what you're trying to do, but the result is pretty close.
Z7i6UTe.png


2) The value of 40 on the trend ribbon doesn't have any intrinsic meaning. It's just the location of the plot of the 3rd longest trend (8 days in the case where the DTC period is 10 - I expanded the DTC plot on the image above so you can see the individual rows plotted; they start with the longest at the bottom and work up). If you really want to go yellow on any bar where any trend below (below in length - above on the chart) the selected trend (number 3 in this case) is shaded, I can work on adding an alternative summary method that does that. Shouldn't be too difficult. I was thinking of some other mods to the DTC code that I'd like to add, also (like being able to do every other length, i.e. 20, 18, 16, etc), so I could add that in at the same time.
 
1) If you change the value of the "dtc trend cutoff" in the inputs, I think it will mostly get you what you're looking for. Example below shows the same timeframe as yours with a trend cutoff value of 19. You can try lower values to adjust the sensitivity. The result isn't explicitly what you're trying to do, but the result is pretty close.
Z7i6UTe.png


2) The value of 40 on the trend ribbon doesn't have any intrinsic meaning. It's just the location of the plot of the 3rd longest trend (8 days in the case where the DTC period is 10 - I expanded the DTC plot on the image above so you can see the individual rows plotted; they start with the longest at the bottom and work up). If you really want to go yellow on any bar where any trend below (below in length - above on the chart) the selected trend (number 3 in this case) is shaded, I can work on adding an alternative summary method that does that. Shouldn't be too difficult. I was thinking of some other mods to the DTC code that I'd like to add, also (like being able to do every other length, i.e. 20, 18, 16, etc), so I could add that in at the same time.
Ok, I like what you've done here. Great! Also, the other lines of code you grayed out are not needed. I think it was from aspects of other indicators that didn't add value to this strategy and I didn't remove them completely. Thanks.
 
Greetings all. I like the overall approach of Chewie's script, but, to be honest, the original version presented in the original post is a bit "busy" to me. There are also a few things that I consider glitches - primarily the way the entry lines and target lines didn't align. So, I wanted to offer an updated script that kept the spirit of Chewie's method but simplified the presentation some.

I've made the following changes to the code:
1) Added Donchian Trend Channel code. Item 2.2 in Chewie's OP says the Donchian Trend Ribbon should be red or green in the direction of your trade. I had already created code that generated a summary value of the DTR to use in an upper study, so I move that to this script. There are several inputs associated with this code:
  • Donchian_Channel_Period = 20; #length to calculate main trend - regular input from the lower study
  • secondary_colors = { default yellow , green_red } - regular input from the lower study
  • DTC_Trend_Cutoff = 20 - the summary code adds up the color values of each of the DTR lengths. This value is the limit of that summation used to determine if the trend is green, yellow (neutral) or red. A value of 20 means the entire trend ribbon has to be the same color. Lower values allow some yellow values to be included. Experiment with the values to see what works for you.
  • plotDTCResult = yes - turns the plot of the summary line on or off. Mostly used for debugging my code. If you're looking for the cleanest chart, set to "No".
2) Added constraints to drawing target lines based on HMA, Supertrend and DTC. Per Chewie's OP, all three of these indicators should be in buy or sell mode before entering the trade. So, I made it so that the entry and target lines won't appear unless that's true.
3) Added ability to remove drawing the Dyno lines and cloud (label and price bar coloring remain). The Dyno lines didn't seem to be used in determining buy/sell conditions, so I just added an input to allow you to turn off the plot of the lines/cloud to clean up the chart.
4) Commented out some code that didn't appear to be doing anything. Looks like it might have been left over from a previous iteration of the code (leaving in for Chewie to evaluate if it's actually needed - see lines 36-37, 54-58 and 150).
5) Made entry and target lines all start/end at the same place. Just some cleanup to the code so that all of these lines appear consistently.
6) Some general cleanup and rearranging (no effect to output)

Here's the updated script:
Code:
#Hull_SuperTrend_Trading_System
# assembled by Chewie 4/10/2022
# many thanks to all the other noted contributors to this system.

# SuperTrend Yahoo Finance Replica - Modified from Modius SuperTrend
# Modified Modius ver. by RConner7
# Modified by Barbaros to replicate look from TradingView version
# Modified by Barbaros to add EMA cross for bubbles and alerts
# Modified by Barbaros to update bar color painting
# v3.3
# Modified by Zetta_wow:
# - Add Donchian Trend Channel code to provide summary value of DTC and include in target lines
# - Added constraints to drawing target lines based on HMA, Supertrend and DTC
# - Added ability to remove drawing the Dyno lines and cloud (label and price bar coloring remain)
# - Commented out some code that didn't appear to be doing anything (leaving in for Chewie to evaluate need)
# - Made entry and target lines all start/end at the same place
# - Some general cleanup and rearranging (no effect to output)

# From the useThinkScript thread introducing Chewie's strategy:
#2. SETUP: You must see three things to define an entry position.
#  1. A top or bottom reversal signal of the Hull Moving Avg plotted with a white square (top) or white triangle (bottom).
#  2. Lower Donchian Trend Ribbon either green or red in the color of the direction you are entering the trade. (Shout out to @halcyonguy who converted this into TOS. Much appreciated, you are awesome!!!)
#  3. Break of the Super Trend indicator. (Default setting is 2.75. Feel free to adjust this if you want in the settings)
#
# HMA signal indicated by Hull_is_buy and Hull_is_sell variables
# Donchian Trend Ribbon signal indicated by DTC_is_buy and DTC_is_sell
# Supertrend signal indicated by Long and Short variables (plots)
# Don't draw entry/1x/2x/3x/4x lines unless all three match signals (buy/long or sell/short)

input Target_Bubbles = no;
input Entry_SL_Bubbles = no;
input Targetlines = yes;
input Labels = yes;
input alertON = yes;
input Bands = yes;
#input EMA1 = 10;  #Inputs for unused code below
#input EMA2 = 20;  #Inputs for unused code below
input AvgType = AverageType.HULL;
input STAtrMult = 2.75;
input nATR = 12;

#======== Calculate the Supertrend =====================================================
def ATR = ATR("length" = nATR, "average type" = AvgType);
def UP_Band_Basic = HL2 + (STAtrMult * ATR);
def LW_Band_Basic = HL2 + (-STAtrMult * ATR);
def UP_Band = if ((UP_Band_Basic < UP_Band[1]) or (close[1] > UP_Band[1])) then UP_Band_Basic else UP_Band[1];
def LW_Band = if ((LW_Band_Basic > LW_Band[1]) or (close[1] < LW_Band[1])) then LW_Band_Basic else LW_Band[1];

def ST = if ((ST[1] == UP_Band[1]) and (close < UP_Band)) then UP_Band
else if ((ST[1] == UP_Band[1]) and (close > Up_Band)) then LW_Band
else if ((ST[1] == LW_Band[1]) and (close > LW_Band)) then LW_Band
else if ((ST[1] == LW_Band) and (close < LW_Band)) then UP_Band
else LW_Band;
#======== This code doesn't do anything that gets used elsewhere ========================
#def EMA1Val = MovAvgExponential(close, EMA1);
#def EMA2Val = MovAvgExponential(close, EMA2);
#def EMADirection = if EMA1Val > EMA2Val then 1 else if EMA1Val < EMA2Val then -1 else 0;
#=======================================================================================
plot Long = if close > ST then ST else Double.NaN;
Long.AssignValueColor(Color.cyan);
Long.SetLineWeight(3);

plot Short = if close < ST then ST else Double.NaN;
Short.AssignValueColor(Color.magenta);
Short.SetLineWeight(3);

def LongTrigger = isNaN(Long[1]) and !isNaN(Long);
def ShortTrigger = isNaN(Short[1]) and !isNaN(Short);

plot LongDot = if LongTrigger then ST else Double.NaN;
LongDot.SetPaintingStrategy(PaintingStrategy.POINTS);
LongDot.AssignValueColor(Color.cyan);
LongDot.SetLineWeight(4);

plot ShortDot = if ShortTrigger then ST else Double.NaN;
ShortDot.SetPaintingStrategy(PaintingStrategy.POINTS);
ShortDot.AssignValueColor(Color.magenta);
ShortDot.SetLineWeight(4);

AddChartBubble(Entry_SL_Bubbles and LongTrigger, ST, "BUY", Color.GREEN, no);
AddChartBubble(Entry_SL_Bubbles and ShortTrigger, ST, "SELL", Color.RED, yes);

#Super Trend Labels

AddLabel(yes and labels and Long, "ST:LONG", color.CYAN);
AddLabel(yes and labels and Short, "ST:SHORT", color.magenta);
#======== End of Supertrend calcs =====================================================

# =====================================================================================
# Hull Moving Average Concavity and Turning Points
#
# Author: Seth Urion (Mahsume)
# Version: 2020-05-01 V4
#
# Now with support for ToS Mobile
#
declare upper;

input HMA_Length = 60;
input lookback = 3;
input arrows = no;

def price = HL2;
plot HMA = HullMovingAvg(price = price, length = HMA_Length);
def delta = HMA[1] - HMA[lookback + 1];
def delta_per_bar = delta / lookback;
def next_bar = HMA[1] + delta_per_bar;
def concavity = if HMA > next_bar then 1 else -1;

HMA.AssignValueColor(color = if concavity[1] == -1 then
    if HMA > HMA[1] then color.dark_orange else color.red else
    if HMA < HMA[1] then color.dark_green else color.green);
HMA.SetLineWeight(3);

#Define turning point where concavity switches directiion
plot turning_point = if concavity[1] != concavity then HMA else double.nan;
turning_point.SetLineWeight(2);
turning_point.SetPaintingStrategy(paintingStrategy = PaintingStrategy.POINTS);
turning_point.SetDefaultColor(color.white);

#Plot maximum/minimum points of HMA
# Note: the HMA[-1] term will cause repainting at the end of the chart (looks forward 1 bar)
plot MA_Max = if HMA[-1] < HMA and HMA > HMA[1] then HMA else Double.NaN;
MA_Max.SetDefaultColor(Color.WHITE);
MA_Max.SetPaintingStrategy(PaintingStrategy.SQUARES);
MA_Max.SetLineWeight(5);

plot MA_Min = if HMA[-1] > HMA and HMA < HMA[1] then HMA else Double.Nan;
MA_Min.SetDefaultColor(Color.WHITE);
MA_Min.SetPaintingStrategy(PaintingStrategy.TRIANGLES);
MA_Min.SetLineWeight(5);

#Define conditions for HMA-based alerts (see end of code)
def BuySetup = HMA > HMA[1] and HMA[1] < HMA[2];
def SellSetup =  HMA < HMA[1] and HMA[1] > HMA[2];

#Plot buy/sell arrows based on HMA
# Up arrow if at a turning point and concavity is "up"
# Down arrow if at a turning point and concavity is "down"
plot sell = if arrows and turning_point and concavity == -1 then high else double.nan;
sell.SetDefaultColor(Color.DARK_ORANGE);
sell.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
sell.SetLineWeight(3);

plot buy = if arrows and turning_point and concavity == 1 then low else double.nan;
buy.SetDefaultColor(Color.CYAN);
buy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
buy.SetLineWeight(3);

#def divergence = HMA - next_bar;  #this term isn't used anywhere else

###################
#
# 2020-05-01
#
# MOBILE TOS SUPPORT
#
# Each color of the HMA needs to be a separate plot as ToS Mobile
# lacks the ability to assign colors the way ToS Desktop does.
# I recommend a plain colored HMA behind the line
# Set the line color of the HMA above to gray or some neutral
#
# CCD_D -> ConCave Down and Decreasing
# CCD_I -> ConCave Down and Increasing
# CCU_D -> ConCave Up and Decreasing
# CCU_I -> ConCave Up and Increasing
#
###################
plot CCD_D = if concavity == -1 and HMA < HMA[1] then HMA else double.nan;
CCD_D.SetDefaultColor(Color.RED);
CCD_D.SetLineWeight(1);

plot CCD_I = if concavity == -1 and HMA >= HMA[1] then HMA else double.nan;
CCD_I.SetDefaultColor(Color.DARK_ORANGE);
CCD_I.SetLineWeight(1);

plot CCU_D = if concavity == 1 and HMA <= HMA[1] then HMA else double.nan;
CCU_D.SetDefaultColor(COLOR.DARK_GREEN);
CCU_D.SetLineWeight(1);

plot CCU_I = if concavity == 1 and HMA > HMA[1] then HMA else double.nan;
CCU_I.SetDefaultColor(COLOR.GREEN);
CCU_I.SetLineWeight(1);
#======= End of mobile HMA coloring support =============================

#Hull Label
AddLabel(yes and labels and CCD_D, "HULL:SELL", color.RED);
AddLabel(yes and labels and CCU_I, "HULL:BUY", color.green);
AddLabel(yes and labels and CCU_D, "HULL:WEAK SELL", color.dark_green);
AddLabel(yes and labels and CCD_I, "HULL:WEAK BUY", color.DARK_ORANGE);

def Hull_is_buy = !IsNaN(CCD_I) or !IsNaN(CCU_I);
def Hull_is_sell = !IsNaN(CCD_D) or !IsNaN(CCU_D);

#============ Create Donchian Trend Ribbon values =======================================
# Donchian Trend Channel parameters
input Donchian_Channel_Period = 20; #length to calculate main trend
input DTC_Trend_Cutoff = 20; #value of sum of all trends to exceed to use for buy/sell signal
input plotDTCResult = yes;
input secondary_colors = { default yellow , green_red };

#=======================================================================
# Donchian Trend Channel calcs
# all plots have been removed leaving only the value calculations

# How it works ?
# - it calculates main trend direction by using the length that is user-defined. so you can change it as you wish
# - then it calculates trend direction for each 9 lower lengths. if you set the length = 20 then the lengths are 19, 18,...11
# - and it checks if the trend directions that came from lower lengths is same or not with main trend direction.
# - it changes the trend color of the ribbon.
# -----------------------------

def dlen = if Donchian_Channel_Period < 10 then 10 else Donchian_Channel_Period;
def na = Double.NaN;

script dchannel {
    input len = 0;
    def hh = Highest(high, len);
    def ll = Lowest(low, len);
    def trend = if BarNumber() == 1 then 0 else if close > hh[1] then 1 else if close < ll[1] then -1 else trend[1];
    plot z = trend;
}

script dchannelalt {
    input len = 0;
    input maintrend = 0;
    def hh = Highest(high, len);
    def ll = Lowest(low, len);
    def trend = if BarNumber() == 1 then 0 else if close > hh[1] then 1 else if close < ll[1] then -1 else trend[1];

    def maincolor =
  if maintrend == 1 then if trend == 1 then 2 else 1
  else if maintrend == -1 then if trend == -1 then -2 else -1
  else 0;

    plot color = maincolor;
}

def maintrend = dchannel(dlen);

# ---------------------------------
def c01 = dchannelalt(dlen - 0, maintrend);

def c02 = dchannelalt(dlen - 1, maintrend);

def c03 = dchannelalt(dlen - 2, maintrend);

def c04 = dchannelalt(dlen - 3, maintrend);

def c05 = dchannelalt(dlen - 4, maintrend);

def c06 = dchannelalt(dlen - 5, maintrend);

def c07 = dchannelalt(dlen - 6, maintrend);

def c08 = dchannelalt(dlen - 7, maintrend);

def c09 = dchannelalt(dlen - 8, maintrend);

def c10 = dchannelalt(dlen - 9, maintrend);

# -----------------------------
# add up color numbers, to come up with a 'trend' number , 20 to -20
def colorsum = ( c01 + c02 + c03 + c04 + c05 + c06 + c07 + c08 + c09 + c10 );

# colors  
# 2 - up trend - green
# 1 - up trend - dark green
# 0 no trend
# -1 - down trend - dark red
# -2 - down trend - red

def DTC_Result = if colorsum >= DTC_Trend_Cutoff then 1
else if colorsum <= -DTC_Trend_Cutoff then -1
else 0;

def seccolor;
switch (secondary_colors) {
case yellow:
    seccolor = 1;
case green_red:
    seccolor = 2;
}

#   colors  
# 2 - up trend - green
# 1 - up trend - dark green
# 0 no trend
# -1 - down trend - dark red
# -2 - down trend - red

plot DTC_Trend = if (plotDTCResult) then (0.995 * low) else na;
DTC_Trend.SetPaintingStrategy(PaintingStrategy.LINE);
DTC_Trend.SetLineWeight(3);
DTC_Trend.DefineColor("up2", Color.GREEN);
DTC_Trend.DefineColor("up1", Color.DARK_GREEN);
DTC_Trend.DefineColor("none", Color.DARK_GRAY);
DTC_Trend.DefineColor("dwn1", Color.DARK_RED);
DTC_Trend.DefineColor("dwn2", Color.RED);
DTC_Trend.DefineColor("alt1", Color.YELLOW);

DTC_Trend.AssignValueColor( if colorsum >= DTC_Trend_Cutoff then DTC_Trend.Color("up2")
else if (colorsum > 0 and colorsum < DTC_Trend_Cutoff) and seccolor == 1 then DTC_Trend.Color("alt1") else if (colorsum > 0 and colorsum < DTC_Trend_Cutoff) and seccolor == 2 then DTC_Trend.Color("up1")
else if colorsum <= -DTC_Trend_Cutoff then DTC_Trend.Color("dwn2")
else if (colorsum < 0 and colorsum > -DTC_Trend_Cutoff) and seccolor == 1 then DTC_Trend.Color("alt1") else if (colorsum < 0 and colorsum > -DTC_Trend_Cutoff) and seccolor == 2 then DTC_Trend.Color("dwn1")
else Color.GRAY);
DTC_Trend.SetHiding(!plotDTCResult);

def DTC_is_buy = if colorsum >= DTC_Trend_Cutoff then yes else no;
def DTC_is_sell = if colorsum <= -DTC_Trend_Cutoff then yes else no;
# === End of Donchian Trend Channel code ===

#Target lines
# created by chewie
#=========== Determine long stoploss, entry point, and target lines =====================
#Stop Loss = minimum point of Hull MA
def line = if IsNaN(MA_Min) then line[1] else MA_Min[0];
plot L_stoploss = if IsNaN(MA_Min) and Hull_is_buy and Long and DTC_is_buy then line else double.nan;
L_stoploss.setpaintingStrategy(paintingStrategy.LINE);
L_stoploss.setlineWeight(3);
L_stoploss.setdefaultColor(color.dark_green);
L_stoploss.hideBubble();
def LSL = (if isNaN(L_stoploss[1]) then L_stoploss else Double.NaN);
addchartBubble(Entry_SL_Bubbles and L_stoploss, LSL,"L/SL",color.DARK_GREEN);

#Long Entry = final value of previous Supertrend (short)
def line4 = if IsNaN(short) then line4[1] else short[0];
plot L_Entry = if IsNaN(short) and Hull_is_buy and DTC_is_buy then line4 else double.nan;
L_Entry.setpaintingStrategy(paintingStrategy.LINE);
L_Entry.setlineWeight(3);
L_Entry.setdefaultColor(color.green);
L_Entry.hideBubble();
def LE = (if isNaN(L_Entry[1]) then L_Entry else Double.NaN);
addchartBubble(Entry_SL_Bubbles and L_Entry, LE,"L/E",color.GREEN);

#HalfX Long
plot x1a_Long = if Targetlines and L_Entry then (L_Entry + (L_Entry - L_Stoploss)/2) else double.nan;
x1a_Long.setpaintingStrategy(paintingStrategy.dashes);
x1a_Long.setlineWeight(1);
x1a_Long.setdefaultColor(color.magenta);
x1a_Long.hideBubble();
def x1aL = (if isNaN(x1a_Long[1]) then x1a_Long else Double.NaN);
addchartBubble(Target_Bubbles and x1a_Long, x1aL,"1/2xL",color.magenta);

#OneX Long
plot x1_Long = if Targetlines and x1a_Long > line4 then (L_Entry +(L_Entry - L_Stoploss)) else double.nan;
x1_Long.setpaintingStrategy(paintingStrategy.dashes);
x1_Long.setlineWeight(1);
x1_Long.setdefaultColor(color.yellow);
def X1L = (if isNaN(x1_Long[1]) then x1_Long else Double.NaN);
addchartBubble(Target_Bubbles and x1_Long, x1L,"1xL",color.yellow);

#TwoX Long
plot x2_Long = if Targetlines then x1_Long + (L_Entry - L_Stoploss) else double.nan;
x2_Long.setpaintingStrategy(paintingStrategy.dashes);
x2_Long.setlineWeight(2);
x2_Long.setdefaultColor(color.light_red);
def X2L = (if isNaN(x2_Long[1]) then x2_Long else Double.NaN);
addchartBubble(Target_Bubbles and x2_Long, x2L,"2xL",color.light_red);

#ThreeX Long
plot x3_Long = if Targetlines then x2_Long + (L_Entry - L_Stoploss) else double.nan;
x3_Long.setpaintingStrategy(paintingStrategy.dashes);
x3_Long.setlineWeight(1);
x3_Long.setdefaultColor(color.cyan);
def X3L = (if isNaN(x3_Long[1]) then x3_Long else Double.NaN);
addchartBubble(Target_Bubbles and x3_Long, x3L,"3xL",color.cyan);

#FourX Long
plot x4_Long = if Targetlines then x3_Long + (L_Entry - L_Stoploss) else double.nan;
x4_Long.setpaintingStrategy(paintingStrategy.dashes);
x4_Long.setlineWeight(1);
x4_Long.setdefaultColor(color.white);
def X4L = (if isNaN(x4_Long[1]) then x4_Long else Double.NaN);
addchartBubble(Target_Bubbles and x4_Long, x4L,"4xL",color.white);

#=========== Determine short stoploss, entry point, and target lines =====================
rec line2 = if IsNaN(MA_Max) then line2[1] else MA_Max[0];
plot S_stoploss = if IsNaN(MA_MAX) and Short and Hull_is_sell and DTC_is_sell then line2 else double.nan;
S_stoploss.setpaintingStrategy(paintingStrategy.LINE);
S_stoploss.setlineWeight(3);
S_stoploss.setdefaultColor(color.dark_red);
S_stoploss.hideBubble();
def SSL = (if isNaN(S_stoploss[1]) then S_stoploss else Double.NaN);
addchartBubble(Entry_SL_Bubbles and S_stoploss, SSL,"S/SL",color.DARK_RED);

#Short Entry
rec line3 = if IsNaN(long) then line3[1] else long[0];
plot S_Entry = if IsNaN(long) and Hull_is_sell and DTC_is_sell then line3 else double.nan;
S_Entry.setpaintingStrategy(paintingStrategy.LINE);
S_Entry.setlineWeight(3);
S_Entry.setdefaultColor(color.red);
S_Entry.hideBubble();
def SE = (if isNaN(S_Entry[1]) then S_Entry else Double.NaN);
addchartBubble(Entry_SL_Bubbles and S_Entry, SE,"S/E",color.RED);

#HalfX Short
plot x1a_Short = if Targetlines and S_Entry then (S_Entry - (S_Stoploss - S_Entry)/2) else double.nan;
x1a_Short.setpaintingStrategy(paintingStrategy.dashes);
x1a_Short.setlineWeight(1);
x1a_Short.setdefaultColor(color.magenta);
x1a_Short.hideBubble();
def x1a = (if isNaN(x1a_Short[1]) then x1a_Short else Double.NaN);
addchartBubble(Target_Bubbles and x1a_Short, x1a,"1/2xS",color.magenta);

#OneX Short
plot x1_Short = if Targetlines and x1a_short < line3 then (S_Entry -(S_Stoploss - S_Entry)) else double.nan;
x1_Short.setpaintingStrategy(paintingStrategy.dashes);
x1_Short.setlineWeight(1);
x1_Short.setdefaultColor(color.yellow);
def X1S = (if isNaN(x1_Short[1]) then x1_Short else Double.NaN);
addchartBubble(Target_Bubbles and x1_Short, x1S,"1xS",color.yellow);

#TwoX Short
plot x2_Short = if Targetlines then x1_Short - (S_Stoploss - S_Entry) else double.nan;
x2_Short.setpaintingStrategy(paintingStrategy.dashes);
x2_Short.setlineWeight(2);
x2_Short.setdefaultColor(color.light_green);
def X2S = (if isNaN(x2_Short[1]) then x2_Short else Double.NaN);
addchartBubble(Target_Bubbles and x2_Short, x2S,"2xS",color.light_green);

#ThreeX Short
plot x3_Short = if Targetlines then x2_Short - (S_Stoploss - S_Entry) else double.nan;
x3_Short.setpaintingStrategy(paintingStrategy.dashes);
x3_Short.setlineWeight(1);
x3_Short.setdefaultColor(color.cyan);
def X3S = (if isNaN(x3_Short[1]) then x3_Short else Double.NaN);
addchartBubble(Target_Bubbles and x3_Short, x3S,"3xS",color.cyan);

#FourX Short
plot x4_Short = if Targetlines then x3_Short - (S_Stoploss - S_Entry) else double.nan;
x4_Short.setpaintingStrategy(paintingStrategy.dashes);
x4_Short.setlineWeight(1);
x4_Short.setdefaultColor(color.white);
def X4S = (if isNaN(x4_Short[1]) then x4_Short else Double.NaN);
addchartBubble(Target_Bubbles and x4_Short, x4S,"4xS",color.white);

#=================================================================
#LinearRegCh100 RegressionDivergence - Trigger Lines - Trend Cross
# From Lizard Indicators Link: https://www.lizardindicators.com/trigger-lines-cross-vs-thrust/
# Line #1 - Fast = LinReg (80)
# Line #2 - Slow = EXPEMA[LinReg (80)]

input LinRegLength = 80;
input EMAlength = 20;
input ColorOn = yes;  #Color price bars based on linear reg
input ShowDynoLines = yes;

#Definitions
def price1 = close;
def displace = 0;
def LinReg = Inertia(price1[-displace], LinRegLength);
def EMA_LR = ExpAverage(LinReg[-displace], EMAlength);
def Body = (open + close)/2;

# Defining Long/Short Filters (these instructions determine entries / exits)
# Entry Requirements
def Long_Entry = close > LinReg and close > EMA_LR and body > LinReg and body > EMA_LR and close > high[1] and body > body[1];
# LinReg > LinReg[1] and
def Long_Stay_In = close > LinReg and close > EMA_LR;
def Long_Exit = (close < LinReg or close < EMA_LR) or Long_Stay_In == 0;
def Long_State = If Long_Entry then 1 else if Long_Exit then 0 else Long_State[1];
def Long1 = Long_State;

# Exit Requirements
def Short_Entry = close < LinReg and close < EMA_LR and body < LinReg and body < EMA_LR and close < low[1] and body < body[1];
# LinReg < LinReg[1] and
def Short_Stay_In = close < LinReg and close < EMA_LR;
def Short_Exit = (close > LinReg or close > EMA_LR) or Short_Stay_In == 0;
def Short_State = If Short_Entry then 1 else if Short_Exit then 0 else Short_State[1];
def Short1 = Short_State;

#Adding plot lines for Linear Regression averages
plot LR = if ShowDynoLines then LinReg else double.NaN;
LR.SetDefaultColor(CreateColor(0, 130, 255));
LR.setlineweight(1);
plot EMA_LinReg = if ShowDynoLines then EMA_LR else double.NaN;
EMA_LinReg.SetDefaultColor(CreateColor(255, 215,0));
EMA_LinReg.setlineweight(2);
#Add cloud between linear reg and EMA of lin reg lines
DefineGlobalColor("Bullish", Color.dark_Green);
DefineGlobalColor("Bearish", Color.dark_Red);
AddCloud(EMA_LinReg, LR, GlobalColor("Bearish"), GlobalColor("Bullish"));

#DYNO Label

AddLabel(yes and labels and Short1, "DYNO:BEARISH", color.RED);
AddLabel(yes and labels and Long1, "DYNO:BULLISH", color.green);
AddLabel(yes and labels and Long1 == Short1, "DYNO:NEUTRAL", color.YELLOW);

#Regression Bands

input deviations = 1.618;  #set your deviation units here.
input length = 500; #set your channel lookback period here.

def stdDeviation = StDevAll(price, length);
plot HighBand = if Bands then EMA_LinReg + deviations * stdDeviation else double.nan;
HighBand.SetDefaultColor(Color.red);
plot LowBand = if Bands then EMA_LinReg - deviations * stdDeviation else double.nan;
LowBand.SetDefaultColor(Color.green);
DefineGlobalColor("Bullish", Color.light_green);
DefineGlobalColor("Bearish", Color.light_RED);

# Coloring Bars
AssignPriceColor(if ColorON and Long_State then Color.GREEN else if ColorON and Short_State then Color.RED else Color.Yellow);
#==========End Dyno / Lin Reg Section ============================

#========= Plot Long Moving Average ==============================
input lengthAvgEXP = 200;

plot AvgExp = ExpAverage(price[-displace], lengthAvgExp);
AvgExp.SetDefaultColor(Color.white);
AvgExp.setlineweight(2);
#========== End Long Moving Average =============================

###################
#
# ALERTS
#
###################

Alert(alertON and LongTrigger, "Long Entry", Alert.BAR, Sound.Ding);

Alert(alertON and ShortTrigger, "Short Entry", Alert.BAR, Sound.Ding);

Alert(alertON and Buysetup, "HULL Buy", Alert.BAR, Sound.Bell);

Alert(alertON and Sellsetup, "HULL Sell", Alert.BAR, Sound.Bell);

Alert(alertON and high > highband, "Short Band", Alert.BAR, Sound.Ding);

Alert(alertON and low < lowband, "Long Band", Alert.BAR, Sound.Ding);
Thanks for us!
Something I have noticed is the Short/Long Entry does not line up with the candles like the original script from chewie. 4m ES today had some misalignment.
 
Ok, I like what you've done here. Great! Also, the other lines of code you grayed out are not needed. I think it was from aspects of other indicators that didn't add value to this strategy and I didn't remove them completely. Thanks.
Is there an updated code for us to use?
 
Thanks for us!
Something I have noticed is the Short/Long Entry does not line up with the candles like the original script from chewie. 4m ES today had some misalignment.
Are you referring to something like this, where the entry and stop loss lines seem to start at the midpoint of the bar, and the 1/2x, 1x, etc lines start at the beginning of the bar?
zFL7A1I.png


If so, I see that in Chewie's original code too. Here's an example of nearly the same place in the day with his code (note the 2x line is offset):
QdZzQfZ.png


I think it's just the way that TOS draws the lines with the different styles. Seems like the solid lines begin at the midpoint of the bar, while the dashed lines start at the left edge. They're all actually on the same bar - it just looks funny.

If it's something else that you're seeing, please give me a time of day to look at, so I can try to track it down better.
 
Are you referring to something like this, where the entry and stop loss lines seem to start at the midpoint of the bar, and the 1/2x, 1x, etc lines start at the beginning of the bar?
zFL7A1I.png


If so, I see that in Chewie's original code too. Here's an example of nearly the same place in the day with his code (note the 2x line is offset):
QdZzQfZ.png


I think it's just the way that TOS draws the lines with the different styles. Seems like the solid lines begin at the midpoint of the bar, while the dashed lines start at the left edge. They're all actually on the same bar - it just looks funny.

If it's something else that you're seeing, please give me a time of day to look at, so I can try to track it down better.
Hi, trying to figure out how to add images - but I'm referring to 8/18 at 9.24 and 12.40 on the 4min TF on /ES. Another one but not so bad at 14.52.
 
Hi, trying to figure out how to add images - but I'm referring to 8/18 at 9.24 and 12.40 on the 4min TF on /ES. Another one but not so bad at 14.52.
What settings are you using for the various inputs? When I add my modified version of the script with default inputs, the 9:24 bar is in the middle of an existing trade, and there's no trade on at 12:40 or 14:52 (I guess another important question is what time zone are you in? My display is based on CDT, so if you're somewhere else, I need to adjust.)

Here's the thread with instructions for posting images: https://usethinkscript.com/threads/how-to-insert-image-in-a-post-thread.277/
 
What settings are you using for the various inputs? When I add my modified version of the script with default inputs, the 9:24 bar is in the middle of an existing trade, and there's no trade on at 12:40 or 14:52 (I guess another important question is what time zone are you in? My display is based on CDT, so if you're somewhere else, I need to adjust.)

Here's the thread with instructions for posting images: https://usethinkscript.com/threads/how-to-insert-image-in-a-post-thread.277/
I'm using EST market hours zone - easiest to reference.

Will check how to add images. Thanks!
 
What settings are you using for the various inputs? When I add my modified version of the script with default inputs, the 9:24 bar is in the middle of an existing trade, and there's no trade on at 12:40 or 14:52 (I guess another important question is what time zone are you in? My display is based on CDT, so if you're somewhere else, I need to adjust.)

Here's the thread with instructions for posting images: https://usethinkscript.com/threads/how-to-insert-image-in-a-post-thread.277/
Here you go - Time is EST on ES 4min yesterday 8/18:
 
Here you go - Time is EST on ES 4min yesterday 8/18:
I don't see anything wrong with the 12:40 image. The solid lines are drawn starting at the midpoint of the bar, and the dashed lines start at the left edge like I described in my other post. That's just the way TOS draws I think.

For your 9:40 example, I can see where it looks like the 1/2x and 1x lines look like they're starting on the next bar, but I wonder if that's just another weirdness in the way TOS is drawing. I've seen people talk about the order of things on screen being determined by the order they appear in the studies dialog. Make sure that the Chewie script is listed first and see if that changes it. I bet they're in the right place, but you can't see the first dash because of something TOS is doing.

Beyond that, I'd still need to know what settings you're using, because my chart doesn't look exactly like yours (notice the inflection points on the HMA are different, and I have no idea why the price bars are different if we're both on 4m charts). For example, here's mine at 8:24a CDT (your 9:24):
Da6ScDC.png
 
Just curious if anyone noticed the last 45 minutes of trading today with ES. I had both setups side by side on a 2m chart and never saw the green entry line on @Zetta_wow version. @chewie76 original showed both green entry line and red stop loss line. Both lines on original appeared at 2:18 CDT. Nothing on the revised version. Again, running on a 2m tf with RTH (Extended hours unchecked). I like the revised as well, but I'll stick with the original unless I'm missing something in settings. If anyone else can check, that would be great. Thanks @Zetta_wow for your efforts! (y)
 
Just curious if anyone noticed the last 45 minutes of trading today with ES. I had both setups side by side on a 2m chart and never saw the green entry line on @Zetta_wow version. @chewie76 original showed both green entry line and red stop loss line. Both lines on original appeared at 2:18 CDT. Nothing on the revised version. Again, running on a 2m tf with RTH (Extended hours unchecked). I like the revised as well, but I'll stick with the original unless I'm missing something in settings. If anyone else can check, that would be great. Thanks @Zetta_wow for your efforts! (y)
Here's the ES 2m chart from the last couple of hours of the day with my version of the code:
dAmK6ia.png


Notice that the Donchian Trend Ribbon (DTR) at the bottom is mostly red with one yellow square throughout basically the last hour, and it was fully red (negative/sell) prior to that. My code incorporates the status of the Donchian into Chewie's logic for showing entry/target lines, and the summary of the DTR that my code uses is the jagged red/yellow line near the bottom of the upper part of the chart. Near the end of the day, the Supertrend was showing a buy (right after the low of the day) and the HMA had put in a minimum (triangle shortly after the ST "buy") but the Donchian summary value never turned green (positive/buy), so my code wouldn't show the lines. Chewie's original code operates on the Supertrend and HMA only, so his went into buy mode after the HMA minimum at 2:18p CDT bar and the Supertrend buy signal.

Neither is right or wrong - I was just trying to incorporate all three of Chewie's criteria for entry from the original post by including the Donchian in the decision tree.
 
Here's the ES 2m chart from the last couple of hours of the day with my version of the code:
dAmK6ia.png


Notice that the Donchian Trend Ribbon (DTR) at the bottom is mostly red with one yellow square throughout basically the last hour, and it was fully red (negative/sell) prior to that. My code incorporates the status of the Donchian into Chewie's logic for showing entry/target lines, and the summary of the DTR that my code uses is the jagged red/yellow line near the bottom of the upper part of the chart. Near the end of the day, the Supertrend was showing a buy (right after the low of the day) and the HMA had put in a minimum (triangle shortly after the ST "buy") but the Donchian summary value never turned green (positive/buy), so my code wouldn't show the lines. Chewie's original code operates on the Supertrend and HMA only, so his went into buy mode after the HMA minimum at 2:18p CDT bar and the Supertrend buy signal.

Neither is right or wrong - I was just trying to incorporate all three of Chewie's criteria for entry from the original post by including the Donchian in the decision tree.
Thank you for the explanation. Makes perfect sense now as to why. Much more conservative and great info. Also, I appreciate the DTR line on the upper chart, but prefer a lower study as you depict above. Can you please share the lower DTR or the appropriate settings? Thanks again for your work and info!!
 
Thank you for the explanation. Makes perfect sense now as to why. Much more conservative and great info. Also, I appreciate the DTR line on the upper chart, but prefer a lower study as you depict above. Can you please share the lower DTR or the appropriate settings? Thanks again for your work and info!!
I got the DTR code from this thread here on useThinkScript: https://usethinkscript.com/threads/donchian-trend-ribbon-for-thinkorswim.10861/

Keep in mind that if you use my version of Chewie's script in the upper chart, the DTR summary line will only match the lower study if you use the default value (20) for the "dtc trend cutoff" input parameter. Changing this value will make the summary line not match the lower study (since that code doesn't have an input to change what it considers the buy/sell range).

Thanks for the feedback, too.
 

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
331 Online
Create Post

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