SuperTrend CCI ATR Trend for ThinkorSwim

oh geesh - sorry - I thought you used the code from your first reply.

here you go:

plot BuySignalArrow = if bar >= newState and State == StateUp and State[1] <> StateUp then low else Double.NaN;
plot SellSignalArrow = if bar >= newState and State == StateDn and State[1] <> StateDn then high else Double.NaN;
 
oh geesh - sorry - I thought you used the code from your first reply.

here you go:

plot BuySignalArrow = if bar >= newState and State == StateUp and State[1] <> StateUp then low else Double.NaN;
plot SellSignalArrow = if bar >= newState and State == StateDn and State[1] <> StateDn then high else Double.NaN;
I just deleted those numbers .99 & 1.00 from plot lines & it seemed to work.
 
I'm trying to figure out this code on line 105 and 106 and I'm just not seeing it. I would like the def LongBars and ShortBars to be calculated into the code on line 219 and 222. If you set the lookback and forward it should see these triggers and respond but I'm doing something wrong. I would be really grateful if someone could point me to the right direction. I'm not very good at this. Thank you!



Code:
input quantity = 100;
input lookback = 7;
input lookforward = 7;
input AtrMult = .60;#hint AtrMult: Modify to FloatingPL Plot-Original set to 1.00
input nATR = 6;
input AvgType = AverageType.HULL;

##__________________________________________________________________

##SuperTrend CCI ATR Trend
##tomsk
##11.18.2019

## V1.0 - 08.10.2019 - dtek - Initial release of SuperTrend CCI ATR Trend
## V2.0 - 11.18.2019 - tomsk - Modified the logic, cleaned up code for consistency

## SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED INTO ONE CHART INDICATOR,
## BOTH IN AGREEMENT IS A VERY POWERFUL SIGNAL IF TRENDING. VERY GOOD AT CATCHING
## REVERSALS. WORKS WELL ON 1 AND 5 MIN CHARTS. PLOT IS THE COMBINATION LOWEST
## FOR UPTREND AND HIGHEST OF THE DOWNTREND. DOTS COLORED IF BOTH IN AGREEMENT
## OR GREY IF NOT - 08/10/2019 DTEK

## Supertrend, extracted from Mobius original code

input ST_Atr_Mult = 1.0; #hint ST_Atr_Mult: For SuperTrend was .70
input ST_nATR = 4; #hint ST_nATR: For SuperTrend
input ST_AvgType = AverageType.HULL; #hint ST_AvgType: For SuperTrend

def ATR = MovingAverage(ST_AvgType, TrueRange(high, close, low), ST_nATR);
def longtrigger = HL2 + (ST_Atr_Mult * ATR);
def shorttrigger = HL2 + (-ST_Atr_Mult * ATR);
def ST = if close < ST[1] then longtrigger else shorttrigger;

## CCI_ATR measures distance from the mean. Calculates a trend
##line based on that distance using ATR as the locator for the line.
## Credit goes to Mobius for the underlying logic

input lengthCCI = 50; #hint lengthCCI: For SuperTrend CCI_ATR-Was 20
input lengthATR = 21; #hint lengthATR: For SuperTrend CCI_ATR-Was 4
input AtrFactor = 1.0; # hint AtrFactor: For SuperTrend CCI_ATR-Was 0.7
input ShowSuperTBubbles = NO;#hint BuySignalArrow: Turn off SuperTrend dots from”Plots”
input CandleColors = YES;#hint CandleColors: Turn off SuperTrend Candle Colors
def ATRCCI = Average(TrueRange(high, close, low), lengthATR) * AtrFactor;
def priceA = close + low + high;
def linDev = LinDev(priceA, lengthCCI);
def CCI = if linDev == 0
then 0
else (priceA - Average(priceA, lengthCCI)) / linDev / 0.015;

def MT1 = if CCI > 0
then Max(MT1[1], HL2 - ATRCCI)
else Min(MT1[1], HL2 + ATRCCI);

## Alignment of Supertrend and CCI ATR indicators

def Pos_State = close > ST and close > MT1;
def Neg_State = close < ST and close < MT1;

##Combined Signal Approach - Supertrend and ATR CCI

##plot CSA = MT1;
#CSA.AssignValueColor(if Pos_State then Color.CYAN
# else if Neg_State then Color.MAGENTA
#else Color.YELLOW);

## Buy/Sell Signals using state transitions

def BuySignal1 = (!Pos_State[1] and Pos_State);
def SellSignal1 = !Neg_State[1] and Neg_State;

##Buy/Sell Arrows

plot BuySignalArrow = if BuySignal1 then 0.995 * MT1 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.CYAN);
BuySignalArrow.SetLineWeight(5);

plot SellSignalArrow = if SellSignal1 then 1.005 * MT1 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.PINK);
SellSignalArrow.SetLineWeight(5);

## Candle Colors

#AssignPriceColor and CandleColors (if Pos_State then Color.GREEN
#else if Neg_State then Color.RED
#else Color.YELLOW);

##new Code

#oem def Long = if close > ST then ST else Double.NaN;

#oem def Short = if close < ST then ST else Double.NaN;

def Long = if close > ST and close > MT1 then ST else Double.NaN;
def Short = if close < ST and close < MT1 then ST else Double.NaN;


#def longBars = if longtrigger then 0 else Pos_State[1] + 1; #try 1
#def shortBars = if shorttrigger then 0 else Neg_State[1] + 1; #try1

#def longBars = if longtrigger then 0 else Pos_State[1] + 1; #try 2
#def shortBars = if shorttrigger then 0 else Neg_State[1] + 1; #try2

def longBars = Pos_State[1] + 1;#try 3
def shortBars = Neg_State[1] + 1;#Try 3

## End SuperTrend CCI ATR Trend

#_______________________________________________________________
#Trend Reversal Indicator
input AverageType = AverageType.EXPONENTIAL;
input ShowRBubbles = YES;#hint ShowRBubbles: Shows Reversal Bubble on Chart

def price = close;#was price
def superfast_length = 9;
def fast_length = 14;
def slow_length = 21;
def displace = 0;

def mov_avg9 = ExpAverage(price[-displace], superfast_length);
def mov_avg14 = ExpAverage(price[-displace], fast_length);
def mov_avg21 = ExpAverage(price[-displace], slow_length);

#moving averages
def Superfast = mov_avg9;
def Fast = mov_avg14;
def Slow = mov_avg21;

def buy = mov_avg9 > mov_avg14 and mov_avg14 > mov_avg21 and low > mov_avg9;
def stopbuy = mov_avg9 <= mov_avg14;
def buynow = !buy[1] and buy;
def buysignal = CompoundValue(1, if buynow and !stopbuy then 1 else if buysignal[1] == 1 and stopbuy then 0 else buysignal[1], 0);

def Buy_Signal = buysignal[1] == 0 and buysignal == 1;

#Alert(condition = buysignal[1] == 0 and buysignal == 1, text = "Buy Signal", sound = Sound.Bell, "alert type" = Alert.BAR);

def Momentum_Down = buysignal[1] == 1 and buysignal == 0;

#Alert(condition = buysignal[1] == 1 and buysignal == 0, text = "Momentum_Down", sound = Sound.Bell, "alert type" = Alert.BAR);

def sell = mov_avg9 < mov_avg14 and mov_avg14 < mov_avg21 and high < mov_avg9;
def stopsell = mov_avg9 >= mov_avg14;
def sellnow = !sell[1] and sell;
def sellsignal = CompoundValue(1, if sellnow and !stopsell then 1 else if sellsignal[1] == 1 and stopsell then 0 else sellsignal[1], 0);

def Sell_Signal = sellsignal[1] == 0 and sellsignal;

#Alert(condition = sellsignal[1] == 0 and sellsignal == 1, text = "Sell Signal", sound = Sound.Bell, "alert type" = Alert.BAR);

def Momentum_Up = sellsignal[1] == 1 and sellsignal == 0;

#Alert(condition = sellsignal[1] == 1 and sellSignal == 0, text = "Momentum_Up", sound = Sound.Bell, "alert type" = Alert.BAR);


#Chaned from plot Colorbars to def Colorbars
def Colorbars = if buysignal == 1 then 1 else if sellsignal == 1 then 2 else if buysignal == 0 or sellsignal == 0 then 3 else 0;
#___________________________________________________________________________

input method = {default average, high_low};
def bubbleoffset = 0.0005;
def percentamount = .01;
def revAmount = .05;
def atrreversal = 2.0;
def atrlength = 5;
def pricehigh = high;
def pricelow = low;
def averagelength = 5;
#def averagetype = AverageType.EXPONENTIAL;
def mah = MovingAverage(AverageType, pricehigh, averagelength);
def mal = MovingAverage(AverageType, pricelow, averagelength);
def priceh = if method == method.high_low then pricehigh else mah;
def pricel = if method == method.high_low then pricelow else mal;
def EI = ZigZagHighLow("price h" = priceh, "price l" = pricel, "percentage reversal" = percentamount, "absolute reversal" = revAmount, "atr length" = atrlength, "atr reversal" = atrreversal);
def reversalAmount = if (close * percentamount / 100) > Max(revAmount < atrreversal * reference ATR(atrlength), revAmount) then (close * percentamount / 100) else if revAmount < atrreversal * reference ATR(atrlength) then atrreversal * reference ATR(atrlength) else revAmount;
rec EISave = if !IsNaN(EI) then EI else GetValue(EISave, 1);
def chg = (if EISave == priceh then priceh else pricel) - GetValue(EISave, 1);
def isUp = chg >= 0;
rec isConf = AbsValue(chg) >= reversalAmount or (IsNaN(GetValue(EI, 1)) and GetValue(isConf, 1));
def EId = if isUp then 1 else 0;
#plot EnhancedLines = if EId <= 1 then EI else Double.NaN;
#EnhancedLines.AssignValueColor(if EId == 1 then Color.GREEN else if EId == 0 then Color.RED else Color.DARK_ORANGE);
#EnhancedLines.SetStyle(Curve.FIRM);
#EnhancedLines.EnableApproximation();
#EnhancedLines.HideBubble();
#Price Change between Enhanceds
def xxhigh = if EISave == priceh then priceh else xxhigh[1];
def chghigh = priceh - xxhigh[1];
def xxlow = if EISave == pricel then pricel else xxlow[1];
def chglow = pricel - xxlow[1];

#Bar Count between Enhanceds
rec EIcount = if EISave[1] != EISave then 1 else if EISave[1] == EISave then EIcount[1] + 1 else 0;
def EIcounthilo = if EIcounthilo[1] == 0 and (EISave == priceh or EISave == pricel) then 1 else if EISave == priceh or EISave == pricel then EIcounthilo[1] + 1 else EIcounthilo[1];
def EIhilo = if EISave == priceh or EISave == pricel then EIcounthilo else EIcounthilo + 1;
def EIcounthigh = if EISave == priceh then EIcount[1] else Double.NaN;
def EIcountlow = if EISave == pricel then EIcount[1] else Double.NaN;
#Arrows
def EIL = if !IsNaN(EI) and !isUp then pricel else GetValue(EIL, 1);
def EIH = if !IsNaN(EI) and isUp then priceh else GetValue(EIH, 1);
def dir = CompoundValue(1, if EIL != EIL[1] or pricel == EIL[1] and pricel == EISave then 1 else if EIH != EIH[1] or priceh == EIH[1] and priceh == EISave then -1 else dir[1], 0);
def signal = CompoundValue(1, if dir > 0 and pricel > EIL then if signal[1] <= 0 then 1 else signal[1] else if dir < 0 and priceh < EIH then if signal[1] >= 0 then -1 else signal[1] else signal[1], 0);
def showarrows = yes;
def U1 = showarrows and signal > 0 and signal[1] <= 0;
def D1 = showarrows and signal < 0 and signal[1] >= 0;
def barnumber = BarNumber()[10];

def longCond = (barnumber and U1) and signal > 0 and signal[1] <= 0 ;
def shortCond = (barnumber and D1) and signal < 0 and signal[1] >= 0;

AddChartBubble(ShowRBubbles and longCond, if isUp then low else high, if showarrows and signal > 0 and signal[1] <= 0 then "Rev:" + low else "" , if Colorbars == 3 then Color.PLUM else Color.UPTICK, no);
AddChartBubble(ShowRBubbles and shortCond, if isUp then low else high, if showarrows and signal < 0 and signal[1] >= 0 then "Rev:" + high else "" , if Colorbars == 3 then Color.PLUM else Color.DOWNTICK, yes);
#Buy Conditions New Code
def longBars1 = if longCond then 0 else longBars1[1] + 1;
def shortBars1 = if shortCond then 0 else shortBars1[1] + 1;


plot buyCondition = (longCond and longBars <= lookback)
or (longtrigger and longBars1 <= lookforward);
;
plot sellCondition = (shortCond and shortBars <= lookback)
or (shorttrigger and shortBars1 <= lookforward);
;
buyCondition.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
sellCondition.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
buyCondition.Hide();
sellCondition.Hide();
#_______________________________________________
#Short Term and Long Term Bearish or Bull trend Direction

input M_AVERAGE1_len = 5;#hint m_average1_len: 8 for Day Trade and 5 for Intraday suggested
input M_AVERAGE2_len = 8;#hint m_average2_len: 13 for Day Trade and 8 for Intraday suggested
input M_AVERAGE3_len = 13;#hint m_average3_len: 21 for Day Trade and 13 for Intraday suggested
input M_AVERAGE4_len = 50;
input M_AVERAGE5_len = 200;
input AverageType_LT_ST_Direction = AverageType.EXPONENTIAL;#hint AverageType: This is for Short and Long Term Direction Setting Above

def M_AVERAGE1 = MovAvgExponential(length = M_AVERAGE1_len);
def M_AVERAGE2 = MovAvgExponential(length = M_AVERAGE2_len);
def M_AVERAGE3 = MovAvgExponential(length = M_AVERAGE3_len);
def M_AVERAGE4 = MovAvgExponential(length = M_AVERAGE4_len);
def M_AVERAGE5 = MovAvgExponential(length = M_AVERAGE5_len);

def bullishStacked = M_AVERAGE1 > M_AVERAGE2 and M_AVERAGE2 > M_AVERAGE3 and M_AVERAGE3 > M_AVERAGE4;
def bearishStacked = M_AVERAGE1 < M_AVERAGE2 and M_AVERAGE2 < M_AVERAGE3 and M_AVERAGE3 < M_AVERAGE4;

AddLabel(yes, if bullishStacked then "ST_Bullish" else if bearishStacked then "ST_Bearish" else "N/A", if bullishStacked then Color.GREEN else if bearishStacked then Color.RED else Color.YELLOW);

#Long Term Bearish or Bull trend Direction

def LT_bullishStacked = M_AVERAGE4 > M_AVERAGE5;
def LT_bearishStacked = M_AVERAGE4 < M_AVERAGE5;

AddLabel(yes, if LT_bullishStacked then "LT_Bullish" else if LT_bearishStacked then "LT_Bearish" else "N/A", if LT_bullishStacked then Color.GREEN else if LT_bearishStacked then Color.RED else Color.YELLOW);

#_______________________________________________

#mADX
#
# Free for use. Header credits must be included when any form of the code included in this package is used.
# User assumes all risk. Author not responsible for errors or use of tool.
# Copyright (c) 2021 B4 Signals
#
# Get support at: https://b4signals.com
# Join us at: https://discord.gg/kD3pKE2CQd
#
#
# v1.0 - chuck - initial integration
# v2.0 - barbaros - cleanup
# v2.1 - barbaros - added adx limit

input ADDON_ADX_show = yes;#hint ADDON_ADX_show: Turn mADX lines ON or OFF
input ADDON_ADX_dmilength = 10;
input ADDON_ADX_limit = 25; #hint ADDON_ADX_limit: 25 for daily and 35 for intraday suggested
input ADDON_ADX_dmiaverageType = AverageType.WILDERS;

def ADDON_ADX_ADX = (DMI(ADDON_ADX_dmilength, ADDON_ADX_dmiaverageType).ADX) - 18;
def ADDON_ADX_signal = ADDON_ADX_ADX > ADDON_ADX_limit and ADDON_ADX_ADX >= 1 and ADDON_ADX_ADX < ADDON_ADX_ADX[1] and ADDON_ADX_ADX[1] > ADDON_ADX_ADX[2];

AddVerticalLine (ADDON_ADX_show and ADDON_ADX_signal, "mADX", Color.WHITE);
Alert(ADDON_ADX_signal, "mADX", Alert.BAR, Sound.Ding);


#AddOrder(OrderType.BUY_AUTO, buyCondition, open()[-1], quantity, Color.WHITE, Color.WHITE);
#AddOrder(OrderType.SELL_AUTO, sellCondition, open()[-1], quantity, Color.WHITE, Color.WHITE);

#Buy Signals
addorder(orderType.BUY_AUTO, buyCondition, open()[-1], quantity, color.white, color.white, "buy");
addorder(orderType.SELL_AUTO, sellCondition, open()[-1], quantity, color.white, color.white, "sell");


#END STRATEGY


I think I was able to figure it out, thank you!

Code:
input quantity = 100;
input lookback = 7;
input lookforward = 7;
input AtrMult = .60;#hint AtrMult: Modify to FloatingPL Plot-Original set to 1.00
input nATR = 6;
input AvgType = AverageType.HULL;

##__________________________________________________________________

##SuperTrend CCI ATR Trend
##tomsk
##11.18.2019

## V1.0 - 08.10.2019 - dtek - Initial release of SuperTrend CCI ATR Trend
## V2.0 - 11.18.2019 - tomsk - Modified the logic, cleaned up code for consistency

## SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED INTO ONE CHART INDICATOR,
## BOTH IN AGREEMENT IS A VERY POWERFUL SIGNAL IF TRENDING. VERY GOOD AT CATCHING
## REVERSALS. WORKS WELL ON 1 AND 5 MIN CHARTS. PLOT IS THE COMBINATION LOWEST
## FOR UPTREND AND HIGHEST OF THE DOWNTREND. DOTS COLORED IF BOTH IN AGREEMENT
## OR GREY IF NOT - 08/10/2019 DTEK

## Supertrend, extracted from Mobius original code

input ST_Atr_Mult = 1.0; #hint ST_Atr_Mult: For SuperTrend was .70
input ST_nATR = 4; #hint ST_nATR: For SuperTrend
input ST_AvgType = AverageType.HULL; #hint ST_AvgType: For SuperTrend

def ATR = MovingAverage(ST_AvgType, TrueRange(high, close, low), ST_nATR);
def longtrigger = HL2 + (ST_Atr_Mult * ATR);
def shorttrigger = HL2 + (-ST_Atr_Mult * ATR);
def ST = if close < ST[1] then longtrigger else shorttrigger;

## CCI_ATR measures distance from the mean. Calculates a trend
##line based on that distance using ATR as the locator for the line.
## Credit goes to Mobius for the underlying logic

input lengthCCI = 50; #hint lengthCCI: For SuperTrend CCI_ATR-Was 20
input lengthATR = 21; #hint lengthATR: For SuperTrend CCI_ATR-Was 4
input AtrFactor = 1.0; # hint AtrFactor: For SuperTrend CCI_ATR-Was 0.7
input ShowSuperTBubbles = NO;#hint BuySignalArrow: Turn off SuperTrend dots from”Plots”
input CandleColors = YES;#hint CandleColors: Turn off SuperTrend Candle Colors
def ATRCCI = Average(TrueRange(high, close, low), lengthATR) * AtrFactor;
def priceA = close + low + high;
def linDev = LinDev(priceA, lengthCCI);
def CCI = if linDev == 0
then 0
else (priceA - Average(priceA, lengthCCI)) / linDev / 0.015;

def MT1 = if CCI > 0
then Max(MT1[1], HL2 - ATRCCI)
else Min(MT1[1], HL2 + ATRCCI);

## Alignment of Supertrend and CCI ATR indicators

def Pos_State = close > ST and close > MT1;
def Neg_State = close < ST and close < MT1;

##Combined Signal Approach - Supertrend and ATR CCI

##plot CSA = MT1;
#CSA.AssignValueColor(if Pos_State then Color.CYAN
# else if Neg_State then Color.MAGENTA
#else Color.YELLOW);

## Buy/Sell Signals using state transitions

def BuySignal1 = (!Pos_State[1] and Pos_State);
def SellSignal1 = !Neg_State[1] and Neg_State;

##Buy/Sell Arrows

plot BuySignalArrow = if BuySignal1 then 0.995 * MT1 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.CYAN);
BuySignalArrow.SetLineWeight(5);

plot SellSignalArrow = if SellSignal1 then 1.005 * MT1 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.PINK);
SellSignalArrow.SetLineWeight(5);

## Candle Colors

#AssignPriceColor and CandleColors (if Pos_State then Color.GREEN
#else if Neg_State then Color.RED
#else Color.YELLOW);

##new Code

def longBars = if BuySignal1 then 0.995 * MT1 else Double.NaN;
def shortBars = if SellSignal1 then 1.005 * MT1 else Double.NaN;

## End SuperTrend CCI ATR Trend

#_______________________________________________________________
#Trend Reversal Indicator
input AverageType = AverageType.EXPONENTIAL;
input ShowRBubbles = YES;#hint ShowRBubbles: Shows Reversal Bubble on Chart

def price = close;#was price
def superfast_length = 9;
def fast_length = 14;
def slow_length = 21;
def displace = 0;

def mov_avg9 = ExpAverage(price[-displace], superfast_length);
def mov_avg14 = ExpAverage(price[-displace], fast_length);
def mov_avg21 = ExpAverage(price[-displace], slow_length);

#moving averages
def Superfast = mov_avg9;
def Fast = mov_avg14;
def Slow = mov_avg21;

def buy = mov_avg9 > mov_avg14 and mov_avg14 > mov_avg21 and low > mov_avg9;
def stopbuy = mov_avg9 <= mov_avg14;
def buynow = !buy[1] and buy;
def buysignal = CompoundValue(1, if buynow and !stopbuy then 1 else if buysignal[1] == 1 and stopbuy then 0 else buysignal[1], 0);

def Buy_Signal = buysignal[1] == 0 and buysignal == 1;

#Alert(condition = buysignal[1] == 0 and buysignal == 1, text = "Buy Signal", sound = Sound.Bell, "alert type" = Alert.BAR);

def Momentum_Down = buysignal[1] == 1 and buysignal == 0;

#Alert(condition = buysignal[1] == 1 and buysignal == 0, text = "Momentum_Down", sound = Sound.Bell, "alert type" = Alert.BAR);

def sell = mov_avg9 < mov_avg14 and mov_avg14 < mov_avg21 and high < mov_avg9;
def stopsell = mov_avg9 >= mov_avg14;
def sellnow = !sell[1] and sell;
def sellsignal = CompoundValue(1, if sellnow and !stopsell then 1 else if sellsignal[1] == 1 and stopsell then 0 else sellsignal[1], 0);

def Sell_Signal = sellsignal[1] == 0 and sellsignal;

#Alert(condition = sellsignal[1] == 0 and sellsignal == 1, text = "Sell Signal", sound = Sound.Bell, "alert type" = Alert.BAR);

def Momentum_Up = sellsignal[1] == 1 and sellsignal == 0;

#Alert(condition = sellsignal[1] == 1 and sellSignal == 0, text = "Momentum_Up", sound = Sound.Bell, "alert type" = Alert.BAR);


#Chaned from plot Colorbars to def Colorbars
def Colorbars = if buysignal == 1 then 1 else if sellsignal == 1 then 2 else if buysignal == 0 or sellsignal == 0 then 3 else 0;
#___________________________________________________________________________

input method = {default average, high_low};
def bubbleoffset = 0.0005;
def percentamount = .01;
def revAmount = .05;
def atrreversal = 2.0;
def atrlength = 5;
def pricehigh = high;
def pricelow = low;
def averagelength = 5;
#def averagetype = AverageType.EXPONENTIAL;
def mah = MovingAverage(AverageType, pricehigh, averagelength);
def mal = MovingAverage(AverageType, pricelow, averagelength);
def priceh = if method == method.high_low then pricehigh else mah;
def pricel = if method == method.high_low then pricelow else mal;
def EI = ZigZagHighLow("price h" = priceh, "price l" = pricel, "percentage reversal" = percentamount, "absolute reversal" = revAmount, "atr length" = atrlength, "atr reversal" = atrreversal);
def reversalAmount = if (close * percentamount / 100) > Max(revAmount < atrreversal * reference ATR(atrlength), revAmount) then (close * percentamount / 100) else if revAmount < atrreversal * reference ATR(atrlength) then atrreversal * reference ATR(atrlength) else revAmount;
rec EISave = if !IsNaN(EI) then EI else GetValue(EISave, 1);
def chg = (if EISave == priceh then priceh else pricel) - GetValue(EISave, 1);
def isUp = chg >= 0;
rec isConf = AbsValue(chg) >= reversalAmount or (IsNaN(GetValue(EI, 1)) and GetValue(isConf, 1));
def EId = if isUp then 1 else 0;
#plot EnhancedLines = if EId <= 1 then EI else Double.NaN;
#EnhancedLines.AssignValueColor(if EId == 1 then Color.GREEN else if EId == 0 then Color.RED else Color.DARK_ORANGE);
#EnhancedLines.SetStyle(Curve.FIRM);
#EnhancedLines.EnableApproximation();
#EnhancedLines.HideBubble();
#Price Change between Enhanceds
def xxhigh = if EISave == priceh then priceh else xxhigh[1];
def chghigh = priceh - xxhigh[1];
def xxlow = if EISave == pricel then pricel else xxlow[1];
def chglow = pricel - xxlow[1];

#Bar Count between Enhanceds
rec EIcount = if EISave[1] != EISave then 1 else if EISave[1] == EISave then EIcount[1] + 1 else 0;
def EIcounthilo = if EIcounthilo[1] == 0 and (EISave == priceh or EISave == pricel) then 1 else if EISave == priceh or EISave == pricel then EIcounthilo[1] + 1 else EIcounthilo[1];
def EIhilo = if EISave == priceh or EISave == pricel then EIcounthilo else EIcounthilo + 1;
def EIcounthigh = if EISave == priceh then EIcount[1] else Double.NaN;
def EIcountlow = if EISave == pricel then EIcount[1] else Double.NaN;
#Arrows
def EIL = if !IsNaN(EI) and !isUp then pricel else GetValue(EIL, 1);
def EIH = if !IsNaN(EI) and isUp then priceh else GetValue(EIH, 1);
def dir = CompoundValue(1, if EIL != EIL[1] or pricel == EIL[1] and pricel == EISave then 1 else if EIH != EIH[1] or priceh == EIH[1] and priceh == EISave then -1 else dir[1], 0);
def signal = CompoundValue(1, if dir > 0 and pricel > EIL then if signal[1] <= 0 then 1 else signal[1] else if dir < 0 and priceh < EIH then if signal[1] >= 0 then -1 else signal[1] else signal[1], 0);
def showarrows = yes;
def U1 = showarrows and signal > 0 and signal[1] <= 0;
def D1 = showarrows and signal < 0 and signal[1] >= 0;
def barnumber = BarNumber()[10];

def longCond = (barnumber and U1) and signal > 0 and signal[1] <= 0 ;
def shortCond = (barnumber and D1) and signal < 0 and signal[1] >= 0;

AddChartBubble(ShowRBubbles and longCond, if isUp then low else high, if showarrows and signal > 0 and signal[1] <= 0 then "Rev:" + low else "" , if Colorbars == 3 then Color.PLUM else Color.UPTICK, no);
AddChartBubble(ShowRBubbles and shortCond, if isUp then low else high, if showarrows and signal < 0 and signal[1] >= 0 then "Rev:" + high else "" , if Colorbars == 3 then Color.PLUM else Color.DOWNTICK, yes);
#Buy Conditions New Code
def longBars1 = if longCond then 0 else longBars1[1] + 1;
def shortBars1 = if shortCond then 0 else shortBars1[1] + 1;


plot buyCondition = (longCond and longBars <= lookback)
or (longtrigger and longBars1 <= lookforward);
;
plot sellCondition = (shortCond and shortBars <= lookback)
or (shorttrigger and shortBars1 <= lookforward);
;
buyCondition.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
sellCondition.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
buyCondition.Hide();
sellCondition.Hide();
#_______________________________________________
#Short Term and Long Term Bearish or Bull trend Direction

input M_AVERAGE1_len = 5;#hint m_average1_len: 8 for Day Trade and 5 for Intraday suggested
input M_AVERAGE2_len = 8;#hint m_average2_len: 13 for Day Trade and 8 for Intraday suggested
input M_AVERAGE3_len = 13;#hint m_average3_len: 21 for Day Trade and 13 for Intraday suggested
input M_AVERAGE4_len = 50;
input M_AVERAGE5_len = 200;
input AverageType_LT_ST_Direction = AverageType.EXPONENTIAL;#hint AverageType: This is for Short and Long Term Direction Setting Above

def M_AVERAGE1 = MovAvgExponential(length = M_AVERAGE1_len);
def M_AVERAGE2 = MovAvgExponential(length = M_AVERAGE2_len);
def M_AVERAGE3 = MovAvgExponential(length = M_AVERAGE3_len);
def M_AVERAGE4 = MovAvgExponential(length = M_AVERAGE4_len);
def M_AVERAGE5 = MovAvgExponential(length = M_AVERAGE5_len);

def bullishStacked = M_AVERAGE1 > M_AVERAGE2 and M_AVERAGE2 > M_AVERAGE3 and M_AVERAGE3 > M_AVERAGE4;
def bearishStacked = M_AVERAGE1 < M_AVERAGE2 and M_AVERAGE2 < M_AVERAGE3 and M_AVERAGE3 < M_AVERAGE4;

AddLabel(yes, if bullishStacked then "ST_Bullish" else if bearishStacked then "ST_Bearish" else "N/A", if bullishStacked then Color.GREEN else if bearishStacked then Color.RED else Color.YELLOW);

#Long Term Bearish or Bull trend Direction

def LT_bullishStacked = M_AVERAGE4 > M_AVERAGE5;
def LT_bearishStacked = M_AVERAGE4 < M_AVERAGE5;

AddLabel(yes, if LT_bullishStacked then "LT_Bullish" else if LT_bearishStacked then "LT_Bearish" else "N/A", if LT_bullishStacked then Color.GREEN else if LT_bearishStacked then Color.RED else Color.YELLOW);

#_______________________________________________

#mADX
#
# Free for use. Header credits must be included when any form of the code included in this package is used.
# User assumes all risk. Author not responsible for errors or use of tool.
# Copyright (c) 2021 B4 Signals
#
# Get support at: https://b4signals.com
# Join us at: https://discord.gg/kD3pKE2CQd
#
#
# v1.0 - chuck - initial integration
# v2.0 - barbaros - cleanup
# v2.1 - barbaros - added adx limit

input ADDON_ADX_show = yes;#hint ADDON_ADX_show: Turn mADX lines ON or OFF
input ADDON_ADX_dmilength = 10;
input ADDON_ADX_limit = 25; #hint ADDON_ADX_limit: 25 for daily and 35 for intraday suggested
input ADDON_ADX_dmiaverageType = AverageType.WILDERS;

def ADDON_ADX_ADX = (DMI(ADDON_ADX_dmilength, ADDON_ADX_dmiaverageType).ADX) - 18;
def ADDON_ADX_signal = ADDON_ADX_ADX > ADDON_ADX_limit and ADDON_ADX_ADX >= 1 and ADDON_ADX_ADX < ADDON_ADX_ADX[1] and ADDON_ADX_ADX[1] > ADDON_ADX_ADX[2];

AddVerticalLine (ADDON_ADX_show and ADDON_ADX_signal, "mADX", Color.WHITE);
Alert(ADDON_ADX_signal, "mADX", Alert.BAR, Sound.Ding);


#AddOrder(OrderType.BUY_AUTO, buyCondition, open()[-1], quantity, Color.WHITE, Color.WHITE);
#AddOrder(OrderType.SELL_AUTO, sellCondition, open()[-1], quantity, Color.WHITE, Color.WHITE);

#Buy Signals
addorder(orderType.BUY_AUTO, buyCondition, open()[-1], quantity, color.white, color.white, "buy");
addorder(orderType.SELL_AUTO, sellCondition, open()[-1], quantity, color.white, color.white, "sell");


#END STRATEGY
 
@dougn
@Tren

I have no clue how to write script but really wanted to use this as a scanner so I tried multiple times until this worked: I created study on TOS scanner and added the script info from the Supertrend CCI below, then added a plot on the last line. You can change the # of bars in the plot line to your liking. Hope this works.

Supertrend+CCI Bull Scanner

input ST_Atr_Mult = 1.0; # was .70
input ST_nATR = 4;
input ST_AvgType = AverageType.HULL;

def ATR = MovingAverage(ST_AvgType, TrueRange(high, close, low), ST_nATR);
def UP = HL2 + (ST_Atr_Mult* ATR);
def DN = HL2 + (-ST_Atr_Mult * ATR);
def ST = if close < ST[1] then UP else DN;

# CCI_ATR measures distance from the mean. Calculates a trend
# line based on that distance using ATR as the locator for the line.
# Credit goes to Mobius for the underlying logic

input lengthCCI = 20; # Was 20
input lengthATR = 4; # Was 4
input AtrFactor = .07; # Was 0.7

def ATRCCI = Average(TrueRange(high, close, low), lengthATR) * AtrFactor;
def price = close + low + high;
def linDev = LinDev(price, lengthCCI);
def CCI = if linDev == 0
then 0
else (price - Average(price, lengthCCI)) / linDev / 0.015;

def MT1 = if CCI > 0
then Max(MT1[1], HL2 - ATRCCI)
else Min(MT1[1], HL2 + ATRCCI);

# Alignment of Supertrend and CCI ATR indicators

def Pos_State = close > ST and close > MT1;

# Combined Signal Approach - Supertrend and ATR CCI

def BuySignal = (!Pos_State[1] and Pos_State);

plot ST_Cross = if (ST crosses below close) within 1 bars then 1 else 0;
 
GOOD MORNING,is there a possible scan for this strategy?

# SuperTrend CCI ATR Trend
# tomsk
# 1.17.2020

# V1.0 - 08.10.2019 - dtek - Initial release of SuperTrend CCI ATR Trend
# V2.0 - 11.18.2019 - tomsk - Modified the logic, cleaned up code for consistency
# V2.1 - 01.17.2020 - tomsk - Enhanced state transition engine to only display latest trend

# SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED INTO ONE CHART INDICATOR,
# BOTH IN AGREEMENT IS A VERY POWERFUL SIGNAL IF TRENDING. VERY GOOD AT CATCHING
# REVERSALS. WORKS WELL ON 1 AND 5 MIN CHARTS. PLOT IS THE COMBINATION LOWEST
# FOR UPTREND AND HIGHEST OF THE DOWNTREND. DOTS COLORED IF BOTH IN AGREEMENT
# OR GREY IF NOT - 08/10/2019 DTEK

# Supertrend, extracted from Mobius original code

input ST_Atr_Mult = 1.0; # was .70
input ST_nATR = 4;
input ST_AvgType = AverageType.HULL;

def ATR = MovingAverage(ST_AvgType, TrueRange(high, close, low), ST_nATR);
def UP = HL2 + (ST_Atr_Mult* ATR);
def DN = HL2 + (-ST_Atr_Mult * ATR);
def ST = if close < ST[1] then UP else DN;

# CCI_ATR measures distance from the mean. Calculates a trend
# line based on that distance using ATR as the locator for the line.
# Credit goes to Mobius for the underlying logic

input lengthCCI = 50; # Was 20
input lengthATR = 21; # Was 4
input AtrFactor = 1.0; # Was 0.7

def bar = barNumber();
def StateUp = 1;
def StateDn = 2;
def ATRCCI = Average(TrueRange(high, close, low), lengthATR) * AtrFactor;
def price = close + low + high;
def linDev = LinDev(price, lengthCCI);
def CCI = if linDev == 0
then 0
else (price - Average(price, lengthCCI)) / linDev / 0.015;
def MT1 = if CCI > 0
then Max(MT1[1], HL2 - ATRCCI)
else Min(MT1[1], HL2 + ATRCCI);

# Alignment of Supertrend and CCI ATR indicators
def State = if close > ST and close > MT1 then StateUp
else if close < ST and close < MT1 then StateDn
else State[1];
def newState = HighestAll(if State <> State[1] then bar else 0);

# Combined Signal Approach - Supertrend and ATR CCI

plot CSA = if bar >= newState then MT1 else Double.NaN;
CSA.AssignValueColor(if bar >= newState
then if State == StateUp then Color.CYAN
else if State == StateDn then Color.YELLOW
else Color.CURRENT
else Color.CURRENT);
# Buy/Sell Arrows
plot BuySignalArrow = if bar >= newState and State == StateUp and State[1] <> StateUp then 0.995 * MT1 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.CYAN);
BuySignalArrow.SetLineWeight(5);

plot SellSignalArrow = if bar >= newState and State == StateDn and State[1] <> StateDn then 1.005 * MT1 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.YELLOW);
SellSignalArrow.SetLineWeight(5);

# Candle Colors
AssignPriceColor(if bar >= newState
then if State == StateUp then Color.GREEN
else if State == StateDn then Color.RED
else Color.YELLOW
else Color.CURRENT);

# End SuperTrend CCI ATR Trend
 
Thank you for sharing this enhanced supertrend version, I toyed with many strategies and indicators last few years but keep coming back to this one. I find its simple ,clean and you can focus on the price action with little noise. I have 2 questions if anyone could help:
A) I would like to paint the volume bars to allign with the red/green supertrend bar paint. Does anyone have a code for that?
B) Any recommendations for lower indicator to compliment st. Mainly looking for suggestions to weed out some of the choppy market entries or for additional conviction/confirmation…i use the ift_StochOsc on a super slow setting but its pretty laggy. Any help appreciated, 🙏
 
Thank you for sharing this enhanced supertrend version, I toyed with many strategies and indicators last few years but keep coming back to this one. I find its simple ,clean and you can focus on the price action with little noise. I have 2 questions if anyone could help:
A) I would like to paint the volume bars to allign with the red/green supertrend bar paint. Does anyone have a code for that?
B) Any recommendations for lower indicator to compliment st. Mainly looking for suggestions to weed out some of the choppy market entries or for additional conviction/confirmation…i use the ift_StochOsc on a super slow setting but its pretty laggy. Any help appreciated, 🙏
  • Currently there is no study available to paint the volume bars with Supertrend colors.
  • An issue with all trend indicators is that they work less than optimally when ranging. Given that this is an issue with ALL trend indicators, applying another trend indicators such as a Stochastic will not resolve the problem. Read more here: https://usethinkscript.com/threads/...nt-to-successful-trading-in-thinkorswim.6114/
 
https://tos.mx/PBDcJex Syracuse------

I've made some changes in filter settings,......and I use a CCI lower,......very interesting results......
# SuperTrend CCI ATR Trend
# tomsk
# 1.17.2020

# V1.0 - 08.10.2019 - dtek - Initial release of SuperTrend CCI ATR Trend
# V2.0 - 11.18.2019 - tomsk - Modified the logic, cleaned up code for consistency
# V2.1 - 01.17.2020 - tomsk - Enhanced state transition engine to only display latest trend

# SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED INTO ONE CHART INDICATOR,
# BOTH IN AGREEMENT IS A VERY POWERFUL SIGNAL IF TRENDING. VERY GOOD AT CATCHING
# REVERSALS. WORKS WELL ON 1 AND 5 MIN CHARTS. PLOT IS THE COMBINATION LOWEST
# FOR UPTREND AND HIGHEST OF THE DOWNTREND. DOTS COLORED IF BOTH IN AGREEMENT
# OR GREY IF NOT - 08/10/2019 DTEK

# Supertrend, extracted from Mobius original code

input ST_Atr_Mult = 1.0; # was 1.
input ST_nATR = 10;#4
input ST_AvgType = AverageType.HULL;

def ATR = MovingAverage(ST_AvgType, TrueRange(high, close, low), ST_nATR);
def UP = HL2 + (ST_Atr_Mult* ATR);
def DN = HL2 + (-ST_Atr_Mult * ATR);
def ST = if close < ST[1] then UP else DN;

# CCI_ATR measures distance from the mean. Calculates a trend
# line based on that distance using ATR as the locator for the line.
# Credit goes to Mobius for the underlying logic

input lengthCCI = 30; # Was 20
input lengthATR = 10; # Was 21, 20
input AtrFactor = 1.5; # Was 1.0

def bar = barNumber();
def StateUp = 1;
def StateDn = 2;
def ATRCCI = Average(TrueRange(high, close, low), lengthATR) * AtrFactor;
def price = close + low + high;
def linDev = LinDev(price, lengthCCI);
def CCI = if linDev == 0
then 0
else (price - Average(price, lengthCCI)) / linDev / 0.015;
def MT1 = if CCI > 0
then Max(MT1[1], HL2 - ATRCCI)
else Min(MT1[1], HL2 + ATRCCI);

# Alignment of Supertrend and CCI ATR indicators
def State = if close > ST and close > MT1 then StateUp
else if close < ST and close < MT1 then StateDn
else State[1];
def newState = HighestAll(if State <> State[1] then bar else 0);

# Combined Signal Approach - Supertrend and ATR CCI

plot CSA = if bar >= newState then MT1 else Double.NaN;
CSA.AssignValueColor(if bar >= newState
then if State == StateUp then Color.blue
else if State == StateDn then Color.plum
else Color.black
else Color.CURRENT);
# Buy/Sell Arrows
plot BuySignalArrow = if bar >= newState and State == StateUp and State[1] <> StateUp then 0.99 * MT1 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.blue);
BuySignalArrow.SetLineWeight(5);

plot SellSignalArrow = if bar >= newState and State == StateDn and State[1] <> StateDn then 1.00 * MT1 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.plum);
SellSignalArrow.SetLineWeight(5);

# Candle Colors
AssignPriceColor(if bar >= newState
then if State == StateUp then Color.blue
else if State == StateDn then Color.Light_RED
else Color.black
else Color.black);
AddLabel(yes, "SuperTrend",if close < ST then Color.RED else Color.blue);

# End SuperTrend CCI ATR Trend
 
Last edited by a moderator:
https://tos.mx/PBDcJex Syracuse------

I've made some changes in filter settings,......and I use a CCI lower,......very interesting results......
# SuperTrend CCI ATR Trend
# tomsk
# 1.17.2020

# V1.0 - 08.10.2019 - dtek - Initial release of SuperTrend CCI ATR Trend
# V2.0 - 11.18.2019 - tomsk - Modified the logic, cleaned up code for consistency
# V2.1 - 01.17.2020 - tomsk - Enhanced state transition engine to only display latest trend

# SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED INTO ONE CHART INDICATOR,
# BOTH IN AGREEMENT IS A VERY POWERFUL SIGNAL IF TRENDING. VERY GOOD AT CATCHING
# REVERSALS. WORKS WELL ON 1 AND 5 MIN CHARTS. PLOT IS THE COMBINATION LOWEST
# FOR UPTREND AND HIGHEST OF THE DOWNTREND. DOTS COLORED IF BOTH IN AGREEMENT
# OR GREY IF NOT - 08/10/2019 DTEK

# Supertrend, extracted from Mobius original code

input ST_Atr_Mult = 1.0; # was 1.
input ST_nATR = 10;#4
input ST_AvgType = AverageType.HULL;

def ATR = MovingAverage(ST_AvgType, TrueRange(high, close, low), ST_nATR);
def UP = HL2 + (ST_Atr_Mult* ATR);
def DN = HL2 + (-ST_Atr_Mult * ATR);
def ST = if close < ST[1] then UP else DN;

# CCI_ATR measures distance from the mean. Calculates a trend
# line based on that distance using ATR as the locator for the line.
# Credit goes to Mobius for the underlying logic

input lengthCCI = 30; # Was 20
input lengthATR = 10; # Was 21, 20
input AtrFactor = 1.5; # Was 1.0

def bar = barNumber();
def StateUp = 1;
def StateDn = 2;
def ATRCCI = Average(TrueRange(high, close, low), lengthATR) * AtrFactor;
def price = close + low + high;
def linDev = LinDev(price, lengthCCI);
def CCI = if linDev == 0
then 0
else (price - Average(price, lengthCCI)) / linDev / 0.015;
def MT1 = if CCI > 0
then Max(MT1[1], HL2 - ATRCCI)
else Min(MT1[1], HL2 + ATRCCI);

# Alignment of Supertrend and CCI ATR indicators
def State = if close > ST and close > MT1 then StateUp
else if close < ST and close < MT1 then StateDn
else State[1];
def newState = HighestAll(if State <> State[1] then bar else 0);

# Combined Signal Approach - Supertrend and ATR CCI

plot CSA = if bar >= newState then MT1 else Double.NaN;
CSA.AssignValueColor(if bar >= newState
then if State == StateUp then Color.blue
else if State == StateDn then Color.plum
else Color.black
else Color.CURRENT);
# Buy/Sell Arrows
plot BuySignalArrow = if bar >= newState and State == StateUp and State[1] <> StateUp then 0.99 * MT1 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.blue);
BuySignalArrow.SetLineWeight(5);

plot SellSignalArrow = if bar >= newState and State == StateDn and State[1] <> StateDn then 1.00 * MT1 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.plum);
SellSignalArrow.SetLineWeight(5);

# Candle Colors
AssignPriceColor(if bar >= newState
then if State == StateUp then Color.blue
else if State == StateDn then Color.Light_RED
else Color.black
else Color.black);
AddLabel(yes, "SuperTrend",if close < ST then Color.RED else Color.blue);

# End SuperTrend CCI ATR Trend
The R labels are a little off the chart, not a big problem, but is it possible to make a scan them in TOS for alerts?
 
https://tos.mx/PBDcJex Syracuse------

I've made some changes in filter settings,......and I use a CCI lower,......very interesting results......
# SuperTrend CCI ATR Trend
# tomsk
# 1.17.2020

# V1.0 - 08.10.2019 - dtek - Initial release of SuperTrend CCI ATR Trend
# V2.0 - 11.18.2019 - tomsk - Modified the logic, cleaned up code for consistency
# V2.1 - 01.17.2020 - tomsk - Enhanced state transition engine to only display latest trend

# SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED INTO ONE CHART INDICATOR,
# BOTH IN AGREEMENT IS A VERY POWERFUL SIGNAL IF TRENDING. VERY GOOD AT CATCHING
# REVERSALS. WORKS WELL ON 1 AND 5 MIN CHARTS. PLOT IS THE COMBINATION LOWEST
# FOR UPTREND AND HIGHEST OF THE DOWNTREND. DOTS COLORED IF BOTH IN AGREEMENT
# OR GREY IF NOT - 08/10/2019 DTEK

# Supertrend, extracted from Mobius original code

input ST_Atr_Mult = 1.0; # was 1.
input ST_nATR = 10;#4
input ST_AvgType = AverageType.HULL;

def ATR = MovingAverage(ST_AvgType, TrueRange(high, close, low), ST_nATR);
def UP = HL2 + (ST_Atr_Mult* ATR);
def DN = HL2 + (-ST_Atr_Mult * ATR);
def ST = if close < ST[1] then UP else DN;

# CCI_ATR measures distance from the mean. Calculates a trend
# line based on that distance using ATR as the locator for the line.
# Credit goes to Mobius for the underlying logic

input lengthCCI = 30; # Was 20
input lengthATR = 10; # Was 21, 20
input AtrFactor = 1.5; # Was 1.0

def bar = barNumber();
def StateUp = 1;
def StateDn = 2;
def ATRCCI = Average(TrueRange(high, close, low), lengthATR) * AtrFactor;
def price = close + low + high;
def linDev = LinDev(price, lengthCCI);
def CCI = if linDev == 0
then 0
else (price - Average(price, lengthCCI)) / linDev / 0.015;
def MT1 = if CCI > 0
then Max(MT1[1], HL2 - ATRCCI)
else Min(MT1[1], HL2 + ATRCCI);

# Alignment of Supertrend and CCI ATR indicators
def State = if close > ST and close > MT1 then StateUp
else if close < ST and close < MT1 then StateDn
else State[1];
def newState = HighestAll(if State <> State[1] then bar else 0);

# Combined Signal Approach - Supertrend and ATR CCI

plot CSA = if bar >= newState then MT1 else Double.NaN;
CSA.AssignValueColor(if bar >= newState
then if State == StateUp then Color.blue
else if State == StateDn then Color.plum
else Color.black
else Color.CURRENT);
# Buy/Sell Arrows
plot BuySignalArrow = if bar >= newState and State == StateUp and State[1] <> StateUp then 0.99 * MT1 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.blue);
BuySignalArrow.SetLineWeight(5);

plot SellSignalArrow = if bar >= newState and State == StateDn and State[1] <> StateDn then 1.00 * MT1 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.plum);
SellSignalArrow.SetLineWeight(5);

# Candle Colors
AssignPriceColor(if bar >= newState
then if State == StateUp then Color.blue
else if State == StateDn then Color.Light_RED
else Color.black
else Color.black);
AddLabel(yes, "SuperTrend",if close < ST then Color.RED else Color.blue);

# End SuperTrend CCI ATR Trend
Definitely eliminates a good deal of chop/false signals. Nice work
 
There was a request yesterday from @blakecmathis to add buy/sell signals on the following study which essentially is a combined study of SuperTrend together with CCI ATR Trend. That study originated from a user called DTEK on 8.10.2019 and was based on Mobius original work several years ago.

https://tos.mx/dDZh6eC
It looked really promising (as most strudies from Mobius are). However after working through the details, it appeared that the embedded logic was a bit complex and confusing. Hence I cleaned up the code, modified the logic, rewrote portions of the underlying engine, added state transitions, implemented buy/sell signals and arrows as well as gave it a new coloring structure.

Since the previous study did not have a name, as a placeholder I'm tagging this study as "Supertrend ATR CCI Trend". Here then is version 2.0 of the code.
Enjoy it folks!

Code:
# SuperTrend CCI ATR Trend
# tomsk
# 11.18.2019

# V1.0 - 08.10.2019 - dtek  - Initial release of SuperTrend CCI ATR Trend
# V2.0 - 11.18.2019 - tomsk - Modified the logic, cleaned up code for consistency

# SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED INTO ONE CHART INDICATOR,
# BOTH IN AGREEMENT IS A VERY POWERFUL SIGNAL IF TRENDING. VERY GOOD AT CATCHING
# REVERSALS. WORKS WELL ON 1 AND 5 MIN CHARTS. PLOT IS THE COMBINATION LOWEST
# FOR UPTREND AND HIGHEST OF THE DOWNTREND. DOTS COLORED IF BOTH IN AGREEMENT
# OR GREY IF NOT -  08/10/2019 DTEK

# Supertrend, extracted from Mobius original code

input ST_Atr_Mult = 1.0;    # was .70
input ST_nATR = 4;
input ST_AvgType = AverageType.HULL;

def ATR = MovingAverage(ST_AvgType, TrueRange(high, close, low), ST_nATR);
def UP = HL2 + (ST_Atr_Mult* ATR);
def DN = HL2 + (-ST_Atr_Mult * ATR);
def ST = if close < ST[1] then UP else DN;

# CCI_ATR measures distance from the mean. Calculates a trend
# line based on that distance using ATR as the locator for the line.
# Credit goes to Mobius for the underlying logic

input lengthCCI = 50;      # Was 20
input lengthATR = 21;      # Was 4
input AtrFactor = 1.0;     # Was 0.7

def ATRCCI = Average(TrueRange(high, close, low), lengthATR) * AtrFactor;
def price = close + low + high;
def linDev = LinDev(price, lengthCCI);
def CCI = if linDev == 0
          then 0
          else (price - Average(price, lengthCCI)) / linDev / 0.015;

def MT1 = if CCI > 0
          then Max(MT1[1], HL2 - ATRCCI)
          else Min(MT1[1], HL2 + ATRCCI);

# Alignment of Supertrend and CCI ATR indicators

def Pos_State = close > ST and close > MT1;
def Neg_State = close < ST and close < MT1;

# Combined Signal Approach - Supertrend and ATR CCI

plot CSA = MT1;
CSA.AssignValueColor(if Pos_State then Color.CYAN
                     else if Neg_State then Color.MAGENTA
                     else Color.YELLOW);

# Buy/Sell Signals using state transitions

def BuySignal = (!Pos_State[1] and Pos_State);
def SellSignal = !Neg_State[1] and Neg_State;

# Buy/Sell Arrows

plot BuySignalArrow = if BuySignal then 0.995 * MT1 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.CYAN);
BuySignalArrow.SetLineWeight(5);

plot SellSignalArrow = if SellSignal then 1.005 * MT1 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.PINK);
SellSignalArrow.SetLineWeight(5);

# Candle Colors

AssignPriceColor(if Pos_State then Color.GREEN
                 else if Neg_State then Color.RED
                 else Color.YELLOW);
# End SuperTrend CCI ATR Trend
@samer800 Would you please assist in adding these as moving average options for this indicator?

McGinley
TEMA
ALMA
LSMA
VWMA

Thank you for your help!
 
@samer800 Would you please assist in adding these as moving average options for this indicator?

McGinley
TEMA
ALMA
LSMA
VWMA

Thank you for your help!
Keep in mind that average type isn't reflecting the type of averaging to use on prices, its just used in finding the ATR value. Finding the trend on the ATR through averages won't matter, it's only needed for the calculation per bar.
 
Can this made to show up as an alert under "MarketWatch" alerts?

in order to show up as an alert under "MarketWatch" alerts" :
We would need to create a scan and then set the scan to alert when changes;
But as this script is too complex for the Scan Hacker that is not possible.
 
Last edited:
should not 'repaints' be appended to the title of this one?
No, the Supertrend is not a "repainter"
For prior candles, the calculations used in Supertrends are set and final and do not repaint.

However, this study, like the majority of indicators on this forum, will continually update the current bar until it is closed.
Think about it, we can not know as a candle is forming what the final close, high, low, of the current bar is going to be, so of course, it updates with the most recent tick.

Find out more about Supertrends:
https://usethinkscript.com/threads/...ius-for-thinkorswim.12346/page-16#post-106205
 
Last edited:
Supertrend CCI ATR Trend Enchanced

This is the script from post#1 to which I added Mobius's Supertrend Cycle Statistics Labels (many thanks to @sunnybabu, who found these on TOS OneNote). I haven't had time to see how having these statistics will affect my trading, yet. But I find them interesting.
Ruby:
# SuperTrend CCI ATR Trend
# tomsk
# 11.18.2019

# V1.0 - 08.10.2019 - dtek  - Initial release of SuperTrend CCI ATR Trend
# V2.0 - 11.18.2019 - tomsk - Modified the logic, cleaned up code for consistency

# SUPERTREND BY MOBIUS AND CCI ATR TREND COMBINED INTO ONE CHART INDICATOR,
# BOTH IN AGREEMENT IS A VERY POWERFUL SIGNAL IF TRENDING. VERY GOOD AT CATCHING
# REVERSALS. WORKS WELL ON 1 AND 5 MIN CHARTS. PLOT IS THE COMBINATION LOWEST
# FOR UPTREND AND HIGHEST OF THE DOWNTREND. DOTS COLORED IF BOTH IN AGREEMENT
# OR GREY IF NOT -  08/10/2019 DTEK

# Supertrend, extracted from Mobius original code

input ST_Atr_Mult = 1.0;    # was .70
input ST_nATR = 4;
input ST_AvgType = AverageType.HULL;
input ShowLabel = yes;
def c = close;
def v = volume;

def ATR = MovingAverage(ST_AvgType, TrueRange(high, close, low), ST_nATR);
def UP = HL2 + (ST_Atr_Mult* ATR);
def DN = HL2 + (-ST_Atr_Mult * ATR);
def ST = if close < ST[1] then UP else DN;

# CCI_ATR measures distance from the mean. Calculates a trend
# line based on that distance using ATR as the locator for the line.
# Credit goes to Mobius for the underlying logic

input lengthCCI = 50;      # Was 20
input lengthATR = 21;      # Was 4
input AtrFactor = 1.0;     # Was 0.7

def ATRCCI = Average(TrueRange(high, close, low), lengthATR) * AtrFactor;
def price = close + low + high;
def linDev = LinDev(price, lengthCCI);
def CCI = if linDev == 0
          then 0
          else (price - Average(price, lengthCCI)) / linDev / 0.015;

def MT1 = if CCI > 0
          then Max(MT1[1], HL2 - ATRCCI)
          else Min(MT1[1], HL2 + ATRCCI);

# Alignment of Supertrend and CCI ATR indicators

def Pos_State = close > ST and close > MT1;
def Neg_State = close < ST and close < MT1;

# Combined Signal Approach - Supertrend and ATR CCI

plot CSA = MT1;
CSA.AssignValueColor(if Pos_State then Color.CYAN
                     else if Neg_State then Color.MAGENTA
                     else Color.YELLOW);

# Buy/Sell Signals using state transitions

def BuySignal = (!Pos_State[1] and Pos_State);
def SellSignal = !Neg_State[1] and Neg_State;

# Buy/Sell Arrows

plot BuySignalArrow = if BuySignal then 0.995 * MT1 else Double.NaN;
BuySignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
BuySignalArrow.SetDefaultColor(Color.CYAN);
BuySignalArrow.SetLineWeight(5);

plot SellSignalArrow = if SellSignal then 1.005 * MT1 else Double.NaN;
SellSignalArrow.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
SellSignalArrow.SetDefaultColor(Color.PINK);
SellSignalArrow.SetLineWeight(5);

# Candle Colors

AssignPriceColor(if Pos_State then Color.GREEN
                 else if Neg_State then Color.RED
                 else Color.YELLOW);
# End SuperTrend CCI ATR Trend
def upBars = if c < ST
             then upBars[1] + 1
             else upBars[1];
def upCycles = if c < ST and c[1] > ST[1]
               then upCycles[1] + 1
               else upCycles[1];

def dnBars = if c > ST
             then dnBars[1] + 1
             else dnBars[1];
def dnCycles = if c > ST and c[1] < ST[1]
               then dnCycles[1] + 1
               else dnCycles[1];
def upCycleCount = upBars / upCycles;
def dnCycleCount = dnBars / dnCycles;

def thisCycle = if c < ST and c[1] > ST[1]
                then 1
                else if c < ST
                then thisCycle[1] + 1
                else if c > ST and c[1] < ST[1]
                     then 1
                     else if c > ST
                          then thisCycle[1] + 1
                          else thisCycle[1];
def Volup = (fold i = 0 to thisCycle
             do if i > 0
                then Volup[1] + v
                else Volup[1]) / thisCycle;
DefineGlobalColor("LabelRed",  CreateColor(225, 0, 0)) ;
DefineGlobalColor("LabelGreen",  CreateColor(0, 165, 0)) ;
AddLabel(ShowLabel, "Up Bars = " + upBars + "; " +
                  "  Up Cycles = " + upCycles + "; " +
                  "  Dn Bars = " + dnBars + "; " +
                  "  Dn Cycles = " + dnCycles + "; " ,
if c < ST then GlobalColor("LabelRed") else GlobalColor("LabelGreen") );   #.... This portion of code modofies by jhf
AddLabel(ShowLabel,
                  "  Avg Up Cycle Count = " + Round(upCycleCount, 0) +
                  "  Avg Dn Cycle Count = " + Round(dnCycleCount, 0) +
                  "  This Cycle = " + thisCycle,
if c < ST then GlobalColor("LabelRed") else GlobalColor("LabelGreen") );   #.... This portion of code modofies by jhf
# End Code SuperTrend
What needs to be smoother to adjust the buy sell arrows to be more restrictive?
 

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