The Confirmation Trend Chart Setup | The End All Be All | For ThinkOrSwim

Status
Not open for further replies.

HODL-Lay-HE-hoo!

Well-known member
VIP
Lifetime
DISCLAIMER: Part of this strategy uses an MTF indicators (multi-timeframe). You will see the MTF signals repaint until the higher timeframe candle closes.

Maj2np8.png


Good people, welcome. The goal of this thread is to provide basic and detailed information concerning chart style(s) and studies modified by yours truly as seen previously in the Confirmation Candles thread authored by the legend @Christopher84. I will post any future modifications, study variations, screenshots, and answer any and all relevant questions from this thread. Thus, our journey down the rabbit hole continues!

qmFWs6W.png


There is not currently, nor will there ever be, an indicator combination of indicators that will replace the need for proper risk management. There is no "End All Be All" indicator. Any reference to "guaranteed" or massive returns in this thread is sarcasm. Unless one is extremely disciplined and master of their domain (it's a Seinfeld quote...), and has complete control over one's emotions, it is highly advisable to determine what risk/reward ratio you are comfortable with.

In addition to risk management, one also needs to always be mindful of price action and important levels. Though price action and key levels are a function of various indicators, they are not infallible. Therefore, users should learn to interpret and determine them without the use of indicators, and as a byproduct, one will better understand the strength and weakness of the indicators in use. (My opinion, of course)

sGtxMwh.png


Here is a link to the VIP version of this thread where I can share the chart setups that use VIP only indicators as needed: https://usethinkscript.com/threads/the-confirmation-trend-chart-setup-vip.16186/
 
Last edited:

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

9YZHJOP.png




oA4rhpS.png


The Zone entry method is tried and true, supply and demand, overbought and oversold, buy and sell… easy right?

xthGLoF.png


CgUujXo.png


z9jJJri.png


P7BDMjv.png


The EMAD entry method is simple and reliable - generally used as confirmation for other entry methods.

iRQl6gN.png


xw05SnL.png


IyUJ3lt.png
⬅️
 

Attachments

  • gvSeLQl.png
    gvSeLQl.png
    406.7 KB · Views: 5,409
  • EMAD E1.png
    EMAD E1.png
    414 KB · Views: 759
  • EMAD E2.png
    EMAD E2.png
    436.7 KB · Views: 678
  • EMAD E3.png
    EMAD E3.png
    420.1 KB · Views: 645
Last edited:
FljGprJ.png


Study link: http://tos.mx/mS7Z3oh (will update the image with the need to know soon!)

LEjD4M9.png


Code:
   ##########################################################################################
   ##########################################################################################
   ###                                                                                    ###
   ###       #############################           #########               #########    ###
   ###     #################################         #########               #########    ###    
   ###    ####################################       #########               #########    ###
   ###   ########                     #########      #########               #########    ###         
   ###   ########  C3_BIG_SPARK_MAX   #########      #########               #########    ###
   ###   ########       +TSV9         #########      #########               #########    ###       
   ###   ########   @Christopher84    #########      #########               #########    ###     
   ###   ########                     #########      #########               #########    ###        
   ###   ######################################      ##################################   ###      
   ###    ####################################       ##################################   ###   
   ###     #################################         ##################################   ###
   ###    ####################################       ##################################   ###     
   ###   ########                     #########                              #########    ###
   ###   ########     @Horserider     #########                              #########    ###
   ###   ########  HORSERIDER VOLUME  #########                              #########    ###            
   ###   ########  TRIPLE EXHAUSTION  #########                              #########    ###        
   ###   ########      @chence27      #########                              #########    ###             
   ###   ########                     #########                              #########    ###         
   ###    ####################################                               #########    ###       
   ###     ##################################                                #########    ###        
   ###      ###############################                                  #########    ###      
   ###                                                                                    ###
   ##########################################################################################
   ##########################################################################################

input keyleveltolerance = 1;
input showverticallineday = yes;
input show_ts_signals = no;  
input showLabels  = yes;
input showCloud = yes;
input trailType = {default modified, unmodified};
input averagetype = AverageType.SIMPLE;
input MACD_AverageType = {SMA, default EMA};
input DMI_averageType = AverageType.WILDERS;
input AvgType = AverageType.HULL;
input length9 = 35;
input length8 = 10;
input length10 = 20;
input length_3x = 1000;
input tradeDaytimeOnly = no; #hint tradeDaytimeOnly: (IntraDay Only) Only perform trades during hours stated
input OpenTime = 0930; #hint OpenTime: Opening time of market
input CloseTime = 1600; #hint CloseTime: Closing time of market
input firstTrade = {default long, short};
input LongTrades = yes; #hint LongTrades: perform long trades
input ShortTrades = yes; #hint ShortTrades: perform short trades
input useStops = no;     #hint useStops: use stop orders
input useAlerts = no;    #hint useAlerts: use alerts on signals
input ATRPeriod = 11;
input ATRFactor = 2.2;
input ATRPeriod2 = 5;
input ATRFactor2 = 1.5;
input AtrMult = 1.0;
input HideBoxLines = no;
input HideCloud = no;
input HideLabels = no;
input Strategy_Confirmation_Factor = 4;
input Strategy_FilterWithTMO = no;
input Strategy_FilterWithTMO_arrows = yes;
input Strategy_HoldTrend = no;
input Strategy_ColoredCandlesOn = yes;
input coloredCandlesOn = yes;
input ColorPrice = yes;
input color_blst = no;
input color_3x = yes;
input color_3xt = yes;
input color_OBOS = no;
input BarsUsedForRange = 2;
input BarsRequiredToRemainInRange = 2;
input TargetMultiple = 0.5;
input trig = 20;# for Blast-off candle color
def HideTargets = no;  
def HideBalance = no;
#####################################################
#TS Strategy_V9 Created by Christopher84 08/10/2021
#####################################################
Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);
def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);
def state = {default init, long, short};
def trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;
    }
}
def price = close;
def TrailingStop = trail;
def LongEnter = (price crosses above TrailingStop);
def LongExit = (price crosses below TrailingStop);
#Addorder(OrderType.BUY_AUTO, condition = LongEnter, price = open[-1], 1, tickcolor = GetColor(1), arrowcolor = Color.LIME);
#AddOrder(OrderType.SELL_AUTO, condition = LongExit, price = open[-1], 1, tickcolor = GetColor(2), arrowcolor = Color.LIME);
def upsignal = (price crosses above TrailingStop);
def downsignal = (price crosses below TrailingStop);
###############################################
##OB_OS_Levels_v5 by Christopher84 12/10/2021
###############################################
#def TrailingStop = trail;
def H = Highest(TrailingStop, 12);
def L = Lowest(TrailingStop, 12);
def BulgeLengthPrice = 100;
def SqueezeLengthPrice = 100;
def BandwidthC3 = (H - L);
#def IntermResistance2 = Highest(BandwidthC3, BulgeLengthPrice);
def IntermSupport2 = Lowest(BandwidthC3, SqueezeLengthPrice);
def sqzTrigger = BandwidthC3 <= IntermSupport2;
def sqzLevel = if !sqzTrigger[1] and sqzTrigger then hl2
               else if !sqzTrigger then Double.NaN
               else sqzLevel[1];
plot Squeeze_Alert = sqzLevel;
Squeeze_Alert.SetPaintingStrategy(PaintingStrategy.POINTS);
Squeeze_Alert.SetLineWeight(3);
Squeeze_Alert.SetDefaultColor(Color.YELLOW);
###############################################
##Yellow Candle_height (OB_OS)
###############################################
def displace = 0;
def factorK2 = 3.25;
def lengthK2 = 20;
def price1 = open;
def trueRangeAverageType = AverageType.SIMPLE;
def ATR_length = 15;
def SMA_lengthS = 6;
def HiLo2 = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef2 = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef2 = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def loss2 = ATRFactor2 * MovingAverage(averageType, trueRange, ATRPeriod2);
def multiplier_factor = 1.25;
def valS = Average(price, SMA_lengthS);
def average_true_range = Average(TrueRange(high, close, low), length = ATR_length);
def Upper_BandS = valS[-displace] + multiplier_factor * average_true_range[-displace];
def Middle_BandS = valS[-displace];
def Lower_BandS = valS[-displace] - multiplier_factor * average_true_range[-displace];
def shiftK2 = factorK2 * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK2);
def averageK2 = MovingAverage(averageType, price, lengthK2);
def AvgK2 = averageK2[-displace];
def Upper_BandK2 = averageK2[-displace] + shiftK2[-displace];
def Lower_BandK2 = averageK2[-displace] - shiftK2[-displace];
def condition_BandRevDn = (Upper_BandS > Upper_BandK2);
def condition_BandRevUp = (Lower_BandS < Lower_BandK2);
def fastLength = 12;
def slowLength = 26;
def MACDLength = 9;
def fastEMA = ExpAverage(price, fastLength);
def slowEMA = ExpAverage(price, slowLength);
def Value;
def Avg;
switch (MACD_AverageType) {
case SMA:
    Value = Average(price, fastLength) - Average(price, slowLength);
    Avg = Average(Value, MACDLength);
case EMA:
    Value = fastEMA - slowEMA;
    Avg = ExpAverage(Value, MACDLength);
}
def Diff = Value - Avg;
def MACDLevel = 0.0;
def Level = MACDLevel;
def condition1 = Value[1] <= Value;
def condition1D = Value[1] > Value;
#RSI
def RSI_length = 14;
def RSI_AverageType = AverageType.WILDERS;
def RSI_OB = 70;
def RSI_OS = 30;
def NetChgAvg = MovingAverage(RSI_AverageType, price - price[1], RSI_length);
def TotChgAvg = MovingAverage(RSI_AverageType, AbsValue(price - price[1]), RSI_length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
def RSI = 50 * (ChgRatio + 1);
def condition2 = (RSI[3] < RSI) is true or (RSI >= 80) is true;
def condition2D = (RSI[3] > RSI) is true or (RSI < 20) is true;
def conditionOB1 = RSI > RSI_OB;
def conditionOS1 = RSI < RSI_OS;
#MFI
def MFI_Length = 14;
def MFIover_Sold = 20;
def MFIover_Bought = 80;
def movingAvgLength = 1;
def MoneyFlowIndex = Average(MoneyFlow(high, close, low, volume, MFI_Length), movingAvgLength);
def MFIOverBought = MFIover_Bought;
def MFIOverSold = MFIover_Sold;
def condition3 = (MoneyFlowIndex[2] < MoneyFlowIndex) is true or (MoneyFlowIndex > 85) is true;
def condition3D = (MoneyFlowIndex[2] > MoneyFlowIndex) is true or (MoneyFlowIndex < 20) is true;
def conditionOB2 = MoneyFlowIndex > MFIover_Bought;
def conditionOS2 = MoneyFlowIndex < MFIover_Sold;
#Forecast
def na = Double.NaN;
def MidLine = 50;
def Momentum = MarketForecast().Momentum;
def NearT =  MarketForecast().NearTerm;
def Intermed = MarketForecast().Intermediate;
def FOB = 80;
def FOS = 20;
def upperLine = 110;
def condition4 = (Intermed[1] <= Intermed) or (NearT >= MidLine);
def condition4D = (Intermed[1] > Intermed) or (NearT < MidLine);
def conditionOB3 = Intermed > FOB;
def conditionOS3 = Intermed < FOS;
def conditionOB4 = NearT > FOB;
def conditionOS4 = NearT < FOS;
#Change in Price
def lengthCIP = 5;
def CIP = (price - price[1]);
def AvgCIP = ExpAverage(CIP[-displace], lengthCIP);
def CIP_UP = AvgCIP > AvgCIP[1];
def CIP_DOWN = AvgCIP < AvgCIP[1];
def condition5 = CIP_UP;
def condition5D = CIP_DOWN;
#EMA_1
def EMA_length = 8;
def AvgExp = ExpAverage(price[-displace], EMA_length);
def condition6 = (price >= AvgExp) and (AvgExp[2] <= AvgExp);
def condition6D = (price < AvgExp) and (AvgExp[2] > AvgExp);
#EMA_2
def EMA_2length = 20;
def displace2 = 0;
def AvgExp2 = ExpAverage(price[-displace2], EMA_2length);
def condition7 = (price >= AvgExp2) and (AvgExp2[2] <= AvgExp);
def condition7D = (price < AvgExp2) and (AvgExp2[2] > AvgExp);
#DMI Oscillator
def DMI_length = 5;#Typically set to 10
def diPlus = DMI(DMI_length, DMI_averageType)."DI+";
def diMinus = DMI(DMI_length, DMI_averageType)."DI-";
def Osc = diPlus - diMinus;
def Hist = Osc;
def ZeroLine = 0;
def condition8 = Osc >= ZeroLine;
def condition8D = Osc < ZeroLine;
#Trend_Periods
def TP_fastLength = 3;#Typically 7
def TP_slowLength = 4;#Typically 15
def Periods = Sign(ExpAverage(close, TP_fastLength) - ExpAverage(close, TP_slowLength));
def condition9 = Periods > 0;
def condition9D = Periods < 0;
#Polarized Fractal Efficiency
def PFE_length = 5;#Typically 10
def smoothingLength = 2.5;#Typically 5
def PFE_diff = close - close[PFE_length - 1];
def val = 100 * Sqrt(Sqr(PFE_diff) + Sqr(PFE_length)) / Sum(Sqrt(1 + Sqr(close - close[1])), PFE_length - 1);
def PFE = ExpAverage(if PFE_diff > 0 then val else -val, smoothingLength);
def UpperLevel = 50;
def LowerLevel = -50;
def condition10 = PFE > 0;
def condition10D = PFE < 0;
def conditionOB5 = PFE > UpperLevel;
def conditionOS5 = PFE < LowerLevel;
#Bollinger Bands PercentB
def BBPB_length = 20;#Typically 20
def Num_Dev_Dn = -2.0;
def Num_Dev_up = 2.0;
def BBPB_OB = 100;
def BBPB_OS = 0;
def upperBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, averagetype).UpperBand;
def lowerBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, averagetype).LowerBand;
def PercentB = (price - lowerBand) / (upperBand - lowerBand) * 100;
def HalfLine = 50;
def UnitLine = 100;
def condition11 = PercentB > HalfLine;
def condition11D = PercentB < HalfLine;
def conditionOB6 = PercentB > BBPB_OB;
def conditionOS6 = PercentB < BBPB_OS;
def condition12 = (Upper_BandS[1] <= Upper_BandS) and (Lower_BandS[1] <= Lower_BandS);
def condition12D = (Upper_BandS[1] > Upper_BandS) and (Lower_BandS[1] > Lower_BandS);
#Klinger Histogram
def Klinger_Length = 13;
def KVOsc = KlingerOscillator(Klinger_Length).KVOsc;
def KVOH = KVOsc - Average(KVOsc, Klinger_Length);
def condition13 = (KVOH > 0);
def condition13D = (KVOH < 0);
#Projection Oscillator
def ProjectionOsc_length = 30;#Typically 10
def MaxBound = HighestWeighted(high, ProjectionOsc_length, LinearRegressionSlope(price = high, length = ProjectionOsc_length));
def MinBound = LowestWeighted(low, ProjectionOsc_length, LinearRegressionSlope(price = low, length = ProjectionOsc_length));
def ProjectionOsc_diff = MaxBound - MinBound;
def PROSC = if ProjectionOsc_diff != 0 then 100 * (close - MinBound) / ProjectionOsc_diff else 0;
def PROSC_OB = 80;
def PROSC_OS = 20;
def condition14 = PROSC > 50;
def condition14D = PROSC < 50;
def conditionOB7 = PROSC > PROSC_OB;
def conditionOS7 = PROSC < PROSC_OS;
# AK Trend
def aktrend_input1 = 3;
def aktrend_input2 = 8;
def aktrend_price = close;
def aktrend_fastmaa = MovAvgExponential(aktrend_price, aktrend_input1);
def aktrend_fastmab = MovAvgExponential(aktrend_price, aktrend_input2);
def aktrend_bspread = (aktrend_fastmaa - aktrend_fastmab) * 1.001;
def cond1_UP = if aktrend_bspread > 0 then 1 else 0;
def cond1_DN = if aktrend_bspread <= 0 then -1 else 0;
# ZSCORE
def zscore_price = close;
def zscore_length = 20;
def zscore_ZavgLength = 20;
def zscore_oneSD = StDev(zscore_price, zscore_length);
def zscore_avgClose = SimpleMovingAvg(zscore_price, zscore_length);
def zscore_ofoneSD = zscore_oneSD * zscore_price[1];
def zscore_Zscorevalue = ((zscore_price - zscore_avgClose) / zscore_oneSD);
def zscore_avgZv = Average(zscore_Zscorevalue, 20);
def zscore_Zscore = ((zscore_price - zscore_avgClose) / zscore_oneSD);
def zscore_avgZscore = Average(zscore_Zscorevalue, zscore_ZavgLength);
def cond2_UP = if zscore_Zscore > 0 then 1 else 0;
def cond2_DN = if zscore_Zscore <= 0 then -1 else 0;
# Ehlers
def ehlers_length = 34;
def ehlers_price = (high + low) / 2;
def ehlers_coeff = ehlers_length * ehlers_price * ehlers_price - 2 * ehlers_price * Sum(ehlers_price, ehlers_length)[1] + Sum(ehlers_price * ehlers_price, ehlers_length)[1];
def ehlers_Ehlers = Sum(ehlers_coeff * ehlers_price, ehlers_length) / Sum(ehlers_coeff, ehlers_length);
def cond3_UP = if close > ehlers_Ehlers then 1 else 0;
def cond3_DN = if close <= ehlers_Ehlers then -1 else 0;
# Anchored Momentum
def amom_src = close;
def amom_MomentumPeriod = 10;
def amom_SignalPeriod = 8;
def amom_SmoothMomentum = no;
def amom_SmoothingPeriod = 7;
def amom_p = 2 * amom_MomentumPeriod + 1;
def amom_t_amom = if amom_SmoothMomentum == yes then ExpAverage(amom_src, amom_SmoothingPeriod) else amom_src;
def amom_amom = 100 * ( (amom_t_amom / ( Average(amom_src, amom_p)) - 1));
def amom_amoms = Average(amom_amom, amom_SignalPeriod);
def cond4_UP = if amom_amom > 0 then 1 else 0;
def cond4_DN = if amom_amom <= 0 then -1 else 0;
# TMO
def tmo_length = 30; #def 14
def tmo_calcLength = 6; #def 5
def tmo_smoothLength = 6; #def 3
def tmo_data = fold i = 0 to tmo_length with s do s + (if close > GetValue(open, i) then 1 else if close < GetValue(open, i) then - 1 else 0);
def tmo_EMA5 = ExpAverage(tmo_data, tmo_calcLength);
def tmo_Main = ExpAverage(tmo_EMA5, tmo_smoothLength);
def tmo_Signal = ExpAverage(tmo_Main, tmo_smoothLength);
def tmo_color = if tmo_Main > tmo_Signal then 1 else -1;
def cond5_UP = if tmo_Main <= 0 then 1 else 0;
def cond5_DN = if tmo_Main >= 0 then -1 else 0;
#Trend Confirmation Calculator
def Confirmation_Factor = 7;
#def Agreement_Level = condition1;
def Agreement_LevelOB = 12;
def Agreement_LevelOS = 2;
def factorK = 2.0;
def lengthK = 20;
def shift = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK);
def averageK = MovingAverage(averageType, price, lengthK);
def AvgK = averageK[-displace];
def Upper_BandK = averageK[-displace] + shift[-displace];
def Lower_BandK = averageK[-displace] - shift[-displace];
def conditionK1UP = price >= Upper_BandK;
def conditionK2UP = (Upper_BandK[1] < Upper_BandK) and (Lower_BandK[1] < Lower_BandK);
def conditionK3DN = (Upper_BandK[1] > Upper_BandK) and (Lower_BandK[1] > Lower_BandK);
def conditionK4DN = price < Lower_BandK;
def Agreement_Level = condition1 + condition2 + condition3 + condition4
                    + condition5 + condition6 + condition7 + condition8 + condition9
                    + condition10 + condition11 + condition12 + condition13 + condition14
                    + conditionK1UP + conditionK2UP;
def Agreement_LevelD = (condition1D + condition2D + condition3D + condition4D + condition5D
                    + condition6D + condition7D + condition8D + condition9D + condition10D
                    + condition11D + condition12D + condition13D + condition14D + conditionK3DN
                    + conditionK4DN);
def Consensus_Level = Agreement_Level - Agreement_LevelD;
def UP = Consensus_Level >= 6;
def DOWN = Consensus_Level < -6;
def priceColor = if UP then 1
                 else if DOWN then -1
                 else priceColor[1];
def Consensus_Level_OB = 14;
def Consensus_Level_OS = -12;
#Super_OB/OS Signal
def OB_Level = conditionOB1 + conditionOB2 + conditionOB3 + conditionOB4 + conditionOB5 + conditionOB6 + conditionOB7;
def OS_Level = conditionOS1 + conditionOS2 + conditionOS3 + conditionOS4 + conditionOS5 + conditionOS6 + conditionOS7;
def Consensus_Line = OB_Level - OS_Level;
def Zero_Line = 0;
def Super_OB = 4;
def Super_OS = -4;
def DOWN_OB = (Agreement_Level > Agreement_LevelOB) and (Consensus_Line > Super_OB) and (Consensus_Level > Consensus_Level_OB);
def UP_OS = (Agreement_Level < Agreement_LevelOS) and (Consensus_Line < Super_OS) and (Consensus_Level < Consensus_Level_OS);
def OS_Buy = UP_OS;
def OB_Sell = DOWN_OB;
def neutral = Consensus_Line < Super_OB and Consensus_Line > Super_OS;
def use_line_limits = yes;#Yes, plots line from/to; No, plot line across entire chart
def linefrom = 100;#Hint linefrom: limits how far line plots in candle area
def lineto   = 12;#Hint lineto: limits how far into expansion the line will plot
def YHOB = if coloredCandlesOn and ((price1 > Upper_BandS) and (condition_BandRevDn)) then high else Double.NaN;
def YHOS = if coloredCandlesOn and ((price1 < Lower_BandS) and (condition_BandRevUp)) then high else Double.NaN;
def YLOB = if coloredCandlesOn and ((price1 > Upper_BandS) and (condition_BandRevDn)) then low else Double.NaN;
def YLOS = if coloredCandlesOn and ((price1 < Lower_BandS) and (condition_BandRevUp)) then low else Double.NaN;
#extend midline of yellow candle
plot YCOB = if !IsNaN(YHOB) then hl2 else Double.NaN;
YCOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOB.SetDefaultColor(Color.GREEN);
def YHextOB = if IsNaN(YCOB) then YHextOB[1] else YCOB;
plot YHextlineOB = YHextOB;
YHextlineOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOB.SetDefaultColor(Color.ORANGE);
YHextlineOB.SetLineWeight(2);
plot YCOS = if !IsNaN(YHOS) then hl2 else Double.NaN;
YCOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOS.SetDefaultColor(Color.GREEN);
def YHextOS = if IsNaN(YCOS) then YHextOS[1] else YCOS;
plot YHextlineOS = YHextOS;
YHextlineOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOS.SetDefaultColor(Color.LIGHT_GREEN);
YHextlineOS.SetLineWeight(2);
def YC = coloredCandlesOn and priceColor == 1 and price1 > Upper_BandS and condition_BandRevDn;
def HH = Highest(high[1], BarsUsedForRange);
def LL = Lowest(low[1], BarsUsedForRange);
def maxH = Highest(HH, BarsRequiredToRemainInRange);
def maxL = Lowest(LL, BarsRequiredToRemainInRange);
def HHn = if maxH == maxH[1] or maxL == maxL then maxH else HHn[1];
def LLn = if maxH == maxH[1] or maxL == maxL then maxL else LLn[1];
def Bh = if high <= HHn and HHn == HHn[1] then HHn else Double.NaN;
def Bl = if low >= LLn and LLn == LLn[1] then LLn else Double.NaN;
def CountH = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountH[1] + 1;
def CountL = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountL[1] + 1;
def ExpH = if BarNumber() == 1 then Double.NaN else
           if CountH[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then HHn[-BarsRequiredToRemainInRange] else
           if high <= ExpH[1] then ExpH[1] else Double.NaN;
def ExpL = if BarNumber() == 1 then Double.NaN else
           if CountL[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then LLn[-BarsRequiredToRemainInRange] else
           if low >= ExpL[1] then ExpL[1] else Double.NaN;
def BoxHigh = if ((DOWN_OB) or (Upper_BandS crosses above Upper_BandK2) or (condition_BandRevDn) and (high > high[1]) and ((price > Upper_BandK2) or (price > Upper_BandS))) then Highest(ExpH) else Double.NaN;
def BoxLow = if (DOWN_OB) or ((Upper_BandS crosses above Upper_BandK2)) then Lowest(low) else Double.NaN;
def BoxHigh2 = if ((UP_OS) or ((Lower_BandS crosses below Lower_BandK2))) then Highest(ExpH) else Double.NaN;
def BH2 = if !IsNaN(BoxHigh2) then high else Double.NaN;
def BH2ext = if IsNaN(BH2) then BH2ext[1] else BH2;
def BH2extline = BH2ext;
plot H_BH2extline = Lowest(BH2extline, 1);
H_BH2extline.SetDefaultColor(Color.GREEN);
def BoxLow2 = if ((UP_OS) or (Lower_BandS crosses below Lower_BandK2) or (condition_BandRevUp) and (low < low[1]) and ((price < Lower_BandK2) or (price < Lower_BandS))) or ((UP_OS[1]) and (low < low[1])) then Lowest(low) else Double.NaN;
def BH1 = if !IsNaN(BoxHigh) then high else Double.NaN;
def BH1ext = if IsNaN(BH1) then BH1ext[1] else BH1;
def BH1extline = BH1ext;
def BL1 = if !IsNaN(BoxLow) then low else Double.NaN;
def BL1ext = if IsNaN(BL1) then BL1ext[1] else BL1;
plot BL1extline = BL1ext;
BL1extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL1extline.SetDefaultColor(Color.RED);
BL1extline.SetLineWeight(1);
def BL2 = if !IsNaN(BoxLow2) then low else Double.NaN;
def BL2ext = if IsNaN(BL2) then BL2ext[1] else BL2;
plot BL2extline = BL2ext;
BL2extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL2extline.SetDefaultColor(Color.GREEN);
BL2extline.SetLineWeight(1);
plot H_BH1extline = Highest(BH1extline, 1);
H_BH1extline.SetDefaultColor(Color.RED);
plot L_BL1extline = Highest(BL1extline, 1);
L_BL1extline.SetDefaultColor(Color.RED);
plot L_BL2extline = Lowest(BL2extline, 1);
L_BL2extline.SetDefaultColor(Color.GREEN);
AddCloud(if !HideCloud then BH1extline else Double.NaN, BL1extline, Color.RED, Color.GRAY);
AddCloud(if !HideCloud then BH2extline else Double.NaN, BL2extline, Color.GREEN, Color.GRAY);
############################################################
##C3_MF_Line_v2 Created by Christopher84 03/06/2022  
############################################################
#Keltner Channel
def BulgeLengthPrice2 = 20;
def SqueezeLengthPrice2 = 20;
def BulgeLengthPrice3 = 12;
def SqueezeLengthPrice3 = 12;
def IntermResistance = Highest(price, BulgeLengthPrice);
def IntermSupport = Lowest(price, SqueezeLengthPrice);
def NearTResistance = Highest(price, BulgeLengthPrice2);
def NearTSupport = Lowest(price, SqueezeLengthPrice2);
def NearTResistance1 = Highest(price, BulgeLengthPrice3);
def NearTSupport1 = Lowest(price, SqueezeLengthPrice3);
script WMA_Smooth {
    input price_WMA = hl2;
    plot smooth = (4 * price_WMA
+ 3 * price_WMA[1]
+ 2 * price_WMA[2]
+ price_WMA[3]) / 10;
}
script Phase_Accumulation {
# This is Ehler's Phase Accumulation code. It has a full cycle delay.
# However, it computes the correction factor to a very high degree.
    input price_WMA = hl2;
    rec Smooth;
    rec Detrender;
    rec Period;
    rec Q1;
    rec I1;
    rec I1p;
    rec Q1p;
    rec Phase1;
    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase1;
    rec InstPeriod1;
    rec InstPeriod;
    def CorrectionFactor;

    if BarNumber() <= 5
    then {
        Period = 0;
        Smooth = 0;
        Detrender = 0;
        CorrectionFactor = 0;
        Q1 = 0;
        I1 = 0;
        Q1p = 0;
        I1p = 0;
        Phase = 0;
        Phase1 = 0;
        DeltaPhase1 = 0;
        DeltaPhase = 0;
        InstPeriod = 0;
        InstPeriod1 = 0;
    } else {
        CorrectionFactor = 0.075 * Period[1] + 0.54;

# Smooth and detrend my smoothed signal:

        Smooth = WMA_Smooth(price_WMA);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

# Compute Quadrature and Phase of Detrended signal:

        Q1p = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1p = Detrender[3];

# Smooth out Quadrature and Phase:

        I1 = 0.15 * I1p + 0.85 * I1p[1];
        Q1 = 0.15 * Q1p + 0.85 * Q1p[1];

# Determine Phase

        if I1 != 0
        then {

# Normally, ATAN gives results from -pi/2 to pi/2.
# We need to map this to circular coordinates 0 to 2pi

            if Q1 >= 0 and I1 > 0
            then { # Quarant 1
                Phase1 = ATan(AbsValue(Q1 / I1));
            } else if Q1 >= 0 and I1 < 0
            then { # Quadrant 2
                Phase1 = Double.Pi - ATan(AbsValue(Q1 / I1));
            } else if Q1 < 0 and I1 < 0
            then { # Quadrant 3
                Phase1 = Double.Pi + ATan(AbsValue(Q1 / I1));
            } else { # Quadrant 4
                Phase1 = 2 * Double.Pi - ATan(AbsValue(Q1 / I1));
            }
        } else if Q1 > 0
        then { # I1 == 0, Q1 is positive
            Phase1 = Double.Pi / 2;
        } else if Q1 < 0
        then { # I1 == 0, Q1 is negative
            Phase1 = 3 * Double.Pi / 2;
        } else { # I1 and Q1 == 0
            Phase1 = 0;
        }

# Convert phase to degrees

        Phase = Phase1 * 180 / Double.Pi;

        if Phase[1] < 90 and Phase > 270
        then {
# This occurs when there is a big jump from 360-0

            DeltaPhase1 = 360 + Phase[1] - Phase;
        } else {
            DeltaPhase1 = Phase[1] - Phase;
        }

# Limit our delta phases between 7 and 60

        if DeltaPhase1 < 7
        then {
            DeltaPhase = 7;
        } else if DeltaPhase1 > 60
        then {
            DeltaPhase = 60;
        } else {
            DeltaPhase = DeltaPhase1;
        }

# Determine Instantaneous period:

        InstPeriod1 =
-1 * (fold i = 0 to 40 with v=0 do
if v < 0 then
v
else if v > 360 then
-i
else
v + GetValue(DeltaPhase, i, 41));

        if InstPeriod1 <= 0
        then {
            InstPeriod = InstPeriod[1];
        } else {
            InstPeriod = InstPeriod1;
        }

        Period = 0.25 * InstPeriod + 0.75 * Period[1];
    }
    plot DC = Period;
}

script Ehler_MAMA {
    input price_WMA = hl2;
    input FastLimit = 0.5;
    input SlowLimit = 0.05;


    rec Period;
    rec Period_raw;
    rec Period_cap;
    rec Period_lim;

    rec Smooth;
    rec Detrender;
    rec I1;
    rec Q1;
    rec jI;
    rec jQ;
    rec I2;
    rec Q2;
    rec I2_raw;
    rec Q2_raw;

    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase_raw;
    rec alpha;
    rec alpha_raw;

    rec Re;
    rec Im;
    rec Re_raw;
    rec Im_raw;

    rec SmoothPeriod;
    rec vmama;
    rec vfama;

    def CorrectionFactor = Phase_Accumulation(price_WMA).CorrectionFactor;

    if BarNumber() <= 5
    then {
        Smooth = 0;
        Detrender = 0;

        Period = 0;
        Period_raw = 0;
        Period_cap = 0;
        Period_lim = 0;
        I1 = 0;
        Q1 = 0;
        I2 = 0;
        Q2 = 0;
        jI = 0;
        jQ = 0;
        I2_raw = 0;
        Q2_raw = 0;
        Re = 0;
        Im = 0;
        Re_raw = 0;
        Im_raw = 0;
        SmoothPeriod = 0;
        Phase = 0;
        DeltaPhase = 0;
        DeltaPhase_raw = 0;
        alpha = 0;
        alpha_raw = 0;
        vmama = 0;
        vfama = 0;
    } else {

# Smooth and detrend my smoothed signal:

        Smooth = WMA_Smooth(price_WMA);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

        Q1 = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1 = Detrender[3];

        jI = ( 0.0962 * I1
+ 0.5769 * I1[2]
- 0.5769 * I1[4]
- 0.0962 * I1[6] ) * CorrectionFactor;

        jQ = ( 0.0962 * Q1
+ 0.5769 * Q1[2]
- 0.5769 * Q1[4]
- 0.0962 * Q1[6] ) * CorrectionFactor;

# This is the complex conjugate

        I2_raw = I1 - jQ;
        Q2_raw = Q1 + jI;

        I2 = 0.2 * I2_raw + 0.8 * I2_raw[1];
        Q2 = 0.2 * Q2_raw + 0.8 * Q2_raw[1];

        Re_raw = I2 * I2[1] + Q2 * Q2[1];
        Im_raw = I2 * Q2[1] - Q2 * I2[1];

        Re = 0.2 * Re_raw + 0.8 * Re_raw[1];
        Im = 0.2 * Im_raw + 0.8 * Im_raw[1];

# Compute the phase

        if Re != 0 and Im != 0
        then {
            Period_raw = 2 * Double.Pi / ATan(Im / Re);
        } else {
            Period_raw = 0;
        }

        if Period_raw > 1.5 * Period_raw[1]
        then {
            Period_cap = 1.5 * Period_raw[1];
        } else if Period_raw < 0.67 * Period_raw[1] {
            Period_cap = 0.67 * Period_raw[1];
        } else {
            Period_cap = Period_raw;
        }

        if Period_cap < 6
        then {
            Period_lim = 6;
        } else if Period_cap > 50
        then {
            Period_lim = 50;
        } else {
            Period_lim = Period_cap;
        }

        Period = 0.2 * Period_lim + 0.8 * Period_lim[1];
        SmoothPeriod = 0.33 * Period + 0.67 * SmoothPeriod[1];

        if I1 != 0
        then {
            Phase = ATan(Q1 / I1);
        } else if Q1 > 0
        then { # Quadrant 1:
            Phase = Double.Pi / 2;
        } else if Q1 < 0
        then { # Quadrant 4:
            Phase = -Double.Pi / 2;
        } else { # Both numerator and denominator are 0.
            Phase = 0;
        }

        DeltaPhase_raw = Phase[1] - Phase;
        if DeltaPhase_raw < 1
        then {
            DeltaPhase = 1;
        } else {
            DeltaPhase = DeltaPhase_raw;
        }

        alpha_raw = FastLimit / DeltaPhase;
        if alpha_raw < SlowLimit
        then {
            alpha = SlowLimit;
        } else {
            alpha = alpha_raw;
        }
        vmama = alpha * price_WMA + (1 - alpha) * vmama[1];
        vfama = 0.5 * alpha * vmama + (1 - 0.5 * alpha) * vfama[1];
    }

    plot MAMA = vmama;
    plot FAMA = vfama;
}
def price2 = hl2;
def FastLimit = 0.5;
def SlowLimit = 0.05;
def MAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).MAMA;
def FAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).FAMA;
def Crossing = Crosses((MAMA < FAMA), yes);
def Crossing1 = Crosses((MAMA > FAMA), yes);
def C3_Line_1 = if ((priceColor == 1) and (price1 > Upper_BandS) and (condition_BandRevDn)) then 1 else 0;
def C3_Line_2 = if ((priceColor == -1) and (price1 < Lower_BandS) and (condition_BandRevUp)) then 1 else 0;
def C3_Green =  ((priceColor == 1));
def C3_red =  ((priceColor == 1));
AddLabel(yes, Concat("MAMA", Concat("",
if MAMA > FAMA then "" else "")),
if MAMA > FAMA then Color.LIGHT_GREEN else Color.LIGHT_RED);
def MF_UP = FAMA < MAMA;
def MF_DN = FAMA > MAMA;
def priceColor10 = if MF_UP then 1
                 else if MF_DN then -1
                 else priceColor10[1];
###################################
##Consensus Level & Squeeze Label
###################################
def MomentumUP = Consensus_Level[1] < Consensus_Level;
def MomentumDOWN = Consensus_Level[1] > Consensus_Level;
def conditionOB = (Consensus_Level >= 12) and (Consensus_Line >= 4);
def conditionOS = (Consensus_Level <= -12) and (Consensus_Line <= -3);
###################################
##Big4 Strategy
###################################
def cond_UP = cond1_UP + cond2_UP + cond3_UP + cond4_UP;
def cond_DN = cond1_DN + cond2_DN + cond3_DN + cond4_DN;
def direction = if cond_UP >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_UP) then 1
else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_DN) then -1
    else if !Strategy_HoldTrend and direction[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
        else if !Strategy_HoldTrend and direction[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0
            else direction[1];
def direction2 = if cond_UP >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_UP) then 1
    else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_DN) then -1
        else if !Strategy_HoldTrend and direction2[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
            else if !Strategy_HoldTrend and direction2[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0 else direction2[1];
#Spark1
plot AvgExp8 = ExpAverage(price[-displace], length8);
def UPD = AvgExp8[1] < AvgExp8;
AvgExp8.SetStyle(Curve.SHORT_DASH);
AvgExp8.SetDefaultColor(CreateColor(255, 128, 0));  #Orange
plot AvgExp9 = ExpAverage(price[-displace], length9);
def UPW = AvgExp9[1] < AvgExp9;
AvgExp9.SetStyle(Curve.SHORT_DASH);
AvgExp9.SetDefaultColor(CreateColor(237, 106, 0));  #Orange
###################################
#SPARK#
###################################
def Below = AvgExp8 < AvgExp9;
def Spark = UPD + UPW + Below;
def UPEMA = AvgExp8[1] < AvgExp8;
def DOWNEMA = AvgExp8[1] > AvgExp8;
def BigUP = direction == 1;
def BigDN = direction == -1;
def BigNa = direction == 0;
AvgExp8.AssignValueColor(if UPEMA then Color.LIGHT_GREEN else if DOWNEMA then Color.RED else Color.YELLOW);
def UPEMA2 = AvgExp9[1] < AvgExp9;
def DOWNEMA2 = AvgExp9[1] > AvgExp9;
def UP8 = UPEMA and UPEMA2;
def DOWN8 = DOWNEMA and DOWNEMA2;
def priceColor8 = if UP8 then 1
                 else if DOWN8 then -1
                 else 0;
def UP11 = UPEMA;
def DOWN11 = DOWNEMA;
def priceColor11 = if UP11 then 1
                 else if DOWN11 then -1
                 else 0;
def UP12 = UPEMA2;
def DOWN12 = DOWNEMA2;
def priceColor12 = if UP12 then 1
                 else if DOWN12 then -1
                 else 0;
def UpCalc = (priceColor == 1) + (priceColor == 1) + (priceColor8 == 1) + (priceColor10 == 1);
def StrongUpCalc = (priceColor == 1) + (priceColor == 1)  + (priceColor10 == 1);
def CandleColor = if (priceColor == 1) and (priceColor12 == 1) and (Spark >= 2) then 1 else
                 if (priceColor == -1) and (Spark < 1) then -1 else 0;
def SparkUP = (Spark == 3) and (CandleColor == 1);
def SparkDN = (Spark == 0) and (CandleColor == -1);
def SparkUP1 = (Spark == 3) and (CandleColor == 1);
def SparkDN1 = (Spark == 0) and (CandleColor == -1);
def hide_SparkUP = if SparkUP1 and (SparkUP1[1] or SparkUP1[2] or SparkUP1[3] or SparkUP1[4] or SparkUP1[5]) then 0 else 1;
def hide_SparkDN = if SparkDN1 and (SparkDN1[1] or SparkDN1[2] or SparkDN1[3] or SparkDN1[4] or SparkDN1[5]) then 0 else 1;
def BigUPs = direction2 == 1 and direction2[1] < 1;
def BigDNs = direction2 == -1 and direction2[1] > -1;
def hide_BigUPs = if BigUPs and (BigUPs[1] or BigUPs[2] or BigUPs[3]) then 1 else 0;
def hide_BigDNs = if BigDNs and (BigDNs[1] or BigDNs[2] or BigDNs[3]) then 1 else 0;

def signal_up_price = if bigups then round(close,2) else signal_up_price[1];
def signal_dn_price = if bigdns then round(close,2) else signal_dn_price[1];
def sigmath = absvalue(signal_up_price - signal_up_price[1]);
def sig2math =  absvalue(signal_up_price - signal_dn_price[1]);
def sig3math =  absvalue(signal_dn_price - signal_dn_price[1]);
def agperiod1 = GetAggregationPeriod();
def timeframe = if agperiod1 <= aggregationperiod.DAY then aggregationperiod.DAY else agperiod1;
def Vol = volume(period = timeframe);
def at_High = high(period = timeframe);
def at_Open = open(period = timeframe);
def at_Close = close(period = timeframe);
def at_Low = low(period = timeframe);
def Vol1 = volume(period = timeframe);
def at_High1 = high(period = timeframe);
def at_Open1 = open(period = timeframe);
def at_Close1 = close(period = timeframe);
def at_Low1 = low(period = timeframe);
def Buy_Volume = RoundUp(Vol * (at_Close - at_Low) / (at_High - at_Low));
def Buy_percent = RoundUp((Buy_Volume / Vol) * 100);
def Sell_Volume = RoundDown(Vol1 * (at_High1 - at_Close1) / (at_High1 - at_Low1));
def Sell_percent = RoundUp((Sell_Volume / Vol1) * 100);
plot avg1 = ExpAverage(close(period = agperiod1), length8);
def height = avg1 - avg1[length8];
avg1.SetStyle(Curve.SHORT_DASH);
avg1.SetLineWeight(1);
def UP1 = avg1[1] < avg1;
def DOWN1 = avg1[1] > avg1;
Avg1.AssignValueColor(if UP1 then Color.LIGHT_GREEN else if DOWN1 then Color.RED else Color.gray);
plot avg2 = ExpAverage(close(period = agperiod1), length8);
def height2 = avg2 - avg2[length10];
avg2.SetStyle(Curve.SHORT_DASH);
avg2.SetLineWeight(1);
def UP2 = avg2[1] < avg2;
def DOWN2 = avg2[1] > avg2;
Avg2.AssignValueColor(if UP2 then Color.LIGHT_GREEN else if DOWN2 then Color.RED else Color.gray);
# --- TRIPLE EXHAUSTION ---
def over_bought_3x = 80;
def over_sold_3x = 20;
def KPeriod_3x = 10;
def DPeriod_3x = 10;
def priceH1 = high(period = agperiod1);
def priceL1 = low(period = agperiod1);
def priceC1 = close(period = agperiod1);
def priceO1 = close(period = agperiod1);
def priceH_3x = high;
def priceL_3x = low;
def priceC_3x = close;    
# --- TRIPLE EXHAUSTION INDICATORS - StochasticSlow / MACD / MACD StDev /DMI+/-
def bn = barnumber();
def SlowK_3x = reference StochasticFull(over_bought_3x, over_sold_3x, KPeriod_3x, DPeriod_3x, priceH_3x, priceL_3x, priceC_3x, 3, averagetype).FullK;
def MACD_3x = reference MACD()."Value";
def priceMean_3x = Average(MACD_3x, length_3x);
def MACD_stdev_3x =  (MACD_3x - priceMean_3x) / StDev(MACD_3x, length_3x);
def dPlus_3x = reference DMI()."DI+";
def dMinus_3x = reference DMI()."DI-";
def sellerRegular = SlowK_3x < 20 and MACD_stdev_3x < -1 and dPlus_3x < 15;
def sellerExtreme = SlowK_3x < 20 and MACD_stdev_3x < -2 and dPlus_3x < 15;
def buyerRegular = SlowK_3x > 80 and MACD_stdev_3x > 1 and dMinus_3x < 15;
def buyerExtreme = SlowK_3x > 80 and MACD_stdev_3x > 2 and dMinus_3x < 15;    
#Arrows/Triggers                                                           
def RegularBuy = if sellerRegular[1] and !sellerRegular then 1 else 0;
def RegularBuy_bn = if RegularBuy then bn else RegularBuy_bn[1];
def ExtremeBuy = if sellerExtreme[1] and !sellerExtreme then 1 else 0;
def ExtremeBuy_bn = if ExtremeBuy then bn else ExtremeBuy_bn[1];
def RegularSell = if buyerRegular[1] and !buyerRegular then 1 else 0;
def RegularSell_bn = if RegularSell then bn else RegularSell_bn[1];
def ExtremeSell = if buyerExtreme[1] and !buyerExtreme then 1 else 0;
def ExtremeSell_bn = if ExtremeSell then bn else ExtremeSell_bn[1];
def Condition1UP = avg1 > avg2;
def Condition1DN = avg1 < avg2;
def Condition2UP = Buy_percent > 50;
def Condition2DN = Buy_percent < 50;
def BullUP = Condition1UP + Condition2UP;
def BearDN = Condition1DN + Condition2DN;
def Bull_Bear = if Condition1UP==1 and Condition2UP == 1 then 1 else if Condition1DN == 1 and Condition2DN == 1 then -1 else 0;
def Condition3UP = if buyerRegular then 1 else 0;
def Condition3DN =  if sellerRegular then 1 else 0;
def Condition4UP =  if buyerExtreme then 1 else 0;
def Condition4DN =  if sellerExtreme then 1 else 0;
def priceColor1 = if ((avg1[1]<avg1) and (avg2[1]<avg2)) then 1
                 else if((avg1[1]>avg1) and (avg2[1]>avg2)) then -1
                 else priceColor[1];
def pd = 22;
def bbl = 20;
def lb = 50;
def ph = 0.85;
def pl = 1.01;
# Downtrend Criterias
def ltLB = 40;
def mtLB = 14;
def str = 3;
def AtrMult_Blst = 1.0;
def nATR_Blst = 4;
def AvgType_Blst = AverageType.HULL;
def trig_Blst = 20;
def pd_Blst = 22;
def bbl_Blst = 20;
def mult = 50;        
def mult_Blst = 2.0;
def lb_Blst = 50;
def ph_Blst = 0.85;
def pl_Blst = 1.01;
def ATR = MovingAverage(AvgType, TrueRange(high, close, low), nATR_Blst);
def UP_B = HL2 + (AtrMult * ATR);
def DN = HL2 + (-AtrMult * ATR);
def ST = if close < ST[1] then UP_B else DN;
def SuperTrend = ST;
def val1 = AbsValue(close - open);
def range = high - low;
def blastOffVal = (val1 / range) * 100;
def trigger = trig;
def alert1 = blastOffVal < trig;
def col = blastOffVal < trig;
def blast_candle = blastOffVal < trig;
# Downtrend Criterias
def ltLB_Blst = 40;
def mtLB_Blst = 14;
def wvf = ((highest(close, pd) - low) / (highest(close, pd))) * 100;
def sDev = mult * stdev(wvf, bbl);
def midLine1 = SimpleMovingAvg(wvf, bbl);
def lowerBand1 = midLine1 - sDev;
def upperBand1 = midLinE1 + sDev;
def rangeHigh = (highest(wvf, lb)) * ph;
#  Filtered Bar Criteria
def upRange = low > low[1] and close > high[1];
def upRange_Aggr = close > close[1] and close > open[1];
def filtered = ((wvf[1] >= upperBand1[1] or wvf[1] >= rangeHigh[1]) and (wvf<upperBand1 and wvf<rangeHigh));
def filtered_Aggr = (wvf[1] >= upperBand1[1] or wvf[1] >= rangeHigh[1]);
# Alerts Criteria 1
def alert4 = upRange_Aggr and close > close[str] and (close < close[ltLB] or close < close[mtLB]) and filtered_Aggr;
def BulgeLengthV = 20;
def SqueezeLengthV = 20;
def BulgeLengthV2 = 20;
def SqueezeLengthV2 = 20;
###################################
##Candle Color
###################################
AssignPriceColor(if Strategy_ColoredCandlesOn then if alert4 and alert4[1] then Color.magenta
else if alert4 then Color.cyan
else if color_OBOS and (C3_LINE_1 OR C3_LINE_2) then Color.YELLOW
else if Color_3x and buyerRegular then Color.green
else if Color_3xt and buyerExtreme then Color.green
else if direction == 1 then Color.LIGHT_GREEN
else if Color_blst and close < ST and blastOffVal < trig then Color.white
else if Color_3x and sellerRegular then Color.dark_red
else if Color_3xt and sellerExtreme then Color.Dark_red
else if direction == -1 then Color.RED
else Color.GRAY
else Color.CURRENT);
###################################
##Plots
###################################

plot TS_UP = if show_ts_signals and upsignal then 1 else 0;   
TS_UP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
TS_UP.AssignValueColor(color.cyan);
plot TS_DN = if show_ts_signals and downsignal then 1 else 0;
TS_DN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
TS_DN.AssignValueColor(Color.cyan); 
plot SparkUP_1 = (SparkUP1 and hide_SparkUP);
SparkUP_1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SparkUP_1.AssignValueColor(Color.green);
plot SparkDN_1 = (SparkDN1 and hide_SparkDN);
SparkDN_1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SparkDN_1.AssignValueColor(Color.Light_red);   
plot signal_up = (direction2 == 1 and direction2[1] < 1);
signal_up.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
signal_up.AssignValueColor(if(direction2 == 1 and direction2[1] < 1)then color.white else color.gray);
signal_up.Hide();
signal_up.HideBubble();
signal_up.HideTitle();
plot signal_dn = (direction2 == -1 and direction2[1] > -1);
signal_dn.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
signal_dn.AssignValueColor(if(direction2 == -1 and direction2[1] > -1) then color.white else color.gray);
signal_dn.Hide();
signal_dn.HideBubble();
signal_dn.HideTitle();
#Ehlers
input ELlength = 34;
def priceE = (high + low) / 2;
def coeff = ELlength * priceE * priceE - 2 * priceE * sum(priceE, ELlength)[1] + sum(priceE * priceE, ELlength)[1];
plot Ehlers = sum(coeff * priceE, ELlength) / sum(coeff, ELlength);
Ehlers.SetDefaultColor(Color.light_gray);
###################################
##Alerts
###################################
Alert(signal_up[1], "Buy", Alert.BAR, Sound.DING);
Alert(signal_dn[1], "Sell", Alert.BAR, Sound.DING);
###################################
##Labels
###################################
def Buy = UP_OS;
def Sell = DOWN_OB;
def conditionLTB = (conditionK2UP and (Consensus_Level < 0));
def conditionLTS = (conditionK3DN and (Consensus_Level > 0));
def conditionBO = ((Upper_BandS[1] < Upper_BandS))
              and ((Lower_BandS[1] < Lower_BandS))
              and ((Upper_BandK[1] < Upper_BandK))
              and ((Lower_BandK[1] < Lower_BandK));
def conditionBD = ((Upper_BandS[1] > Upper_BandS))
              and ((Lower_BandS[1] > Lower_BandS))
              and ((Upper_BandK[1] > Upper_BandK))
              and ((Lower_BandK[1] > Lower_BandK));
# --- C3 LABELS ---      
AddLabel(yes, if conditionLTB then "BULL: Look to Buy"
         else if conditionLTS then "BEAR: Look to Sell"
         else if conditionK2UP then "TREND: BULL"
         else if conditionK3DN then "TREND: BEAR" else "TREND: CONSOLIDATION",
              if conditionLTB then Color.GREEN
         else if conditionLTS then Color.RED
         else if conditionK2UP then Color.LIGHT_GREEN
         else if conditionK3DN then Color.LIGHT_RED else Color.GRAY);
AddLabel(yes, if conditionBD then "BREAKDOWN"
         else if conditionBO then "BREAKOUT" else "NO BREAK",
              if conditionBD then Color.RED
         else if conditionBO then Color.GREEN else Color.GRAY);
def Spark_2_label = yes;
def Spark_3_label = yes;
def Spark_4_label = yes;
#Spark 1
AddLabel(showLabels, if (Spark == 3) then "SPARK: " + Round(Spark, 1)
         else if (Spark == 0) then  "SPARK: " + Round(Spark, 1) else "SPARK: " + Round(Spark, 1),
              if (Spark == 3) then Color.YELLOW
         else if (Spark == 2) then Color.GREEN
         else if (Spark == 0) then Color.RED else Color.GRAY);
#--- END ---
AddLabel(showlabels, if  Condition1UP==1 and Condition2UP == 1 and (Condition3UP == 1 or Condition4UP == 1) then "**CALLS ONLY!**"
else if Condition1UP == 1 and Condition2UP == 1 then "Very Bullish"  
else if direction == 1 then "Bullish"               
else if Condition1DN == 1 and Condition2DN == 1 and (Condition3DN == 1 or Condition4DN == 1) then "**PUTS ONLY!**"
else if Condition1DN == 1 and Condition2DN == 1 then "Very Bearish"
else if direction == -1 then "Bearish"             
else if ((avg[1] > avg) and (avg > avg2) and (Buy_percent > 50)) then "Bullish Retracement"
                else if ((avg[1] < avg) and (avg < avg2) and (Buy_percent < 50)) then "Bearish Retracement" 
                else "CHOP",
                     if Condition1UP == 1 and Condition2UP == 1 and (Condition3UP == 1 or Condition4UP == 1) then Color.cyan
                else if Condition1DN == 1 and Condition2DN == 1 and (Condition3DN == 1 or Condition4DN == 1) then Color.Magenta
                else if Condition1UP == 1 and Condition2UP == 1 then Color.GREEN
else if direction == 1 then Color.green                         
else if Condition1DN == 1 and Condition2DN == 1 then Color.RED
else if direction == -1 then Color.red          
                else Color.orange);
AddLabel(yes, if MomentumUP then "Consensus Increasing = " + Round(Consensus_Level, 1) else if MomentumUP or MomentumDOWN and conditionOB then "Consensus OVERBOUGHT = " + Round(Consensus_Level, 1) else if MomentumDOWN then  "Consensus Decreasing = " + Round(Consensus_Level, 1) else if MomentumUP or MomentumDOWN and conditionOS then "Consensus OVERSOLD = " + Round(Consensus_Level, 1) else "Consensus = " + Round(Consensus_Level, 1), if conditionOB then Color.dark_RED else if conditionOS then Color.dark_GREEN else Color.GRAY);
AddLabel(squeeze_Alert, "SQUEEZE ALERT", if Squeeze_Alert then Color.YELLOW else Color.GRAY);
AddVerticalLine(showverticallineday and( GetDay() <> GetDay()[1]), "", Color.dark_gray, Curve.SHORT_DASH);
def KeylevelOB = if ((BH1extline > YHextlineOB) and (BL1extline < YHextlineOB))then 1 else 0;
def KeylevelOS = if ((BH2extline > YHextlineOS) and (BL2extline < YHextlineOS))then 1 else 0;
def Keylevel2OB = (round(absvalue(close - yhextlineOB),1));
def Keylevel2OS = (round(absvalue(close - yhextlineOS),1));
def Keylevel2OB2 = if (KeyLevel2OB < KeylevelOS) then 1 else 0;
def Keylevel2OS2 = if (KeyLevel2OS < KeylevelOB) then 1 else 0;

AddLabel(keylevel2OS and Keylevel2OS2," Near Key Level ", if keylevel2OS then color.light_green else color.white);
AddLabel(keylevel2OB and Keylevel2OB2," Near Key Level ", if keylevel2OB then color. orange else Color.white);
#how many bounces off the line within the range
input KeyLevelLookback = 5;
def Keylevel_lookback = fold uu = 1 to KeyLevelLookback with pp do pp + keylevel2OS[uu];
input Alert4Lookback = 5;
def alert4_lookback = fold uuu = 1 to Alert4Lookback with ppp do ppp + alert4[uuu];

def keylevelbounce = if Keylevel_lookback and alert4_lookback then 1 else 0;
AddLabel(keylevelbounce," Bounce Incoming ", if keylevel2OB then color. orange else Color.white);




#

lpWS1gE.png


Study Share Link - http://tos.mx/pMiwtkC (4/25/23)

Description
The Confirmation Trend | End All Be All | Chart Style is built upon the foundation of C3_Max_Spark_Filtered, aimed at facilitating a clearer interpretation of price action within the context of key levels. (This study does not repaint)

Levels / Zones
  • Supply & Demand Zones
  • Previously Overbought & Previously Oversold Levels
  • Key Levels
The C3_Max_Spark_Filtered study not only identifies key levels, but also provides insights into momentum, price action, etc. by indicating when EMAs are transitioning (in the process of turning over), known as "Spark," denoted by green and red arrows. Here's an overview of how it operates:

Spark is calculated using two EMAs (10 & 35) and a condition (let’s call it “condition 2”) to account for momentum, price action, etc.
  1. One EMA can be up while the other is down
  2. Both EMAs can be up or down
  3. One EMA crosses over the other
  4. If one of the EMA conditions exist and “condition 2” is true - this creates a spark
  5. There are 3 EMA conditions (see number 1, 2, & 3 above) which is why the Spark label indications Spark 1, 2, or 3
Spark Filter
The study name includes filtereddue to the Spark arrows being filtered in order not to show multiple consecutive arrows (not a major change just makes for a not so busy chart)

Screenshots

UMf1Du8.png

D16RF5f.png

i0KYjcX.png

6eGfyO3.png


Code:
   ##########################################################################################
   ##########################################################################################
   ###                                                                                    ###
   ###       #############################           #########               #########    ###
   ###     #################################         #########               #########    ###
   ###    ####################################       #########               #########    ###                                                                                         
   ###   ########                     #########      #########               #########    ###
   ###   ########    C3_MAX_SPARK     #########      #########               #########    ###                                                                                        
   ###   ########      Filtered       #########      #########               #########    ###
   ###   ########   @Christopher84    #########      #########               #########    ###
   ###   ########                     #########      #########               #########    ###
   ###   ######################################      ##################################   ###
   ###    ####################################       ##################################   ###
   ###     #################################         ##################################   ###
   ###    ####################################       ##################################   ###
   ###   ########                     #########                              #########    ###
   ###   ########                     #########                              #########    ###                                                                                             
   ###   ########                     #########                              #########    ###
   ###   ########                     #########                              #########    ###
   ###   ########                     #########                              #########    ###
   ###   ########                     #########                              #########    ###
   ###    ####################################                               #########    ###
   ###     ##################################                                #########    ###
   ###      ###############################                                  #########    ###
   ###                                                                                    ###
   ##########################################################################################
   ##########################################################################################





# Created by Christopher84 06/30/2022                                                                                          
# Based off of the Confirmation Candles Study. Main difference is that CC Candles weigh factors of positive                                                                                      
# and negative price movement to create the Consensus_Level. The Consensus_Level is considered positive if                                                                                      
# above zero and negative if below zero.                                                                                      
# HODL added spark arrow filter 4/25/23

declare upper;

#input ShowBroadMkt = yes;
input showtitle = no;

AddLabel(showtitle, " C3: ", Color.light_gray);
 
#AssignPriceColor(if ColoredCandlesOn and (priceColor_V5 == 1) then Color.GREEN else if ColoredCandlesOn and (priceColor_V5 == -1) then Color.RED else Color.GRAY);                     
                      
# --- C3 MAX ---                                                                                 
input lengthEL = 23;
#input coloredCandlesOn = no;
input show_elhers = no;
def priceEL = (high + low) / 2;

def coeff = lengthEL * priceEL * priceEL - 2 * priceEL * sum(priceEL, lengthEL)[1] + sum(priceEL * priceEL, lengthEL)[1];

plot Ehlers = sum(coeff * priceEL, lengthEL) / sum(coeff, lengthEL);
Ehlers.SetDefaultColor(Color.Light_gray);
Ehlers.Sethiding(Show_Elhers);


       
input Price = CLOSE;                                                                                      
def ShortLength1 = 5;                                                                                      
def ShortLength2 = 14;                                                                                      
def ShortLength3 = 5;                                                                                      
def LongLength1 = 12;                                                                                      
def LongLength2 = 55;                                                                                      
def LongLength3 = 7;                                                                                      
input Color_Candles = yes;                                                                                      
                                                                                                                                    

# --- TRIPLE EXHAUSTION ---
                                                                                                                                     
input averageType_3x = AverageType.SIMPLE;
input length_3x = 1000;

def over_bought_3x = 80;
def over_sold_3x = 20;
def KPeriod_3x = 10;
def DPeriod_3x = 10;
def priceH_3x = high;
def priceL_3x = low;
def priceC_3x = close;                                                                                                                                                  
                                                                                  
# --- TRIPLE EXHAUSTION INDICATORS - StochasticSlow / MACD / MACD StDev / DMI+/-                                                                               

def SlowK_3x = reference StochasticFull(over_bought_3x, over_sold_3x, KPeriod_3x, DPeriod_3x, priceH_3x, priceL_3x, priceC_3x, 3, averageType_3x).FullK;
def MACD_3x = reference MACD()."Value";
def priceMean_3x = Average(MACD_3x, length_3x);
def MACD_stdev_3x =  (MACD_3x - priceMean_3x) / StDev(MACD_3x, length_3x);
def dPlus_3x = reference DMI()."DI+";
def dMinus_3x = reference DMI()."DI-";

def sellerRegular = SlowK_3x < 20 and MACD_stdev_3x < -1 and dPlus_3x < 15;
def sellerExtreme = SlowK_3x < 20 and MACD_stdev_3x < -2 and dPlus_3x < 15;

def buyerRegular = SlowK_3x > 80 and MACD_stdev_3x > 1 and dMinus_3x < 15;
def buyerExtreme = SlowK_3x > 80 and MACD_stdev_3x > 2 and dMinus_3x < 15;
                                                                                                                                            
# --- Arrows/Triggers                                          
plot ExtremeBuy = if sellerExtreme[1] and !sellerExtreme then low else Double.NaN;
plot RegularBuy = if sellerRegular[1] and !sellerRegular then low else Double.NaN;

plot ExtremeSell = if buyerExtreme[1] and !buyerExtreme then high else Double.NaN;
plot RegularSell = if buyerRegular[1] and !buyerRegular then high else Double.NaN;

def RegularBuy3 = if sellerRegular[1] and !sellerRegular then 1 else 0;
def ExtremeBuy3 = if sellerExtreme[1] and !sellerExtreme then 1 else 0;

def RegularSell3 = if buyerRegular[1] and !buyerRegular then 1 else 0;
def ExtremeSell3 = if buyerExtreme[1] and !buyerExtreme then 1 else 0;


input point_size_3x = 5;
ExtremeBuy.SetLineWeight((point_size_3x));
RegularBuy.SetLineWeight((point_size_3x));
ExtremeSell.SetLineWeight((point_size_3x));
RegularSell.SetLineWeight((point_size_3x));

ExtremeBuy.SetDefaultColor((Color.Light_Green));
RegularBuy.SetDefaultColor((Color.GREEN));
ExtremeSell.SetDefaultColor((Color.Light_REd));
RegularSell.SetDefaultColor((Color.RED));
                                                                                          

RegularBuy.SetPaintingStrategy(PaintingStrategy.POINTS);
ExtremeBuy.SetPaintingStrategy(PaintingStrategy.POINTS);
RegularSell.SetPaintingStrategy(PaintingStrategy.POINTS);
ExtremeSell.SetPaintingStrategy(PaintingStrategy.POINTS);

#addverticalline(x,"",color.cyan);
#addverticalline(RegularSell,"",color.red);
#addverticalline(extremeBuy,"",color.green);
#addverticalline(extremeSell,"",color.dark_red);
 
# --- C3 MAX --- #                                                                                      
                      
# Momentum Oscillators                                                                                      

def MS = Average(Average(price, ShortLength1) - Average(price, ShortLength2), ShortLength3);
def MS2 = Average(Average(price, LongLength1) - Average(price, LongLength2), LongLength3);                                                                                      
                      
# Wave A                                                                                      

def MSGreens = If (MS >= 0, MS, 0);
def MSReds = If (MS < 0, MS, 0);                                                                                      
                      
# Wave C                                                                                      

def MS2Blues = If (MS2 >= 0, MS2, 0);
def MS2Yellows = If (MS2 < 0, MS2, 0);
def MayhemBullish = MSGreens > MSGreens[1] and  MS2Blues > MS2Blues[1];
def MayhemBearish =  MSReds < MSReds[1] and  MS2Yellows < MS2Yellows[1];
def MS_Pos = MSGreens;
def MS_Neg = MSReds;
def MS2_Pos = MS2Blues;
def MS2_Neg = MS2Yellows;                                                                                      
                      
# Squeeze Indicator                                                                                                                                                                                           

def length = 20;
def nK = 1.5;
def nBB = 2.0;
def BBHalfWidth = StDev(price, length);
def KCHalfWidth = nK * Average(TrueRange(high,  close,  low),  length);
def isSqueezed = nBB * BBHalfWidth / KCHalfWidth < 1;
def BBS_Ind = If(isSqueezed, 0, Double.NaN);                                                                                      
                      
# Bollinger Resolution                                                                                      

def BBSMA = Average(price, length);
def BBSMAL = BBSMA + (-nBB * BBHalfWidth);
def BBSMAU = BBSMA + (nBB * BBHalfWidth);
def PerB = RoundUp((price - BBSMAL) / (BBSMAU - BBSMAL) * 100, 0);
 
# Parabolic SAR Signal                                                                                      

input accelerationFactor = 0.0275;
input accelerationLimit = 0.2;

def SAR = ParabolicSAR(accelerationFactor = accelerationFactor, accelerationLimit = accelerationLimit);
def bearishCross = Crosses(SAR, price, CrossingDirection.ABOVE);
def signalDown = bearishCross;#If(bearishCross, 0, Double.NaN);                                                                                      
def bullishCross = Crosses(SAR, price, CrossingDirection.BELOW);
def signalUp =  bullishCross;#If(bullishCross, 0, Double.NaN);                                                                                      
def UP = bullishCross;
def DOWN = bearishCross;
def priceColor = if UP then 1 else if DOWN then -1 else priceColor[1];                                                                                      
                      
# OB_OS_Levels_v5 by Christopher84 12/10/2021                                                                                      

input BarsUsedForRange = 2;
input BarsRequiredToRemainInRange = 2;
input ColorPrice = YES;
input HideTargets = no;
input HideBalance = no;
input HideBoxLines = no;
input HideCloud = no;
input HideLabels = no;                                                                                                                                                                                           
                      
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                      


input trailType23 = {default modified2, unmodified2};

input ATRPeriod23 = 11;

input ATRFactor23 = 2.2;

input firstTrade23 = {default long2, short2};

input averageType23 = AverageType.SIMPLE;

def ATRPeriod = 5;
def ATRFactor = 2.0;


def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1] then high - close[1] else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1] then close[1] - low else (close[1] - low) - 0.5 * (low[1] - high);

def high23 = high;
def low23 = low;
def close23 = close;

def price_V92 = close23;


input trailType = {default modified, unmodified};
def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}

input averageType = AverageType.SIMPLE;
input firstTrade = {default long, short};

def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);
def state = {default init, long, short};

def trail;

switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
case long:
        state = state.long;
        trail =  close - loss;
case short:
        state = state.short;
        trail = close + loss;}
    } else {
        state = state.init;
        trail = Double.NaN;}
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;}
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;}}


Assert(ATRFactor23 > 0, "'atr factor' must be positive: " + ATRFactor23);

def HiLo23 = Min(high23 - low23, 1.5 * Average(high23 - low23, ATRPeriod23));
def HRef23 = if low23 <= high23[1]
    then high23 - close23[1]
    else (high23 - close23[1]) - 0.5 * (low23 - high23[1]);
def LRef23 = if high23 >= low23[1]
    then close23[1] - low23
    else (close23[1] - low23) - 0.5 * (low23[1] - high23);

def trueRange23;
switch (trailType23) {
    case modified2:
        trueRange23 = Max(HiLo23, Max(HRef23, LRef23));
    case unmodified2:
        trueRange23 = TrueRange(high23, close23, low23);
}
def loss23 = ATRFactor23 * MovingAverage(averageType23, trueRange23, ATRPeriod23);

def state23 = {default init2, long2, short2};
def trail23;
switch (state23[1]) {
    case init2:
        if (!IsNaN(loss23)) {
            switch (firstTrade23) {
                case long2:
                    state23 = state23.long2;
                    trail23 = close23 - loss23;
                case short2:
                    state23 = state23.short2;
                    trail23 = close23 + loss23;
            }
        } else {
            state23 = state23.init2;
            trail23 = Double.NaN;
        }
    case long2:
        if (close23 > trail23[1]) {
            state23 = state23.long2;
            trail23 = Max(trail23[1], close23- loss23);
        } else {
            state23 = state23.short2;
            trail23 = close23 + loss23;
        }
    case short2:
        if (close23 < trail23[1]) {
            state23 = state23.short2;
            trail23 = Min(trail23[1], close23 + loss23);
        } else {
            state23 = state23.long2;
            trail23 = close23 - loss23;
        }
}



def TrailingStop23 = trail23;
def LongEnter2 = (price_v92 crosses above TrailingStop23);
def LongExit2 = (price_v92 crosses below TrailingStop23) ;




#Alert(price_v9 crosses above TrailingStop, "long", Alert.BAR, Sound.Ding);
Alert(price_v92 crosses above TrailingStop23, "long", Alert.BAR, Sound.Ding);

#Alert(price_v9 crosses below TrailingStop, "short", Alert.BAR, Sound.Ding);
Alert(price_v92 crosses below TrailingStop23, "short", Alert.BAR, Sound.Ding);

#def upsignal = (price_V9 crosses above TrailingStop);
def upsignal23 = (price_V92 crosses above TrailingStop23);

#def downsignal = (price_v9 crosses below TrailingStop);
def downsignal23 = (price_v92 crosses below TrailingStop23);



def TrailingStop = trail;
def H = Highest(TrailingStop, 12);
def L = Lowest(TrailingStop, 12);
def BulgeLengthPrice = 100;
def SqueezeLengthPrice = 100;
def BandwidthC3 = (H - L);
def IntermResistance2 = Highest(BandwidthC3, BulgeLengthPrice);
def IntermSupport2 = Lowest(BandwidthC3, SqueezeLengthPrice);
def sqzTrigger = BandwidthC3 <= IntermSupport2;
def sqzLevel = if !sqzTrigger[1] and sqzTrigger then hl2                                                                                      
               else if !sqzTrigger then Double.NaN                                                                                      
               else sqzLevel[1];

def TrailingStop233 = trail23;
def H_A1 = Highest(TrailingStop23, 12);
def L_A1 = Lowest(TrailingStop23, 12);
def BulgeLengthPrice_A1 = 100;
def SqueezeLengthPrice_A1 = 100;
def BandwidthC3_A1 = (H_A1 - L_A1);
def IntermResistance2_A1 = Highest(BandwidthC3_A1, BulgeLengthPrice_A1);
def IntermSupport2_A1 = Lowest(BandwidthC3_A1, SqueezeLengthPrice_A1);
def sqzTrigger_A1 = BandwidthC3_A1 <= IntermSupport2_A1;
def sqzLevel_A1 = if !sqzTrigger_A1[1] and sqzTrigger_A1 then hl2                                                                                      
                 else if !sqzTrigger_A1 then Double.NaN                                                                                      
                 else sqzLevel_A1[1];
#input show_Squeeze = no;
plot Squeeze_Alert = sqzLevel;
Squeeze_Alert.SetPaintingStrategy(PaintingStrategy.POINTS);
Squeeze_Alert.SetLineWeight(3);
Squeeze_Alert.SetDefaultColor(Color.YELLOW);

#plot Squeeze_Alert_A1 = sqzLevel_A1 ;
#Squeeze_Alert_A1.SetPaintingStrategy(PaintingStrategy.POINTS);
#Squeeze_Alert_A1.SetLineWeight(3);
#Squeeze_Alert_A1.SetDefaultColor(Color.magenta);

                                                                       
                      
#-----------------------------                                                                                      
#Yellow Candle_height (OB_OS)                                                                                      
#-----------------------------                                                                                      

def displace = 0;
def factorK2 = 3.25;
def lengthK2 = 20;
def price1 = open;
def trueRangeAverageType = AverageType.SIMPLE;
def ATR_length = 15;
def SMA_lengthS = 6;                                                                                      
def ATRPeriod2 = 5;                                                                                      
def ATRFactor2 = 1.5;                                                                                      
                      
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                      

#def ATRPeriod2 = 5;
#def ATRFactor2 = 1.5;

def HiLo2 = Min(high - low, 1.5 * Average(high - low, ATRPeriod));

def HRef2 = if (low <= high[1]) then (high - close[1]) else
               (high - close[1]) - 0.5 * (low - high[1]);

def LRef2 = if (high >= low[1]) then (close[1] - low) else
               (close[1] - low) - 0.5 * (low[1] - high);

def loss2 = ATRFactor2 * MovingAverage(averageType, trueRange, ATRPeriod2);
def multiplier_factor = 1.25;
def valS = Average(price, SMA_lengthS);
def average_true_range = Average(TrueRange(high, close, low), length = ATR_length);
def Upper_BandS = valS[-displace] + multiplier_factor * average_true_range[-displace];
def Middle_BandS = valS[-displace];
def Lower_BandS = valS[-displace] - multiplier_factor * average_true_range[-displace];
def shiftK2 = factorK2 * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK2);
def averageK2 = MovingAverage(averageType, price, lengthK2);
def AvgK2 = averageK2[-displace];
def Upper_BandK2 = averageK2[-displace] + shiftK2[-displace];
def Lower_BandK2 = averageK2[-displace] - shiftK2[-displace];
def condition_BandRevDn = (Upper_BandS > Upper_BandK2);
def condition_BandRevUp = (Lower_BandS < Lower_BandK2);
def fastLength = 12;
def slowLength = 26;
def MACDLength = 9;

input MACD_AverageType = {SMA, default EMA};

def fastEMA = ExpAverage(price, fastLength);
def slowEMA = ExpAverage(price, slowLength);
def Value;
def Avg1;

switch (MACD_AverageType) {
case SMA:
    Value = Average(price, fastLength) - Average(price, slowLength);
    Avg1 = Average(Value, MACDLength);
case EMA:
    Value = fastEMA - slowEMA;
    Avg1 = ExpAverage(Value, MACDLength);}

def Diff = Value - Avg1;
def MACDLevel = 0.0;
def Level = MACDLevel;
def condition1 = Value[1] <= Value;
def condition1D = Value[1] > Value;                                                                                      
                      
#RSI                                                                                      

def RSI_length = 14;
def RSI_AverageType = AverageType.WILDERS;
def RSI_OB = 70;
def RSI_OS = 30;

def NetChgAvg = MovingAverage(RSI_AverageType, price - price[1], RSI_length);
def TotChgAvg = MovingAverage(RSI_AverageType, AbsValue(price - price[1]), RSI_length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
def RSI = 50 * (ChgRatio + 1);

def condition2 = (RSI[3] < RSI) is true or (RSI >= 80) is true;
def condition2D = (RSI[3] > RSI) is true or (RSI < 20) is true;
def conditionOB1 = RSI > RSI_OB;
def conditionOS1 = RSI < RSI_OS;                                                                                      
                      
#MFI                                                                                      

def MFI_Length = 14;
def MFIover_Sold = 20;
def MFIover_Bought = 80;
def movingAvgLength = 1;
def MoneyFlowIndex = Average(MoneyFlow(high, close, low, volume, MFI_Length), movingAvgLength);
def MFIOverBought = MFIover_Bought;
def MFIOverSold = MFIover_Sold;

def condition3 = (MoneyFlowIndex[2] < MoneyFlowIndex) is true or (MoneyFlowIndex > 85) is true;
def condition3D = (MoneyFlowIndex[2] > MoneyFlowIndex) is true or (MoneyFlowIndex < 20) is true;
def conditionOB2 = MoneyFlowIndex > MFIover_Bought;
def conditionOS2 = MoneyFlowIndex < MFIover_Sold;                                                                                      
                      
#Forecast                                                                                      

def na = Double.NaN;
def MidLine = 50;
def Momentum = MarketForecast().Momentum;
def NearT =  MarketForecast().NearTerm;
def Intermed = MarketForecast().Intermediate;
def FOB = 80;
def FOS = 20;
def upperLine = 110;

def condition4 = (Intermed[1] <= Intermed) or (NearT >= MidLine);
def condition4D = (Intermed[1] > Intermed) or (NearT < MidLine);
def conditionOB3 = Intermed > FOB;
def conditionOS3 = Intermed < FOS;
def conditionOB4 = NearT > FOB;
def conditionOS4 = NearT < FOS;                                                                                      
                      
#Change in Price                                                                                      

def lengthCIP = 5;
def CIP = (price - price[1]);
def AvgCIP = ExpAverage(CIP[-displace], lengthCIP);
def CIP_UP = AvgCIP > AvgCIP[1];
def CIP_DOWN = AvgCIP < AvgCIP[1];
def condition5 = CIP_UP;
def condition5D = CIP_DOWN;                                                                                      
                      
#EMA_1                                                                                      

def EMA_length = 8;
def AvgExp = ExpAverage(price[-displace], EMA_length);
def condition6 = (price >= AvgExp) and (AvgExp[2] <= AvgExp);
def condition6D = (price < AvgExp) and (AvgExp[2] > AvgExp);                                                                                      
                      
#EMA_2                                                                                      

def EMA_2length = 20;
def displace2 = 0;
def AvgExp2 = ExpAverage(price[-displace2], EMA_2length);
def condition7 = (price >= AvgExp2) and (AvgExp2[2] <= AvgExp);
def condition7D = (price < AvgExp2) and (AvgExp2[2] > AvgExp);                                                                                      
                      
#DMI Oscillator                                                                                      

def DMI_length = 5;#Typically set to 10                                                                                      
input DMI_averageType = AverageType.WILDERS;
def diPlus = DMI(DMI_length, DMI_averageType)."DI+";
def diMinus = DMI(DMI_length, DMI_averageType)."DI-";
def Osc = diPlus - diMinus;
def Hist = Osc;
def ZeroLine = 0;
def condition8 = Osc >= ZeroLine;
def condition8D = Osc < ZeroLine;                                                                                      
                      
#Trend_Periods                                                                                      

def TP_fastLength = 3;#Typically 7                                                                                      
def TP_slowLength = 4;#Typically 15                                                                                      
def Periods = Sign(ExpAverage(close, TP_fastLength) - ExpAverage(close, TP_slowLength));
def condition9 = Periods > 0;
def condition9D = Periods < 0;                                                                                      
                      
#Polarized Fractal Efficiency                                                                                      

def PFE_length = 5;#Typically 10                                                                                      
def smoothingLength = 2.5;#Typically 5                                                                                      
def PFE_diff = close - close[PFE_length - 1];
def val = 100 * Sqrt(Sqr(PFE_diff) + Sqr(PFE_length)) / Sum(Sqrt(1 + Sqr(close - close[1])), PFE_length - 1);
def PFE = ExpAverage(if PFE_diff > 0 then val else -val, smoothingLength);
def UpperLevel = 50;
def LowerLevel = -50;
def condition10 = PFE > 0;
def condition10D = PFE < 0;
def conditionOB5 = PFE > UpperLevel;
def conditionOS5 = PFE < LowerLevel;                                                                                      
                      
#Bollinger Bands Percent_B                                                                                      

input BBPB_averageType = AverageType.SIMPLE;
def BBPB_length = 20;#Typically 20                                                                                      
def Num_Dev_Dn = -2.0;
def Num_Dev_up = 2.0;
def BBPB_OB = 100;
def BBPB_OS = 0;
def upperBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, BBPB_averageType).UpperBand;
def lowerBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, BBPB_averageType).LowerBand;
def PercentB = (price - lowerBand) / (upperBand - lowerBand) * 100;
def HalfLine = 50;
def UnitLine = 100;
def condition11 = PercentB > HalfLine;
def condition11D = PercentB < HalfLine;
def conditionOB6 = PercentB > BBPB_OB;
def conditionOS6 = PercentB < BBPB_OS;
def condition12 = (Upper_BandS[1] <= Upper_BandS) and (Lower_BandS[1] <= Lower_BandS);
def condition12D = (Upper_BandS[1] > Upper_BandS) and (Lower_BandS[1] > Lower_BandS);                                                                                      
                      
#Klinger Histogram                                                                                      

def Klinger_Length = 13;
def KVOsc = KlingerOscillator(Klinger_Length).KVOsc;
def KVOH = KVOsc - Average(KVOsc, Klinger_Length);
def condition13 = (KVOH > 0);
def condition13D = (KVOH < 0);                                                                                      
                      
#Projection Oscillator                                                                                      

def ProjectionOsc_length = 30;#Typically 10                                                                                      
def MaxBound = HighestWeighted(high, ProjectionOsc_length, LinearRegressionSlope(price = high, length = ProjectionOsc_length));
def MinBound = LowestWeighted(low, ProjectionOsc_length, LinearRegressionSlope(price = low, length = ProjectionOsc_length));
def ProjectionOsc_diff = MaxBound - MinBound;
def PROSC = if ProjectionOsc_diff != 0 then 100 * (close - MinBound) / ProjectionOsc_diff else 0;
def PROSC_OB = 80;
def PROSC_OS = 20;
def condition14 = PROSC > 50;
def condition14D = PROSC < 50;
def conditionOB7 = PROSC > PROSC_OB;
def conditionOS7 = PROSC < PROSC_OS;                                                                                      
                      
#Trend Confirmation Calculator                                                                                      
#Confirmation_Factor range 1-15.                                                                                      

input Confirmation_Factor = 7;                                                                                      
#Use for testing conditions individually. Remove # from line below and change Confirmation_Factor to 1.                                                                                      
#def Agreement_Level = condition1;                                                                                      

def Agreement_LevelOB = 12;
def Agreement_LevelOS = 2;
def factorK = 2.0;

#Spark 1
def lengthK = 20;
def shift = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK);
def averageK = MovingAverage(averageType, price, lengthK);
def AvgK = averageK[-displace];
def Upper_BandK = averageK[-displace] + shift[-displace];
def Lower_BandK = averageK[-displace] - shift[-displace];
#Spark 2
def lengthK_S2 = 20;
def shift_S2 = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK_S2);
def averageK_S2 = MovingAverage(averageType, price, lengthK_S2);
def AvgK_S2 = averageK_S2[-displace];
def Upper_BandK_S2 = averageK_S2[-displace] + shift_S2[-displace];
def Lower_BandK_S2 = averageK_S2[-displace] - shift_S2[-displace];
#Spark 3
def lengthK_S3 = 20;
def shift_S3 = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK_S3);
def averageK_S3 = MovingAverage(averageType, price, lengthK_S3);
def AvgK_S3  = averageK_S3[-displace];
def Upper_BandK_S3  = averageK_S3[-displace] + shift_S3[-displace];
def Lower_BandK_S3  = averageK_S3[-displace] - shift_S3[-displace];
#Spark 4
def lengthK_S4 = 20;
def shift_S4 = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK_S4);
def averageK_S4 = MovingAverage(averageType, price, lengthK_S4);
def AvgK_S4  = averageK_S4[-displace];
def Upper_BandK_S4  = averageK_S4[-displace] + shift_S4[-displace];
def Lower_BandK_S4 = averageK_S4[-displace] - shift_S4[-displace];

def conditionK1UP = price >= Upper_BandK;
def conditionK2UP = (Upper_BandK[1] < Upper_BandK) and (Lower_BandK[1] < Lower_BandK);
def conditionK3DN = (Upper_BandK[1] > Upper_BandK) and (Lower_BandK[1] > Lower_BandK);
def conditionK4DN = price < Lower_BandK;

def Agreement_Level =   condition1 + condition2 + condition3 + condition4 + condition5 +
                        condition6 + condition7 + condition8 + condition9 + condition10 +
                        condition11 + condition12 + condition13 + condition14 + conditionK1UP +
                        conditionK2UP;

def Agreement_LevelD = (condition1D + condition2D + condition3D + condition4D + condition5D +
                        condition6D + condition7D + condition8D + condition9D + condition10D +
                        condition11D + condition12D + condition13D + condition14D + conditionK3DN +
                        conditionK4DN);

def Consensus_Level = Agreement_Level - Agreement_LevelD;

def UP2 = Consensus_Level >= 10;
def DOWN2 = Consensus_Level < -10;
def priceColor2 = if UP2 then 1                                                                                      
                 else if DOWN2 then -1                                                                                      
                 else priceColor2[1];
def Consensus_Level_OB = 10;
def Consensus_Level_OS = -10;                                                                                      
                      
#Super_OB/OS Signal                                                                                      

def OB_Level = conditionOB1 + conditionOB2 + conditionOB3 + conditionOB4 + conditionOB5 + conditionOB6 + conditionOB7;
def OS_Level = conditionOS1 + conditionOS2 + conditionOS3 + conditionOS4 + conditionOS5 + conditionOS6 + conditionOS7;
def Consensus_Line = OB_Level - OS_Level;
def Zero_Line = 0;
def Super_OB = 4;
def Super_OS = -4;
def DOWN_OB = (Agreement_Level > Agreement_LevelOB) and (Consensus_Line > Super_OB) and (Consensus_Level > Consensus_Level_OB);
def UP_OS = (Agreement_Level < Agreement_LevelOS) and (Consensus_Line < Super_OS) and (Consensus_Level < Consensus_Level_OS);
def OS_Buy = UP_OS;
def OB_Sell = DOWN_OB;
def neutral = Consensus_Line < Super_OB and Consensus_Line > Super_OS;

input use_line_limits = yes;#Yes, plots line from/to; No, plot line across entire chart                                                                                      
input linefrom = 100;#Hint linefrom: limits how far line plots in candle area                                                                                      
input lineto   = 12;#Hint lineto: limits how far into expansion the line will plot                                                                                      

def YHOB = if Color_Candles and ((price1 > Upper_BandS) and (condition_BandRevDn)) then high else Double.NaN;
def YHOS = if Color_Candles and ((price1 < Lower_BandS) and (condition_BandRevUp)) then high else Double.NaN;
def YLOB = if Color_Candles and ((price1 > Upper_BandS) and (condition_BandRevDn)) then low else Double.NaN;
def YLOS = if Color_Candles and ((price1 < Lower_BandS) and (condition_BandRevUp)) then low else Double.NaN;                                                                                      
                      
#extend midline of yellow candle                                                                                      

plot YCOB = if !IsNaN(YHOB) then hl2 else Double.NaN;
YCOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOB.SetDefaultColor(Color.GREEN);
def YHextOB = if IsNaN(YCOB) then YHextOB[1] else YCOB;

plot YHextlineOB = YHextOB;
YHextlineOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOB.SetDefaultColor(Color.ORANGE);
YHextlineOB.SetLineWeight(2);

plot YCOS = if !IsNaN(YHOS) then hl2 else Double.NaN;
YCOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOS.SetDefaultColor(Color.GREEN);
def YHextOS = if IsNaN(YCOS) then YHextOS[1] else YCOS;

plot YHextlineOS = YHextOS;
YHextlineOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOS.SetDefaultColor(Color.LIGHT_GREEN);
YHextlineOS.SetLineWeight(2);

def YC = Color_Candles and priceColor2 == 1 and price1 > Upper_BandS and condition_BandRevDn;                                                                                      
                      
#Additional Signals                                                                                      

input showCloud = yes;                                                                                      
#AddCloud(if showCloud and condition_BandRevUp then Lower_BandK2 else Double.NaN,  Lower_BandS,  Color.LIGHT_GREEN,  Color.CURRENT);                                                                                      
#AddCloud(if showCloud and condition_BandRevDn then Upper_BandS else Double.NaN,  Upper_BandK2,  Color.LIGHT_RED,  Color.CURRENT);                                                                                      
                      
# Identify Consolidation                                                                                      

def HH = Highest(high[1], BarsUsedForRange);
def LL = Lowest(low[1], BarsUsedForRange);
def maxH = Highest(HH, BarsRequiredToRemainInRange);
def maxL = Lowest(LL, BarsRequiredToRemainInRange);
def HHn = if maxH == maxH[1] or maxL == maxL then maxH else HHn[1];
def LLn = if maxH == maxH[1] or maxL == maxL then maxL else LLn[1];
def Bh = if high <= HHn and HHn == HHn[1] then HHn else Double.NaN;
def Bl = if low >= LLn and LLn == LLn[1] then LLn else Double.NaN;
def CountH = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountH[1] + 1;
def CountL = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountL[1] + 1;

def ExpH = if BarNumber() == 1 then Double.NaN else                                                                                      
           if CountH[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then HHn[-BarsRequiredToRemainInRange] else                                                                                      
           if high <= ExpH[1] then ExpH[1] else Double.NaN;

def ExpL = if BarNumber() == 1 then Double.NaN else                                                                                      
           if CountL[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then LLn[-BarsRequiredToRemainInRange] else                                                                                      
           if low >= ExpL[1] then ExpL[1] else Double.NaN;                                                                                      
                      
# Plot the High and Low of the Box; Paint Cloud                                                                                      

def BoxHigh = if ((DOWN_OB) or (Upper_BandS crosses above Upper_BandK2)
                            or (condition_BandRevDn) and (high > high[1]) and ((price > Upper_BandK2)
                            or (price > Upper_BandS))) then Highest(ExpH) else Double.NaN;      

def BoxLow = if (DOWN_OB) or ((Upper_BandS crosses above Upper_BandK2)) then Lowest(low) else Double.NaN;                                                             
def BoxHigh2 = if ((UP_OS) or ((Lower_BandS crosses below Lower_BandK2))) then Highest(ExpH) else Double.NaN;
def BH2 = if !IsNaN(BoxHigh2) then high else Double.NaN;
def BH2ext = if IsNaN(BH2) then BH2ext[1] else BH2;
def BH2extline = BH2ext;

plot H_BH2extline = Lowest(BH2extline, 1);
H_BH2extline.SetDefaultColor(Color.GREEN);

def BoxLow2 = if ((UP_OS) or (Lower_BandS crosses below Lower_BandK2)
                          or (condition_BandRevUp) and (low < low[1]) and ((price < Lower_BandK2)
                          or (price < Lower_BandS))) or ((UP_OS[1]) and (low < low[1])) then Lowest(low) else Double.NaN;
                      
# extend the current YCHigh line to the right edge of the chart                                                                                      

def BH1 = if !IsNaN(BoxHigh) then high else Double.NaN;
def BH1ext = if IsNaN(BH1) then BH1ext[1] else BH1;
def BH1extline = BH1ext;
def BL1 = if !IsNaN(BoxLow) then low else Double.NaN;
def BL1ext = if IsNaN(BL1) then BL1ext[1] else BL1;

plot BL1extline = BL1ext;
BL1extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL1extline.SetDefaultColor(Color.RED);
BL1extline.SetLineWeight(1);

def BL2 = if !IsNaN(BoxLow2) then low else Double.NaN;
def BL2ext = if IsNaN(BL2) then BL2ext[1] else BL2;

plot BL2extline = BL2ext;
BL2extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL2extline.SetDefaultColor(Color.GREEN);
BL2extline.SetLineWeight(1);

plot H_BH1extline = Highest(BH1extline, 1);
H_BH1extline.SetDefaultColor(Color.RED);

plot L_BL1extline = Highest(BL1extline, 1);
L_BL1extline.SetDefaultColor(Color.RED);

plot L_BL2extline = Lowest(BL2extline, 1);
L_BL2extline.SetDefaultColor(Color.GREEN);                                                                                                                                                                                                                                      
AddCloud(if !HideCloud then BH1extline else Double.NaN, BL1extline, Color.RED, Color.GRAY);
AddCloud(if !HideCloud then BH2extline else Double.NaN, BL2extline, Color.GREEN, Color.GRAY);



script WMA_Smooth {
    input price_WMA = hl2;
    plot smooth = (4 * price_WMA
+ 3 * price_WMA[1]
+ 2 * price_WMA[2]
+ price_WMA[3]) / 10;
}

script Phase_Accumulation {

# This is Ehler's Phase Accumulation code. It has a full cycle delay.
# However, it computes the correction factor to a very high degree.

    input price_WMA = hl2;

    rec Smooth;
    rec Detrender;
    rec Period;
    rec Q1;
    rec I1;
    rec I1p;
    rec Q1p;
    rec Phase1;
    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase1;
    rec InstPeriod1;
    rec InstPeriod;
    def CorrectionFactor;

    if BarNumber() <= 5
    then {
        Period = 0;
        Smooth = 0;
        Detrender = 0;
        CorrectionFactor = 0;
        Q1 = 0;
        I1 = 0;
        Q1p = 0;
        I1p = 0;
        Phase = 0;
        Phase1 = 0;
        DeltaPhase1 = 0;
        DeltaPhase = 0;
        InstPeriod = 0;
        InstPeriod1 = 0;
    } else {
        CorrectionFactor = 0.075 * Period[1] + 0.54;

# Smooth and detrend my smoothed signal:

        Smooth = WMA_Smooth(price_WMA);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

# Compute Quadrature and Phase of Detrended signal:

        Q1p = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1p = Detrender[3];

# Smooth out Quadrature and Phase:

        I1 = 0.15 * I1p + 0.85 * I1p[1];
        Q1 = 0.15 * Q1p + 0.85 * Q1p[1];

# Determine Phase

        if I1 != 0
        then {

# Normally, ATAN gives results from -pi/2 to pi/2.
# We need to map this to circular coordinates 0 to 2pi

            if Q1 >= 0 and I1 > 0
            then { # Quarant 1
                Phase1 = ATan(AbsValue(Q1 / I1));
            } else if Q1 >= 0 and I1 < 0
            then { # Quadrant 2
                Phase1 = Double.Pi - ATan(AbsValue(Q1 / I1));
            } else if Q1 < 0 and I1 < 0
            then { # Quadrant 3
                Phase1 = Double.Pi + ATan(AbsValue(Q1 / I1));
            } else { # Quadrant 4
                Phase1 = 2 * Double.Pi - ATan(AbsValue(Q1 / I1));
            }
        } else if Q1 > 0
        then { # I1 == 0, Q1 is positive
            Phase1 = Double.Pi / 2;
        } else if Q1 < 0
        then { # I1 == 0, Q1 is negative
            Phase1 = 3 * Double.Pi / 2;
        } else { # I1 and Q1 == 0
            Phase1 = 0;
        }

# Convert phase to degrees

        Phase = Phase1 * 180 / Double.Pi;

        if Phase[1] < 90 and Phase > 270
        then {
# This occurs when there is a big jump from 360-0

            DeltaPhase1 = 360 + Phase[1] - Phase;
        } else {
            DeltaPhase1 = Phase[1] - Phase;
        }

# Limit our delta phases between 7 and 60

        if DeltaPhase1 < 7
        then {
            DeltaPhase = 7;
        } else if DeltaPhase1 > 60
        then {
            DeltaPhase = 60;
        } else {
            DeltaPhase = DeltaPhase1;
        }

# Determine Instantaneous period:

        InstPeriod1 =
-1 * (fold i = 0 to 40 with v=0 do
if v < 0 then
v
else if v > 360 then
-i
else
v + GetValue(DeltaPhase, i, 41));

        if InstPeriod1 <= 0
        then {
            InstPeriod = InstPeriod[1];
        } else {
            InstPeriod = InstPeriod1;
        }

        Period = 0.25 * InstPeriod + 0.75 * Period[1];
    }
    plot DC = Period;
}

script Ehler_MAMA {
    input price_WMA = hl2;
    input FastLimit = 0.5;
    input SlowLimit = 0.05;


    rec Period;
    rec Period_raw;
    rec Period_cap;
    rec Period_lim;

    rec Smooth;
    rec Detrender;
    rec I1;
    rec Q1;
    rec jI;
    rec jQ;
    rec I2;
    rec Q2;
    rec I2_raw;
    rec Q2_raw;

    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase_raw;
    rec alpha;
    rec alpha_raw;

    rec Re;
    rec Im;
    rec Re_raw;
    rec Im_raw;

    rec SmoothPeriod;
    rec vmama;
    rec vfama;

    def CorrectionFactor = Phase_Accumulation(price_WMA).CorrectionFactor;

    if BarNumber() <= 5
    then {
        Smooth = 0;
        Detrender = 0;

        Period = 0;
        Period_raw = 0;
        Period_cap = 0;
        Period_lim = 0;
        I1 = 0;
        Q1 = 0;
        I2 = 0;
        Q2 = 0;
        jI = 0;
        jQ = 0;
        I2_raw = 0;
        Q2_raw = 0;
        Re = 0;
        Im = 0;
        Re_raw = 0;
        Im_raw = 0;
        SmoothPeriod = 0;
        Phase = 0;
        DeltaPhase = 0;
        DeltaPhase_raw = 0;
        alpha = 0;
        alpha_raw = 0;
        vmama = 0;
        vfama = 0;
    } else {

# Smooth and detrend my smoothed signal:

        Smooth = WMA_Smooth(price_WMA);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

        Q1 = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1 = Detrender[3];

        jI = ( 0.0962 * I1
+ 0.5769 * I1[2]
- 0.5769 * I1[4]
- 0.0962 * I1[6] ) * CorrectionFactor;

        jQ = ( 0.0962 * Q1
+ 0.5769 * Q1[2]
- 0.5769 * Q1[4]
- 0.0962 * Q1[6] ) * CorrectionFactor;

# This is the complex conjugate

        I2_raw = I1 - jQ;
        Q2_raw = Q1 + jI;

        I2 = 0.2 * I2_raw + 0.8 * I2_raw[1];
        Q2 = 0.2 * Q2_raw + 0.8 * Q2_raw[1];

        Re_raw = I2 * I2[1] + Q2 * Q2[1];
        Im_raw = I2 * Q2[1] - Q2 * I2[1];

        Re = 0.2 * Re_raw + 0.8 * Re_raw[1];
        Im = 0.2 * Im_raw + 0.8 * Im_raw[1];

# Compute the phase

        if Re != 0 and Im != 0
        then {
            Period_raw = 2 * Double.Pi / ATan(Im / Re);
        } else {
            Period_raw = 0;
        }

        if Period_raw > 1.5 * Period_raw[1]
        then {
            Period_cap = 1.5 * Period_raw[1];
        } else if Period_raw < 0.67 * Period_raw[1] {
            Period_cap = 0.67 * Period_raw[1];
        } else {
            Period_cap = Period_raw;
        }

        if Period_cap < 6
        then {
            Period_lim = 6;
        } else if Period_cap > 50
        then {
            Period_lim = 50;
        } else {
            Period_lim = Period_cap;
        }

        Period = 0.2 * Period_lim + 0.8 * Period_lim[1];
        SmoothPeriod = 0.33 * Period + 0.67 * SmoothPeriod[1];

        if I1 != 0
        then {
            Phase = ATan(Q1 / I1);
        } else if Q1 > 0
        then { # Quadrant 1:
            Phase = Double.Pi / 2;
        } else if Q1 < 0
        then { # Quadrant 4:
            Phase = -Double.Pi / 2;
        } else { # Both numerator and denominator are 0.
            Phase = 0;
        }

        DeltaPhase_raw = Phase[1] - Phase;
        if DeltaPhase_raw < 1
        then {
            DeltaPhase = 1;
        } else {
            DeltaPhase = DeltaPhase_raw;
        }

        alpha_raw = FastLimit / DeltaPhase;
        if alpha_raw < SlowLimit
        then {
            alpha = SlowLimit;
        } else {
            alpha = alpha_raw;
        }
        vmama = alpha * price_WMA + (1 - alpha) * vmama[1];
        vfama = 0.5 * alpha * vmama + (1 - 0.5 * alpha) * vfama[1];
    }

    plot MAMA = vmama;
    plot FAMA = vfama;
}

def price2 = hl2;
def FastLimit = 0.5;
def SlowLimit = 0.05;

def MAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).MAMA;
def FAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).FAMA;

def Crossing = Crosses((MAMA < FAMA), yes);

def Crossing1 = Crosses((MAMA > FAMA), yes);

# --- C3 MAX --- LABELS ---

AddLabel(yes, Concat("MAMA", Concat("",
if MAMA > FAMA then "" else "")),
if MAMA > FAMA then Color.LIGHT_GREEN else Color.LIGHT_RED);


def MF_UP = FAMA < MAMA;
def MF_DN = FAMA > MAMA;
def priceColor10 = if MF_UP then 1
                 else if MF_DN then -1
                 else priceColor10[1];

input extension_length_limited_to = 10;
def lastbar = if IsNaN(close[-1]) and !IsNaN(close) then BarNumber() else Double.NaN;


def length8E = 10;
def length9E = 35;
def length10E = 12;
input show_ema_cloud = no;
def price1E = close;
#input coloredCandlesOn = no;
#def showBreakoutSignals = no;
def displaceE = 0;

def AvgExp8E = ExpAverage(price1E[-displaceE], length8E);
def UPDE = AvgExp8E[1] < AvgExp8E;
#AvgExp8.SetStyle(Curve.SHORT_DASH);
#AvgExp8.SetLineWeight(1);

def AvgExp9E = ExpAverage(price1E[-displaceE], length9E);
def UPWE = AvgExp9E[1] < AvgExp9E;
#AvgExp9.SetStyle(Curve.SHORT_DASH);
#AvgExp9.SetLineWeight(1);

def BelowE = AvgExp8E < AvgExp9E;
def SparkE = UPDE + UPWE + BelowE;

def UPEMAE = AvgExp8E[1] < AvgExp8E;
def DOWNEMAE = AvgExp8E[1] > AvgExp8E;
#AvgExp8.AssignValueColor(if UPEMA then Color.LIGHT_GREEN else if DOWNEMA then Color.RED else Color.YELLOW);

def UPEMA2E = AvgExp9E[1] < AvgExp9E;
def DOWNEMA2E = AvgExp9E[1] > AvgExp9E;
#AvgExp9.AssignValueColor(if UPEMA2 then Color.LIGHT_GREEN else if DOWNEMA2 then Color.RED else Color.YELLOW);

def EMADE = (price1E - AvgExp8E);
def UPEMADE = EMADE >= EMADE[1];
def DOWNEMADE = EMADE < EMADE[1];
#EMAD.AssignValueColor(if UPEMAD then Color.LIGHT_GREEN else if DOWNEMAD then Color.RED else Color.GRAY);

def EMAD2E = (price1E - AvgExp9E);
def UPEMAD2E = EMAD2E >= EMAD2E[1];
def DOWNEMAD2E = EMAD2E < EMAD2E[1];
#EMAD2.AssignValueColor(if UPEMAD2 then Color.White else if DOWNEMAD2 then Color.BLUE else Color.GRAY);

def EMADAvgE = (EMADE + EMAD2E) / 2;
def UPEMADAvgE = EMADAvgE >= EMADAvgE[1];
def DOWNEMADAvgE = EMADAvgE < EMADAvgE[1];
#EMADAvg.AssignValueColor(if UPEMADAvg then Color.LIGHT_GREEN else if DOWNEMADAvg then Color.RED else Color.GRAY);

def EMADSmooth = ExpAverage(EMADAvgE[-displaceE], length10E);


#########################################
input lengthE = 14;
input averageTypeE = AverageType.WILDERS;
def priceE = EMADSmooth;
#def bottom = Min(close[1], low);
#input agperiod1 = AggregationPeriod.DAY;

def oE = (EMADSmooth + EMADSmooth[1]) / 2;

def hE = Max(EMADSmooth, EMADSmooth[1]);

def lE = Min(EMADSmooth, EMADSmooth[1]);

def cE = EMADSmooth;

#def open = open(period = agperiod1);
#def high = high(period = agperiod1);
#def low = low(period = agperiod1);
#def close = close(period = agperiod1);

def bottom = Min(cE[1], lE);
def tr = TrueRange(hE, cE, lE);

def ptr = tr / (bottom + tr / 2);


def APTR = MovingAverage(averageType, ptr, lengthE);
#APTR.SetDefaultColor(GetColor(8));
def UpperBandE = cE[1] + (APTR * oE);
#UpperBand.SetDefaultColor(Color.GRAY);

def LowerBandE = cE[1] - (APTR * oE);
#LowerBand.SetDefaultColor(Color.GRAY);

def MidBand = (UpperBandE + LowerBandE) / 2;
#MidBand.AssignValueColor(if (MidBand > EMADSmooth) then Color.RED else if (MidBand < EMADSmooth) then Color.GREEN else Color.GRAY);
#EMADSmooth.AssignValueColor(if (MidBand > EMADSmooth) then Color.RED else if (MidBand < EMADSmooth) then Color.GREEN else Color.GRAY);

AddCloud(if show_ema_cloud and (MidBand > EMADSmooth) then MidBand else Double.NaN, EMADSmooth, Color.RED, Color.CURRENT);
AddCloud(if show_ema_cloud and (EMADSmooth >= MidBand) then EMADSmooth else Double.NaN, MidBand, Color.GREEN, Color.CURRENT);

def BulgeLength = 100;
def SqueezeLength = 100;
def BulgeLength2 = 200;
def SqueezeLength2 = 200;

#plot ZeroLineE = 0;
#ZeroLineE.AssignValueColor(if (EMADSmooth > ZeroLineE) then Color.GREEN else if (EMADSmooth < ZeroLineE) then Color.RED else Color.YELLOW);

#def EMADSUp = EMADSmooth > ZeroLineE;
#def EMADSDown = EMADSmooth < ZeroLineE;

def EMADdown = (MidBand > EMADSmooth);
def EMADup = (EMADSmooth >= MidBand);

def crossUP = if (MidBand[1] > EMADSmooth[1])and(MidBand < EMADSmooth) then 1 else 0;
def crossDOWN = if (EMADSmooth[1] > MidBand[1])and(EMADSmooth < MidBand) then 1 else 0;

Def ValueUP = if crossup then midband else 0;
Def ValueDown = if crossdown then midband else 0;


#AssignPriceColor (if coloredCandlesOn and (MidBand > EMADSmooth) then Color.RED  else if coloredCandlesOn and (MidBand < EMADSmooth) then Color.GREEN else Color.GRAY);

#Vertical Line
#AddVerticalLine(( GetDay() <> GetDay()[1]), "", Color.Dark_Gray, Curve.SHORT_DASH);

DEF Bulge = Highest(MidBand, BulgeLength);
#Bulge.SetDefaultColor(Color.WHITE);
DEF Squeeze = Lowest(MidBand, SqueezeLength);
#Squeeze.SetDefaultColor(Color.WHITE);
def CrossUPline = if (ValueUP - squeeze) == 0 then 1 else 0;
def CrossDownline = if (ValueDown - bulge) == 0 then 1 else 0;
#EMA_Candles / Spark
#Created by Christopher84 11/30/2021

input showBreakoutSignals = no;

#Spark1 (1min chart)
input length8 = 10;
input length9 = 35;

#Spark2 (5min chart)
#input length8_S2 = 50;
#input length9_S2 = 175;

#Spark3 (10min chart)
#input length8_S3 = 100;
#input length9_S3 = 350;

#input length8_S4 = 100   ;
#input length9_S4 = 2100;

#Spark4 (1hr chart)
def agperiodSPK = getAggregationPeriod();

#Spark2
def length8_S2 = if agperiodSPK == AggregationPeriod.MIN then 20
            else if agperiodSPK == AggregationPeriod.two_MIN then 15
            else if agperiodSPK == AggregationPeriod.three_MIN then 17
            else if agperiodSPK == AggregationPeriod.five_MIN then 20
            else if agperiodSPK == AggregationPeriod.ten_MIN then 15
            else if agperiodSPK == AggregationPeriod.fifteen_MIN then 20
            else if agperiodSPK == AggregationPeriod.thirty_MIN then 20
            else if agperiodSPK == AggregationPeriod.hour then 20
            else if agperiodSPK == AggregationPeriod.two_hours then 20
            else if agperiodSPK == AggregationPeriod.four_hours then 20
            else if agperiodSPK == AggregationPeriod.day then 20
            else AggregationPeriod.thirty_MIN;
 
def length9_S2 = if agperiodSPK == AggregationPeriod.MIN then 70
            else if agperiodSPK == AggregationPeriod.two_MIN then 53
            else if agperiodSPK == AggregationPeriod.three_MIN then 58
            else if agperiodSPK == AggregationPeriod.five_MIN then 70
            else if agperiodSPK == AggregationPeriod.ten_MIN then 53
            else if agperiodSPK == AggregationPeriod.fifteen_MIN then 70
            else if agperiodSPK == AggregationPeriod.thirty_MIN then 70
            else if agperiodSPK == AggregationPeriod.hour then 70
            else if agperiodSPK == AggregationPeriod.two_hours then 70
            else if agperiodSPK == AggregationPeriod.four_hours then 70
            else if agperiodSPK == AggregationPeriod.day then 70
            else AggregationPeriod.thirty_MIN;

#Spark3 (10min chart)
def length8_S3 = if agperiodSPK == AggregationPeriod.MIN then 30
            else if agperiodSPK == AggregationPeriod.two_MIN then 25
            else if agperiodSPK == AggregationPeriod.three_MIN then 33
            else if agperiodSPK == AggregationPeriod.five_MIN then 30
            else if agperiodSPK == AggregationPeriod.ten_MIN then 30
            else if agperiodSPK == AggregationPeriod.fifteen_MIN then 40
            else if agperiodSPK == AggregationPeriod.thirty_MIN then 40
            else if agperiodSPK == AggregationPeriod.hour then 40
            else if agperiodSPK == AggregationPeriod.two_hours then 40
            else if agperiodSPK == AggregationPeriod.four_hours then 40
            else if agperiodSPK == AggregationPeriod.day then 40
            else AggregationPeriod.thirty_MIN;


def length9_S3 = if agperiodSPK == AggregationPeriod.MIN then 105
            else if agperiodSPK == AggregationPeriod.two_MIN then 88
            else if agperiodSPK == AggregationPeriod.three_MIN then 117
            else if agperiodSPK == AggregationPeriod.five_MIN then 105
            else if agperiodSPK == AggregationPeriod.ten_MIN then 105
            else if agperiodSPK == AggregationPeriod.fifteen_MIN then 140
            else if agperiodSPK == AggregationPeriod.thirty_MIN then 140
            else if agperiodSPK == AggregationPeriod.hour then 140
            else if agperiodSPK == AggregationPeriod.two_hours then 140
            else if agperiodSPK == AggregationPeriod.four_hours then 140
            else if agperiodSPK == AggregationPeriod.day then 140
            else AggregationPeriod.thirty_MIN;

#Spark4 (1hr chart)
def length8_S4 = if agperiodSPK == AggregationPeriod.MIN then 50
            else if agperiodSPK == AggregationPeriod.two_MIN then 50
            else if agperiodSPK == AggregationPeriod.three_MIN then 50
            else if agperiodSPK == AggregationPeriod.five_MIN then 60
            else if agperiodSPK == AggregationPeriod.ten_MIN then 60
            else if agperiodSPK == AggregationPeriod.fifteen_MIN then 80
            else if agperiodSPK == AggregationPeriod.thirty_MIN then 80
            else if agperiodSPK == AggregationPeriod.hour then 80
            else if agperiodSPK == AggregationPeriod.two_hours then 80
            else if agperiodSPK == AggregationPeriod.four_hours then 80
            else if agperiodSPK == AggregationPeriod.day then 80
            else AggregationPeriod.thirty_MIN;

def length9_S4 = if agperiodSPK == AggregationPeriod.MIN then 175
            else if agperiodSPK == AggregationPeriod.two_MIN then 175
            else if agperiodSPK == AggregationPeriod.three_MIN then 175
            else if agperiodSPK == AggregationPeriod.five_MIN then 210
            else if agperiodSPK == AggregationPeriod.ten_MIN then 210
            else if agperiodSPK == AggregationPeriod.fifteen_MIN then 280
            else if agperiodSPK == AggregationPeriod.thirty_MIN then 280
            else if agperiodSPK == AggregationPeriod.hour then 280
            else if agperiodSPK == AggregationPeriod.two_hours then 280
            else if agperiodSPK == AggregationPeriod.four_hours then 280
            else if agperiodSPK == AggregationPeriod.day then 280
            else AggregationPeriod.thirty_MIN;



#input show_ema_cloud = yes;
def opacity = 50;

#####################################################################################################################################################

#Spark1
plot AvgExp8 = ExpAverage(price[-displace], length8);
def UPD = AvgExp8[1] < AvgExp8;
AvgExp8.SetStyle(Curve.SHORT_DASH);
AvgExp8.SetDefaultColor(CreateColor(255, 128, 0));  #Orange

plot AvgExp9 = ExpAverage(price[-displace], length9);
def UPW = AvgExp9[1] < AvgExp9;
AvgExp9.SetStyle(Curve.SHORT_DASH);
AvgExp9.SetDefaultColor(CreateColor(237, 106, 0));  #Orange

#Spark2
plot AvgExp8_S2 = ExpAverage(price[-displace], length8_S2);
def UPD_S2 = AvgExp8_S2 [1] < AvgExp8_S2 ;
AvgExp8_S2.SetStyle(Curve.SHORT_DASH);
AvgExp8_S2.SetDefaultColor(CreateColor(221,  88, 0));  #Orange

plot AvgExp9_S2 = ExpAverage(price[-displace], Length9_S2);
def UPW_S2 = AvgExp9_S2[1] < AvgExp9_S2;
AvgExp9_S2.SetStyle(Curve.SHORT_DASH);
AvgExp9_S2.SetDefaultColor(CreateColor(205,  73, 0));  #Orange

#Spark3
plot AvgExp8_S3 = ExpAverage(price[-displace], length8_S3);
def UPD_S3 = AvgExp8_S3 [1] < AvgExp8_S3 ;
AvgExp8_S3.SetStyle(Curve.SHORT_DASH);
AvgExp8_S3.SetDefaultColor(CreateColor(191,  61, 0));  #Orange

plot AvgExp9_S3 = ExpAverage(price[-displace], Length9_S3);
def UPW_S3 = AvgExp9_S3[1] < AvgExp9_S3;
AvgExp9_S3.SetStyle(Curve.SHORT_DASH);
AvgExp9_S3.SetDefaultColor(CreateColor(177,  50, 0));  #Orange

#Spark4
plot AvgExp8_S4 = ExpAverage(price[-displace], length8_S4);
def UPD_S4 = AvgExp8_S4[1] < AvgExp8_S4 ;
AvgExp8_S4.SetStyle(Curve.SHORT_DASH);
AvgExp8_S4.SetDefaultColor(CreateColor(165,  42, 0));  #Orange

plot AvgExp9_S4 = ExpAverage(price[-displace], Length9_S4);
def UPW_S4 = AvgExp9_S4[1] < AvgExp9_S4;
AvgExp9_S4.SetStyle(Curve.SHORT_DASH);
AvgExp9_S4.SetDefaultColor(CreateColor(153,  33, 0));  #Orange


###################################################################################################################################################################
#SPARK#
###################################################################################################################################################

#Spark 1
def Below = AvgExp8 < AvgExp9;
def Spark = UPD + UPW + Below;

def UPEMA = AvgExp8[1] < AvgExp8;
def DOWNEMA = AvgExp8[1] > AvgExp8;

#Spark 2
def Below_Spark_2 = AvgExp8_S2 < AvgExp9_S2;
def Spark_2  = UPD_S2 + UPW_S2 + Below_Spark_2;

def UPEMA_S2  = AvgExp8_S2[1] < AvgExp8_S2;
def DOWNEMA_S2  = AvgExp8_S2[1] > AvgExp8_S2;

#Spark 3
def Below_Spark_3 = AvgExp8_S3 < AvgExp9_S3;
def Spark_3  = UPD_S3 + UPW_S3 + Below_Spark_3;

def UPEMA_S3  = AvgExp8_S3[1] < AvgExp8_S3;
def DOWNEMA_S3  = AvgExp8_S3[1] > AvgExp8_S3;

#Spark 4
def Below_Spark_4 = AvgExp8_S4 < AvgExp9_S4;
def Spark_4  = UPD_S4 + UPW_S4 + Below_Spark_4;

def UPEMA_S4  = AvgExp8_S4[1] < AvgExp8_S4;
def DOWNEMA_S4  = AvgExp8_S4[1] > AvgExp8_S4;

AvgExp8.AssignValueColor(if UPEMA then Color.LIGHT_GREEN else if DOWNEMA then Color.RED else Color.YELLOW);

#Spark 1
def UPEMA2 = AvgExp9[1] < AvgExp9;
def DOWNEMA2 = AvgExp9[1] > AvgExp9;

#Spark 2
def UPEMA2_S2  = AvgExp9_S2[1] < AvgExp9_S2;
def DOWNEMA2_S2  = AvgExp9_S2[1] > AvgExp9_S2;

#Spark 3
def UPEMA2_S3  = AvgExp9_S3 [1] < AvgExp9_S3;
def DOWNEMA2_S3  = AvgExp9_S3 [1] > AvgExp9_S3;

#Spark 4
def UPEMA2_S4  = AvgExp9_S4 [1] < AvgExp9_S4;
def DOWNEMA2_S4  = AvgExp9_S4 [1] > AvgExp9_S4;

AvgExp9.AssignValueColor(if UPEMA2 then Color.LIGHT_GREEN else if DOWNEMA2 then Color.RED else Color.YELLOW);

AddCloud(if show_ema_cloud and (AvgExp9 > AvgExp8) then AvgExp9 else Double.NaN, AvgExp8, Color.LIGHT_RED, Color.CURRENT);
AddCloud(if show_ema_cloud and (AvgExp8 > AvgExp9) then AvgExp8 else Double.NaN,  AvgExp9,  Color.LIGHT_GREEN, Color.CURRENT);

#Spark 1
def UP8 = UPEMA and UPEMA2;
def DOWN8 = DOWNEMA and DOWNEMA2;
def priceColor8 = if UP8 then 1
                 else if DOWN8 then -1
                 else 0;
def UP11 = UPEMA;
def DOWN11 = DOWNEMA;
def priceColor11 = if UP11 then 1
                 else if DOWN11 then -1
                 else 0;
def UP12 = UPEMA2;
def DOWN12 = DOWNEMA2;
def priceColor12 = if UP12 then 1
                 else if DOWN12 then -1
                 else 0;


#Spark 2
def UP8_S2 = UPEMA_S2  and UPEMA2_S2;
def DOWN8_S2 = DOWNEMA_S2  and DOWNEMA2_S2 ;
def priceColor8_S2 = if UP8_S2  then 1
                 else if DOWN8_S2  then -1
                 else 0;
def UP11_S2 = UPEMA_S2 ;
def DOWN11_S2 = DOWNEMA_S2 ;
def priceColor11_S2 = if UP11_S2 then 1
                 else if DOWN11_S2 then -1
                 else 0;
def UP12_S2 = UPEMA2_S2;
def DOWN12_S2 = DOWNEMA2_S2;
def priceColor12_S2 = if UP12_S2 then 1
                 else if DOWN12_S2 then -1
                 else 0;

#Spark 3
def UP8_S3 = UPEMA_S3  and UPEMA2_S3;
def DOWN8_S3 = DOWNEMA_S3  and DOWNEMA2_S3 ;
def priceColor8_S3 = if UP8_S3  then 1
                 else if DOWN8_S3  then -1
                 else 0;
def UP11_S3 = UPEMA_S3 ;
def DOWN11_S3 = DOWNEMA_S3 ;
def priceColor11_S3 = if UP11_S3 then 1
                 else if DOWN11_S2 then -1
                 else 0;
def UP12_S3 = UPEMA2_S3;
def DOWN12_S3 = DOWNEMA2_S3;
def priceColor12_S3 = if UP12_S3 then 1
                 else if DOWN12_S3 then -1
                 else 0;

#Spark 4
def UP8_S4 = UPEMA_S4  and UPEMA2_S4;
def DOWN8_S4 = DOWNEMA_S4  and DOWNEMA2_S4 ;
def priceColor8_S4 = if UP8_S4  then 1
                 else if DOWN8_S4  then -1
                 else 0;
def UP11_S4 = UPEMA_S4 ;
def DOWN11_S4 = DOWNEMA_S4 ;
def priceColor11_S4 = if UP11_S4 then 1
                 else if DOWN11_S2 then -1
                 else 0;
def UP12_S4 = UPEMA2_S4;
def DOWN12_S4 = DOWNEMA2_S4;
def priceColor12_S4 = if UP12_S4 then 1
                 else if DOWN12_S4 then -1
                 else 0;


###################################################################


def UpCalc =  (priceColor == 1) + (priceColor2 == 1) + (priceColor8 == 1) + (priceColor10 == 1);
def StrongUpCalc =  (priceColor == 1) + (priceColor2 == 1)  + (priceColor10 == 1);

#Spark 1
def CandleColor = if (priceColor2 == 1) and (priceColor12 == 1) and (Spark >= 2) then 1 else
                 if (priceColor2 == -1) and (Spark < 1) then -1 else 0;

#Spark 2
def CandleColor_S2 = if (priceColor12_S2 == 1) and (Spark_2 >= 2) then 1 else
                 if (Spark_2 < 1)  then -1 else 0;

#Spark 3
def CandleColor_S3 = if (priceColor12_S3 == 1) and (Spark_3 >= 2) then 1 else
                  if (Spark_3 < 1)  then -1 else 0;

#Spark 4
def CandleColor_S4 = if (priceColor12_S4 == 1) and (Spark_4 >= 2) then 1 else
                  if  (Spark_4 < 1)  then -1 else 0;


#Spark 1
def SparkUP = (Spark == 3) and (CandleColor == 1);
#SparkUP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SparkUP.AssignValueColor(Color.LIGHT_GREEN);

def SparkDN = (Spark == 0) and (CandleColor == -1);
#SparkDN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SparkDN.AssignValueColor(Col
##########################################################################################################
##########################################################################################################
##########################################################################################################


##########################################################################################################
##########################################################################################################
##########################################################################################################


##########################################################################################################
##########################################################################################################
##########################################################################################################


#Spark 1
#plot SparkUP1 = (Spark == 3) and (CandleColor == 1);
#SparkUP1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SparkUP1.AssignValueColor(Color.LIGHT_GREEN);

#plot SparkDN1 = (Spark == 0) and (CandleColor == -1);
#SparkDN1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SparkDN1.AssignValueColor(Color.RED);

#Spark 1
def SparkUP1 = (Spark == 3) and (CandleColor == 1);
#SparkUP1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SparkUP1.AssignValueColor(Color.LIGHT_GREEN);

def SparkDN1 = (Spark == 0) and (CandleColor == -1);
#SparkDN1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SparkDN1.AssignValueColor(Color.RED);
 
#Spark 1
def SparkUP2 = (Spark_2 == 3) and (CandleColor_S2 == 1);
#SparkUP2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SparkUP2.AssignValueColor(Color.GREEN);

def SparkDN2 = (Spark_2 == 0) and (CandleColor_S2  == -1);
#SparkDN2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SparkDN2.AssignValueColor(Color.Light_RED);
 
#Spark
def SparkUP3 = (Spark_3 == 3) and (CandleColor_S3  == 1);
#SparkUP3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SparkUP3.AssignValueColor(Color.white);

def SparkDN3 = (Spark_3 == 0) and (CandleColor_S3  == -1);
#SparkDN3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SparkDN3.AssignValueColor(Color.white);
 
#Spark
def SparkUP4 = (Spark_4 == 3) and (CandleColor_S4  == 1);
#SparkUP4.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SparkUP4.AssignValueColor(Color.blue);

def SparkDN4 = (Spark_4 == 0) and (CandleColor_S4 == -1);
#SparkDN4.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SparkDN4.AssignValueColor(Color.blue);

def hide_SparkUP = if SparkUP1 and (SparkUP1[1] or SparkUP1[2] or SparkUP1[3] or SparkUP1[4] or SparkUP1[5]) then 0 else 1;
def hide_SparkDN = if SparkDN1 and (SparkDN1[1] or SparkDN1[2] or SparkDN1[3] or SparkDN1[4] or SparkDN1[5]) then 0 else 1;

def hide_SparkUP2 = if SparkUP2 and (SparkUP2[1] or SparkUP2[2] or SparkUP2[3] or SparkUP2[4] or SparkUP2[5]) then 0 else 1;
def hide_SparkDN2 = if SparkDN2 and (SparkDN2[1] or SparkDN2[2] or SparkDN2[3] or SparkDN2[4] or SparkDN2[5]) then 0 else 1;

def hide_SparkUP3 = if SparkUP3 and (SparkUP3[1] or SparkUP3[2] or SparkUP3[3] or SparkUP3[4] or SparkUP3[5]) then 0 else 1;
def hide_SparkDN3 = if SparkDN3 and (SparkDN3[1] or SparkDN3[2] or SparkDN3[3] or SparkDN3[4] or SparkDN3[5]) then 0 else 1;

def hide_SparkUP4 = if SparkUP4 and (SparkUP4[1] or SparkUP4[2] or SparkUP4[3] or SparkUP4[4] or SparkUP4[5]) then 0 else 1;
def hide_SparkDN4 = if SparkDN4 and (SparkDN4[1] or SparkDN4[2] or SparkDN4[3] or SparkDN4[4] or SparkDN4[5]) then 0 else 1;

#Spark 1
plot SparkUP_1 = if (SparkUP1 and hide_SparkUP) then 1 else 0;
SparkUP_1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SparkUP_1.AssignValueColor(Color.green);

plot SparkDN_1 = if (SparkDN1 and hide_SparkDN) then 1 else 0;
SparkDN_1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SparkDN_1.AssignValueColor(Color.Light_red);

#plot SparkUP2_2 = if (SparkUP2 and hide_SparkUP2) then 1 else 0;;
#SparkUP2_2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SparkUP2_2.AssignValueColor(Color.PLUM);

#plot SparkDN2_2 =  if (SparkDN2 and hide_SparkDN2) then 1 else 0;;
#SparkDN2_2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SparkDN2_2.AssignValueColor(Color.PLUM);
 
#Spark 1
#plot SparkUP3_3 = if (SparkUP3 and hide_SparkUP3) then 1 else 0;;
#SparkUP3_3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SparkUP3_3.AssignValueColor(Color.white);

#plot SparkDN3_3 =  if (SparkDN3 and hide_SparkDN3) then 1 else 0;;
#SparkDN3_3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SparkDN3_3.AssignValueColor(Color.white);
 
#Spark 1
#plot SparkUP4_4 = if (SparkUP4 and hide_SparkUP4) then 1 else 0;;
#SparkUP4_4.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#SparkUP4_4.AssignValueColor(Color.orange);

#plot SparkDN4_4 =  if (SparkDN4 and hide_SparkDN4) then 1 else 0;;
#SparkDN4_4.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SparkDN4_4.AssignValueColor(Color.orange);                          
               

 
def Buy = UP_OS;
def Sell = DOWN_OB;
def conditionLTB = (conditionK2UP and (Consensus_Level < 0));
def conditionLTS = (conditionK3DN and (Consensus_Level > 0));

def conditionBO = ((Upper_BandS[1] < Upper_BandS))
              and ((Lower_BandS[1] < Lower_BandS))
              and ((Upper_BandK[1] < Upper_BandK))
              and ((Lower_BandK[1] < Lower_BandK));

def conditionBD = ((Upper_BandS[1] > Upper_BandS))
              and ((Lower_BandS[1] > Lower_BandS))
              and ((Upper_BandK[1] > Upper_BandK))
              and ((Lower_BandK[1] > Lower_BandK));

def MomentumUP = Consensus_Level[1] < Consensus_Level;
def MomentumDOWN = Consensus_Level[1] > Consensus_Level;
def Squeeze_Signal = !IsNaN(Squeeze_Alert);
def conditionOB = (Consensus_Level >= 12) and (Consensus_Line >= 4);
def conditionOS = (Consensus_Level <= -12) and (Consensus_Line <= -3);


# --- C3 LABELS ---

AddLabel(yes, if conditionLTB then "BULL: Look to Buy"
         else if conditionLTS then "BEAR: Look to Sell"
         else if conditionK2UP then "TREND: BULL"
         else if conditionK3DN then "TREND: BEAR" else "TREND: CONSOLIDATION",
              if conditionLTB then Color.GREEN
         else if conditionLTS then Color.RED
         else if conditionK2UP then Color.LIGHT_GREEN
         else if conditionK3DN then Color.LIGHT_RED else Color.GRAY);

AddLabel(yes, if conditionBD then "BREAKDOWN"
         else if conditionBO then "BREAKOUT" else "NO BREAK",
              if conditionBD then Color.RED
         else if conditionBO then Color.GREEN else Color.GRAY);
input Spark_1_label = no;
def Spark_2_label = yes;
def Spark_3_label = yes;
def Spark_4_label = yes;

#Spark 1
AddLabel(Spark_1_label, if (Spark == 3) then "SPARK: " + Round(Spark, 1)
         else if (Spark == 0) then  "SPARK: " + Round(Spark, 1) else "SPARK: " + Round(Spark, 1),
              if (Spark == 3) then Color.YELLOW
         else if (Spark == 2) then Color.GREEN
         else if (Spark == 0) then Color.RED else Color.GRAY);

#Spark 2
#AddLabel(Spark_2_label, if (Spark_2 == 3) then "2nd SPARK: " + Round(Spark_2, 1)
#         else if (Spark_2 == 0) then  "2nd SPARK: " + Round(Spark_2, 1) else "2nd SPARK: " + Round(Spark_2, 1),
#              if (Spark_2 == 3) then Color.YELLOW
#         else if (Spark_2 == 2) then Color.GREEN
#         else if (Spark_2 == 0) then Color.RED else Color.GRAY);

#Spark 3
#AddLabel(Spark_3_label, if (Spark_3 == 3) then "3rd SPARK: " + Round(Spark_3, 1)
#         else if (Spark_3 == 0) then  "3rd SPARK: " + Round(Spark_3, 1) else "3rd SPARK: " + Round(Spark_3, 1),
#              if (Spark_3 == 3) then Color.YELLOW
#         else if (Spark_3 == 2) then Color.GREEN
#         else if (Spark_3 == 0) then Color.RED else Color.GRAY);

#Spark 4
#AddLabel(Spark_4_label, if (Spark_4 == 3) then "4th SPARK: " + Round(Spark_4, 1)
#         else if (Spark_4 == 0) then  "4th SPARK: " + Round(Spark_4, 1) else "4th SPARK: " + Round(Spark_4, 1),
#              if (Spark_4 == 3) then Color.YELLOW
#         else if (Spark_4 == 2) then Color.GREEN
#         else if (Spark_4 == 0) then Color.RED else Color.GRAY);
def Squeeze_Bias_UP = if Squeeze_signal and (EMADUP == 1 and (EMADsmooth > zeroline)) then 1 else 0;
def Squeeze_Bias_DN = if Squeeze_signal and (EMADUP == 0 and (EMADsmooth < zeroline)) then 1 else 0;


#AddLabel(yes, if Squeeze_Signal then "SQZ!" else if Squeeze_Bias_UP then "SQZ!" + " | Bias: UP " else if Squeeze_Bias_DN then "SQZ!" + " | Bias: DOWN " else "SQZ!", if Squeeze_Signal then Color.YELLOW else Color.GRAY);
#AddLabel(yes, "SQZ!" + " | Bias: UP ", if Squeeze_Bias_UP then Color.YELLOW else Color.GRAY);
#AddLabel(yes, "SQZ!" + " | Bias: DOWN ", if Squeeze_Bias_DN then Color.YELLOW else Color.GRAY);

#AddLabel(yes, if MomentumUP then "CSNS UP: " + Round(Consensus_Level, 1)
#         else if MomentumUP or MomentumDOWN and conditionOB then "CSNS OB: " + Round(Consensus_Level, 1)
#         else if MomentumDOWN then  "CSNS DOWN:" + Round(Consensus_Level, 1)
#         else if MomentumUP or MomentumDOWN and conditionOS then "CSNS OS: " + Round(Consensus_Level, 1) else "CSNS = " + Round(Consensus_Level, 1),
#              if conditionOB then Color.RED else
#              if conditionOS then Color.GREEN else Color.GRAY);

#AddLabel(yes, Concat("BAND%: ", PerB), if PerB < 0 then Color.YELLOW else if PerB > 0 and PerB[1] < 0 then Color.GREEN else Color.WHITE);                                                                                      


#--- END ---
input hideverticalline = no;
AddVerticalLine(hideverticalline and( GetDay() <> GetDay()[1]), "", Color.Light_gray, Curve.SHORT_DASH);

#--- END ---
 
Last edited:
1ceMljQ.png


Study Share Link - http://tos.mx/hbqFHVK (4/25/23)

Updated share link - https://tos.mx/bpz2CEh (5/4/23) (updated to lessen repaint issues - still have a few things to work out but just make sure the label "Closed Signals Only" is shown if not change setting)

Here is a link to a lower study with ten aggregations I added in attempt to use for testing atr factor and atr period settings - I will not be using this for live trading as it is subject to repaint: https://usethinkscript.com/threads/dashboard-atr-trailing-stop-for-thinkorswim.9375/post-126309

Note concerning repaint workaround:
Currently working on a label where a signal that plots based on a prior ag 2 signal will show “subject to repaint: AG2” until the ag2 bar is closed and same for AG3 signal… however at the moment it only appears for one bar of the current timeframe when at times it should remain for another bar or two - still a work in progress


6/3/23 UPDATE - READ ME: replaced the code with the updated version though it is not functioning quite as intended. The only change is the "subject to repaint" label - however it will also repaint but when the signal appears you will know that it is plotting based on one of the higher aggregation filters that has not closed whereas a signal that appears without the label will (should) not repaint once that bar is closed. Also I would suggest turning off the "wins" label... it does calculate based on the signals shown but since they can repaint until the higher ag is closed it doesn't mean much. For the most part the filtered version is like having the original version open on three different TF charts to see when the signals are close to one another - with the filtered version it just eliminates all the signals in between, the trade off being the possibility of repaint.

Description
The TS_V9_Filtered study is derived from the original TS_V9 strategy based on a modified trailing stop. *** the original TS_V9 on the confirmation candles thread does not repaint as it does not use more than one aggregation - the “filtered” version below can repaint until the 3rd aggregation bar is closed!

Aggregations
The TS_V9_Filtered study consists of 3 aggregations (timeframes):
  • AG 1 = Current chart aggregation
  • AG 2 = adjusts automatically to the next aggregation above AG 1
  • AG 3 = adjusts automatically to the next aggregation above AG 2
Signals & Filter
The AG 1 signal is filtered by previous AG 2 and AG 3 signal direction
  • AG 1 signal condition is true —> and one or more filter condition is true
  • Filter conditions
    • The previous AG 2 signal direction matches the current signal direction
    • The previous AG 3 signal direction matches the current signal direction
The default settings show two labels:
  • Closed Orders - the number of trades (used to calculate the “Wins %”)
  • Wins % - the percentage of winning trades
The following settings will effect the amount of closed orders as well as the wins percent. (Note that after hours on or off will effect orders and wins percent)

Trade Daytime Only - Set to “yes” signals will only plot within the user input times:
  • Open Time - 0930 is default - change to any time before or after market open
  • Close Time - 1600 is default - change to any time before or after market close
Trade Daytime Only - Set to “no” signals will plot at any time available on the chart

ATR Factor & ATR Period - change to effect the location of entry & exit signals
  • How to determine which numbers to use
    • change the numbers at random and comparing the wins % and amount of closed orders
  • Not sure?
    • Use default settings.
AG Skip - AG Skip “on” will cause AG 2 and AG 3 to skip to the nexttimeframe
  • Default setting is off
Show Higher AG - “on” plots signals from AG 2 / AG 3
  • Default setting is off
Disclaimer
Signals can disappear / reappear (repaint) until the bar of the next chart aggregation up or the one above that closes. This is not always the case as the most recent signal can be present several bars before.

Example
If you have the 1min chart open the TS_V9_Filtered study will plot a signal if it agrees with the most recent AG2 or AG3 signal
  • Looking at the 1min chart - AG2 is 2min / AG3 is 3mins - therefore the signal cannot repaint after 2 or 3mins have passed

Screenshots

3lXib0q.png


OfDJ1Fg.png


ABmwxVg.png


8vuZVj1.png


Code:
#TS_V9_Filtered - Modified 4/25/23 to include 2 higher ags to filter lower via previous signal
#TS Strategy_V9 Created by Christopher84 08/10/2021
#Modified 05/23/2022 to include Chart Bubbles and Labels.
#Modified 05/25/2022 to include Targets and Stoplosses.
#Modified 05/26/2022 to include Line Labels by Dcstocks
#Modified 05/27/2022 to include target 7.

input Hide_AG2_Sell = yes; #hint Yes = Do NOT show higher aggregation signals
input Hide_AG2_Buy  = yes; #hint Yes = Do NOT show higher aggregation signals
input show_Last_lbl = yes; #hint Yes = Do NOT show higher aggregation signals

input ag_skip = no;
input ag_skip2 = no;
input ag_skip_lbl = no;

input AutoAgg = yes;
input AutoAgg2 = yes;

input tradeDaytimeOnly = no; #hint tradeDaytimeOnly: (IntraDay Only) Only perform trades during hours stated
input tradeDaytimeOnly2 = no; #hint tradeDaytimeOnly2: (IntraDay Only) Only perform trades during hours stated
input tradeDaytimeOnly3 = no; #hint tradeDaytimeOnly3: (IntraDay Only) Only perform trades during hours stated


input OpenTime = 0930;
input OpenTime2 = 0930;
input OpenTime3 = 0930;
input CloseTime = 1600;
input CloseTime2 = 1600;
input CloseTime3 = 1600;

def coloredCandlesOn = no;
def show_3x = yes;
input length = 23;

input ATRPeriod = 11;
input ATRPeriod2 = 11;
input ATRPeriod3 = 11;

input ATRFactor = 2.2;
input ATRFactor2 = 2.2;
input ATRFactor3 = 2.2;

input bars_back = 10;


#input OpenTime = {"0630","0645","0700","0715","0730","0745","0800","0815","0830","0845","0900","0915",default"0930","0945","1000","1015","1030","1045","1100","1115","1130"};
#input OpenTime2 = {"0630","0645","0700","0715","0730","0745","0800","0815","0830","0845","0900","0915",default"0930","0945","1000","1015","1030","1045","1100","1115","1130"};
#input OpenTime3 = {"0630","0645","0700","0715","0730","0745","0800","0815","0830","0845","0900","0915",default"0930","0945","1000","1015","1030","1045","1100","1115","1130"};

#input CloseTime = {"1230","1245","1300","1315","1330","1345","1400","1415","1430","1445","1500","1515","1530","1545",default "1600","1615","1630","1645","1700","1715","1730", "1745","1800"};
#input CloseTime2 = {"1230","1245","1300","1315","1330","1345","1400","1415","1430","1445","1500","1515","1530","1545",default "1600","1615","1630","1645","1700","1715","1730", "1745","1800"};
#input CloseTime3 = {"1230","1245","1300","1315","1330","1345","1400","1415","1430","1445","1500","1515","1530","1545",default "1600","1615","1630","1645","1700","1715","1730", "1745","1800"};



input trailType = {default modified, unmodified};
input trailType2 = {default modified2, unmodified2};
input trailType3 = {default modified3, unmodified3};

input firstTrade = {default long, short};
input firstTrade2 = {default long2, short2};
input firstTrade3 = {default long3, short3};

input averageType = AverageType.SIMPLE;
def averageType2 = AverageType.SIMPLE;
def averageType3 = AverageType.SIMPLE;

input Market_Open_Lbl = no;
def Market_Open_Lbl2 = no;
def Market_Open_Lbl3 = no;

def Tick_Size_Lbl =  no;
def Tick_Size_Lbl2 = no;
def Tick_Size_Lbl3 = no;

input Long_Short_Lbl =  no;
def Long_Short_Lbl2 = no;
def Long_Short_Lbl3 = no;

input Closed_Orders_Lbl =  yes;
def Closed_Orders_Lbl2 = no;
def Closed_Orders_Lbl3 = no;

input Profit_Lbl =  no;
def Profit_Lbl2 = no;
def Profit_Lbl3 = no;

input PL_Lbl = no;
def PL_Lbl2 = no;
def PL_Lbl3 = no;

input Max_Lbl =  no;
def Max_Lbl2 = no;
def Max_Lbl3 = no;

input Open_Trades_Lbl =  no;
def Open_Trades_Lbl2 = no;
def Open_Trades_Lbl3 = no;

input Profit_Pct_Lbl =  no;
def Profit_Pct_Lbl2 = no;
def Profit_Pct_Lbl3 = no;

input Avg_Per_Lbl =  no;
def Avg_Per_Lbl2 = no;
def Avg_Per_Lbl3 = no;

input LabelsOn = yes;
def LabelsOn2 = no;
def LabelsOn3 = no;

def agperiod1 = GetAggregationPeriod();
def agperiod2 =
                if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.MIN then AggregationPeriod.two_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.MIN then AggregationPeriod.three_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.two_MIN then AggregationPeriod.three_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.two_MIN then AggregationPeriod.five_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.three_MIN then AggregationPeriod.five_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.three_MIN then AggregationPeriod.ten_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.five_MIN then AggregationPeriod.ten_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.five_MIN then AggregationPeriod.fifteen_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.ten_MIN then AggregationPeriod.fifteen_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.ten_MIN then AggregationPeriod.thirty_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.fifteen_MIN then AggregationPeriod.thirty_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.fifteen_MIN then AggregationPeriod.HOUR
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.thirty_MIN then AggregationPeriod.hour
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.thirty_MIN then AggregationPeriod.two_hours
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.hour then AggregationPeriod.two_hours
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.HOUR then AggregationPeriod.four_hours
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.two_hours then AggregationPeriod.four_hours
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.two_HOURS then AggregationPeriod.Day
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.four_hours then AggregationPeriod.day
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.four_HOURS then AggregationPeriod.Week
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.day then AggregationPeriod.week
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.day then AggregationPeriod.month
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.week then AggregationPeriod.month
           else agperiod1[1];

def agperiod3 =
                if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.MIN then AggregationPeriod.two_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.MIN then AggregationPeriod.three_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.two_MIN then AggregationPeriod.three_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.two_MIN then AggregationPeriod.five_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.three_MIN then AggregationPeriod.five_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.three_MIN then AggregationPeriod.ten_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.five_MIN then AggregationPeriod.ten_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.five_MIN then AggregationPeriod.fifteen_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.ten_MIN then AggregationPeriod.fifteen_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.ten_MIN then AggregationPeriod.thirty_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.fifteen_MIN then AggregationPeriod.thirty_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.fifteen_MIN then AggregationPeriod.HOUR
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.thirty_MIN then AggregationPeriod.hour
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.thirty_MIN then AggregationPeriod.two_hours
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.hour then AggregationPeriod.two_hours
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.HOUR then AggregationPeriod.four_hours
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.two_hours then AggregationPeriod.four_hours
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.two_HOURS then AggregationPeriod.Day
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.four_hours then AggregationPeriod.day
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.four_HOURS then AggregationPeriod.Week
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.day then AggregationPeriod.week
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.day then AggregationPeriod.month
           else agperiod2[1];
 

#########################################################################################################################################################


#########################################################################################################################################################

def high2 = high(period = agperiod2);
def low2 = low(period = agperiod2);
def close2 = close(period = agperiod2);

#########################################################################################################################################################


#########################################################################################################################################################

input showSignals = yes; #hint showSignals: show buy and sell arrows
def showSignals2 = yes; #hint showSignals2: show buy and sell arrows
def showSignals3 = yes; #hint showSignals3: show buy and sell arrows

input LongTrades = yes; #hint LongTrades: perform long trades
def LongTrades2 = yes; #hint LongTrades2: perform long trades
def LongTrades3 = yes; #hint LongTrades3: perform long trades

input ShortTrades = yes; #hint ShortTrades: perform short trades
def ShortTrades2 = yes; #hint ShortTrades2: perform short trades
def ShortTrades3 = yes; #hint ShortTrades3: perform short trades

input showLabels  = yes; #hint showLabels: show PL labels at top
def showLabels2 = no; #hint showLabels3: show PL labels at top
def showLabels3 = no; #hint showLabels3: show PL labels at top

input useStops = no;     #hint useStops: use stop orders
def useStops2 = no; #hint useStops2: use stop orders
def useStops3 = no; #hint useStops3: use stop orders

input useAlerts = no;    #hint useAlerts: use alerts on signals
def useAlerts2 = no; #hint useAlerts2: use alerts on signals
def useAlerts3 = no; #hint useAlerts3: use alerts on signals


def high3 = high(period = agperiod3);
def low3 = low(period = agperiod3);
def close3 = close(period = agperiod3);

#########################################################################################################################################################


#########################################################################################################################################################

def price_V9 = close;
def price_V92 = close2;
def price_V93 = close3;

#input coloredCandlesOn = no;
#input coloredCandlesOn2 = no;

#########################################################################################################################################################

def bn = barnumber();

#########################################################################################################################################################

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);

def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);

def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;
    }
}

#########################################################################################################################################################


#########################################################################################################################################################

Assert(ATRFactor2 > 0, "'atr factor' must be positive: " + ATRFactor2);

def HiLo2 = Min(high2 - low2, 1.5 * Average(high2 - low2, ATRPeriod2));
def HRef2 = if low2 <= high2[1]
    then high2 - close2[1]
    else (high2 - close2[1]) - 0.5 * (low2 - high2[1]);
def LRef2 = if high2 >= low2[1]
    then close2[1] - low2
    else (close2[1] - low2) - 0.5 * (low2[1] - high2);

def trueRange2;
switch (trailType2) {
    case modified2:
        trueRange2 = Max(HiLo2, Max(HRef2, LRef2));
    case unmodified2:
        trueRange2 = TrueRange(high2, close2, low2);
}
def loss2 = ATRFactor2 * MovingAverage(averageType2, trueRange2, ATRPeriod2);

def state2 = {default init2, long2, short2};
def trail2;
switch (state2[1]) {
    case init2:
        if (!IsNaN(loss2)) {
            switch (firstTrade2) {
                case long2:
                    state2 = state2.long2;
                    trail2 = close2 - loss2;
                case short2:
                    state2 = state2.short2;
                    trail2 = close2 + loss2;
            }
        } else {
            state2 = state2.init2;
            trail2 = Double.NaN;
        }
    case long2:
        if (close2 > trail2[1]) {
            state2 = state2.long2;
            trail2 = Max(trail2[1], close2 - loss2);
        } else {
            state2 = state2.short2;
            trail2 = close2 + loss2;
        }
    case short2:
        if (close2 < trail2[1]) {
            state2 = state2.short2;
            trail2 = Min(trail2[1], close2 + loss2);
        } else {
            state2 = state2.long2;
            trail2 = close2 - loss2;
        }
}

#########################################################################################################################################################


#########################################################################################################################################################

Assert(ATRFactor3 > 0, "'atr factor' must be positive: " + ATRFactor3);

def HiLo3 = Min(high3 - low3, 1.5 * Average(high3 - low3, ATRPeriod3));
def HRef3 = if low3 <= high3[1]
    then high3 - close3[1]
    else (high3 - close3[1]) - 0.5 * (low3 - high3[1]);
def LRef3 = if high3 >= low3[1]
    then close3[1] - low3
    else (close3[1] - low3) - 0.5 * (low3[1] - high3);

def trueRange3;
switch (trailType3) {
    case modified3:
        trueRange3 = Max(HiLo3, Max(HRef3, LRef3));
    case unmodified3:
        trueRange3 = TrueRange(high3, close3, low3);
}
def loss3 = ATRFactor3 * MovingAverage(averageType3, trueRange3, ATRPeriod3);

def state3 = {default init3, long3, short3};
def trail3;
switch (state3[1]) {
    case init3:
        if (!IsNaN(loss3)) {
            switch (firstTrade3) {
                case long3:
                    state3 = state3.long3;
                    trail3 = close3 - loss3;
                case short3:
                    state3 = state3.short3;
                    trail3 = close3 + loss3;
            }
        } else {
            state3 = state3.init3;
            trail3 = Double.NaN;
        }
    case long3:
        if (close3 > trail3[1]) {
            state3 = state3.long3;
            trail3 = Max(trail3[1], close3 - loss3);
        } else {
            state3 = state3.short3;
            trail3 = close3 + loss3;
        }
    case short3:
        if (close3 < trail3[1]) {
            state3 = state3.short3;
            trail3 = Min(trail3[1], close3 + loss3);
        } else {
            state3 = state3.long3;
            trail3 = close3 - loss3;
        }
}

#########################################################################################################################################################


#########################################################################################################################################################

def TrailingStop = trail;
def LongEnter = (price_v9 crosses above TrailingStop);
def LongExit = (price_v9 crosses below TrailingStop);

def TrailingStop2 = trail2;
def LongEnter2 = (price_v92 crosses above TrailingStop2);
def LongExit2 = (price_v92 crosses below TrailingStop2) ;

def TrailingStop3 = trail3;
def LongEnter3 = (price_v93 crosses above TrailingStop3);
def LongExit3 = (price_v93 crosses below TrailingStop3);

#########################################################################################################################################################


#########################################################################################################################################################

#AssignPriceColor(if coloredCandlesOn and ((price > TrailingStop)) then Color.GREEN else if coloredCandlesOn and ((price < TrailingStop)) then Color.RED else Color.GRAY);
Alert(price_v9 crosses above TrailingStop, "long", Alert.BAR, Sound.Ding);
Alert(price_v92 crosses above TrailingStop2, "long", Alert.BAR, Sound.Ding);
Alert(price_v93 crosses above TrailingStop3, "long", Alert.BAR, Sound.Ding);

Alert(price_v9 crosses below TrailingStop, "short", Alert.BAR, Sound.Ding);
Alert(price_v92 crosses below TrailingStop2, "short", Alert.BAR, Sound.Ding);
Alert(price_v93 crosses below TrailingStop3, "short", Alert.BAR, Sound.Ding);

#########################################################################################################################################################


#########################################################################################################################################################

def upsignal = (price_V9 crosses above TrailingStop);
def upsignal2 = (price_V92 crosses above TrailingStop2);
def upsignal3 = (price_V93 crosses above TrailingStop3);

def downsignal = (price_v9 crosses below TrailingStop);
def downsignal2 = (price_v92 crosses below TrailingStop2);
def downsignal3 = (price_v93 crosses below TrailingStop3);

#########################################################################################################################################################


#########################################################################################################################################################

def Begin = SecondsFromTime(OpenTime);
def End = SecondsTillTime(CloseTime);

def Begin2 = SecondsFromTime(OpenTime2);
def End2 = SecondsTillTime(CloseTime2);

def Begin3 = SecondsFromTime(OpenTime3);
def End3 = SecondsTillTime(CloseTime3);

#########################################################################################################################################################


#########################################################################################################################################################

# Only use market hours when using intraday timeframe
def isIntraDay = if GetAggregationPeriod() > 14400000 or GetAggregationPeriod() == 0 then 0 else 1;
def MarketOpen = if !tradeDaytimeOnly or !isIntraDay then 1 else if tradeDaytimeOnly and isIntraDay and Begin > 0 and End > 0 then 1 else 0;

def isIntraDay2 = if GetAggregationPeriod() > 14400000 or GetAggregationPeriod() == 0 then 0 else 1;
def MarketOpen2 = if !tradeDaytimeOnly2 or !isIntraDay2 then 1 else if tradeDaytimeOnly2 and isIntraDay2 and Begin2 > 0 and End2 > 0 then 1 else 0;

def isIntraDay3 = if GetAggregationPeriod() > 14400000 or GetAggregationPeriod() == 0 then 0 else 1;
def MarketOpen3 = if !tradeDaytimeOnly3 or !isIntraDay3 then 1 else if tradeDaytimeOnly3 and isIntraDay3 and Begin3 > 0 and End3 > 0 then 1 else 0;

######################################################
##  Create Signals -
##  FILL IN THIS SECTION
##      replace 0>0 with your conditions for signals
######################################################

def PLBuySignal_1 = if  MarketOpen and (upsignal) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLBuySignal_1_bn = if PLBuySignal_1 then bn else PLBuySignal_1_bn[1];

def PLBuySignal2_2 = if MarketOpen2 and (Upsignal2) then 1 else 0; # insert condition to create long position in place of the 0>0
def PLBuySignal2_2_bn = if PLBuySignal2_2 then bn else PLBuySignal2_2_bn[1];

def PLBuySignal3_3 = if MarketOpen3 and (Upsignal3) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLBuySignal3_3_bn = if PLBuySignal3_3 then bn else PLBuySignal3_3_bn[1];

###################################################################################

def PLSellSignal_1 =  if MarketOpen and (downsignal) then 1 else 0; # insert condition to create short position in place of the 0>0
def PLSellSignal_1_bn = if PLSellSignal_1 then bn else PLSellSignal_1_bn[1];

def PLSellSignal2_2 = if MarketOpen2 and (downsignal2) then 1 else 0; # insert condition to create short position in place of the 0>0
def PLSellSignal2_2_bn = if PLSellSignal2_2 then bn else PLSellSignal2_2_bn[1];

def PLSellSignal3_3 = if MarketOpen3 and (downsignal3) then 1 else 0; # insert condition to create short position in place of the 0>0
def PLSellSignal3_3_bn = if PLSellSignal3_3 then bn else PLSellSignal3_3_bn[1];

#########################################################################################################################################################

def Prev_Bar_Buy_1 = if (PLBuySignal_1 or PLBuySignal_1[1] or PLBuySignal_1[2] or PLBuySignal_1[3]) then 1 else 0;
def Prev_Bar_Buy_2 = if (PLBuySignal2_2 or PLBuySignal2_2[1] or PLBuySignal2_2[2] or PLBuySignal2_2[3]) then 1 else 0;
def Prev_Bar_Buy_3 = if (PLBuySignal3_3 or PLBuySignal3_3[1] or PLBuySignal3_3[2] or PLBuySignal3_3[3]) then 1 else 0;

def Prev_Bar_Sell_1 = if (PLSellSignal_1 or PLSellSignal_1[1] or PLSellSignal_1[2] or PLSellSignal_1[3]) then 1 else 0;
def Prev_Bar_Sell_2 = if (PLSellSignal2_2 or PLSellSignal2_2[1] or PLSellSignal2_2[2] or PLSellSignal2_2[3]) then 1 else 0;
def Prev_Bar_Sell_3 = if (PLSellSignal3_3 or PLSellSignal3_3[1] or PLSellSignal3_3[2] or PLSellSignal3_3[3]) then 1 else 0;

def Prev_Buy_2 = if upsignal and (PLSellSignal2_2_bn < PLBuySignal2_2_bn) then 1 else 0;
def Prev_Buy_3 = if upsignal and (PLSellSignal3_3_bn < PLBuySignal3_3_bn) then 1 else 0;
def Prev_Buy_4 = if upsignal and (PLSellSignal2_2_bn < PLBuySignal2_2_bn) then 1 else 0;
def Prev_Buy_5 = if upsignal and (PLSellSignal3_3_bn < PLBuySignal3_3_bn) then 1 else 0;

def Prev_Sell_2 = if downsignal and (PLSellSignal2_2_bn > PLBuySignal2_2_bn) then 1 else 0;
def Prev_Sell_3 = if downsignal and (PLSellSignal3_3_bn > PLBuySignal3_3_bn) then 1 else 0;
def Prev_Sell_4 = if downsignal2 and (PLSellSignal2_2_bn > PLBuySignal2_2_bn) then 1 else 0;
def Prev_Sell_5 = if downsignal and (PLSellSignal3_3_bn > PLBuySignal3_3_bn) then 1 else 0;

#########################################################################################################################################################

####################################################
#diff signal same agg bn
####################################################

def Sell_Minus_Buy1_1 = (PLSellSignal_1_bn - PLBuySignal_1_bn);
def Buy_Minus_Sell1_1 = (PLBuySignal_1_bn - PLSellSignal_1_bn);

def Sell2_Minus_Buy2_2 = (PLSellSignal2_2_bn - PLBuySignal2_2_bn);
def Buy2_Minus_Sell2_2 = (PLBuySignal2_2_bn - PLSellSignal2_2_bn);

def Sell3_Minus_Buy3_3 = (PLSellSignal3_3_bn - PLBuySignal3_3_bn);
def Buy3_Minus_Sell3_3 = (PLBuySignal3_3_bn - PLSellSignal3_3_bn);

####################################################
#opposite signal Same ag within x bars
####################################################

def Sell_dist_Buy_1 = Sell_Minus_Buy1_1 >= bars_back;
def Buy_dist_Sell_1 = Buy_Minus_Sell1_1 >= bars_back;

def Sell_dist_Buy_2 = Sell2_Minus_Buy2_2 >= bars_back;
def Buy_dist_Sell_2 = Buy2_Minus_Sell2_2 >= bars_back;

def Sell_dist_Buy_3 = Sell3_Minus_Buy3_3 >= bars_back;
def Buy_dist_Sell_3 = Buy3_Minus_Sell3_3 >= bars_back;

####################################################
#opposite signal higher ag bn
####################################################

def Sell_Minus_Buy2_1 = (PLSellSignal_1_bn - PLBuySignal2_2_bn);
def Buy_Minus_Sell2_1 = (PLBuySignal_1_bn - PLSellSignal2_2_bn);

def Sell_Minus_Buy3_1 = (PLSellSignal_1_bn - PLBuySignal3_3_bn);
def Buy_Minus_Sell3_1 = (PLBuySignal_1_bn - PLSellSignal3_3_bn);

def Sell2_Minus_Buy3_2 = (PLSellSignal2_2_bn - PLBuySignal3_3_bn);
def Buy2_Minus_Sell3_2 = (PLBuySignal2_2_bn - PLSellSignal3_3_bn);

####################################################
#opposite signal higher ag within x bars
####################################################

def Sell_dist_Buy2_1 = Sell_Minus_Buy2_1 >= bars_back;
def Buy_dist_Sell2_1 = Buy_Minus_Sell2_1 >= bars_back;

def Sell_dist_Buy3_3 = Sell_Minus_Buy3_1 >= bars_back;
def Buy_dist_Sell3_3 = Buy_Minus_Sell3_1 >= bars_back;

def Sell2_dist_Buy3_2 = Sell2_Minus_Buy3_2 >= bars_back;
def Buy2_dist_Sell3_2 = Buy2_Minus_Sell3_2 >= bars_back;

####################################################
#same signal higher agg
####################################################

def Sell_Minus_Sell2_1 = (PLSellSignal_1_bn - PLSellSignal2_2_bn);
def Buy_Minus_Buy2_1 = (PLBuySignal_1_bn - PLBuySignal2_2_bn);

def Sell_Minus_Sell3_1 = (PLSellSignal_1_bn - PLSellSignal3_3_bn);
def Buy_Minus_Buy3_1 = (PLBuySignal_1_bn - PLBuySignal3_3_bn);

def Sell2_Minus_Sell3_2 = (PLSellSignal2_2_bn - PLSellSignal3_3_bn);
def Buy2_Minus_Buy3_2 = (PLBuySignal2_2_bn - PLBuySignal3_3_bn);

####################################################
#Same signal higher ag within x bars
####################################################

def Sell_dist_Sell2_1 = Sell_Minus_Sell2_1 >= bars_back;
def Buy_dist_Buy2_1 = Buy_Minus_Buy2_1 >= bars_back;

def Sell_dist_Sell3_1 = Sell_Minus_Sell3_1 >= bars_back;
def Buy_dist_Buy3_1 = Buy_Minus_Buy3_1 >= bars_back;

def Sell2_dist_Sell3_2 = Sell2_Minus_Sell3_2 >= bars_back;
def Buy2_dist_Buy3_2 =  Buy2_Minus_Buy3_2 >= bars_back;

####################################################
#Last signal higher ag
####################################################

def Last_Sell_2 = if downsignal and Sell_Minus_Sell2_1 < Sell_Minus_Buy2_1 then 1 else 0;
def Last_Buy_2 = if upsignal and  Sell_Minus_Sell2_1 > Sell_Minus_Buy2_1 then 1 else 0;

def Last_Sell_3 = if downsignal and  Sell_Minus_Sell3_1 < Sell_Minus_Buy3_1 then 1 else 0;
def Last_Buy_3 = if upsignal and  Sell_Minus_Sell3_1 > Sell_Minus_Buy3_1 then 1 else 0;

def Last2_Sell_3 = if downsignal and  Sell2_Minus_Sell3_2 < Sell2_Minus_Buy3_2 then 1 else 0;
def Last2_Buy_3 = if upsignal and  Sell2_Minus_Sell3_2 > Sell2_Minus_Buy3_2 then 1 else 0;

####################################################
#higher ag prev sell bn > than prev buy bn
####################################################

def SellSig_First_2 = if downsignal and (PLSellSignal2_2_bn > PLBuySignal2_2_bn) then 1 else 0;
def BuySig_First_2 = if upsignal and (PLBuySignal2_2_bn > PLSellSignal2_2_bn) then 1 else 0;

def SellSig_First_3 = if downsignal2 and (PLSellSignal3_3_bn > PLBuySignal3_3_bn) then 1 else 0;
def BuySig_First_3 = if upsignal2 and (PLBuySignal3_3_bn > PLSellSignal3_3_bn) then 1 else 0;

#########################################################################################################################################################



#def PLBuySignal = if  MarketOpen and (upsignal) and (Last_Buy_2 or Last_Buy_3 or Last2_Buy_3) then 1 else 0 ; # insert condition to create long position in place of the 0>0
#def PLSellSignal =  if MarketOpen and (downsignal) and (Last_Sell_2 or Last_Sell_3 or Last2_Sell_3) then 1 else 0; # insert condition to create short position in place of the 0>0

def PLBuySignal_51 = if  MarketOpen and (upsignal) and (BuySig_First_2) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLSellSignal_51 =  if MarketOpen and (downsignal) and (SellSig_First_2) then 1 else 0; # insert condition to create short position in place of the 0>0

def PLSellSignal2 = if MarketOpen2 and (downsignal2) and  (SellSig_First_3)  then 1 else 0; # insert condition to create short position in place of the 0>0
def PLBuySignal2 = if MarketOpen2 and (UPsignal2) and (BuySig_First_3) then 1 else 0; # insert condition to create short position in place of the 0>0

def PLSellSignal3 = if MarketOpen2 and (downsignal3)then 1 else 0; # insert condition to create short position in place of the 0>0
def PLBuySignal3 = if MarketOpen2 and (UPsignal3)then 1 else 0; # insert condition to create short position in place of the 0>0

def PLBuySignal = if (PLBuySignal_51 or PLBuySignal2 or PLBuySignal3) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLSellSignal =  if (PLSellSignal_51 or PLSellSignal2 or PLSellSignal3) then 1 else 0; # insert condition to create short position in place of the 0>0



def PLBuySignal_bn = if PLBuySignal then bn else PLBuySignal_bn[1];
def PLSellSignal_bn = if PLSellSignal then bn else PLSellSignal_bn[1];

#########################################################################################################################################################

def PLBuyStop  = if !useStops then 0 else if  (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0<0
def PLBuyStop2 = if !useStops2 then 0 else if (0 > 0) then 1 else 0 ; # insert condition to stop in place of the 0<0
def PLBuyStop3 = if !useStops3 then 0 else if (0 > 0) then 1 else 0 ; # insert condition to stop in place of the 0<0

def PLSellStop = if !useStops then 0 else if (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0>0
def PLSellStop2 = if !useStops2 then 0 else if (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0>0
def PLSellStop3 = if !useStops3 then 0 else if (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0>0

def PLMktStop = if MarketOpen[-1] == 0 then 1 else 0; # If tradeDaytimeOnly is set, then stop at end of day
def PLMktStop2 = if MarketOpen2[-1] == 0 then 1 else 0; # If tradeDaytimeOnly is set, then stop at end of day
def PLMktStop3 = if MarketOpen3[-1] == 0 then 1 else 0; # If tradeDaytimeOnly is set, then stop at end of day

#########################################################################################################################################################

#########################################################################################################################################################

#######################################
##  Maintain the position of trades
#######################################
# change CurrentPosition to CurrentPosition2, PLBuySignal tp PLBuySignal2, LongTrades to LongTrades2, ShortTrades to ShortTrades2, PLBuyStop to PLBuyStop2, useStops to useStops2, PLMktStop to PLMktStop2

#########################################################################################################################################################


#########################################################################################################################################################

def CurrentPosition;  # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition[1]) {
    CurrentPosition = 0;
} else {
    if CurrentPosition[1] == 0 {            # FLAT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == 1 {      # LONG
        if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else if ((PLBuyStop and useStops) or PLMktStop or (PLSellSignal and ShortTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == -1 {     # SHORT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if ((PLSellStop and useStops) or PLMktStop or (PLBuySignal and LongTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else {
        CurrentPosition = CurrentPosition[1];
    }
}

#########################################################################################################################################################


#########################################################################################################################################################

def CurrentPosition2;  # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition2[1]) {
    CurrentPosition2 = 0;
} else {
    if CurrentPosition2[1] == 0 {            # FLAT
        if (PLBuySignal2 and LongTrades2) {
            CurrentPosition2 = 1;
        } else if (PLSellSignal2 and ShortTrades2) {
            CurrentPosition2 = -1;
        } else {
            CurrentPosition2 = CurrentPosition2[1];
        }
    } else if CurrentPosition2[1] == 1 {      # LONG
        if (PLSellSignal2 and ShortTrades2) {
            CurrentPosition2 = -1;
        } else if ((PLBuyStop2 and useStops2) or PLMktStop2 or (PLSellSignal2 and ShortTrades2 == 0)) {
            CurrentPosition2 = 0;
        } else {
            CurrentPosition2 = CurrentPosition2[1];
        }
    } else if CurrentPosition2[1] == -1 {     # SHORT
        if (PLBuySignal2 and LongTrades2) {
            CurrentPosition2 = 1;
        } else if ((PLSellStop2 and useStops2) or PLMktStop2 or (PLBuySignal2 and LongTrades2 == 0)) {
            CurrentPosition2 = 0;
        } else {
            CurrentPosition2 = CurrentPosition2[1];
        }
    } else {
        CurrentPosition2 = CurrentPosition2[1];
    }
}

#########################################################################################################################################################


#########################################################################################################################################################

def CurrentPosition3;  # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition3[1]) {
    CurrentPosition3 = 0;
} else {
    if CurrentPosition3[1] == 0 {            # FLAT
        if (PLBuySignal3 and LongTrades3) {
            CurrentPosition3 = 1;
        } else if (PLSellSignal3 and ShortTrades3) {
            CurrentPosition3 = -1;
        } else {
            CurrentPosition3 = CurrentPosition3[1];
        }
    } else if CurrentPosition3[1] == 1 {      # LONG
        if (PLSellSignal3 and ShortTrades3) {
            CurrentPosition3 = -1;
        } else if ((PLBuyStop3 and useStops3) or PLMktStop3 or (PLSellSignal3 and ShortTrades3 == 0)) {
            CurrentPosition3 = 0;
        } else {
            CurrentPosition3 = CurrentPosition3[1];
        }
    } else if CurrentPosition3[1] == -1 {     # SHORT
        if (PLBuySignal3 and LongTrades3) {
            CurrentPosition3 = 1;
        } else if ((PLSellStop3 and useStops3) or PLMktStop3 or (PLBuySignal3 and LongTrades3 == 0)) {
            CurrentPosition3 = 0;
        } else {
            CurrentPosition3 = CurrentPosition3[1];
        }
    } else {
        CurrentPosition3 = CurrentPosition3[1];
    }
}

#########################################################################################################################################################


#########################################################################################################################################################

def isLong  = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat  = if CurrentPosition == 0 then 1 else 0;

def isLong2  = if CurrentPosition2 == 1 then 1 else 0;
def isShort2 = if CurrentPosition2 == -1 then 1 else 0;
def isFlat2  = if CurrentPosition2 == 0 then 1 else 0;

def isLong3  = if CurrentPosition3 == 1 then 1 else 0;
def isShort3 = if CurrentPosition3 == -1 then 1 else 0;
def isFlat3  = if CurrentPosition3 == 0 then 1 else 0;




def BuySig = if (((isShort[1] and LongTrades) or (isFlat[1] and LongTrades)) and PLBuySignal and showSignals)  then 1 else 0;
#BuySig.AssignValueColor(Color.cyan);
#BuySig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#BuySig.SetLineWeight(1);
def buysigbn = if BuySig then bn else buysigbn[1];

def BuySig2 = if (((isShort2[1] and LongTrades2) or (isFlat2[1] and LongTrades2)) and PLBuySignal2 and showSignals2) then 1 else 0;
#BuySig2.AssignValueColor(Color.white);
#BuySig2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#BuySig2.SetLineWeight(1);
def buysig2bn = if BuySig2 then bn else buysig2bn[1];

###################################################################################################################################
def BuySig3 = if (((isShort3[1] and LongTrades3) or (isFlat3[1] and LongTrades3)) and PLBuySignal3 and showSignals3) then 1 else 0;
#BuySig3.AssignValueColor(Color.ORANGE);
#BuySig3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#BuySig3.SetLineWeight(1);
def buysig3bn = if BuySig3 then bn else buysig3bn[1];
def buy_11 = if (BuySig ) then 1 else 0;
def buy_21 = if (BuySig or BuySig2 or BuySig3) then 1 else 0;
def buy = if (Hide_AG2_Buy == yes) then Buy_11 else if (Hide_AG2_Buy == no) then buy_21 else buy[1];
#Buy.AssignValueColor(Color.Magenta);
#Buy.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#Buy.SetLineWeight(1);
###################################################################################################################################

Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);

#Plot BuySig2 = if (!isLong[1] and PLBuySignal2 and showSignals2 and LongTrades2) then 1 else 0;

Alert(BuySig2 and useAlerts2, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig2 and useAlerts2, "Buy Signal", Alert.BAR, Sound.Ding);

# If not already short and get a PLSellSignal
def SellSig = if (((isLong[1] and ShortTrades) or (isFlat[1] and ShortTrades)) and PLSellSignal and showSignals) then 1 else 0;
#SellSig.AssignValueColor(Color.cyan);
#SellSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SellSig.SetLineWeight(1);
def Sellsigbn = if SellSig then bn else SellSigbn[1];
#addverticalLine(Sellsig,"",Color.red);

###################################################################################################################################
def SellSig2 = if (((isLong2[1] and ShortTrades2) or (isFlat2[1] and ShortTrades2)) and PLSellSignal2 and showSignals2)then 1 else 0;
#SellSig2.AssignValueColor(Color.white);
#SellSig2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SellSig2.SetLineWeight(1);
def Sellsig2bn = if SellSig2 then bn else SellSig2bn[1];

Alert(BuySig3 and useAlerts3, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig3 and useAlerts3, "Buy Signal", Alert.BAR, Sound.Ding);

def SellSig3 = if (((isLong3[1] and ShortTrades3) or (isFlat3[1] and ShortTrades3)) and PLSellSignal3 and showSignals3) then 1 else 0;
#SellSig3.AssignValueColor(Color.orange);
#SellSig3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#SellSig3.SetLineWeight(1);
def Sellsig3bn = if SellSig3 then bn else SellSig3bn[1];
def Sell_11 = if (SellSig or SellSig2 or SellSig3) then 1 else 0;
def Sell_21 = (SellSig);
def Sell = if (Hide_AG2_Sell == yes) then sell_21  else if (Hide_AG2_Sell == no) then (sell_11) else sell[1] ;
#def Sell = if (SellSig or SellSig2 or SellSig3) then 1 else 0;

#Sell.AssignValueColor(Color.Magenta);
#Sell.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
#Sell.SetLineWeight(1);

def Hide_Sell = if Sell and (Sell[1] or sell[2] or sell[3] or sell[4]) then 0 else 1;
def Hide_Buy = if Buy and (Buy[1] or Buy[2] or Buy[3] or Buy[4]) then 0 else 1;

##################################################################################################################################

plot Sell_1 = if (Sell) and (Hide_Sell == 1) then 1 else 0;
Sell_1.AssignValueColor(Color.cyan);
Sell_1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
Sell_1.SetLineWeight(1);
def sellbn = if sell_1 then bn else sellbn[1];

plot Buy_1 = if (Buy) and (Hide_Buy == 1) then 1 else 0;
Buy_1.AssignValueColor(Color.cyan);
Buy_1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Buy_1.SetLineWeight(1);
def Buybn = if Buy_1 then bn else buybn[1];

##################################################################################################################################


#addchartbubble(BuySig and usealerts,low, "TS", Color.Light_Green,no);
#addchartbubble(SellSig and usealerts,High, "TS", Color.red,no);
Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);
Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);

#If not already short and get a PLSellSignal2


#addchartbubble(BuySig2 and usealerts2,low, "TS", Color.Light_Green,no);
#addchartbubble(SellSig2 and usealerts2,High, "TS", Color.red,no);
#Alert(SellSig2 and useAlerts2, "Sell Signal", Alert
Alert(SellSig2 and useAlerts2, "Sell Signal2", Alert.BAR, Sound.Ding);
Alert(SellSig2 and useAlerts2, "Sell Signal2", Alert.BAR, Sound.Ding);


#addchartbubble(BuySig3 and usealerts3,low, "TS", Color.Light_Green,no);
#addchartbubble(SellSig3 and usealerts3,High, "TS", Color.red,no);
#Alert(SellSig3 and useAlerts3, "Sell Signal", Alert
Alert(SellSig3 and useAlerts3, "Sell Signal3", Alert.BAR, Sound.Ding);
Alert(SellSig3 and useAlerts3, "Sell Signal3", Alert.BAR, Sound.Ding);

###################################################################################################################################

# If long and get a PLBuyStop
plot BuyStpSig = if (PLBuyStop and isLong[1] and showSignals and useStops) or (isLong[1] and PLMktStop) or (isLong[1] and PLSellSignal and !ShortTrades) then 1 else 0;
BuyStpSig.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(1);

Alert(BuyStpSig and useAlerts, "Buy Stop Signal", Alert.BAR, Sound.Ding);
Alert(BuyStpSig and useAlerts, "Buy Stop Signal", Alert.BAR, Sound.Ding);

#If long and get a PLBuyStop
plot BuyStpSig2 = if (PLBuyStop2 and isLong2[1] and showSignals2 and useStops2) or (isLong2[1] and PLMktStop2) or (isLong2[1] and PLSellSignal2 and !ShortTrades2) then 1 else 0;
BuyStpSig2.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig2.SetLineWeight(1);

Alert(BuyStpSig2 and useAlerts2, "Buy Stop Signal", Alert.BAR, Sound.Ding);
Alert(BuyStpSig2 and useAlerts2, "Buy Stop Signal", Alert.BAR, Sound.Ding);

plot BuyStpSig3 = if (PLBuyStop3 and isLong3[1] and showSignals3 and useStops3) or (isLong3[1] and PLMktStop3) or (isLong3[1] and PLSellSignal3 and !ShortTrades3) then 1 else 0;
BuyStpSig3.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig3.SetLineWeight(1);

Alert(BuyStpSig3 and useAlerts3, "Buy Stop Signal", Alert.BAR, Sound.Ding);
Alert(BuyStpSig3 and useAlerts3, "Buy Stop Signal", Alert.BAR, Sound.Ding);

###################################################################################################################################


###################################################################################################################################

# If short and get a PLSellStop
plot SellStpSig = if (PLSellStop and isShort[1] and showSignals and useStops) or (isShort[1] and PLMktStop) or (isShort[1] and PLBuySignal and !LongTrades) then 1 else 0;
SellStpSig.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(1);

Alert(SellStpSig and useAlerts, "Sell Stop Signal", Alert.BAR, Sound.Ding);
Alert(SellStpSig and useAlerts, "Sell Stop Signal", Alert.BAR, Sound.Ding);

#If short and get a PLSellStop
plot SellStpSig2 = if (PLSellStop2 and isShort2[1] and showSignals2 and useStops2) or (isShort2[1] and PLMktStop2) or (isShort2[1] and PLBuySignal2 and !LongTrades2) then 1 else 0;
SellStpSig2.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig2.SetLineWeight(1);

Alert(SellStpSig2 and useAlerts2, "Sell Stop Signal", Alert.BAR, Sound.Ding);
Alert(SellStpSig2 and useAlerts2, "Sell Stop Signal", Alert.BAR, Sound.Ding);

plot SellStpSig3 = if (PLSellStop3 and isShort3[1] and showSignals3 and useStops3) or (isShort3[1] and PLMktStop3) or (isShort3[1] and PLBuySignal3 and !LongTrades3) then 1 else 0;
SellStpSig3.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig3.SetLineWeight(1);

Alert(SellStpSig3 and useAlerts3, "Sell Stop Signal", Alert.BAR, Sound.Ding);
Alert(SellStpSig3 and useAlerts3, "Sell Stop Signal", Alert.BAR, Sound.Ding);

###################################################################################################################################

#######################################
##  Orders
#######################################

def isOrder = if ((isFlat[1] and (BuySig and LongTrades) or (SellSig and ShortTrades)) or (isLong[1] and BuyStpSig or (SellSig and ShortTrades)) or (isShort[1] and SellStpSig or (BuySig and LongTrades))) then 1 else 0 ;
# If there is an order, then the price is the next days close
def orderPrice = if (isOrder and ((BuySig and LongTrades) or (SellSig and ShortTrades))) then close else orderPrice[1];

def orderCount = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if (BuySig or SellSig) then orderCount[1] + 1 else orderCount[1], 0);

def isOrder2 = if ((isFlat2[1] and (BuySig2 and LongTrades2) or (SellSig2 and ShortTrades2)) or (isLong2[1] and BuyStpSig2 or (SellSig2 and ShortTrades2)) or (isShort2[1] and SellStpSig2 or (BuySig2 and LongTrades2))) then 1 else 0 ;

#If there is an order, then the price is the next days close
def orderPrice2 = if (isOrder2 and ((BuySig2 and LongTrades2) or (SellSig2 and ShortTrades2))) then close2 else orderPrice2[1];

def orderCount2 = CompoundValue(1, if IsNaN(isOrder2) or BarNumber() == 1 then 0 else if (BuySig2 or SellSig2) then orderCount2[1] + 1 else orderCount2[1], 0);

def isOrder3 = if ((isFlat3[1] and (BuySig3 and LongTrades3) or (SellSig3 and ShortTrades3)) or (isLong3[1] and BuyStpSig3 or (SellSig3 and ShortTrades3)) or (isShort3[1] and SellStpSig3 or (BuySig3 and LongTrades3))) then 1 else 0 ;

#If there is an order, then the price is the next days close
def orderPrice3 = if (isOrder3 and ((BuySig3 and LongTrades3) or (SellSig3 and ShortTrades3))) then close3 else orderPrice3[1];

def orderCount3 = CompoundValue(1, if IsNaN(isOrder3) or BarNumber() == 1 then 0 else if (BuySig3 or SellSig3) then orderCount3[1] + 1 else orderCount3[1], 0);

#######################################
##  Price and Profit
#######################################

def profitLoss;

if (!isOrder or orderPrice[1] == 0) {
    profitLoss = 0;
} else if ((isOrder and isLong[1]) and (SellSig or BuyStpSig)) {
    profitLoss = close - orderPrice[1];
} else if ((isOrder and isShort[1]) and (BuySig or SellStpSig)) {
    profitLoss = orderPrice[1] - close;
} else {
    profitLoss = 0;
}

def profitLoss2;

if (!isOrder2 or orderPrice2[1] == 0) {
profitLoss2 = 0;
} else if ((isOrder2 and isLong2[1]) and (SellSig2 or BuyStpSig2)) {
profitLoss2 = close2 - orderPrice2[1];
} else if ((isOrder2 and isShort2[1]) and (BuySig2 or SellStpSig2)) {
profitLoss2 = orderPrice2[1] - close2;
} else {
profitLoss2 = 0;
}

def profitLoss3;

if (!isOrder3 or orderPrice3[1] == 0) {
profitLoss3 = 0;
} else if ((isOrder3 and isLong3[1]) and (SellSig3 or BuyStpSig3)) {
profitLoss3 = close3 - orderPrice3[1];
} else if ((isOrder3 and isShort3[1]) and (BuySig3 or SellStpSig3)) {
profitLoss3 = orderPrice3[1] - close3;
} else {
profitLoss3 = 0;
}

# Total Profit or Loss
def profitLossSum = CompoundValue(1, if IsNaN(isOrder)  or BarNumber() == 1 then 0 else if isOrder then profitLossSum[1] + profitLoss else profitLossSum[1], 0);

#Total Profit or Loss
def profitLossSum2 = CompoundValue(1, if IsNaN(isOrder2) or BarNumber() == 1 then 0 else if isOrder2 then profitLossSum2[1] + profitLoss2 else profitLossSum2[1], 0);

#Total Profit or Loss
def profitLossSum3 = CompoundValue(1, if IsNaN(isOrder3) or BarNumber() == 1 then 0 else if isOrder3 then profitLossSum3[1] + profitLoss3 else profitLossSum3[1], 0);

# How many trades won or lost
def profitWinners = CompoundValue(1, if IsNaN(profitWinners[1]) or BarNumber() == 1 then 0 else if isOrder and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1], 0);
def profitLosers = CompoundValue(1, if IsNaN(profitLosers[1])  or BarNumber() == 1 then 0 else if isOrder and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1], 0);
def profitPush = CompoundValue(1, if IsNaN(profitPush[1])  or BarNumber() == 1 then 0 else if isOrder and profitLoss == 0 then profitPush[1] + 1 else profitPush[1], 0);

#How many trades won or lost
def profitWinners2 = CompoundValue(1, if IsNaN(profitWinners2[1]) or BarNumber() == 1 then 0 else if isOrder2 and profitLoss2 > 0 then profitWinners2[1] + 1 else profitWinners2[1], 0);
def profitLosers2 = CompoundValue(1, if IsNaN(profitLosers2[1]) or BarNumber() == 1 then 0 else if isOrder2 and profitLoss2 < 0 then profitLosers2[1] + 1 else profitLosers2[1], 0);
def profitPush2 = CompoundValue(1, if IsNaN(profitPush2[1]) or BarNumber() == 1 then 0 else if isOrder2 and profitLoss2 == 0 then profitPush2[1] + 1 else profitPush2[1], 0);

#How many trades won or lost
def profitWinners3 = CompoundValue(1, if IsNaN(profitWinners3[1]) or BarNumber() == 1 then 0 else if isOrder3 and profitLoss3 > 0 then profitWinners3[1] + 1 else profitWinners3[1], 0);
def profitLosers3 = CompoundValue(1, if IsNaN(profitLosers3[1]) or BarNumber() == 1 then 0 else if isOrder3 and profitLoss3 < 0 then profitLosers3[1] + 1 else profitLosers3[1], 0);
def profitPush3 = CompoundValue(1, if IsNaN(profitPush3[1]) or BarNumber() == 1 then 0 else if isOrder3 and profitLoss3 == 0 then profitPush3[1] + 1 else profitPush3[1], 0);

# Current Open Trade Profit or Loss
def TradePL = if isLong then Round(((close - orderPrice) / TickSize()) * TickValue()) else if isShort then Round(((orderPrice - close) / TickSize()) * TickValue()) else 0;

#Current Open Trade Profit or Loss
def TradePL2 = if isLong2 then Round(((close2 - orderPrice2) / TickSize()) * TickValue()) else if isShort2 then Round(((orderPrice2 - close2) / TickSize()) * TickValue()) else 0;

#Current Open Trade Profit or Loss
def TradePL3 = if isLong3 then Round(((close3 - orderPrice3) / TickSize()) * TickValue()) else if isShort3 then Round(((orderPrice3 - close3) / TickSize()) * TickValue()) else 0;

# Convert to actual dollars based on Tick Value for bubbles
def dollarProfitLoss = if orderPrice[1] == 0 or IsNaN(orderPrice[1]) then 0 else Round((profitLoss / TickSize()) * TickValue());

#Convert to actual dollars based on Tick Value for bubbles
def dollarProfitLoss2 = if orderPrice2[1] == 0 or IsNaN(orderPrice2[1]) then 0 else Round((profitLoss2 / TickSize()) * TickValue());

#Convert to actual dollars based on Tick Value for bubbles
def dollarProfitLoss3 = if orderPrice3[1] == 0 or IsNaN(orderPrice3[1]) then 0 else Round((profitLoss3 / TickSize()) * TickValue());

# Closed Orders dollar P/L
def dollarPLSum = Round((profitLossSum / TickSize()) * TickValue());

#Closed Orders dollar P/L
def dollarPLSum2 = Round((profitLossSum2 / TickSize()) * TickValue());

#Closed Orders dollar P/L
def dollarPLSum3 = Round((profitLossSum3 / TickSize()) * TickValue());

# Split profits or losses by long and short trades
def profitLong = CompoundValue(1, if IsNaN(profitLong[1])  or BarNumber() == 1 then 0 else if isOrder and isLong[1] then profitLong[1] + dollarProfitLoss else profitLong[1], 0);
def profitLong2 = CompoundValue(1, if IsNaN(profitLong2[1]) or BarNumber() == 1 then 0 else if isOrder2 and isLong2[1] then profitLong2[1] + dollarProfitLoss2 else profitLong2[1],0);
def profitLong3 = CompoundValue(1, if IsNaN(profitLong3[1]) or BarNumber() == 1 then 0 else if isOrder3 and isLong3[1] then profitLong3[1] + dollarProfitLoss3 else profitLong3[1], 0);

def profitShort = CompoundValue(1, if IsNaN(profitShort[1])  or BarNumber() == 1 then 0 else if isOrder and isShort[1] then profitShort[1] + dollarProfitLoss else profitShort[1],0);
def profitShort2 = CompoundValue(1, if IsNaN(profitShort2[1]) or BarNumber() == 1 then 0 else if isOrder2 and isShort2[1] then profitShort2[1] + dollarProfitLoss2 else profitShort2[1], 0);
def profitShort3 = CompoundValue(1, if IsNaN(profitShort3[1]) or BarNumber() == 1 then 0 else if isOrder3 and isShort3[1] then profitShort3[1] + dollarProfitLoss3 else profitShort3[1], 0);

def countLong = CompoundValue(1, if IsNaN(countLong[1])  or BarNumber() == 1 then 0 else if isOrder and isLong[1] then countLong[1] + 1 else countLong[1], 0);
def countLong2 = CompoundValue(1, if IsNaN(countLong2[1]) or BarNumber() == 1 then 0 else if isOrder2 and isLong2[1] then countLong2[1] + 1 else countLong2[1], 0);
def countLong3 = CompoundValue(1, if IsNaN(countLong3[1]) or BarNumber() == 1 then 0 else if isOrder3 and isLong3[1] then countLong3[1] + 1 else countLong3[1], 0);

def countShort = CompoundValue(1, if IsNaN(countShort[1])  or BarNumber() == 1 then 0 else if isOrder and isShort[1] then countShort[1] + 1 else countShort[1], 0);
def countShort2 = CompoundValue(1, if IsNaN(countShort2[1]) or BarNumber() == 1 then 0 else if isOrder2 and isShort2[1] then countShort2[1] + 1 else countShort2[1], 0);
def countShort3 = CompoundValue(1, if IsNaN(countShort3[1]) or BarNumber() == 1 then 0 else if isOrder3 and isShort3[1] then countShort3[1] + 1 else countShort3[1], 0); #What was the biggest winning and losing trade

# What was the biggest winning and losing trade
def biggestWin = CompoundValue(1, if IsNaN(biggestWin[1]) or BarNumber() == 1 then 0 else if isOrder and (dollarProfitLoss > 0) and (dollarProfitLoss > biggestWin[1]) then dollarProfitLoss else biggestWin[1], 0);
def biggestLoss = CompoundValue(1, if IsNaN(biggestLoss[1]) or BarNumber() == 1 then 0 else if isOrder and (dollarProfitLoss < 0) and (dollarProfitLoss < biggestLoss[1]) then dollarProfitLoss else biggestLoss[1], 0);

def biggestWin2 = CompoundValue(1, if IsNaN(biggestWin2[1]) or BarNumber() == 1 then 0 else if isOrder2 and (dollarProfitLoss2 > 0) and (dollarProfitLoss2 > biggestWin2[1]) then dollarProfitLoss2 else biggestWin2[1], 0);
def biggestLoss2 = CompoundValue(1, if IsNaN(biggestLoss2[1]) or BarNumber() == 1 then 0 else if isOrder2 and (dollarProfitLoss2 < 0) and (dollarProfitLoss2 < biggestLoss2[1]) then dollarProfitLoss2 else biggestLoss2[1], 0);

def biggestWin3 = CompoundValue(1, if IsNaN(biggestWin3[1]) or BarNumber() == 1 then 0 else if isOrder3 and (dollarProfitLoss3 > 0) and (dollarProfitLoss3 > biggestWin3[1]) then dollarProfitLoss3 else biggestWin3[1], 0);
def biggestLoss3 = CompoundValue(1, if IsNaN(biggestLoss3[1]) or BarNumber() == 1 then 0 else if isOrder3 and (dollarProfitLoss3 < 0) and (dollarProfitLoss3 < biggestLoss3[1]) then dollarProfitLoss3 else biggestLoss3[1], 0);

def ClosedTradeCount = if (isLong or isShort) then orderCount - 1 else orderCount;
def ClosedTradeCount2 = if (isLong2 or isShort2) then orderCount2 - 1 else orderCount2;
def ClosedTradeCount3 = if (isLong3 or isShort3) then orderCount3 - 1 else orderCount3;

def OpenTrades = if (isLong or isShort) then 1 else 0;
def OpenTrades2 = if (isLong2 or isShort2) then 1 else 0;
def OpenTrades3 = if (isLong3 or isShort3) then 1 else 0;

# What percent were winners
def PCTWin = if (OpenTrades and (TradePL < 0)) then Round((profitWinners / (ClosedTradeCount + 1)) * 100, 2)
else if (OpenTrades and (TradePL > 0)) then Round(((profitWinners + 1) / (ClosedTradeCount + 1)) * 100, 2)
else Round(((profitWinners) / (ClosedTradeCount)) * 100, 2) ;

#What percent were winners
def PCTWin2 = if (OpenTrades2 and (TradePL2 < 0)) then Round((profitWinners2 / (ClosedTradeCount2 + 1)) * 100, 2)
else if (OpenTrades2 and (TradePL2 > 0)) then Round(((profitWinners2 + 1) / (ClosedTradeCount2 + 1)) * 100, 2)
else Round(((profitWinners2) / (ClosedTradeCount2)) * 100, 2) ;

#What percent were winners
def PCTWin3 = if (OpenTrades3 and (TradePL3 < 0)) then Round((profitWinners3 / (ClosedTradeCount3 + 1)) * 100, 2)
else if (OpenTrades3 and (TradePL3 > 0)) then Round(((profitWinners3 + 1) / (ClosedTradeCount3 + 1)) * 100, 2)
else Round(((profitWinners3) / (ClosedTradeCount3)) * 100, 2) ;

# Average trade
def avgTrade = if (OpenTrades and (TradePL < 0)) then Round(((dollarPLSum - TradePL) / (ClosedTradeCount + 1)), 2)
else if (OpenTrades and (TradePL > 0)) then Round(((dollarPLSum + TradePL) / (ClosedTradeCount + 1)), 2)
else Round(((dollarPLSum) / (ClosedTradeCount)), 2) ;

#Average trade
def avgTrade2 = if (OpenTrades2 and (TradePL < 0)) then Round(((dollarPLSum2 - TradePL2) / (ClosedTradeCount2 + 1)), 2)
else if (OpenTrades2 and (TradePL2 > 0)) then Round(((dollarPLSum2 + TradePL2) / (ClosedTradeCount2 + 1)), 2)
else Round(((dollarPLSum2) / (ClosedTradeCount2)), 2) ;

#Average trade
def avgTrade3 = if (OpenTrades3 and (TradePL < 0)) then Round(((dollarPLSum3 - TradePL3) / (ClosedTradeCount3 + 1)), 2)
else if (OpenTrades3 and (TradePL3 > 0)) then Round(((dollarPLSum3 + TradePL3) / (ClosedTradeCount3 + 1)), 2)
else Round(((dollarPLSum3) / (ClosedTradeCount3)), 2) ;

input showtitle = no;
input trade_day = no;
input trade_day_2 = no;
input trade_day_3 = no;



AddLabel(showtitle, " TS_V9: ", Color.light_gray);
AddLabel(Market_Open_Lbl and isIntraDay, if MarketOpen then "Market Open" else "Market Closed", Color.WHITE);
AddLabel(Tick_Size_Lbl, GetSymbol() + " Tick Size: " + TickSize() + " Value: " + TickValue(), Color.WHITE);
AddLabel(Long_Short_Lbl and (LongTrades and ShortTrades), "Long+Short Trades", Color.WHITE);
AddLabel(Long_Short_Lbl and (LongTrades and !ShortTrades), "Long Trades Only", Color.WHITE);
AddLabel(Long_Short_Lbl and (!LongTrades and ShortTrades), "Short Trades Only", Color.WHITE);
AddLabel(Closed_Orders_Lbl, "Closed Orders: " + ClosedTradeCount ,
if dollarPLSum > 0 then Color.GREEN else
if dollarPLSum < 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNaN(orderPrice) and PL_Lbl then 1 else 0, "Closed+Open P/L: " + AsDollars(TradePL + dollarPLSum),
if ((TradePL + dollarPLSum) > 0) then Color.GREEN else
if ((TradePL + dollarPLSum) < 0) then Color.RED else Color.GRAY);
AddLabel(Avg_Per_Lbl, "Avg per Trade: " + AsDollars(avgTrade),
if avgTrade > 0 then Color.GREEN else
if avgTrade < 0 then Color.RED else Color.GRAY);

AddLabel(Max_Lbl, "MaxUp: " + AsDollars(biggestWin) + " MaxDown: " + AsDollars(biggestLoss), Color.WHITE);
AddLabel(Profit_Lbl, "Long Profit: " + AsDollars(profitLong),
if profitLong > 0 then Color.GREEN else
if profitLong < 0 then Color.RED else Color.GRAY);
AddLabel(Profit_Lbl, "Short Profit: " + AsDollars(profitShort),
if profitShort > 0 then Color.GREEN else
if profitShort < 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNaN(CurrentPosition) and Open_Trades_Lbl and OpenTrades then 1 else 0, "Open: " +
(if isLong then "Bought" else "Sold") + " @ " + orderPrice, Color.WHITE);
AddLabel(if !IsNaN(orderPrice) and Open_Trades_Lbl and OpenTrades then 1 else 0, "Open Trade P/L: " + AsDollars(TradePL),
if (TradePL > 0) then Color.GREEN else
if (TradePL < 0) then Color.RED else Color.GRAY);
AddLabel(Profit_Pct_Lbl, "Profit Percentile: " + aspercent(TradePL/BiggestWin),
if (TradePL > 0) then Color.GREEN else
if (TradePL < 0) then Color.RED else Color.GRAY);
#########################################################################################################################
AddLabel(showLabels,(if tradeDaytimeOnly then  " Trade Daytime | " else "") + "WINS: " + PCTWin + "%",
if PCTWin > 50 then Color.GREEN else
if PCTWin > 40 then Color.YELLOW else Color.GRAY);
################################################

#############################################################################
AddLabel(Market_Open_Lbl2 and isIntraDay2, if MarketOpen2 then "Market Open" else "Market Closed", Color.WHITE);
AddLabel(Tick_Size_Lbl2, GetSymbol() + " Tick Size: " + TickSize() + " Value: " + TickValue(), Color.WHITE);
AddLabel(Long_Short_Lbl2 and (LongTrades2 and ShortTrades2), "Long+Short Trades", Color.WHITE);
AddLabel(Long_Short_Lbl2 and (LongTrades2 and !ShortTrades2), "Long Trades Only", Color.WHITE);
AddLabel(Long_Short_Lbl2 and (!LongTrades2 and ShortTrades2), "Short Trades Only", Color.WHITE);
AddLabel(Closed_Orders_Lbl2, "CO: " + ClosedTradeCount2 ,
if dollarPLSum2 > 0 then Color.GREEN else
if dollarPLSum2 < 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNaN(orderPrice2) and PL_Lbl2 then 1 else 0, "Closed+Open P/L: " + AsDollars(TradePL2 + dollarPLSum2),
if ((TradePL2 + dollarPLSum2) > 0) then Color.GREEN else
if ((TradePL2 + dollarPLSum2) < 0) then Color.RED else Color.GRAY);
AddLabel(Avg_Per_Lbl2, "Avg per Trade: " + AsDollars(avgTrade2),
if avgTrade2 > 0 then Color.GREEN else
if avgTrade2 < 0 then Color.RED else Color.GRAY);

AddLabel(Max_Lbl2, "MaxUp: " + AsDollars(biggestWin2) + " MaxDown: " + AsDollars(biggestLoss2), Color.WHITE);
AddLabel(Profit_Lbl2, "Long Profit: " + AsDollars(profitLong2),
if profitLong2 > 0 then Color.GREEN else
if profitLong2 < 0 then Color.RED else Color.GRAY);
AddLabel(Profit_Lbl2, "Short Profit: " + AsDollars(profitShort2),
if profitShort2 > 0 then Color.GREEN else
if profitShort2 < 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNaN(CurrentPosition2) and Open_Trades_Lbl2 and OpenTrades2 then 1 else 0, "Open: " +
(if isLong2 then "Bought" else "Sold") + " @ " + orderPrice2, Color.WHITE);
AddLabel(if !IsNaN(orderPrice2) and Open_Trades_Lbl2 and OpenTrades2 then 1 else 0, "Open Trade P/L: " + AsDollars(TradePL2),
if (TradePL2 > 0) then Color.GREEN else
if (TradePL2 < 0) then Color.RED else Color.GRAY);
AddLabel(Profit_Pct_Lbl2, "Profit Percentile: " + aspercent(TradePL2/BiggestWin2),
if (TradePL2 > 0) then Color.GREEN else
if (TradePL2 < 0) then Color.RED else Color.GRAY);

def ag2_Label_min =if (agperiod2 == aggregationPeriod.MIN) then 1 else 0;
def ag2_Label_two_min =if (agperiod2 == aggregationPeriod.TWO_MIN) then 1 else 0;
def ag2_Label_three_min =if (agperiod2 == aggregationPeriod.THREE_MIN) then 1 else 0;
def ag2_Label_Five_min =if (agperiod2 == aggregationPeriod.FIVE_MIN) then 1 else 0;
def ag2_Label_Ten_min =if (agperiod2 == aggregationPeriod.TEN_MIN) then 1 else 0;
def ag2_Label_fifteen_min =if (agperiod2 == aggregationPeriod.FIFTEEN_MIN) then 1 else 0;
def ag2_Label_thirty_min =if (agperiod2 == aggregationPeriod.THIRTY_MIN) then 1 else 0;
def ag2_Label_Hour =if (agperiod2 == aggregationPeriod.HOUR) then 1 else 0;
def ag2_Label_two_Hour =if (agperiod2 == aggregationPeriod.TWO_HOURS) then 1 else 0;
def ag2_Label_Four_Hour =if (agperiod2 == aggregationPeriod.FOUR_HOURS) then 1 else 0;
def ag2_Label_Day =if (agperiod2 == aggregationPeriod.Day) then 1 else 0;
def ag2_Label_week =if (agperiod2 == aggregationPeriod.week) then 1 else 0;
def ag2_Label_month =if (agperiod2 == aggregationPeriod.month) then 1 else 0;

AddLabel(showLabels2,if ag2_Label_min         and trade_day_2 then "1 min | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_min         then "1 min | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_two_min     and trade_day_2 then "2 min | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_two_min     then "2 min | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_three_min   and trade_day_2 then "3 min | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_three_min   then "3 min | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_five_min    and trade_day_2 then "5 min | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_five_min    then "5 min | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_ten_min     and trade_day_2 then "10 min | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_ten_min     then "10 min | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_fifteen_min and trade_day_2 then "15 min | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_fifteen_min then "15 min | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_thirty_min  and trade_day_2 then "30 min | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_thirty_min  then "30 min | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_Hour        and trade_day_2 then "1 hour | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_Hour        then "1 hour | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_two_Hour    and trade_day_2 then "2 hour | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_two_Hour    then "2 hour | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_four_Hour   and trade_day_2 then "4 hour | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_four_Hour   then "4 hour | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_day         and trade_day_2 then "Day | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_day         then "Day | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_week        and trade_day_2 then "Week | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_week        then "Week | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_month       and trade_day_2 then "Month | DT | WINS AG2: "+ PCTWin2 + "%" else
                     if ag2_Label_month       then "Month | WINS AG2: "+ PCTWin2 + "%" else "",
                     if PCTWin2 > 50 then Color.GREEN else if PCTWin2 > 40 then Color.YELLOW else Color.GRAY);

AddLabel(ag_Skip_lbl,if AutoAgg == no then "Manual AG2" else
                         if AutoAgg == yes and ag_skip == yes then "Auto AG2 | AG Skip" else
                         if AutoAgg == yes and ag_skip == no then "Auto AG2" else "", Color.Gray);

AddLabel(Market_Open_Lbl3 and isIntraDay3, if MarketOpen3 then "Market Open" else "Market Closed", Color.WHITE);
AddLabel(Tick_Size_Lbl3, GetSymbol() + " Tick Size: " + TickSize() + " Value: " + TickValue(), Color.WHITE);
AddLabel(Long_Short_Lbl3 and (LongTrades3 and ShortTrades3), "Long+Short Trades", Color.WHITE);
AddLabel(Long_Short_Lbl3 and (LongTrades3 and !ShortTrades3), "Long Trades Only", Color.WHITE);
AddLabel(Long_Short_Lbl3 and (!LongTrades3 and ShortTrades3), "Short Trades Only", Color.WHITE);
AddLabel(Closed_Orders_Lbl3, "CO: " + ClosedTradeCount3 ,
if dollarPLSum3 > 0 then Color.GREEN else
if dollarPLSum3 < 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNaN(orderPrice3) and PL_Lbl3 then 1 else 0, "Closed+Open P/L: " + AsDollars(TradePL3 + dollarPLSum3),
if ((TradePL3 + dollarPLSum3) > 0) then Color.GREEN else
if ((TradePL3 + dollarPLSum3) < 0) then Color.RED else Color.GRAY);
AddLabel(Avg_Per_Lbl3, "Avg per Trade: " + AsDollars(avgTrade3),
if avgTrade3 > 0 then Color.GREEN else
if avgTrade3 < 0 then Color.RED else Color.GRAY);

AddLabel(Max_Lbl3, "MaxUp: " + AsDollars(biggestWin3) + " MaxDown: " + AsDollars(biggestLoss3), Color.WHITE);
AddLabel(Profit_Lbl3, "Long Profit: " + AsDollars(profitLong3),
if profitLong3 > 0 then Color.GREEN else
if profitLong3 < 0 then Color.RED else Color.GRAY);
AddLabel(Profit_Lbl3, "Short Profit: " + AsDollars(profitShort3),
if profitShort3 > 0 then Color.GREEN else
if profitShort3 < 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNaN(CurrentPosition3) and Open_Trades_Lbl3 and OpenTrades3 then 1 else 0, "Open: " +
(if isLong3 then "Bought" else "Sold") + " @ " + orderPrice3, Color.WHITE);
AddLabel(if !IsNaN(orderPrice3) and Open_Trades_Lbl3 and OpenTrades3 then 1 else 0, "Open Trade P/L: " + AsDollars(TradePL3),
if (TradePL3 > 0) then Color.GREEN else
if (TradePL3 < 0) then Color.RED else Color.GRAY);
AddLabel(Profit_Pct_Lbl3, "Profit Percentile: " + aspercent(TradePL3/BiggestWin3),
if (TradePL3 > 0) then Color.GREEN else
if (TradePL3 < 0) then Color.RED else Color.GRAY);;

def ag3_Label_min =if (agperiod3 == aggregationPeriod.MIN) then 1 else 0;
def ag3_Label_two_min =if (agperiod3 == aggregationPeriod.TWO_MIN) then 1 else 0;
def ag3_Label_three_min =if (agperiod3 == aggregationPeriod.THREE_MIN) then 1 else 0;
def ag3_Label_Five_min =if (agperiod3 == aggregationPeriod.FIVE_MIN) then 1 else 0;
def ag3_Label_Ten_min =if (agperiod3 == aggregationPeriod.TEN_MIN) then 1 else 0;
def ag3_Label_fifteen_min =if (agperiod3 == aggregationPeriod.FIFTEEN_MIN) then 1 else 0;
def ag3_Label_thirty_min =if (agperiod3 == aggregationPeriod.THIRTY_MIN) then 1 else 0;
def ag3_Label_Hour =if (agperiod3 == aggregationPeriod.HOUR) then 1 else 0;
def ag3_Label_two_Hour =if (agperiod3 == aggregationPeriod.TWO_HOURS) then 1 else 0;
def ag3_Label_Four_Hour =if (agperiod3 == aggregationPeriod.FOUR_HOURS) then 1 else 0;
def ag3_Label_Day =if (agperiod3 == aggregationPeriod.Day) then 1 else 0;
def ag3_Label_week =if (agperiod3 == aggregationPeriod.week) then 1 else 0;
def ag3_Label_month =if (agperiod3 == aggregationPeriod.month) then 1 else 0;

AddLabel(showLabels3,if ag3_Label_min         and trade_day_3 then "1 min | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_min         then "1 min | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_two_min     and trade_day_3 then "2 min | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_two_min     then "2 min | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_three_min   and trade_day_3 then "3 min | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_three_min   then "3 min | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_five_min    and trade_day_3 then "5 min | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_five_min    then "5 min | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_ten_min     and trade_day_3 then "10 min | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_ten_min     then "10 min | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_fifteen_min and trade_day_3 then "15 min | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_fifteen_min then "15 min | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_thirty_min  and trade_day_3 then "30 min | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_thirty_min  then "30 min | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_Hour        and trade_day_3 then "1 hour | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_Hour        then "1 hour | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_two_Hour    and trade_day_3 then "2 hour | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_two_Hour    then "2 hour | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_four_Hour   and trade_day_3 then "4 hour | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_four_Hour   then "4 hour | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_day         and trade_day_3 then "Day | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_day         then "Day | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_week        and trade_day_3 then "Week | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_week        then "Week | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_month       and trade_day_3 then "Month | DT | WINS AG3: "+ PCTWin3 + "%" else
                     if ag3_Label_month       then "Month | DT | WINS AG3: "+ PCTWin3 + "%" else "",
                     if PCTWin3 > 50 then Color.GREEN else if PCTWin3 > 40 then Color.YELLOW else Color.GRAY);





AddLabel(ag_Skip_lbl,if AutoAgg2 == no then "Manual AG3" else
                         if AutoAgg2 == yes and ag_skip2 == yes then "Auto AG3 | AG Skip" else
                         if AutoAgg2 == yes and ag_skip2 == no then "Auto AG3" else "", Color.Gray);

addlabel(show_Last_lbl, if (buybn > sellbn) then "Last Signal: " + "BUY" else if (sellbn > buybn) then "Last Signal: " + "SELL" else "",if (buybn > sellbn) then color.cyan else if (sellbn > buybn) then Color.magenta else color.gray);
 
Last edited:
tLR38Fc.png


Study link updated 7/30/23 Big7 (Single Aggregation) - http://tos.mx/L0WEnVc

gpW9kNW.png


Code:
#TS_V9_Filtered - Modified 4/25/23 to include 2 higher ags to filter lower via previous signal
#TS Strategy_V9 Created by Christopher84 08/10/2021
#Modified 05/23/2022 to include Chart Bubbles and Labels.
#Modified 05/25/2022 to include Targets and Stoplosses.
#Modified 05/26/2022 to include Line Labels by Dcstocks
#Modified 05/27/2022 to include target 7.


input Show_Open_Signals = no;
input show_repaint_Lbl = yes;
input Show_Signals_lbl = yes;
input show2 = yes;
input show3 = yes;
input Hide_AG2_Sell = yes; #hint Yes = Do NOT show higher aggregation signals
input Hide_AG2_Buy  = yes; #hint Yes = Do NOT show higher aggregation signals
input Hide_AG3_Sell = yes; #hint Yes = Do NOT show higher aggregation signals
input Hide_AG3_Buy  = yes; #hint Yes = Do NOT show higher aggregation signals
input Hide_AG2_Sell_Closed = yes; #hint Yes = Do NOT show higher aggregation signals
input Hide_AG2_Buy_Closed  = yes; #hint Yes = Do NOT show higher aggregation signals
input Hide_AG3_Sell_Closed = yes; #hint Yes = Do NOT show higher aggregation signals
input Hide_AG3_Buy_Closed  = yes; #hint Yes = Do NOT show higher aggregation signals
input show_Last_lbl = yes; #hint Yes = Do NOT show higher aggregation signals
input ag_skip = no;
input ag_skip2 = no;
input ag_skip_lbl = no;
def AutoAgg = yes;
def AutoAgg2 = yes;
input tradeDaytimeOnly = no; #hint tradeDaytimeOnly: (IntraDay Only) Only perform trades during hours stated
input tradeDaytimeOnly2 = no; #hint tradeDaytimeOnly2: (IntraDay Only) Only perform trades during hours stated
input tradeDaytimeOnly3 = no; #hint tradeDaytimeOnly3: (IntraDay Only) Only perform trades during hours stated


input OpenTime = 0930;
input OpenTime2 = 0930;
input OpenTime3 = 0930;
input CloseTime = 1600;
input CloseTime2 = 1600;
input CloseTime3 = 1600;

def coloredCandlesOn = no;
def show_3x = yes;
input length = 23;

input ATRPeriod = 11;
input ATRPeriod2 = 11;
input ATRPeriod3 = 11;

input ATRFactor = 2.2;
input ATRFactor2 = 2.2;
input ATRFactor3 = 2.2;

def bars_back = 10;

input lengthE = 23;

input show_elhers = no;
def price = (high + low) / 2;

def coeff = lengthE * price * price - 2 * price * sum(price, lengthE)[1] + sum(price * price, lengthE)[1];

plot Ehlers = sum(coeff * price, lengthE) / sum(coeff, lengthE);
Ehlers.SetDefaultColor(GetColor(1));

def UP1 = (Price > Ehlers);
def DN1 = (Price < Ehlers);

input trailType = {default modified, unmodified};
input trailType2 = {default modified2, unmodified2};
input trailType3 = {default modified3, unmodified3};

input firstTrade = {default long, short};
input firstTrade2 = {default long2, short2};
input firstTrade3 = {default long3, short3};

input averageType = AverageType.SIMPLE;
def averageType2 = AverageType.SIMPLE;
def averageType3 = AverageType.SIMPLE;

def Market_Open_Lbl = no;
def Market_Open_Lbl2 = no;
def Market_Open_Lbl3 = no;

def Tick_Size_Lbl =  no;
def Tick_Size_Lbl2 = no;
def Tick_Size_Lbl3 = no;

def Long_Short_Lbl =  no;
def Long_Short_Lbl2 = no;
def Long_Short_Lbl3 = no;

input Closed_Orders_Lbl =  yes;
def Closed_Orders_Lbl2 = no;
def Closed_Orders_Lbl3 = no;

def Profit_Lbl =  no;
def Profit_Lbl2 = no;
def Profit_Lbl3 = no;

def PL_Lbl = no;
def PL_Lbl2 = no;
def PL_Lbl3 = no;

def Max_Lbl =  no;
def Max_Lbl2 = no;
def Max_Lbl3 = no;

def Open_Trades_Lbl =  no;
def Open_Trades_Lbl2 = no;
def Open_Trades_Lbl3 = no;

def Profit_Pct_Lbl =  no;
def Profit_Pct_Lbl2 = no;
def Profit_Pct_Lbl3 = no;

def Avg_Per_Lbl =  no;
def Avg_Per_Lbl2 = no;
def Avg_Per_Lbl3 = no;

input LabelsOn = yes;
def LabelsOn2 = no;
def LabelsOn3 = no;

def agperiod1 = GetAggregationPeriod();
def agperiod2 =
                if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.MIN then AggregationPeriod.two_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.MIN then AggregationPeriod.three_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.two_MIN then AggregationPeriod.three_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.two_MIN then AggregationPeriod.five_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.three_MIN then AggregationPeriod.five_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.three_MIN then AggregationPeriod.ten_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.five_MIN then AggregationPeriod.ten_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.five_MIN then AggregationPeriod.fifteen_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.ten_MIN then AggregationPeriod.fifteen_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.ten_MIN then AggregationPeriod.thirty_MIN
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.fifteen_MIN then AggregationPeriod.thirty_MIN
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.fifteen_MIN then AggregationPeriod.HOUR
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.thirty_MIN then AggregationPeriod.hour
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.thirty_MIN then AggregationPeriod.two_hours
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.hour then AggregationPeriod.two_hours
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.HOUR then AggregationPeriod.four_hours
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.two_hours then AggregationPeriod.four_hours
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.two_HOURS then AggregationPeriod.Day
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.four_hours then AggregationPeriod.day
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.four_HOURS then AggregationPeriod.Week
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.day then AggregationPeriod.week
           else if AutoAgg == yes and ag_skip == yes and agperiod1 == AggregationPeriod.day then AggregationPeriod.month
           else if AutoAgg == yes and ag_skip == no and agperiod1 == AggregationPeriod.week then AggregationPeriod.month
           else agperiod1[1];        

def agperiod3 =
                if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.MIN then AggregationPeriod.two_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.MIN then AggregationPeriod.three_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.two_MIN then AggregationPeriod.three_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.two_MIN then AggregationPeriod.five_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.three_MIN then AggregationPeriod.five_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.three_MIN then AggregationPeriod.ten_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.five_MIN then AggregationPeriod.ten_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.five_MIN then AggregationPeriod.fifteen_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.ten_MIN then AggregationPeriod.fifteen_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.ten_MIN then AggregationPeriod.thirty_MIN
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.fifteen_MIN then AggregationPeriod.thirty_MIN
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.fifteen_MIN then AggregationPeriod.HOUR
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.thirty_MIN then AggregationPeriod.hour
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.thirty_MIN then AggregationPeriod.two_hours
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.hour then AggregationPeriod.two_hours
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.HOUR then AggregationPeriod.four_hours
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.two_hours then AggregationPeriod.four_hours
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.two_HOURS then AggregationPeriod.Day
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.four_hours then AggregationPeriod.day
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.four_HOURS then AggregationPeriod.Week
           else if AutoAgg2 == yes and ag_skip2 == no and agperiod2 == AggregationPeriod.day then AggregationPeriod.week
           else if AutoAgg2 == yes and ag_skip2 == yes and agperiod2 == AggregationPeriod.day then AggregationPeriod.month
           else agperiod2[1];        
       

#########################################################################################################################################################

#########################################################################################################################################################

def high2 = high(period = agperiod2);
def low2 = low(period = agperiod2);
def close2 = close(period = agperiod2);

#Big_7
#added Blst off - triple exhaustion - vix alert4 to the big 4 - HODL

#######################################
##  Create Labels
#######################################
input showtitle = no;
input showlabels = yes;

input timeframe = aggregationperiod.DAY;

#input length = 10;
input length2 = 20;

def Vol = volume(period = timeframe);
def at_High = high(period = timeframe);
def at_Open = open(period = timeframe);
def at_Close = close(period = timeframe);
def at_Low = low(period = timeframe);
def Vol1 = volume(period = timeframe);
def at_High1 = high(period = timeframe);
def at_Open1 = open(period = timeframe);
def at_Close1 = close(period = timeframe);
def at_Low1 = low(period = timeframe);

# Buy_Volume forumla is volume * (close_price minus low_price) / (High_price minus low_price)
def Buy_Volume = RoundUp(Vol * (at_Close - at_Low) / (at_High - at_Low));
def Buy_percent = RoundUp((Buy_Volume / Vol) * 100);
#Sell_Volume forumla is  volume * (High_price minus Close_price) / (High_price minus Low_price)
def Sell_Volume = RoundDown(Vol1 * (at_High1 - at_Close1) / (at_High1 - at_Low1));
def Sell_percent = RoundUp((Sell_Volume / Vol1) * 100);
#input price = close;
input length_BB = 10;
input length_BB2 = 20;
plot avg = ExpAverage(close(period = agperiod1), length_BB);
#plot avg = ExpAverage((price), length);
def height = avg - avg[length];
avg.SetStyle(Curve.SHORT_DASH);
avg.SetLineWeight(1);

def UP = avg[1] < avg;
def DOWN = avg[1] > avg;
Avg.AssignValueColor(if UP then Color.LIGHT_GREEN else if DOWN then Color.RED else Color.YELLOW);

plot avg2 = ExpAverage(close(period = agperiod2), length_BB);
#plot avg2 = ExpAverage((price), length2);
def height2 = avg2 - avg2[length_BB2];
avg2.SetStyle(Curve.SHORT_DASH);
avg2.SetLineWeight(1);

def UP2 = avg2[1] < avg2;
def DOWN2 = avg2[1] > avg2;
Avg2.AssignValueColor(if UP2 then Color.LIGHT_GREEN else if DOWN2 then Color.RED else Color.YELLOW);

# --- TRIPLE EXHAUSTION ---
input DI_Length = 14;
                                                                                                                                                       input averageType_3x = AverageType.SIMPLE;
input length_3x = 1000;
def over_bought_3x = 80;
def over_sold_3x = 20;
def KPeriod_3x = 10;
def DPeriod_3x = 10;
def priceH1 = high(period = agperiod2);
def priceL1 = low(period = agperiod2);
def priceC1 = close(period = agperiod2);
def priceO1 = close(period = agperiod2);
def priceH_3x = high;
def priceL_3x = low;
def priceC_3x = close; 
# --- TRIPLE EXHAUSTION INDICATORS - StochasticSlow / MACD / MACD StDev / DMI+/-                                                                                             
def bn = barnumber();
def SlowK_3x = reference StochasticFull(over_bought_3x, over_sold_3x, KPeriod_3x, DPeriod_3x, priceH_3x, priceL_3x, priceC_3x, 3, averageType_3x).FullK;
#def SlowK1 = reference StochasticFull(over_bought_3x, over_sold_3x, KPeriod_3x, DPeriod_3x, priceH1, priceL1, priceC1, 3, averageType).FullK;

def MACD_3x = reference MACD()."Value";
#def MACD1 = (ExpAverage(priceC1[1], 12)) - (ExpAverage(priceC1[1], 26));

def priceMean_3x = Average(MACD_3x, length_3x);
#def priceMean1 = SimpleMovingAvg(MACD1, length);

def MACD_stdev_3x =  (MACD_3x - priceMean_3x) / StDev(MACD_3x, length_3x);
#def MACD_stdev1 = (MACD1 - priceMean1) / StDev(MACD1, length);

def dPlus_3x = reference DMI()."DI+";
def dMinus_3x = reference DMI()."DI-";

def sellerRegular = SlowK_3x < 20 and MACD_stdev_3x < -1 and dPlus_3x < 15;
#def sellerRegular1 = SlowK1 < 20 and MACD_stdev1 < -1 and dPlus1 < 15;

def sellerExtreme = SlowK_3x < 20 and MACD_stdev_3x < -2 and dPlus_3x < 15;
#def sellerExtreme1 = SlowK1 < 20 and MACD_stdev1 < -2 and dPlus1 < 15;

def buyerRegular = SlowK_3x > 80 and MACD_stdev_3x > 1 and dMinus_3x < 15;
#def buyerRegular1 = SlowK1 > 80 and MACD_stdev1 > 1 and dMinus1 < 15;

def buyerExtreme = SlowK_3x > 80 and MACD_stdev_3x > 2 and dMinus_3x < 15; 
#def buyerExtreme1 = SlowK1 > 80 and MACD_stdev1 > 2 and dMinus1 < 15;
                                                                                                                                                        
# --- Arrows/Triggers                                                        

def RegularBuy = if sellerRegular[1] and !sellerRegular then 1 else 0;
def RegularBuy_bn = if RegularBuy then bn else RegularBuy_bn[1];

def ExtremeBuy = if sellerExtreme[1] and !sellerExtreme then 1 else 0;
def ExtremeBuy_bn = if ExtremeBuy then bn else ExtremeBuy_bn[1];

def RegularSell = if buyerRegular[1] and !buyerRegular then 1 else 0;
def RegularSell_bn = if RegularSell then bn else RegularSell_bn[1];

def ExtremeSell = if buyerExtreme[1] and !buyerExtreme then 1 else 0;
def ExtremeSell_bn = if ExtremeSell then bn else ExtremeSell_bn[1];

def Condition1UP = avg > avg2;
def Condition1DN = avg < avg2;

def Condition2UP = Buy_percent > 50;
def Condition2DN = Buy_percent < 50;

def BullUP = Condition1UP + Condition2UP;
def BearDN = Condition1DN + Condition2DN;

def Bull_Bear = if Condition1UP==1 and Condition2UP == 1 then 1 else if Condition1DN == 1 and Condition2DN == 1 then -1 else 0;

def Condition3UP = if buyerRegular then 1 else 0;
def Condition3DN =  if sellerRegular then 1 else 0;

def Condition4UP =  if buyerExtreme then 1 else 0;
def Condition4DN =  if sellerExtreme then 1 else 0;

def priceColor = if ((avg[1]<avg) and (avg2[1]<avg2)) then 1
                 else if((avg[1]>avg) and (avg2[1]>avg2)) then -1
                 else priceColor[1];


input show_Vol_Labels = no;
AddLabel(showtitle, " Big_6: ", Color.Light_gray);

# AK Trend

def aktrend_input1 = 3;
def aktrend_input2 = 8;
def aktrend_price = close;

def aktrend_fastmaa = MovAvgExponential(aktrend_price, aktrend_input1);
def aktrend_fastmab = MovAvgExponential(aktrend_price, aktrend_input2);
def aktrend_bspread = (aktrend_fastmaa - aktrend_fastmab) * 1.001;

def cond1_UP = if aktrend_bspread > 0 then 1 else 0;
def cond1_DN = if aktrend_bspread <= 0 then -1 else 0;

# ZSCORE

def zscore_price = close;
def zscore_length = 20;
def zscore_ZavgLength = 20;

def zscore_oneSD = StDev(zscore_price, zscore_length);
def zscore_avgClose = SimpleMovingAvg(zscore_price, zscore_length);
def zscore_ofoneSD = zscore_oneSD * zscore_price[1];
def zscore_Zscorevalue = ((zscore_price - zscore_avgClose) / zscore_oneSD);
def zscore_avgZv = Average(zscore_Zscorevalue, 20);
def zscore_Zscore = ((zscore_price - zscore_avgClose) / zscore_oneSD);
def zscore_avgZscore = Average(zscore_Zscorevalue, zscore_ZavgLength);

def cond2_UP = if zscore_Zscore > 0 then 1 else 0;
def cond2_DN = if zscore_Zscore <= 0 then -1 else 0;

# Ehlers

def ehlers_length = 34;

def ehlers_price = (high + low) / 2;
def ehlers_coeff = ehlers_length * ehlers_price * ehlers_price - 2 * ehlers_price * Sum(ehlers_price, ehlers_length)[1] + Sum(ehlers_price * ehlers_price, ehlers_length)[1];
def ehlers_Ehlers = Sum(ehlers_coeff * ehlers_price, ehlers_length) / Sum(ehlers_coeff, ehlers_length);

def cond3_UP = if close > ehlers_Ehlers then 1 else 0;
def cond3_DN = if close <= ehlers_Ehlers then -1 else 0;

# Anchored Momentum

def amom_src = close;
def amom_MomentumPeriod = 10;
def amom_SignalPeriod = 8;
def amom_SmoothMomentum = no;
def amom_SmoothingPeriod = 7;

def amom_p = 2 * amom_MomentumPeriod + 1;
def amom_t_amom = if amom_SmoothMomentum == yes then ExpAverage(amom_src, amom_SmoothingPeriod) else amom_src;
def amom_amom = 100 * ( (amom_t_amom / ( Average(amom_src, amom_p)) - 1));
def amom_amoms = Average(amom_amom, amom_SignalPeriod);


def cond4_UP = if amom_amom > 0 then 1 else 0;
def cond4_DN = if amom_amom <= 0 then -1 else 0;

# TMO

def tmo_length = 30; #def 14
def tmo_calcLength = 6; #def 5
def tmo_smoothLength = 6; #def 3

def tmo_data = fold i = 0 to tmo_length with s do s + (if close > GetValue(open, i) then 1 else if close < GetValue(open, i) then - 1 else 0);
def tmo_EMA5 = ExpAverage(tmo_data, tmo_calcLength);
def tmo_Main = ExpAverage(tmo_EMA5, tmo_smoothLength);
def tmo_Signal = ExpAverage(tmo_Main, tmo_smoothLength);
def tmo_color = if tmo_Main > tmo_Signal then 1 else -1;

def cond5_UP = if tmo_Main <= 0 then 1 else 0;
def cond5_DN = if tmo_Main >= 0 then -1 else 0;

# Strategy

input Strategy_Confirmation_Factor = 4;
input Strategy_FilterWithTMO = no;
input Strategy_FilterWithTMO_arrows = yes;
input Strategy_ColoredCandlesOn = yes;
input Strategy_VerticalLinesOn = no;
input Strategy_HoldTrend = no;

def cond_UP = cond1_UP + cond2_UP + cond3_UP + cond4_UP;
def cond_DN = cond1_DN + cond2_DN + cond3_DN + cond4_DN;

def direction = if cond_UP >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_UP) then 1
                else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_DN) then -1
                else if !Strategy_HoldTrend and direction[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
                else if !Strategy_HoldTrend and direction[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0
                else direction[1];

def direction2 = if cond_UP >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_UP) then 1
                else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_DN) then -1
                else if !Strategy_HoldTrend and direction2[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
                else if !Strategy_HoldTrend and direction2[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0
                else direction2[1];

def pd = 22;
def bbl = 20;
def mult = 2.0;
def lb = 50;
def ph = 0.85;
def pl = 1.01;

# Downtrend Criterias

def ltLB = 40;
def mtLB = 14;
def str = 3;
# --- Inputs

def AtrMult_Blst = 1.0;
def nATR_Blst = 4;
def AvgType_Blst = AverageType.HULL;
def trig_Blst = 20;

def pd_Blst = 22;
def bbl_Blst = 20;
def mult_Blst = 2.0;
def lb_Blst = 50;
def ph_Blst = 0.85;
def pl_Blst = 1.01;

input AtrMult = 1.0;
input nATR = 4;
input AvgType = AverageType.HULL;
input trig = 20;


# --- From Blast off Indicator
def ATR = MovingAverage(AvgType, TrueRange(high, close, low), nATR);
def UP_B = HL2 + (AtrMult * ATR);
def DN = HL2 + (-AtrMult * ATR);
def ST = if close < ST[1] then UP_B else DN;
def SuperTrend = ST;
# --- End Blast off

# --- From Blast off Indicator 2
def val = AbsValue(close - open);
def range = high - low;
def blastOffVal = (val / range) * 100;
def trigger = trig;
def alert1 = blastOffVal < trig;
def col = blastOffVal < trig;
def blast_candle = blastOffVal < trig;
# --- End Blast off 2
# Downtrend Criterias

def ltLB_Blst = 40;
def mtLB_Blst = 14;

def wvf = ((highest(close, pd) - low) / (highest(close, pd))) * 100;
def sDev = mult * stdev(wvf, bbl);
def midLine = SimpleMovingAvg(wvf, bbl);
def lowerBand = midLine - sDev;
def upperBand = midLine + sDev;
def rangeHigh = (highest(wvf, lb)) * ph;

#  Filtered Bar Criteria

def upRange = low > low[1] and close > high[1];
def upRange_Aggr = close > close[1] and close > open[1];
def filtered = ((wvf[1] >= upperBand[1] or wvf[1] >= rangeHigh[1]) and(wvf<upperBand and wvf<rangeHigh));
def filtered_Aggr = (wvf[1] >= upperBand[1] or wvf[1] >= rangeHigh[1]);

# Alerts Criteria 1
def alert4 = upRange_Aggr and close > close[str] and (close < close[ltLB] or close < close[mtLB]) and filtered_Aggr;


def BulgeLengthV = 20;
def SqueezeLengthV = 20;
def BulgeLengthV2 = 20;
def SqueezeLengthV2 = 20;
input color_blst = no;
input color_3x = yes;
input color_3xt = yes;

def signal_up_b7 = direction2 == 1 and direction2[1] < 1;
def signal_dn_b7 = direction2 == -1 and direction2[1] > -1;

AddLabel(showtitle, " BB_V5: ", Color.light_gray);
AddLabel(showlabels, if  Condition1UP==1 and Condition2UP == 1 and (Condition3UP == 1 or Condition4UP == 1) then "**CALLS ONLY!**"
else if Condition1UP == 1 and Condition2UP == 1 then "Very Bullish"
else if direction == 1 then "Bullish"            
else if Condition1DN == 1 and Condition2DN == 1 and (Condition3DN == 1 or Condition4DN == 1) then "**PUTS ONLY!**"
else if Condition1DN == 1 and Condition2DN == 1 then "Very Bearish"
else if direction == -1 then "Bearish"          
else if ((avg[1] > avg) and (avg > avg2) and (Buy_percent > 50)) then "Bullish Retracement"
                else if ((avg[1] < avg) and (avg < avg2) and (Buy_percent < 50)) then "Bearish Retracement" + " | "
                else "CHOP",
                     if Condition1UP == 1 and Condition2UP == 1 and (Condition3UP == 1 or Condition4UP == 1) then Color.cyan
                else if Condition1DN == 1 and Condition2DN == 1 and (Condition3DN == 1 or Condition4DN == 1) then Color.Magenta
                else if Condition1UP == 1 and Condition2UP == 1 then Color.GREEN
else if direction == 1 then Color.green                      
else if Condition1DN == 1 and Condition2DN == 1 then Color.RED
else if direction == -1 then Color.red       
                else Color.orange);
#########################################################################################################################################################


#########################################################################################################################################################

input showSignals = yes; #hint showSignals: show buy and sell arrows
def showSignals2 = yes; #hint showSignals2: show buy and sell arrows
def showSignals3 = yes; #hint showSignals3: show buy and sell arrows

input LongTrades = yes; #hint LongTrades: perform long trades
def LongTrades2 = yes; #hint LongTrades2: perform long trades
def LongTrades3 = yes; #hint LongTrades3: perform long trades

input ShortTrades = yes; #hint ShortTrades: perform short trades
def ShortTrades2 = yes; #hint ShortTrades2: perform short trades
def ShortTrades3 = yes; #hint ShortTrades3: perform short trades

#input showLabels  = yes; #hint showLabels: show PL labels at top
def showLabels2 = no; #hint showLabels3: show PL labels at top
def showLabels3 = no; #hint showLabels3: show PL labels at top

input useStops = no;     #hint useStops: use stop orders
def useStops2 = no; #hint useStops2: use stop orders
def useStops3 = no; #hint useStops3: use stop orders

input useAlerts = no;    #hint useAlerts: use alerts on signals
def useAlerts2 = no; #hint useAlerts2: use alerts on signals
def useAlerts3 = no; #hint useAlerts3: use alerts on signals


def high3 = high(period = agperiod3);
def low3 = low(period = agperiod3);
def close3 = close(period = agperiod3);

#########################################################################################################################################################


#########################################################################################################################################################

def price_V9 = close;
def price_V92 = close2;
def price_V93 = close3;

#input coloredCandlesOn = no;
#input coloredCandlesOn2 = no;

#########################################################################################################################################################

#def bn = barnumber();

#########################################################################################################################################################

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);

def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);

def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;
    }
}

#########################################################################################################################################################


#########################################################################################################################################################

Assert(ATRFactor2 > 0, "'atr factor' must be positive: " + ATRFactor2);

def HiLo2 = Min(high2 - low2, 1.5 * Average(high2 - low2, ATRPeriod2));
def HRef2 = if low2 <= high2[1]
    then high2 - close2[1]
    else (high2 - close2[1]) - 0.5 * (low2 - high2[1]);
def LRef2 = if high2 >= low2[1]
    then close2[1] - low2
    else (close2[1] - low2) - 0.5 * (low2[1] - high2);

def trueRange2;
switch (trailType2) {
    case modified2:
        trueRange2 = Max(HiLo2, Max(HRef2, LRef2));
    case unmodified2:
        trueRange2 = TrueRange(high2, close2, low2);
}
def loss2 = ATRFactor2 * MovingAverage(averageType2, trueRange2, ATRPeriod2);

def state2 = {default init2, long2, short2};
def trail2;
switch (state2[1]) {
    case init2:
        if (!IsNaN(loss2)) {
            switch (firstTrade2) {
                case long2:
                    state2 = state2.long2;
                    trail2 = close2 - loss2;
                case short2:
                    state2 = state2.short2;
                    trail2 = close2 + loss2;
            }
        } else {
            state2 = state2.init2;
            trail2 = Double.NaN;
        }
    case long2:
        if (close2 > trail2[1]) {
            state2 = state2.long2;
            trail2 = Max(trail2[1], close2 - loss2);
        } else {
            state2 = state2.short2;
            trail2 = close2 + loss2;
        }
    case short2:
        if (close2 < trail2[1]) {
            state2 = state2.short2;
            trail2 = Min(trail2[1], close2 + loss2);
        } else {
            state2 = state2.long2;
            trail2 = close2 - loss2;
        }
}

#########################################################################################################################################################


#########################################################################################################################################################

Assert(ATRFactor3 > 0, "'atr factor' must be positive: " + ATRFactor3);

def HiLo3 = Min(high3 - low3, 1.5 * Average(high3 - low3, ATRPeriod3));
def HRef3 = if low3 <= high3[1]
    then high3 - close3[1]
    else (high3 - close3[1]) - 0.5 * (low3 - high3[1]);
def LRef3 = if high3 >= low3[1]
    then close3[1] - low3
    else (close3[1] - low3) - 0.5 * (low3[1] - high3);

def trueRange3;
switch (trailType3) {
    case modified3:
        trueRange3 = Max(HiLo3, Max(HRef3, LRef3));
    case unmodified3:
        trueRange3 = TrueRange(high3, close3, low3);
}
def loss3 = ATRFactor3 * MovingAverage(averageType3, trueRange3, ATRPeriod3);

def state3 = {default init3, long3, short3};
def trail3;
switch (state3[1]) {
    case init3:
        if (!IsNaN(loss3)) {
            switch (firstTrade3) {
                case long3:
                    state3 = state3.long3;
                    trail3 = close3 - loss3;
                case short3:
                    state3 = state3.short3;
                    trail3 = close3 + loss3;
            }
        } else {
            state3 = state3.init3;
            trail3 = Double.NaN;
        }
    case long3:
        if (close3 > trail3[1]) {
            state3 = state3.long3;
            trail3 = Max(trail3[1], close3 - loss3);
        } else {
            state3 = state3.short3;
            trail3 = close3 + loss3;
        }
    case short3:
        if (close3 < trail3[1]) {
            state3 = state3.short3;
            trail3 = Min(trail3[1], close3 + loss3);
        } else {
            state3 = state3.long3;
            trail3 = close3 - loss3;
        }
}

#########################################################################################################################################################


#########################################################################################################################################################

def TrailingStop = trail;
def LongEnter = (price_v9 crosses above TrailingStop);
def LongExit = (price_v9 crosses below TrailingStop);

def TrailingStop2 = trail2;
def LongEnter2 = (price_v92 crosses above TrailingStop2);
def LongExit2 = (price_v92 crosses below TrailingStop2) ;

def TrailingStop3 = trail3;
def LongEnter3 = (price_v93 crosses above TrailingStop3);
def LongExit3 = (price_v93 crosses below TrailingStop3);

#########################################################################################################################################################


#########################################################################################################################################################

#AssignPriceColor(if coloredCandlesOn and ((price > TrailingStop)) then Color.GREEN else if coloredCandlesOn and ((price < TrailingStop)) then Color.RED else Color.GRAY);
Alert(price_v9 crosses above TrailingStop, "long", Alert.BAR, Sound.Ding);
Alert(price_v92 crosses above TrailingStop2, "long", Alert.BAR, Sound.Ding);
Alert(price_v93 crosses above TrailingStop3, "long", Alert.BAR, Sound.Ding);

Alert(price_v9 crosses below TrailingStop, "short", Alert.BAR, Sound.Ding);
Alert(price_v92 crosses below TrailingStop2, "short", Alert.BAR, Sound.Ding);
Alert(price_v93 crosses below TrailingStop3, "short", Alert.BAR, Sound.Ding);

#########################################################################################################################################################


#########################################################################################################################################################

def upsignal = (price_V9 crosses above TrailingStop);
def upsignal2 = (price_V92 crosses above TrailingStop2);
def upsignal3 = (price_V93 crosses above TrailingStop3);

def downsignal = (price_v9 crosses below TrailingStop);
def downsignal2 = (price_v92 crosses below TrailingStop2);
def downsignal3 = (price_v93 crosses below TrailingStop3);

#########################################################################################################################################################


#########################################################################################################################################################

def Begin = SecondsFromTime(OpenTime);
def End = SecondsTillTime(CloseTime);

def Begin2 = SecondsFromTime(OpenTime2);
def End2 = SecondsTillTime(CloseTime2);

def Begin3 = SecondsFromTime(OpenTime3);
def End3 = SecondsTillTime(CloseTime3);

#########################################################################################################################################################


#########################################################################################################################################################

# Only use market hours when using intraday timeframe
def isIntraDay = if GetAggregationPeriod() > 14400000 or GetAggregationPeriod() == 0 then 0 else 1;
def MarketOpen = if !tradeDaytimeOnly or !isIntraDay then 1 else if tradeDaytimeOnly and isIntraDay and Begin > 0 and End > 0 then 1 else 0;

def isIntraDay2 = if GetAggregationPeriod() > 14400000 or GetAggregationPeriod() == 0 then 0 else 1;
def MarketOpen2 = if !tradeDaytimeOnly2 or !isIntraDay2 then 1 else if tradeDaytimeOnly2 and isIntraDay2 and Begin2 > 0 and End2 > 0 then 1 else 0;

def isIntraDay3 = if GetAggregationPeriod() > 14400000 or GetAggregationPeriod() == 0 then 0 else 1;
def MarketOpen3 = if !tradeDaytimeOnly3 or !isIntraDay3 then 1 else if tradeDaytimeOnly3 and isIntraDay3 and Begin3 > 0 and End3 > 0 then 1 else 0;

######################################################
##  Create Signals -
##  FILL IN THIS SECTION
##      replace 0>0 with your conditions for signals
######################################################

def PLBuySignal_1 = if  MarketOpen and (upsignal) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLBuySignal_1_bn = if PLBuySignal_1 then bn else PLBuySignal_1_bn[1];

def PLBuySignal2_2 = if MarketOpen2 and (Upsignal2) then 1 else 0; # insert condition to create long position in place of the 0>0
def PLBuySignal2_2_bn = if PLBuySignal2_2 then bn else PLBuySignal2_2_bn[1];

def PLBuySignal3_3 = if MarketOpen3 and (Upsignal3) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLBuySignal3_3_bn = if PLBuySignal3_3 then bn else PLBuySignal3_3_bn[1];

###################################################################################

def PLSellSignal_1 =  if MarketOpen and (downsignal) then 1 else 0; # insert condition to create short position in place of the 0>0
def PLSellSignal_1_bn = if PLSellSignal_1 then bn else PLSellSignal_1_bn[1];

def PLSellSignal2_2 = if MarketOpen2 and (downsignal2) then 1 else 0; # insert condition to create short position in place of the 0>0
def PLSellSignal2_2_bn = if PLSellSignal2_2 then bn else PLSellSignal2_2_bn[1];

def PLSellSignal3_3 = if MarketOpen3 and (downsignal3) then 1 else 0; # insert condition to create short position in place of the 0>0
def PLSellSignal3_3_bn = if PLSellSignal3_3 then bn else PLSellSignal3_3_bn[1];

#########################################################################################################################################################

def Prev_Bar_Buy_1 = if (PLBuySignal_1 or PLBuySignal_1[1] or PLBuySignal_1[2] or PLBuySignal_1[3]) then 1 else 0;
def Prev_Bar_Buy_2 = if (PLBuySignal2_2 or PLBuySignal2_2[1] or PLBuySignal2_2[2] or PLBuySignal2_2[3]) then 1 else 0;
def Prev_Bar_Buy_3 = if (PLBuySignal3_3 or PLBuySignal3_3[1] or PLBuySignal3_3[2] or PLBuySignal3_3[3]) then 1 else 0;

def Prev_Bar_Sell_1 = if (PLSellSignal_1 or PLSellSignal_1[1] or PLSellSignal_1[2] or PLSellSignal_1[3]) then 1 else 0;
def Prev_Bar_Sell_2 = if (PLSellSignal2_2 or PLSellSignal2_2[1] or PLSellSignal2_2[2] or PLSellSignal2_2[3]) then 1 else 0;
def Prev_Bar_Sell_3 = if (PLSellSignal3_3 or PLSellSignal3_3[1] or PLSellSignal3_3[2] or PLSellSignal3_3[3]) then 1 else 0;

def Prev_Buy_2 = if upsignal and (PLSellSignal2_2_bn < PLBuySignal2_2_bn) then 1 else 0;
def Prev_Buy_3 = if upsignal and (PLSellSignal3_3_bn < PLBuySignal3_3_bn) then 1 else 0;
def Prev_Buy_4 = if upsignal and (PLSellSignal2_2_bn < PLBuySignal2_2_bn) then 1 else 0;
def Prev_Buy_5 = if upsignal and (PLSellSignal3_3_bn < PLBuySignal3_3_bn) then 1 else 0;

def Prev_Sell_2 = if downsignal and (PLSellSignal2_2_bn > PLBuySignal2_2_bn) then 1 else 0;
def Prev_Sell_3 = if downsignal and (PLSellSignal3_3_bn > PLBuySignal3_3_bn) then 1 else 0;
def Prev_Sell_4 = if downsignal2 and (PLSellSignal2_2_bn > PLBuySignal2_2_bn) then 1 else 0;
def Prev_Sell_5 = if downsignal and (PLSellSignal3_3_bn > PLBuySignal3_3_bn) then 1 else 0;

#########################################################################################################################################################

####################################################
#diff signal same agg bn
####################################################

def Sell_Minus_Buy1_1 = (PLSellSignal_1_bn - PLBuySignal_1_bn);
def Buy_Minus_Sell1_1 = (PLBuySignal_1_bn - PLSellSignal_1_bn);

def Sell2_Minus_Buy2_2 = (PLSellSignal2_2_bn - PLBuySignal2_2_bn);
def Buy2_Minus_Sell2_2 = (PLBuySignal2_2_bn - PLSellSignal2_2_bn);

def Sell3_Minus_Buy3_3 = (PLSellSignal3_3_bn - PLBuySignal3_3_bn);
def Buy3_Minus_Sell3_3 = (PLBuySignal3_3_bn - PLSellSignal3_3_bn);

####################################################
#opposite signal higher ag bn
####################################################

def Sell_Minus_Buy2_1 = (PLSellSignal_1_bn - PLBuySignal2_2_bn);
def Buy_Minus_Sell2_1 = (PLBuySignal_1_bn - PLSellSignal2_2_bn);

def Sell_Minus_Buy3_1 = (PLSellSignal_1_bn - PLBuySignal3_3_bn);
def Buy_Minus_Sell3_1 = (PLBuySignal_1_bn - PLSellSignal3_3_bn);

def Sell2_Minus_Buy3_2 = (PLSellSignal2_2_bn - PLBuySignal3_3_bn);
def Buy2_Minus_Sell3_2 = (PLBuySignal2_2_bn - PLSellSignal3_3_bn);

####################################################
#same signal higher agg
####################################################

def Sell_Minus_Sell2_1 = (PLSellSignal_1_bn - PLSellSignal2_2_bn);
def Buy_Minus_Buy2_1 = (PLBuySignal_1_bn - PLBuySignal2_2_bn);

def Sell_Minus_Sell3_1 = (PLSellSignal_1_bn - PLSellSignal3_3_bn);
def Buy_Minus_Buy3_1 = (PLBuySignal_1_bn - PLBuySignal3_3_bn);

def Sell2_Minus_Sell3_2 = (PLSellSignal2_2_bn - PLSellSignal3_3_bn);
def Buy2_Minus_Buy3_2 = (PLBuySignal2_2_bn - PLBuySignal3_3_bn);

####################################################
#opposite signal Same ag within x bars
####################################################

def Sell_dist_Buy_1 = Sell_Minus_Buy1_1 >= bars_back;
def Buy_dist_Sell_1 = Buy_Minus_Sell1_1 >= bars_back;

def Sell_dist_Buy_2 = Sell2_Minus_Buy2_2 >= bars_back;
def Buy_dist_Sell_2 = Buy2_Minus_Sell2_2 >= bars_back;

def Sell_dist_Buy_3 = Sell3_Minus_Buy3_3 >= bars_back;
def Buy_dist_Sell_3 = Buy3_Minus_Sell3_3 >= bars_back;


####################################################
#opposite signal higher ag within x bars
####################################################

def Sell_dist_Buy2_1 = Sell_Minus_Buy2_1 >= bars_back;
def Buy_dist_Sell2_1 = Buy_Minus_Sell2_1 >= bars_back;

def Sell_dist_Buy3_3 = Sell_Minus_Buy3_1 >= bars_back;
def Buy_dist_Sell3_3 = Buy_Minus_Sell3_1 >= bars_back;

def Sell2_dist_Buy3_2 = Sell2_Minus_Buy3_2 >= bars_back;
def Buy2_dist_Sell3_2 = Buy2_Minus_Sell3_2 >= bars_back;

####################################################
#Same signal higher ag within x bars
####################################################

def Sell_dist_Sell2_1 = Sell_Minus_Sell2_1 >= bars_back;
def Buy_dist_Buy2_1 = Buy_Minus_Buy2_1 >= bars_back;

def Sell_dist_Sell3_1 = Sell_Minus_Sell3_1 >= bars_back;
def Buy_dist_Buy3_1 = Buy_Minus_Buy3_1 >= bars_back;

def Sell2_dist_Sell3_2 = Sell2_Minus_Sell3_2 >= bars_back;
def Buy2_dist_Buy3_2 =  Buy2_Minus_Buy3_2 >= bars_back;

####################################################
#Last signal higher ag
####################################################

def Last_Sell_2 = if downsignal and Sell_Minus_Sell2_1 < Sell_Minus_Buy2_1 then 1 else 0;
def Last_Buy_2 = if upsignal and  Sell_Minus_Sell2_1 > Sell_Minus_Buy2_1 then 1 else 0;

def Last_Sell_3 = if downsignal and  Sell_Minus_Sell3_1 < Sell_Minus_Buy3_1 then 1 else 0;
def Last_Buy_3 = if upsignal and  Sell_Minus_Sell3_1 > Sell_Minus_Buy3_1 then 1 else 0;

def Last2_Sell_3 = if downsignal and  Sell2_Minus_Sell3_2 < Sell2_Minus_Buy3_2 then 1 else 0;
def Last2_Buy_3 = if upsignal and  Sell2_Minus_Sell3_2 > Sell2_Minus_Buy3_2 then 1 else 0;

############################################################################################
#higher ag prev sell bn > than prev buy bn ********  ADDED HIGHER AG BAR IS CLOSED *********
############################################################################################

def SellSig_First_2 = if downsignal and (PLSellSignal2_2_bn > PLBuySignal2_2_bn) and (PLSellSignal2_2_bn < PLSellSignal_1_bn) then 1 else 0;
def SellSig_First_22 = if downsignal and (PLSellSignal2_2_bn > PLBuySignal2_2_bn) then 1 else 0;

def SellSig_Closed_2_only = if (Show_Open_Signals  == yes) then SellSig_First_22 else SellSig_First_2;

def BuySig_First_2 = if upsignal and (PLBuySignal2_2_bn > PLSellSignal2_2_bn)and (PLBuySignal2_2_bn < PLBuySignal_1_bn) then 1 else 0;
def BuySig_First_22 = if upsignal and (PLBuySignal2_2_bn > PLSellSignal2_2_bn) then 1 else 0;

def BuySig_Closed_2_only = if (Show_Open_Signals == yes) then BuySig_First_22 else BuySig_First_2;

def SellSig_First_3 = if downsignal2 and (PLSellSignal3_3_bn > PLBuySignal3_3_bn) and (PLSellSignal3_3_bn < PLSellSignal2_2_bn) then 1 else 0;
def SellSig_First_33 = if downsignal2 and (PLSellSignal3_3_bn > PLBuySignal3_3_bn) then 1 else 0;

def SellSig_Closed_3_only = if (Show_Open_Signals == yes) then SellSig_First_33 else SellSig_First_3;

def BuySig_First_3 = if upsignal2 and (PLBuySignal3_3_bn > PLSellSignal3_3_bn) and (PLBuySignal3_3_bn < PLBuySignal2_2_bn) then 1 else 0;
def BuySig_First_33 = if upsignal2 and (PLBuySignal3_3_bn > PLSellSignal3_3_bn) then 1 else 0;

def BuySig_Closed_3_only = if (Show_Open_Signals == yes) then BuySig_First_33 else BuySig_First_3;

def b7_conditionup = if (signal_up_b7 or signal_up_b7[1] or signal_up_b7[2] or signal_up_b7[3])then 1 else 0;
def b7_conditiondn = if (signal_dn_b7 or signal_dn_b7[1] or signal_dn_b7[2] or signal_dn_b7[3])then 1 else 0;

#########################################################################################################################################################

def PLBuySignal_11 = if MarketOpen and (upsignal)  and ( BuySig_Closed_2_only ) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLBuySignal_22 = if MarketOpen and (upsignal)  and ( BuySig_Closed_2_only ) then 1 else 0 ; # insert condition to create long position in place of the


def PLSellSignal_11 = if MarketOpen and (downsignal) and (SellSig_Closed_2_only) then 1 else 0; # insert condition to create short position in place of the 0>0
def PLSellSignal_22 = if MarketOpen and (downsignal) and (SellSig_Closed_2_only) then 1 else 0; # insert condition to create short position in place of the

def alertsell = if (alert4 or alert4[1] or alert4[2] or alert4[3]) then 0 else 1;

def PLBuySignal2 = if MarketOpen2   and (UPsignal2) and ( BuySig_Closed_3_only) then 1 else 0; # insert condition to create long position in place

def PLSellSignal2 = if MarketOpen2   and (downsignal2) and ( SellSig_Closed_3_only) then 1 else 0; # insert condition to create short position in

def alertsell2 = if plsellsignal2 and (alert4 or alert4[1] or alert4[2]) then 0 else 1;


def PLBuySignal3 = if MarketOpen2   and (UPsignal3) then 1 else 0; # insert condition to create long position in place of the 0>0

def PLSellSignal3 = if MarketOpen2   and (downsignal3) then 1 else 0; # insert condition to create short position in place of the 0>0

def alertsell3 = if (alert4 or alert4[1] or alert4[2]) then 0 else 1;

#########################################################################################################################################################

def PLBuySignal = if (PLBuySignal_11 or PLBuySignal2 or PLBuySignal3) and  b7_conditionup then 1 else 0 ; # insert condition to create long position in place of the 0>0


def PLSellSignal =  if (PLSellSignal_11 or PLSellSignal2 or PLSellSignal3) and  b7_conditiondn then 1 else 0; # insert condition to create short position in place of the 0>0


#########################################################################################################################################################

def PLBuySignal_bn = if PLBuySignal then bn else PLBuySignal_bn[1];
def PLSellSignal_bn = if PLSellSignal then bn else PLSellSignal_bn[1];

#########################################################################################################################################################

def PLBuyStop  = if !useStops then 0 else if  (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0<0
def PLBuyStop2 = if !useStops2 then 0 else if (0 > 0) then 1 else 0 ; # insert condition to stop in place of the 0<0
def PLBuyStop3 = if !useStops3 then 0 else if (0 > 0) then 1 else 0 ; # insert condition to stop in place of the 0<0

def PLSellStop = if !useStops then 0 else if (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0>0
def PLSellStop2 = if !useStops2 then 0 else if (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0>0
def PLSellStop3 = if !useStops3 then 0 else if (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0>0

def PLMktStop = if MarketOpen[-1] == 0 then 1 else 0; # If tradeDaytimeOnly is set, then stop at end of day
def PLMktStop2 = if MarketOpen2[-1] == 0 then 1 else 0; # If tradeDaytimeOnly is set, then stop at end of day
def PLMktStop3 = if MarketOpen3[-1] == 0 then 1 else 0; # If tradeDaytimeOnly is set, then stop at end of day

#########################################################################################################################################################

#########################################################################################################################################################

#######################################
##  Maintain the position of trades
#######################################
# change CurrentPosition to CurrentPosition2, PLBuySignal tp PLBuySignal2, LongTrades to LongTrades2, ShortTrades to ShortTrades2, PLBuyStop to PLBuyStop2, useStops to useStops2, PLMktStop to PLMktStop2

#########################################################################################################################################################


#########################################################################################################################################################

def CurrentPosition;  # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition[1]) {
    CurrentPosition = 0;
} else {
    if CurrentPosition[1] == 0 {            # FLAT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == 1 {      # LONG
        if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else if ((PLBuyStop and useStops) or PLMktStop or (PLSellSignal and ShortTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == -1 {     # SHORT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if ((PLSellStop and useStops) or PLMktStop or (PLBuySignal and LongTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else {
        CurrentPosition = CurrentPosition[1];
    }
}

#########################################################################################################################################################


#########################################################################################################################################################

def CurrentPosition2;  # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition2[1]) {
    CurrentPosition2 = 0;
} else {
    if CurrentPosition2[1] == 0 {            # FLAT
        if (PLBuySignal2 and LongTrades2) {
            CurrentPosition2 = 1;
        } else if (PLSellSignal2 and ShortTrades2) {
            CurrentPosition2 = -1;
        } else {
            CurrentPosition2 = CurrentPosition2[1];
        }
    } else if CurrentPosition2[1] == 1 {      # LONG
        if (PLSellSignal2 and ShortTrades2) {
            CurrentPosition2 = -1;
        } else if ((PLBuyStop2 and useStops2) or PLMktStop2 or (PLSellSignal2 and ShortTrades2 == 0)) {
            CurrentPosition2 = 0;
        } else {
            CurrentPosition2 = CurrentPosition2[1];
        }
    } else if CurrentPosition2[1] == -1 {     # SHORT
        if (PLBuySignal2 and LongTrades2) {
            CurrentPosition2 = 1;
        } else if ((PLSellStop2 and useStops2) or PLMktStop2 or (PLBuySignal2 and LongTrades2 == 0)) {
            CurrentPosition2 = 0;
        } else {
            CurrentPosition2 = CurrentPosition2[1];
        }
    } else {
        CurrentPosition2 = CurrentPosition2[1];
    }
}

#########################################################################################################################################################


#########################################################################################################################################################

def CurrentPosition3;  # holds whether flat = 0 long = 1 short = -1

if (BarNumber() == 1) or IsNaN(CurrentPosition3[1]) {
    CurrentPosition3 = 0;
} else {
    if CurrentPosition3[1] == 0 {            # FLAT
        if (PLBuySignal3 and LongTrades3) {
            CurrentPosition3 = 1;
        } else if (PLSellSignal3 and ShortTrades3) {
            CurrentPosition3 = -1;
        } else {
            CurrentPosition3 = CurrentPosition3[1];
        }
    } else if CurrentPosition3[1] == 1 {      # LONG
        if (PLSellSignal3 and ShortTrades3) {
            CurrentPosition3 = -1;
        } else if ((PLBuyStop3 and useStops3) or PLMktStop3 or (PLSellSignal3 and ShortTrades3 == 0)) {
            CurrentPosition3 = 0;
        } else {
            CurrentPosition3 = CurrentPosition3[1];
        }
    } else if CurrentPosition3[1] == -1 {     # SHORT
        if (PLBuySignal3 and LongTrades3) {
            CurrentPosition3 = 1;
        } else if ((PLSellStop3 and useStops3) or PLMktStop3 or (PLBuySignal3 and LongTrades3 == 0)) {
            CurrentPosition3 = 0;
        } else {
            CurrentPosition3 = CurrentPosition3[1];
        }
    } else {
        CurrentPosition3 = CurrentPosition3[1];
    }
}

#########################################################################################################################################################


#########################################################################################################################################################

def isLong  = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat  = if CurrentPosition == 0 then 1 else 0;

def isLong2  = if CurrentPosition2 == 1 then 1 else 0;
def isShort2 = if CurrentPosition2 == -1 then 1 else 0;
def isFlat2  = if CurrentPosition2 == 0 then 1 else 0;

def isLong3  = if CurrentPosition3 == 1 then 1 else 0;
def isShort3 = if CurrentPosition3 == -1 then 1 else 0;
def isFlat3  = if CurrentPosition3 == 0 then 1 else 0;

###################################################################################################################################

def BuySig = if (((isShort[1] and LongTrades) or (isFlat[1] and LongTrades)) and PLBuySignal and showSignals)  then 1 else 0;
def BuySig2 = if (((isShort2[1] and LongTrades2) or (isFlat2[1] and LongTrades2)) and PLBuySignal2 and showSignals2) then 1 else 0;
def BuySig3 = if (((isShort3[1] and LongTrades3) or (isFlat3[1] and LongTrades3)) and PLBuySignal3 and showSignals3) then 1 else 0;

###################################################################################################################################

def buy_11 = if (BuySig ) then 1 else 0;
def buy_21 = if (BuySig or BuySig2 or BuySig3) then 1 else 0;
def buy = if (Hide_AG2_Buy == yes) then Buy_11 else if (Hide_AG2_Buy == no) then buy_21 else buy[1];

Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig and useAlerts, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig2 and useAlerts2, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig2 and useAlerts2, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig3 and useAlerts3, "Buy Signal", Alert.BAR, Sound.Ding);
Alert(BuySig3 and useAlerts3, "Buy Signal", Alert.BAR, Sound.Ding);

def buysigbn = if BuySig then bn else buysigbn[1];
def buysig2bn = if BuySig2 then bn else buysig2bn[1];
def buysig3bn = if BuySig3 then bn else buysig3bn[1];

###################################################################################################################################

# If not already short and get a PLSellSignal
def SellSig = if (((isLong[1] and ShortTrades) or (isFlat[1] and ShortTrades)) and PLSellSignal and showSignals) then 1 else 0;
def SellSig2 = if (((isLong2[1] and ShortTrades2) or (isFlat2[1] and ShortTrades2)) and PLSellSignal2 and showSignals2)then 1 else 0;
def SellSig3 = if (((isLong3[1] and ShortTrades3) or (isFlat3[1] and ShortTrades3)) and PLSellSignal3 and showSignals3) then 1 else 0;

###################################################################################################################################

def Sell_11 = if (SellSig or SellSig2 or SellSig3) then 1 else 0;
def Sell_21 = (SellSig);
def Sell = if (Hide_AG2_Sell == yes) then sell_21  else if (Hide_AG2_Sell == no) then (sell_11) else sell[1] ;

def Hide_Sell = if Sell and (Sell[1] or sell[2] or sell[3] or sell[4]) then 0 else 1;
def Hide_Buy = if Buy and (Buy[1] or Buy[2] or Buy[3] or Buy[4]) then 0 else 1;



def Hide_Sell3 = if (PLSellSignal3) and (PLSellSignal3[1] or PLSellSignal3[2] or PLSellSignal3[3] or PLSellSignal3[4]) then 0 else 1;
def Hide_Buy3 = if PLBuySignal3 and (PLBuySignal3[1] or PLBuySignal3[2] or PLBuySignal3[3] or PLBuySignal3[4]) then 0 else 1;



def Sellsigbn = if SellSig then bn else SellSigbn[1];
def Sellsig2bn = if SellSig2 then bn else SellSig2bn[1];
def Sellsig3bn = if SellSig3 then bn else SellSig3bn[1];

##################################################################################################################################

def Sell_1 = if (Sell) and (Hide_Sell == 1) then 1 else 0;

def sellbn = if sell_1 then bn else sellbn[1];



def Buy_1 = if (Buy) and (Hide_Buy == 1) then 1 else 0;

def Buybn = if Buy_1 then bn else buybn[1];

def Hide_Buy_2 = if Buy  then 0 else 1;

#def Hide_Sell_2 = if Sellbn2 then 0 else 1;
##################################################################################################################################

def PLSell1_sell = if sell and PLSellSignal_11 then 1 else 0;
def PLSell2_sell = if sell and PLSellSignal2 then 1 else 0;
def PLSell3_sell = if sell and PLSellSignal3 then 1 else 0;

def PLbuy1_buy = if buy and PLBuySignal_11 then 1 else 0;
def PLbuy2_buy = if buy and PLBuySignal2 then 1 else 0;
def PLbuy3_buy = if buy and PLBuySignal3 then 1 else 0;

# and (Hide_Sell == 1)

#def Buybn12 = if Buy_12 then bn else buybn12[1];

def Buy_133 = if alert4 and (alert4[1] or alert4[2] or alert4[3] or alert4[4]) then 1 else 0;
def hide133 = if buy_133 and buy_133[1] then 0 else 1;
def Buy_1333 = if (ALERT4 OR alert4[1] or alert4[2] or alert4[3] or alert4[4]) then 1 else 0;

plot Buy_13 = if buy_133 and hide133 then 1 else 0;
Buy_13.AssignValueColor(Color.magenta);
Buy_13.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Buy_13.SetLineWeight(1);

#plot Buy_A4 = if (buy_12) and BUY_1333 then 1 else 0;
Buy_13.AssignValueColor(Color.YELLOW);
Buy_13.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Buy_13.SetLineWeight(5);
#def Buybn12 = if Buy_12 then bn else buybn12[1];

#plot Buy_14 = if (PLbuy3_buy) and (Hide_Buy == 1) then 1 else 0;
#Buy_12.AssignValueColor(Color.orange);
#Buy_12.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#Buy_12.SetLineWeight(1);
#def Buybn12 = if Buy_12 then bn else buybn12[1];


#plot Buy_13 = if (PLBuySignal3) and (Hide_Buy == 1) then 1 else 0;
#Buy_13.AssignValueColor(Color.orange);
#Buy_13.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
#Buy_13.SetLineWeight(1);
#def Buybn13 = if Buy_13 then bn else Buybn13[1];
##################################################################################################################################


#addchartbubble(BuySig and usealerts,low, "TS", Color.Light_Green,no);
#addchartbubble(SellSig and usealerts,High, "TS", Color.red,no);
Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);
Alert(SellSig and useAlerts, "Sell Signal", Alert.BAR, Sound.Ding);

#If not already short and get a PLSellSignal2


#addchartbubble(BuySig2 and usealerts2,low, "TS", Color.Light_Green,no);
#addchartbubble(SellSig2 and usealerts2,High, "TS", Color.red,no);
#Alert(SellSig2 and useAlerts2, "Sell Signal", Alert
Alert(SellSig2 and useAlerts2, "Sell Signal2", Alert.BAR, Sound.Ding);
Alert(SellSig2 and useAlerts2, "Sell Signal2", Alert.BAR, Sound.Ding);


#addchartbubble(BuySig3 and usealerts3,low, "TS", Color.Light_Green,no);
#addchartbubble(SellSig3 and usealerts3,High, "TS", Color.red,no);
#Alert(SellSig3 and useAlerts3, "Sell Signal", Alert
Alert(SellSig3 and useAlerts3, "Sell Signal3", Alert.BAR, Sound.Ding);
Alert(SellSig3 and useAlerts3, "Sell Signal3", Alert.BAR, Sound.Ding);

###################################################################################################################################

# If long and get a PLBuyStop
plot BuyStpSig = if (PLBuyStop and isLong[1] and showSignals and useStops) or (isLong[1] and PLMktStop) or (isLong[1] and PLSellSignal and !ShortTrades) then 1 else 0;
BuyStpSig.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig.SetLineWeight(1);

Alert(BuyStpSig and useAlerts, "Buy Stop Signal", Alert.BAR, Sound.Ding);
Alert(BuyStpSig and useAlerts, "Buy Stop Signal", Alert.BAR, Sound.Ding);

#If long and get a PLBuyStop
plot BuyStpSig2 = if (PLBuyStop2 and isLong2[1] and showSignals2 and useStops2) or (isLong2[1] and PLMktStop2) or (isLong2[1] and PLSellSignal2 and !ShortTrades2) then 1 else 0;
BuyStpSig2.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig2.SetLineWeight(1);

Alert(BuyStpSig2 and useAlerts2, "Buy Stop Signal", Alert.BAR, Sound.Ding);
Alert(BuyStpSig2 and useAlerts2, "Buy Stop Signal", Alert.BAR, Sound.Ding);

plot BuyStpSig3 = if (PLBuyStop3 and isLong3[1] and showSignals3 and useStops3) or (isLong3[1] and PLMktStop3) or (isLong3[1] and PLSellSignal3 and !ShortTrades3) then 1 else 0;
BuyStpSig3.AssignValueColor(Color.LIGHT_GRAY);
BuyStpSig3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
BuyStpSig3.SetLineWeight(1);

Alert(BuyStpSig3 and useAlerts3, "Buy Stop Signal", Alert.BAR, Sound.Ding);
Alert(BuyStpSig3 and useAlerts3, "Buy Stop Signal", Alert.BAR, Sound.Ding);

###################################################################################################################################


###################################################################################################################################

# If short and get a PLSellStop
plot SellStpSig = if (PLSellStop and isShort[1] and showSignals and useStops) or (isShort[1] and PLMktStop) or (isShort[1] and PLBuySignal and !LongTrades) then 1 else 0;
SellStpSig.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig.SetLineWeight(1);

Alert(SellStpSig and useAlerts, "Sell Stop Signal", Alert.BAR, Sound.Ding);
Alert(SellStpSig and useAlerts, "Sell Stop Signal", Alert.BAR, Sound.Ding);

#If short and get a PLSellStop
plot SellStpSig2 = if (PLSellStop2 and isShort2[1] and showSignals2 and useStops2) or (isShort2[1] and PLMktStop2) or (isShort2[1] and PLBuySignal2 and !LongTrades2) then 1 else 0;
SellStpSig2.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig2.SetLineWeight(1);

Alert(SellStpSig2 and useAlerts2, "Sell Stop Signal", Alert.BAR, Sound.Ding);
Alert(SellStpSig2 and useAlerts2, "Sell Stop Signal", Alert.BAR, Sound.Ding);

plot SellStpSig3 = if (PLSellStop3 and isShort3[1] and showSignals3 and useStops3) or (isShort3[1] and PLMktStop3) or (isShort3[1] and PLBuySignal3 and !LongTrades3) then 1 else 0;
SellStpSig3.AssignValueColor(Color.LIGHT_GRAY);
SellStpSig3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SellStpSig3.SetLineWeight(1);

Alert(SellStpSig3 and useAlerts3, "Sell Stop Signal", Alert.BAR, Sound.Ding);
Alert(SellStpSig3 and useAlerts3, "Sell Stop Signal", Alert.BAR, Sound.Ding);

###################################################################################################################################

#######################################
##  Orders
#######################################

def isOrder = if ((isFlat[1] and (BuySig and LongTrades) or (SellSig and ShortTrades)) or (isLong[1] and BuyStpSig or (SellSig and ShortTrades)) or (isShort[1] and SellStpSig or (BuySig and LongTrades))) then 1 else 0 ;
# If there is an order, then the price is the next days close
def orderPrice = if (isOrder and ((BuySig and LongTrades) or (SellSig and ShortTrades))) then close else orderPrice[1];

def orderCount = CompoundValue(1, if IsNaN(isOrder) or BarNumber() == 1 then 0 else if (BuySig or SellSig) then orderCount[1] + 1 else orderCount[1], 0);

#######################################
##  Price and Profit
#######################################

def profitLoss;

if (!isOrder or orderPrice[1] == 0) {
    profitLoss = 0;
} else if ((isOrder and isLong[1]) and (SellSig or BuyStpSig)) {
    profitLoss = close - orderPrice[1];
} else if ((isOrder and isShort[1]) and (BuySig or SellStpSig)) {
    profitLoss = orderPrice[1] - close;
} else {
    profitLoss = 0;
}



# Total Profit or Loss
def profitLossSum = CompoundValue(1, if IsNaN(isOrder)  or BarNumber() == 1 then 0 else if isOrder then profitLossSum[1] + profitLoss else profitLossSum[1], 0);

# How many trades won or lost
def profitWinners = CompoundValue(1, if IsNaN(profitWinners[1]) or BarNumber() == 1 then 0 else if isOrder and profitLoss > 0 then profitWinners[1] + 1 else profitWinners[1], 0);
def profitLosers = CompoundValue(1, if IsNaN(profitLosers[1])  or BarNumber() == 1 then 0 else if isOrder and profitLoss < 0 then profitLosers[1] + 1 else profitLosers[1], 0);
def profitPush = CompoundValue(1, if IsNaN(profitPush[1])  or BarNumber() == 1 then 0 else if isOrder and profitLoss == 0 then profitPush[1] + 1 else profitPush[1], 0);


# Current Open Trade Profit or Loss
def TradePL = if isLong then Round(((close - orderPrice) / TickSize()) * TickValue()) else if isShort then Round(((orderPrice - close) / TickSize()) * TickValue()) else 0;

# Convert to actual dollars based on Tick Value for bubbles
def dollarProfitLoss = if orderPrice[1] == 0 or IsNaN(orderPrice[1]) then 0 else Round((profitLoss / TickSize()) * TickValue());


# Closed Orders dollar P/L
def dollarPLSum = Round((profitLossSum / TickSize()) * TickValue());


# Split profits or losses by long and short trades
def profitLong = CompoundValue(1, if IsNaN(profitLong[1])  or BarNumber() == 1 then 0 else if isOrder and isLong[1] then profitLong[1] + dollarProfitLoss else profitLong[1], 0);

def profitShort = CompoundValue(1, if IsNaN(profitShort[1])  or BarNumber() == 1 then 0 else if isOrder and isShort[1] then profitShort[1] + dollarProfitLoss else profitShort[1],0);

def countLong = CompoundValue(1, if IsNaN(countLong[1])  or BarNumber() == 1 then 0 else if isOrder and isLong[1] then countLong[1] + 1 else countLong[1], 0);

def countShort = CompoundValue(1, if IsNaN(countShort[1])  or BarNumber() == 1 then 0 else if isOrder and isShort[1] then countShort[1] + 1 else countShort[1], 0);

# What was the biggest winning and losing trade
def biggestWin = CompoundValue(1, if IsNaN(biggestWin[1]) or BarNumber() == 1 then 0 else if isOrder and (dollarProfitLoss > 0) and (dollarProfitLoss > biggestWin[1]) then dollarProfitLoss else biggestWin[1], 0);
def biggestLoss = CompoundValue(1, if IsNaN(biggestLoss[1]) or BarNumber() == 1 then 0 else if isOrder and (dollarProfitLoss < 0) and (dollarProfitLoss < biggestLoss[1]) then dollarProfitLoss else biggestLoss[1], 0);

def ClosedTradeCount = if (isLong or isShort) then orderCount - 1 else orderCount;

def OpenTrades = if (isLong or isShort) then 1 else 0;

# What percent were winners
def PCTWin = if (OpenTrades and (TradePL < 0)) then Round((profitWinners / (ClosedTradeCount + 1)) * 100, 2)
else if (OpenTrades and (TradePL > 0)) then Round(((profitWinners + 1) / (ClosedTradeCount + 1)) * 100, 2)
else Round(((profitWinners) / (ClosedTradeCount)) * 100, 2) ;

# Average trade
def avgTrade = if (OpenTrades and (TradePL < 0)) then Round(((dollarPLSum - TradePL) / (ClosedTradeCount + 1)), 2)
else if (OpenTrades and (TradePL > 0)) then Round(((dollarPLSum + TradePL) / (ClosedTradeCount + 1)), 2)
else Round(((dollarPLSum) / (ClosedTradeCount)), 2) ;


#input showtitle = no;


AddLabel(showtitle, " TS_V9: ", Color.light_gray);
AddLabel(Market_Open_Lbl and isIntraDay, if MarketOpen then "Market Open" else "Market Closed", Color.WHITE);
AddLabel(Tick_Size_Lbl, GetSymbol() + " Tick Size: " + TickSize() + " Value: " + TickValue(), Color.WHITE);
AddLabel(Long_Short_Lbl and (LongTrades and ShortTrades), "Long+Short Trades", Color.WHITE);
AddLabel(Long_Short_Lbl and (LongTrades and !ShortTrades), "Long Trades Only", Color.WHITE);
AddLabel(Long_Short_Lbl and (!LongTrades and ShortTrades), "Short Trades Only", Color.WHITE);
AddLabel(Closed_Orders_Lbl, "Closed Orders: " + ClosedTradeCount ,
if dollarPLSum > 0 then Color.GREEN else
if dollarPLSum < 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNaN(orderPrice) and PL_Lbl then 1 else 0, "Closed+Open P/L: " + AsDollars(TradePL + dollarPLSum),
if ((TradePL + dollarPLSum) > 0) then Color.GREEN else
if ((TradePL + dollarPLSum) < 0) then Color.RED else Color.GRAY);
AddLabel(Avg_Per_Lbl, "Avg per Trade: " + AsDollars(avgTrade),
if avgTrade > 0 then Color.GREEN else
if avgTrade < 0 then Color.RED else Color.GRAY);

AddLabel(Max_Lbl, "MaxUp: " + AsDollars(biggestWin) + " MaxDown: " + AsDollars(biggestLoss), Color.WHITE);
AddLabel(Profit_Lbl, "Long Profit: " + AsDollars(profitLong),
if profitLong > 0 then Color.GREEN else
if profitLong < 0 then Color.RED else Color.GRAY);
AddLabel(Profit_Lbl, "Short Profit: " + AsDollars(profitShort),
if profitShort > 0 then Color.GREEN else
if profitShort < 0 then Color.RED else Color.GRAY);
AddLabel(if !IsNaN(CurrentPosition) and Open_Trades_Lbl and OpenTrades then 1 else 0, "Open: " +
(if isLong then "Bought" else "Sold") + " @ " + orderPrice, Color.WHITE);
AddLabel(if !IsNaN(orderPrice) and Open_Trades_Lbl and OpenTrades then 1 else 0, "Open Trade P/L: " + AsDollars(TradePL),
if (TradePL > 0) then Color.GREEN else
if (TradePL < 0) then Color.RED else Color.GRAY);
AddLabel(Profit_Pct_Lbl, "Profit Percentile: " + aspercent(TradePL/BiggestWin),
if (TradePL > 0) then Color.GREEN else
if (TradePL < 0) then Color.RED else Color.GRAY);
#########################################################################################################################
AddLabel(showLabels,(if tradeDaytimeOnly then  " Trade Daytime | " else "") + "WINS: " + PCTWin + "%",
if PCTWin > 50 then Color.GREEN else
if PCTWin > 40 then Color.YELLOW else Color.GRAY);
#######################################
#Assign Price Color
#######################################
def Ceiling = biggestWin;
def Floor = biggestLoss;
def MidCAT = (((biggestWin + avgTrade) / 2) + avgTrade) / 2;
def MidFAT = (((biggestLoss + avgTrade) / 2) + avgTrade) / 2;
def AvgProfitWinners = (((profitWinners) / (ClosedTradeCount + 1)));
input mult_profit = 50;

########################################
##Long Stop
########################################
def LongStop = if (BuySig) then low else Double.NaN;
def LongStopext = if (IsNaN(LongStop) and isLong) then LongStopext[1] else LongStop;
plot LongStopextline = LongStopext;
LongStopextline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
LongStopextline.SetDefaultColor(Color.ORANGE);
LongStopextline.SetLineWeight(2);

########################################
##Long Targets
########################################
plot LongEntry = if isLong then (orderPrice) else Double.NaN;
LongEntry.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
LongEntry.SetDefaultColor(Color.GREEN);
LongEntry.SetLineWeight(2);

plot AvgProfitLL = if isLong then (orderPrice + ((dollarPLSum) / (ClosedTradeCount) / mult_profit)) else Double.NaN;
AvgProfitLL.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
AvgProfitLL.SetDefaultColor(Color.WHITE);
AvgProfitLL.SetLineWeight(1);


#########################################
##Short Stop
#########################################
def ShortStop = if SellSig then high else Double.NaN;
def ShortStopext = if (IsNaN(ShortStop) and isShort) then ShortStopext[1] else ShortStop;
plot ShortStopextline = ShortStopext;
ShortStopextline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ShortStopextline.SetDefaultColor(Color.ORANGE);
ShortStopextline.SetLineWeight(2);

########################################
##Short Targets
########################################

plot ShortEntry = if isShort then (orderPrice) else Double.NaN;
;
ShortEntry.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
ShortEntry.SetDefaultColor(Color.RED);
ShortEntry.SetLineWeight(2);

plot AvgProfitLS = if isShort then (orderPrice - ((dollarPLSum) / (ClosedTradeCount) / mult_profit)) else Double.NaN;
AvgProfitLS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
AvgProfitLS.SetDefaultColor(Color.WHITE);
AvgProfitLS.SetLineWeight(1);


###################################
##Candle Color
###################################

###################################
##Line Bubbles
###################################
AddChartBubble(LabelsOn and BuySig, AvgProfitLL, "Avg Profit: $" + avgTrade, Color.LiGHT_GREEN);
AddChartBubble(LabelsOn and BuySig, LongStop, "Stop: $ -" + (Orderprice - LongStop) * mult_profit, Color.ORANGE);

AddChartBubble(LabelsOn and SellSig, AvgprofitLS, "Avg Profit: $" + AVGTrade, Color.Red);
AddChartBubble(LabelsOn and SellSig, ShortStop, "Stop: $ -" + (ShortStop - Orderprice) * mult_profit, Color.ORANGE);

## LABELS
plot Sell_12 = if (sell) and hide_sell == 1 then 1 else 0;
Sell_12.AssignValueColor(Color.cyan);
Sell_12.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
Sell_12.SetLineWeight(1);
#Sell_12.Sethiding(if alert4 or alert4[1] or alert4[2] then 0 else 1);
def sellbn12 = if sell_12 then bn else sellbn12[1];

plot Buy_12 = if (buy)  and hide_buy == 1 then 1 else 0;
Buy_12.AssignValueColor(Color.cyan);
Buy_12.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Buy_12.SetLineWeight(1);
Buy_12.Sethiding(PLbuy3_buy);

plot signal_up = direction2 == 1 and direction2[1] < 1;
signal_up.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
signal_up.SetDefaultColor(Color.WHITE);
signal_up.Hide();
signal_up.HideBubble();
signal_up.HideTitle();

plot signal_dn = direction2 == -1 and direction2[1] > -1;
signal_dn.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
signal_dn.SetDefaultColor(Color.WHITE);
signal_dn.Hide();
signal_dn.HideBubble();
signal_dn.HideTitle();

AssignPriceColor(if Strategy_ColoredCandlesOn then  if alert4 and alert4[1] then Color.magenta
else if alert4 then Color.cyan
else if Color_3x and buyerRegular then Color.green
else if Color_3xt and buyerExtreme then Color.green
else if direction == 1 then Color.LIGHT_GREEN
else if Color_blst and close < ST and blastOffVal < trig then Color.white
else if Color_3x and sellerRegular then Color.dark_red
else if Color_3xt and sellerExtreme then Color.Dark_red
else if direction == -1 then Color.RED
else Color.GRAY
else Color.CURRENT);

AddLabel(ag_Skip_lbl,    if AutoAgg2 == no then "Manual AG3" else
                         if AutoAgg2 == yes and ag_skip2 == yes then "Auto AG3 | AG Skip" else
                         if AutoAgg2 == yes and ag_skip2 == no then "Auto AG3" else "", Color.Gray);


AddLabel(Show_Signals_lbl, if Show_Open_Signals == no then "Closed Signals Only" else
                           if Show_Open_Signals == yes then "Show Open Signals" else
                           "", Color.Gray);

AddLabel(show_repaint_Lbl,    if  Sell_12 and PLSellSignal3 then " Subject to repaint: AG3 " else
                         if Sell_12 and PLSellSignal2 then " Subject to repaint: AG2 " else
                         if Sell_12 and PLSellSignal_11 then "" else
                         if Buy_12 and PLBuySignal3 then " Subject to repaint: AG3 " else
                         if Buy_12 and PLBuySignal2 then " Subject to repaint: AG2 " else
                         if Buy_12 and PLBuySignal_11 then ""
                         else "",  if Sell_12 == PLSellSignal3 then Color.cyan else
                         if Buy_12 == PLBuySignal3 then Color.magenta else color.gray);

addlabel(show_Last_lbl, if (buybn > sellbn) then "Last Signal: " + "BUY" else if (sellbn > buybn) then "Last Signal: " + "SELL" else  if (buybn > sellbn) then "Current Signal: " + "BUY" else if (sellbn > buybn) and sell_12 then "Current Signal: " + "SELL" else "",if (buybn > sellbn) or ((buybn > sellbn) and buy_12) then color.cyan else if (sellbn > buybn) or ((sellbn > buybn) and Sell_12) then Color.magenta else color.gray);
 
Last edited:
Mrjs4Cz.png


Study Share Link - http://tos.mx/LPDfqC1 (4/25/23)

Screenshots
dp36FpT.png


Example: C3 line to determine reversal / breakout probability
gFCrzd2.png


Code:
# C3_MF_Line_v2 Created by Christopher84 03/06/2022
# Based off of the Confirmation Candles Study. Main difference is that CC Candles weigh factors of positive
# and negative price movement to create the Consensus_Level. The Consensus_Level is considered positive if
# above zero and negative if below zero.

#Keltner Channel
declare upper;
def displace = 0;
def factorK = 2.0;
def lengthK = 20;
def price = close;
def price1 = open;
input averageType = AverageType.SIMPLE;
def trueRangeAverageType = AverageType.SIMPLE;
def BulgeLengthPrice = 100;
def SqueezeLengthPrice = 100;
def BulgeLengthPrice2 = 20;
def SqueezeLengthPrice2 = 20;
def BulgeLengthPrice3 = 12;
def SqueezeLengthPrice3 = 12;

def shift = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK);
def averageK = MovingAverage(averageType, price, lengthK);
def AvgK = averageK[-displace];
def Upper_BandK = averageK[-displace] + shift[-displace];
def Lower_BandK = averageK[-displace] - shift[-displace];

def conditionK1UP = price >= Upper_BandK;
def conditionK2UP = (Upper_BandK[1] < Upper_BandK) and (Lower_BandK[1] < Lower_BandK);
def conditionK3DN = (Upper_BandK[1] > Upper_BandK) and (Lower_BandK[1] > Lower_BandK);
def conditionK4DN = price < Lower_BandK;
def BandwidthK = (Upper_BandK - Lower_BandK) / AvgK * 100;

def IntermResistance = Highest(price, BulgeLengthPrice);
#IntermResistance.AssignValueColor(if (conditionK2UP) then Color.GREEN else if (conditionK3DN) then Color.RED else Color.GRAY);
def IntermSupport = Lowest(price, SqueezeLengthPrice);
#IntermSupport.AssignValueColor(if (conditionK2UP) then Color.GREEN else if (conditionK3DN) then Color.RED else Color.GRAY);

def NearTResistance = Highest(price, BulgeLengthPrice2);
#NearTResistance.AssignValueColor(if (conditionK2UP) then Color.GREEN else if (conditionK3DN) then Color.RED else Color.GRAY);
#NearTResistance.SetStyle(Curve.SHORT_DASH);
def NearTSupport = Lowest(price, SqueezeLengthPrice2);
#NearTSupport.AssignValueColor(if (conditionK2UP) then Color.GREEN else if (conditionK3DN) then Color.RED else Color.GRAY);
#NearTSupport.SetStyle(Curve.SHORT_DASH);

def NearTResistance1 = Highest(price, BulgeLengthPrice3);
def NearTSupport1 = Lowest(price, SqueezeLengthPrice3);

#MACD with Price
def fastLength = 12;
def slowLength = 26;
def MACDLength = 9;
input MACD_AverageType = {SMA, default EMA};
def MACDLevel = 0.0;

def fastEMA = ExpAverage(price, fastLength);
def slowEMA = ExpAverage(price, slowLength);
def Value;
def Avg;
switch (MACD_AverageType) {
case SMA:
    Value = Average(price, fastLength) - Average(price, slowLength);
    Avg = Average(Value, MACDLength);
case EMA:
    Value = fastEMA - slowEMA;
    Avg = ExpAverage(Value, MACDLength);
}
def Diff = Value - Avg;
def Level = MACDLevel;

def condition1 = Value[1] <= Value;
def condition1D = Value[1] > Value;

#RSI
def RSI_length = 14;
def RSI_AverageType = AverageType.WILDERS;
def RSI_OB = 70;
def RSI_OS = 30;

def NetChgAvg = MovingAverage(RSI_AverageType, price - price[1], RSI_length);
def TotChgAvg = MovingAverage(RSI_AverageType, AbsValue(price - price[1]), RSI_length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
def RSI = 50 * (ChgRatio + 1);

def condition2 = (RSI[3] < RSI) is true or (RSI >= 80) is true;
def condition2D = (RSI[3] > RSI) is true or (RSI < 20) is true;
def conditionOB1 = RSI > RSI_OB;
def conditionOS1 = RSI < RSI_OS;

#MFI
def MFI_Length = 14;
def MFIover_Sold = 20;
def MFIover_Bought = 80;
def movingAvgLength = 1;
def MoneyFlowIndex = Average(MoneyFlow(high, close, low, volume, MFI_Length), movingAvgLength);
def MFIOverBought = MFIover_Bought;
def MFIOverSold = MFIover_Sold;

def condition3 = (MoneyFlowIndex[2] < MoneyFlowIndex) is true or (MoneyFlowIndex > 85) is true;
def condition3D = (MoneyFlowIndex[2] > MoneyFlowIndex) is true or (MoneyFlowIndex < 20) is true;
def conditionOB2 = MoneyFlowIndex > MFIover_Bought;
def conditionOS2 = MoneyFlowIndex < MFIover_Sold;

#Forecast
def na = Double.NaN;
def MidLine = 50;
def Momentum = MarketForecast().Momentum;
def NearT =  MarketForecast().NearTerm;
def Intermed = MarketForecast().Intermediate;
def FOB = 80;
def FOS = 20;
def upperLine = 110;

def condition4 = (Intermed[1] <= Intermed) or (NearT >= MidLine);
def condition4D = (Intermed[1] > Intermed) or (NearT < MidLine);
def conditionOB3 = Intermed > FOB;
def conditionOS3 = Intermed < FOS;
def conditionOB4 = NearT > FOB;
def conditionOS4 = NearT < FOS;

#Change in Price
def lengthCIP = 5;
def CIP = (price - price[1]);
def AvgCIP = ExpAverage(CIP[-displace], lengthCIP);
def CIP_UP = AvgCIP > AvgCIP[1];
def CIP_DOWN = AvgCIP < AvgCIP[1];

def condition5 = CIP_UP;
def condition5D = CIP_DOWN;

#EMA_1
def EMA_length = 8;
def AvgExp = ExpAverage(price[-displace], EMA_length);

def condition6 = (price >= AvgExp) and (AvgExp[2] <= AvgExp);
def condition6D = (price < AvgExp) and (AvgExp[2] > AvgExp);

#EMA_2
def EMA_2length = 20;
def displace2 = 0;
def AvgExp2 = ExpAverage(price[-displace2], EMA_2length);

def condition7 = (price >= AvgExp2) and (AvgExp2[2] <= AvgExp);
def condition7D = (price < AvgExp2) and (AvgExp2[2] > AvgExp);

#DMI Oscillator
def DMI_length = 5;#Typically set to 10
input DMI_averageType = AverageType.WILDERS;
def diPlus = DMI(DMI_length, DMI_averageType)."DI+";
def diMinus = DMI(DMI_length, DMI_averageType)."DI-";
def Osc = diPlus - diMinus;
def Hist = Osc;
def ZeroLine = 0;

def condition8 = Osc >= ZeroLine;
def condition8D = Osc < ZeroLine;

#Trend_Periods
def TP_fastLength = 3;#Typically 7
def TP_slowLength = 4;#Typically 15
def Periods = Sign(ExpAverage(close, TP_fastLength) - ExpAverage(close, TP_slowLength));

def condition9 = Periods > 0;
def condition9D = Periods < 0;

#Polarized Fractal Efficiency
def PFE_length = 5;#Typically 10
def smoothingLength = 2.5;#Typically 5
def PFE_diff = close - close[PFE_length - 1];
def val = 100 * Sqrt(Sqr(PFE_diff) + Sqr(PFE_length)) / Sum(Sqrt(1 + Sqr(close - close[1])), PFE_length - 1);
def PFE = ExpAverage(if PFE_diff > 0 then val else -val, smoothingLength);
def UpperLevel = 50;
def LowerLevel = -50;

def condition10 = PFE > 0;
def condition10D = PFE < 0;
def conditionOB5 = PFE > UpperLevel;
def conditionOS5 = PFE < LowerLevel;

#Bollinger Bands PercentB
input BBPB_averageType = AverageType.SIMPLE;
def BBPB_length = 20;#Typically 20
def Num_Dev_Dn = -2.0;
def Num_Dev_up = 2.0;
def BBPB_OB = 100;
def BBPB_OS = 0;
def upperBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, BBPB_averageType).UpperBand;
def lowerBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, BBPB_averageType).LowerBand;
def PercentB = (price - lowerBand) / (upperBand - lowerBand) * 100;
def HalfLine = 50;
def UnitLine = 100;

def condition11 = PercentB > HalfLine;
def condition11D = PercentB < HalfLine;
def conditionOB6 = PercentB > BBPB_OB;
def conditionOS6 = PercentB < BBPB_OS;

#STARC Bands
def ATR_length = 15;
def SMA_lengthS = 6;
def multiplier_factor = 1.25;
def valS = Average(price, SMA_lengthS);
def average_true_range = Average(TrueRange(high, close, low), length = ATR_length);
def Upper_BandS = valS[-displace] + multiplier_factor * average_true_range[-displace];
def Middle_BandS = valS[-displace];
def Lower_BandS = valS[-displace] - multiplier_factor * average_true_range[-displace];

def condition12 = (Upper_BandS[1] <= Upper_BandS) and (Lower_BandS[1] <= Lower_BandS);
def condition12D = (Upper_BandS[1] > Upper_BandS) and (Lower_BandS[1] > Lower_BandS);

#Klinger Histogram
def Klinger_Length = 13;
def KVOsc = KlingerOscillator(Klinger_Length).KVOsc;
def KVOH = KVOsc - Average(KVOsc, Klinger_Length);
def condition13 = (KVOH > 0);
def condition13D = (KVOH < 0);

#Projection Oscillator
def ProjectionOsc_length = 30;#Typically 10
def MaxBound = HighestWeighted(high, ProjectionOsc_length, LinearRegressionSlope(price = high, length = ProjectionOsc_length));
def MinBound = LowestWeighted(low, ProjectionOsc_length, LinearRegressionSlope(price = low, length = ProjectionOsc_length));
def ProjectionOsc_diff = MaxBound - MinBound;
def PROSC = if ProjectionOsc_diff != 0 then 100 * (close - MinBound) / ProjectionOsc_diff else 0;
def PROSC_OB = 80;
def PROSC_OS = 20;

def condition14 = PROSC > 50;
def condition14D = PROSC < 50;
def conditionOB7 = PROSC > PROSC_OB;
def conditionOS7 = PROSC < PROSC_OS;

#Trend Confirmation Calculator
#Confirmation_Factor range 1-15.
input coloredCandlesOn = yes;
input Confirmation_Factor = 7;
#Use for testing conditions individually. Remove # from line below and change Confirmation_Factor to 1.
#def Agreement_Level = condition1;
def Agreement_LevelOB = 10;
def Agreement_LevelOS = -10;

def Agreement_Level = condition1 + condition2 + condition3 + condition4 + condition5 + condition6 + condition7 + condition8 + condition9 + condition10 + condition11 + condition12 + condition13 + condition14 + conditionK1UP + conditionK2UP;

def Agreement_LevelD = (condition1D + condition2D + condition3D + condition4D + condition5D + condition6D + condition7D + condition8D + condition9D + condition10D + condition11D + condition12D + condition13D + condition14D + conditionK3DN + conditionK4DN);

def Consensus_Level = Agreement_Level - Agreement_LevelD;

def UP = Consensus_Level >= 6;
def DOWN = Consensus_Level < -6;

def priceColor = if UP then 1
                 else if DOWN then -1
                 else priceColor[1];

#Keltner #2
input showCloud = yes;
def factorK2 = 3.25;
def lengthK2 = 20;

def shiftK2 = factorK2 * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK2);
def averageK2 = MovingAverage(averageType, price, lengthK2);
def AvgK2 = averageK2[-displace];
def Upper_BandK2 = averageK2[-displace] + shiftK2[-displace];
def Lower_BandK2 = averageK2[-displace] - shiftK2[-displace];
def condition_BandRevDn = (Upper_BandS > Upper_BandK2);
def condition_BandRevUp = (Lower_BandS < Lower_BandK2);

#Consensus_Level.AssignValueColor(
#if Consensus_Level > Consensus_Level[1] and Consensus_Level >= 0 then Color.LIGHT_GREEN
#else if Consensus_Level < Consensus_Level[1] and Consensus_Level >= 0 then Color.LIGHT_GREEN
#else if Consensus_Level < Consensus_Level[1] and Consensus_Level < 0 then Color.RED else
#if Consensus_Level > Consensus_Level[1] and Consensus_Level < 0 then Color.RED
#else Color.GRAY);

def Zero_Line = 0;


#AddCloud(Consensus_Level, Agreement_LevelOB, Color.LIGHT_RED, Color.CURRENT);
#AddCloud(Consensus_Level, Agreement_LevelOS, Color.CURRENT, Color.LIGHT_GREEN);

#plot BulgeCC = Highest(Consensus_Level, BulgeLengthCC);
#BulgeCC.AssignValueColor(if (conditionK2) then Color.GREEN else if (conditionK3) then Color.RED else Color.GRAY);

#plot SqueezeCC = Lowest(Consensus_Level, SqueezeLengthCC);
#SqueezeCC.AssignValueColor(if (conditionK2) then Color.GREEN else if (conditionK3) then Color.RED else Color.GRAY);

#plot BulgeCC2 = Highest(Consensus_Level, BulgeLengthCC2);
#BulgeCC2.AssignValueColor(if (conditionK2) then Color.GREEN else if (conditionK3) then Color.RED else Color.GRAY);
#BulgeCC2.SetStyle(Curve.SHORT_DASH);

#plot SqueezeCC2 = Lowest(Consensus_Level, SqueezeLengthCC2);
#SqueezeCC2.AssignValueColor(if (conditionK2) then Color.GREEN else if (conditionK3) then Color.RED else Color.GRAY);
#SqueezeCC2.SetStyle(Curve.SHORT_DASH);
##########################################################################################################################

script WMA_Smooth {
    input price = hl2;
    plot smooth = (4 * price
+ 3 * price[1]
+ 2 * price[2]
+ price[3]) / 10;
}

script Phase_Accumulation {
# This is Ehler's Phase Accumulation code. It has a full cycle delay.
# However, it computes the correction factor to a very high degree.
#
    input price = hl2;

    rec Smooth;
    rec Detrender;
    rec Period;
    rec Q1;
    rec I1;
    rec I1p;
    rec Q1p;
    rec Phase1;
    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase1;
    rec InstPeriod1;
    rec InstPeriod;
    def CorrectionFactor;

    if BarNumber() <= 5
    then {
        Period = 0;
        Smooth = 0;
        Detrender = 0;
        CorrectionFactor = 0;
        Q1 = 0;
        I1 = 0;
        Q1p = 0;
        I1p = 0;
        Phase = 0;
        Phase1 = 0;
        DeltaPhase1 = 0;
        DeltaPhase = 0;
        InstPeriod = 0;
        InstPeriod1 = 0;
    } else {
        CorrectionFactor = 0.075 * Period[1] + 0.54;

# Smooth and detrend my smoothed signal:
        Smooth = WMA_Smooth(price);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

# Compute Quadrature and Phase of Detrended signal:
        Q1p = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1p = Detrender[3];

# Smooth out Quadrature and Phase:
        I1 = 0.15 * I1p + 0.85 * I1p[1];
        Q1 = 0.15 * Q1p + 0.85 * Q1p[1];

# Determine Phase
        if I1 != 0
        then {
# Normally, ATAN gives results from -pi/2 to pi/2.
# We need to map this to circular coordinates 0 to 2pi

            if Q1 >= 0 and I1 > 0
            then { # Quarant 1
                Phase1 = ATan(AbsValue(Q1 / I1));
            } else if Q1 >= 0 and I1 < 0
            then { # Quadrant 2
                Phase1 = Double.Pi - ATan(AbsValue(Q1 / I1));
            } else if Q1 < 0 and I1 < 0
            then { # Quadrant 3
                Phase1 = Double.Pi + ATan(AbsValue(Q1 / I1));
            } else { # Quadrant 4
                Phase1 = 2 * Double.Pi - ATan(AbsValue(Q1 / I1));
            }
        } else if Q1 > 0
        then { # I1 == 0, Q1 is positive
            Phase1 = Double.Pi / 2;
        } else if Q1 < 0
        then { # I1 == 0, Q1 is negative
            Phase1 = 3 * Double.Pi / 2;
        } else { # I1 and Q1 == 0
            Phase1 = 0;
        }

# Convert phase to degrees
        Phase = Phase1 * 180 / Double.Pi;

        if Phase[1] < 90 and Phase > 270
        then {
# This occurs when there is a big jump from 360-0
            DeltaPhase1 = 360 + Phase[1] - Phase;
        } else {
            DeltaPhase1 = Phase[1] - Phase;
        }

# Limit our delta phases between 7 and 60
        if DeltaPhase1 < 7
        then {
            DeltaPhase = 7;
        } else if DeltaPhase1 > 60
        then {
            DeltaPhase = 60;
        } else {
            DeltaPhase = DeltaPhase1;
        }

# Determine Instantaneous period:
        InstPeriod1 =
-1 * (fold i = 0 to 40 with v=0 do
if v < 0 then
v
else if v > 360 then
-i
else
v + GetValue(DeltaPhase, i, 41)
);

        if InstPeriod1 <= 0
        then {
            InstPeriod = InstPeriod[1];
        } else {
            InstPeriod = InstPeriod1;
        }

        Period = 0.25 * InstPeriod + 0.75 * Period[1];
    }
    plot DC = Period;
}

script Ehler_MAMA {
    input price = hl2;
    input FastLimit = 0.5;
    input SlowLimit = 0.05;


    rec Period;
    rec Period_raw;
    rec Period_cap;
    rec Period_lim;

    rec Smooth;
    rec Detrender;
    rec I1;
    rec Q1;
    rec jI;
    rec jQ;
    rec I2;
    rec Q2;
    rec I2_raw;
    rec Q2_raw;

    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase_raw;
    rec alpha;
    rec alpha_raw;

    rec Re;
    rec Im;
    rec Re_raw;
    rec Im_raw;

    rec SmoothPeriod;
    rec vmama;
    rec vfama;

    def CorrectionFactor = Phase_Accumulation(price).CorrectionFactor;

    if BarNumber() <= 5
    then {
        Smooth = 0;
        Detrender = 0;

        Period = 0;
        Period_raw = 0;
        Period_cap = 0;
        Period_lim = 0;
        I1 = 0;
        Q1 = 0;
        I2 = 0;
        Q2 = 0;
        jI = 0;
        jQ = 0;
        I2_raw = 0;
        Q2_raw = 0;
        Re = 0;
        Im = 0;
        Re_raw = 0;
        Im_raw = 0;
        SmoothPeriod = 0;
        Phase = 0;
        DeltaPhase = 0;
        DeltaPhase_raw = 0;
        alpha = 0;
        alpha_raw = 0;
        vmama = 0;
        vfama = 0;
    } else {
# Smooth and detrend my smoothed signal:
        Smooth = WMA_Smooth(price);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

        Q1 = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1 = Detrender[3];

        jI = ( 0.0962 * I1
+ 0.5769 * I1[2]
- 0.5769 * I1[4]
- 0.0962 * I1[6] ) * CorrectionFactor;

        jQ = ( 0.0962 * Q1
+ 0.5769 * Q1[2]
- 0.5769 * Q1[4]
- 0.0962 * Q1[6] ) * CorrectionFactor;

# This is the complex conjugate
        I2_raw = I1 - jQ;
        Q2_raw = Q1 + jI;

        I2 = 0.2 * I2_raw + 0.8 * I2_raw[1];
        Q2 = 0.2 * Q2_raw + 0.8 * Q2_raw[1];

        Re_raw = I2 * I2[1] + Q2 * Q2[1];
        Im_raw = I2 * Q2[1] - Q2 * I2[1];

        Re = 0.2 * Re_raw + 0.8 * Re_raw[1];
        Im = 0.2 * Im_raw + 0.8 * Im_raw[1];

# Compute the phase
        if Re != 0 and Im != 0
        then {
            Period_raw = 2 * Double.Pi / ATan(Im / Re);
        } else {
            Period_raw = 0;
        }

        if Period_raw > 1.5 * Period_raw[1]
        then {
            Period_cap = 1.5 * Period_raw[1];
        } else if Period_raw < 0.67 * Period_raw[1] {
            Period_cap = 0.67 * Period_raw[1];
        } else {
            Period_cap = Period_raw;
        }

        if Period_cap < 6
        then {
            Period_lim = 6;
        } else if Period_cap > 50
        then {
            Period_lim = 50;
        } else {
            Period_lim = Period_cap;
        }

        Period = 0.2 * Period_lim + 0.8 * Period_lim[1];
        SmoothPeriod = 0.33 * Period + 0.67 * SmoothPeriod[1];

        if I1 != 0
        then {
            Phase = ATan(Q1 / I1);
        } else if Q1 > 0
        then { # Quadrant 1:
            Phase = Double.Pi / 2;
        } else if Q1 < 0
        then { # Quadrant 4:
            Phase = -Double.Pi / 2;
        } else { # Both numerator and denominator are 0.
            Phase = 0;
        }

        DeltaPhase_raw = Phase[1] - Phase;
        if DeltaPhase_raw < 1
        then {
            DeltaPhase = 1;
        } else {
            DeltaPhase = DeltaPhase_raw;
        }

        alpha_raw = FastLimit / DeltaPhase;
        if alpha_raw < SlowLimit
        then {
            alpha = SlowLimit;
        } else {
            alpha = alpha_raw;
        }
        vmama = alpha * price + (1 - alpha) * vmama[1];
        vfama = 0.5 * alpha * vmama + (1 - 0.5 * alpha) * vfama[1];
    }

    plot MAMA = vmama;
    plot FAMA = vfama;
}


input price2 = hl2;
input FastLimit = 0.5;
input SlowLimit = 0.05;

def MAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).MAMA;
def FAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).FAMA;

def Crossing = Crosses((MAMA < FAMA), yes);
#Crossing.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

def Crossing1 = Crosses((MAMA > FAMA), yes);
#Crossing1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

##################################
plot C3_MF_Line = (MAMA + FAMA) / 2;
C3_MF_Line.SetPaintingStrategy(PaintingStrategy.Line);
C3_MF_Line.SetLineWeight(3);
C3_MF_Line.AssignValueColor(if coloredCandlesOn and ((priceColor == 1) and (price1 > Upper_BandS) and (condition_BandRevDn)) then Color.YELLOW else if coloredCandlesOn and ((priceColor == -1) and (price1 < Lower_BandS) and (condition_BandRevUp)) then Color.YELLOW else if coloredCandlesOn and priceColor == -1 then Color.RED  else if coloredCandlesOn and (priceColor == 1) then Color.GREEN else Color.CURRENT);

#Vertical Line
#AddVerticalLine(( GetDay() <> GetDay()[1]), "", Color.Dark_Gray, Curve.SHORT_DASH);
 
Last edited:
VjEsdpF.png


EMAD Range (newest version "V1000") - http://tos.mx/5jmDs9c

2k8hZIM.png


Code:
#EMAD Range by @ Christopher84
#EMAD V1000 - added arrow conditions - histogram - and color conditions HODL

#DECLARATIONS
declare lower;


#USER INPUTS
input showHLLH = no;
input showHowToLabel = yes;
input ShowColorCodeLabel = no;
input showtestlabels = no;
input showEMACloud = yes;
input showBubbles = no;
input showTripleExh = yes;
input showehlers = no;
input showMAD = no;
input showverticalline = yes;
input bandLength = 100;
input bandLength2 = 100;
input ELlength = 34;
Input LengtH_MAD = 4;
input fastLength = 10;
input slowLength = 35;
input lengthBAD = 3;
input smoothLength = 12;
input smoothLength2 = 14;
input ATRPeriod = 5;
input ATRFactor = 2.0;
input length_3x = 1000;
input priceType = close;
input emadLineWeight = 2;
input averageType = AverageType.WILDERS;
input averageType_Sq = AverageType.SIMPLE;
input firstTrade_Sq = {default long, short};
input trailType = {default modified, unmodified};
input firstTrade = {default long, short};
input filterBounceArrows = 1;
input filter_3x = 50;
input Control_3x = 3;
input crossabovebelowzero = 20;
input bandlengthbottom2 = 3;
input Lookback = 20;
input cloudlinelook = 20;
input LHHL_Lookback = 1;
input Steplookback = 10;
input filterZeroline = 20;
input topbanddownlookback = 1;
input bottombanduplookback = 1;
input SqueezeLook = 5;
input alert4lookback = 21;
input PreviousStepsDown = 2;
input PreviousStepsUp = 2;
input alert4control = 2;
input tradeDaytimeOnly = yes; #hint tradeDaytimeOnly: (IntraDay Only) Only perform trades during hours stated
input OpenTime = 0730; #hint OpenTime: Opening time of market
input CloseTime = 1800; #hint CloseTime: Closing time of market

def bn = barnumber();
def Begin = SecondsFromTime(OpenTime);
def End = SecondsTillTime(CloseTime);
def isIntraDay = if GetAggregationPeriod() > 14400000 or GetAggregationPeriod() == 0 then 0 else 1;
def MarketOpen = if !tradeDaytimeOnly or !isIntraDay then 1 else if tradeDaytimeOnly and isIntraDay and Begin > 0 and End > 0 then 1 else 0;

#GLOBAL COLOR DEFINITIONS
DefineGlobalColor("Green", CreateColor(0, 155, 0));
DefineGlobalColor("Red", CreateColor(225, 105, 105));
DefineGlobalColor("Gray", CreateColor(192, 192, 192));
DefineGlobalColor("Yellow", CreateColor(231, 190, 0));

## UPPER EMAD LINE
def fastExpAvg = ExpAverage(priceType, fastLength);
def slowExpAvg = ExpAverage(priceType, slowLength);
def EMAD = (priceType - fastExpAvg);
def EMAD2 = (priceType - slowExpAvg);
def EMADAvg = (EMAD + EMAD2) / 2;
def upperEMADLine = ExpAverage(EMADAvg, smoothLength);
## LOWER EMAD LINE
def emadOpen = (upperEMADLine + upperEMADLine[1]) / 2;
def emadHigh = Max(upperEMADLine, upperEMADLine[1]);
def emadLow = Min(upperEMADLine, upperEMADLine[1]);
def emadClose = upperEMADLine;
def bottom = Min(emadClose[1], emadLow);
def tr = TrueRange(emadHigh, emadClose, emadLow);
def ptr = tr / (bottom + tr / 2);
def APTR = MovingAverage(averageType, ptr, smoothLength2);
def upperBand = emadClose[1] + (APTR * emadOpen);
def lowerBand = emadClose[1] - (APTR * emadOpen);
def lowerEMADLine = (upperBand + lowerBand) / 2;
## TOP AND BOTTOM BANDS
def zeroLineData = if IsNaN(close) then Double.NaN else 0;
def EMADSUp = upperEMADLine > zeroLineData;
def EMADSDown = upperEMADLine < zeroLineData;
def EMADdown = (lowerEMADLine > upperEMADLine);
def EMADup = (upperEMADLine >= lowerEMADLine);
def topBand = Highest(lowerEMADLine, bandLength);
def bottomBand = Lowest(lowerEMADLine, bandLength);
def zerolinedatacondition = if (zerolinedata > topBand) then topBand else if (zerolinedata < bottomBand) then bottomBand else 0;
## Master
def masteremadline = (upperEMADLine + lowerEMADLine) / 2;
## BAND DIRECTION (USED ONLY FOR COLORING - NOT USED FOR PLOTS)
def topBandStepDown = if topBand < topBand[1] then 1 else 0;
def topBandStepUp = if topBand > topBand[1] then 1 else 0;
def bottomBandStepDown = if bottomBand < bottomBand[1] then 1 else 0;
def bottomBandStepUp = if bottomBand > bottomBand[1] then 1 else 0;
def bothBandsDown = bottomBandStepDown and topBandStepDown;
def bothBandsUp = bottomBandStepUp and topBandStepUp;
def bullBias = (bottomBand > zeroLineData);
def bearBias = (topBand < zeroLineData);
## BUBBLE CALCULATIONS (USED ONLY FOR BUBBLES)
def midBand = (upperBand + lowerBand) / 2;
def crossesUp = if (midBand[1] > upperEMADLine[1])and(midBand < upperEMADLine) then 1 else 0;
def crossesDown = if (upperEMADLine[1] > midBand[1])and(upperEMADLine < midBand) then 1 else 0;
def valueUp = if crossesUp then midBand else 0;
def valueDown = if crossesDown then midBand else 0;
def crossesUpline = if (valueUp - bottomBand) == 0 then 1 else 0;
def crossesDownline = if (valueDown - topBand) == 0 then 1 else 0;
def crossesUpline_filter = if crossesUpline and (crossesUpline[1] or crossesUpline[2]  or crossesUpline[3]   or crossesUpline[4])then 0 else 1;
def crossesDownline_filter = if crossesDownline and (crossesDownline[1] or crossesDownline[2]  or crossesDownline[3]   or crossesDownline[4])then 0 else 1;
def crossesUpZeroline = if (valueUp) == 0 then 1 else 0;
def crossesDownZeroline = if (valueDown) == 0 then 1 else 0;
def crossesUpBottomlinebn = if crossesUpline and !crossesUpline[1] then bn else crossesUpBottomlinebn[1];
def crossesDownToplinebn = if crossesDownline and !crossesDownline[1] then bn else crossesDownToplinebn[1];
def crossuplinewithin = if crossesUpBottomlinebn < bn then bn - crossesUpBottomlinebn else crossuplinewithin[1];
def crossdownlinewithin = if crossesDownToplinebn < bn then bn - crossesDownToplinebn else crossdownlinewithin[1];
def crosslinefirst = if crossuplinewithin < crossdownlinewithin then 1 else 0;
def crosslinelogic = crossesUpBottomlinebn > crossesDownToplinebn;
def HL = crossesUpline == 0 and crossesDownline == 0 and upperEMADLine crosses above lowerEMADLine;  #Normal HL LH condition
def LH = crossesDownline == 0 and upperEMADLine crosses below lowerEMADLine; #Normal HL LH condition
def bounceUpOnce = crossesUpline <> crossesUpline[1]; #XUpBtm happened previous bar or on current bar
def bounceDnOnce = crossesDownline <> crossesDownline[1];
def trackCrUp = if bounceUpOnce then 0 else if HL then 1 else trackCrUp[1];
def trackCrDn = if bounceDnOnce then 0 else if LH then 1 else trackCrDn[1];
## SECOND HL AND LH
def HLalready = if trackCrUp and !trackCrUp[1] then 1 else 0;
def LHalready = if trackCrDn and !trackCrDn[1] then 1 else 0;
def HL2 = HLalready == 0 and upperEMADLine crosses above lowerEMADLine;
def LH2 = LHalready == 0 and upperEMADLine crosses below lowerEMADLine;
def crossedUpOnce = HLalready <> HLalready[1];
def crossedDnOnce = LHalready <> LHalready[1];
def trackCrUp2 = if crossedUpOnce then 0 else if HL2 then 1 else trackCrUp2[1];
def trackCrDn2 = if crossedDnOnce then 0 else if LH2 then 1 else trackCrDn2[1];
#####################################################
##                                                 ##
#####################################################
def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def trueRange_Sq;
switch (trailType) {
case modified:
    trueRange_Sq = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange_Sq = TrueRange(high, close, low);
}
def loss_Sq = ATRFactor * MovingAverage(averageType_Sq, trueRange_Sq, ATRPeriod);
def state_Sq = {default init, long, short};
def trail_Sq;
switch (state_Sq[1]) {
case init:
    if (!IsNaN(loss_Sq)) {
        switch (firstTrade) {
        case long:
            state_Sq = state_Sq.long;
            trail_Sq =  close - loss_Sq;
        case short:
            state_Sq = state_Sq.short;
            trail_Sq = close + loss_Sq;
    }
    } else {
        state_Sq = state_Sq.init;
        trail_Sq = Double.NaN;
    }
case long:
    if (close > trail_Sq[1]) {
        state_Sq = state_Sq.long;
        trail_Sq = Max(trail_Sq[1], close - loss_Sq);
    } else {
        state_Sq = state_Sq.short;
        trail_Sq = close + loss_Sq;
    }
case short:
    if (close < trail_Sq[1]) {
        state_Sq = state_Sq.short;
        trail_Sq = Min(trail_Sq[1], close + loss_Sq);
    } else {
        state_Sq = state_Sq.long;
        trail_Sq =  close - loss_Sq;
    }
}
def TrailingStop_Sq = trail_Sq;
def H = Highest(TrailingStop_Sq, 12);
def L = Lowest(TrailingStop_Sq, 12);
def BulgeLengthPrice = 100;
def SqueezeLengthPrice = 100;
def BandwidthC3 = (H - L);
def IntermResistance2 = Highest(BandwidthC3, BulgeLengthPrice);
def IntermSupport2 = Lowest(BandwidthC3, SqueezeLengthPrice);
def sqzTrigger = BandwidthC3 <= IntermSupport2;
def sqzLevel = if !sqzTrigger[1] and sqzTrigger then hl2 else if !sqzTrigger then Double.NaN else sqzLevel[1];
def Squeeze_Alert_1 = if sqzLevel then (upperEMADLine + lowerEMADLine) / 2 else (upperEMADLine + lowerEMADLine) / 2 ;
#####################################################
##                                                 ##
#####################################################
def over_bought_3x = 80;
def over_sold_3x = 20;
def KPeriod_3x = 10;
def DPeriod_3x = 10;
def priceH1 = high;
def priceL1 = low;
def priceC1 = close;
def priceO1 = close;
def priceH_3x = high;
def priceL_3x = low;
def priceC_3x = close;
def SlowK_3x = reference StochasticFull(over_bought_3x,  over_sold_3x,  KPeriod_3x,  DPeriod_3x,  priceH_3x,  priceL_3x,  priceC_3x,  3, if (averageType == 1) then AverageType.SIMPLE else AverageType.EXPONENTIAL).FullK;
def MACD_3x = reference MACD()."Value";
def priceMean_3x = Average(MACD_3x, length_3x);
def MACD_stdev_3x =  (MACD_3x - priceMean_3x) / StDev(MACD_3x, length_3x);
def dPlus_3x = reference DMI()."DI+";
def dMinus_3x = reference DMI()."DI-";
def sellerRegular = SlowK_3x < 20 and MACD_stdev_3x < -1 and dPlus_3x < 15;
def sellerExtreme = SlowK_3x < 20 and MACD_stdev_3x < -2 and dPlus_3x < 15;
def buyerRegular = SlowK_3x > 80 and MACD_stdev_3x > 1 and dMinus_3x < 15;
def buyerExtreme = SlowK_3x > 80 and MACD_stdev_3x > 2 and dMinus_3x < 15;
def ExtremeBuy1 = if sellerExtreme[1] and !sellerExtreme then 1 else 0;
def ExtremeSell1 = if buyerExtreme[1] and !buyerExtreme then 1 else 0;
def RegularSell1 = if buyerRegular[1] and !buyerRegular then 1 else 0;
def RegularBuy1= if sellerRegular[1] and !sellerRegular then 1 else 0;
#####################################################
##                                                 ##
#####################################################
def priceE = (emadhigh + emadlow) / 2;
def coeff = ELlength * priceE * priceE - 2 * priceE * sum(priceE, ELlength)[1] + sum(priceE * priceE, ELlength)[1];
def Ehlers =  sum(coeff * priceE, ELlength) / sum(coeff, ELlength);
#####################################################
##                                                 ##
#####################################################
def dataA = masterEMADLine;
def dataA1 =
    fold aD = 0
    to LengtH_MAD
    with k = 0
    do k + dataA[aD];
def MAEMAD = dataA1 / LengtH_MAD;
def MAD = MAEMAD;
def ElCrossDN = ehlers crosses above masterEMADline;
def ElCrossUP = ehlers crosses below masterEMADline;
def bullBias2 = (emadsup);
def bearBias2 = (emadsdown);
def MADehlers = (MAD - Ehlers)/2;
def Madebad = madehlers + ehlers;
def madebadavg = average(madebad, lengthBAD);
def crossmadeup = madebad > madebad[1];
def crossmadedn = madebad < madebad[1];
def crossmade2up = if (madebad < masterEMADLine) and crossmadeup and (bullBias2 > 0) then 1 else 0;
def crossmade2dn = if (madebad > masterEMADLine) and crossmadedn and (bearBias2 > 0) then 1 else 0;
def crossmade2 = if (madebad < masterEMADLine) and crossmadeup and (bullBias2 > 0) then 1 else if (madebad > masterEMADLine) and crossmadedn and (bearBias2 > 0) then -1 else 0;
def crossmade0 = if (!crossmade2[1] or !crossmade2[1]) and (crossmade2 == 0) then 1 else 0;
#####################################################
##                                                 ##
#####################################################
def pd = 22;
def bbl = 20;
def mult = 2.0;
def lb = 50;
def ph = 0.85;
def ltLB = 40;
def mtLB = 14;
def str = 3;
def wvf = ((Highest(close, pd) - low) / (Highest(close, pd))) * 100;
def sDev = mult * StDev(wvf, bbl);
def midLine1 = SimpleMovingAvg(wvf, bbl);
def lowerBand1 = midLine1 - sDev;
def upperBand1 = midLine1 + sDev;
def rangeHigh = (Highest(wvf, lb)) * ph;
def upRange = low > low[1] and close > high[1];
def upRange_Aggr = close > close[1] and close > open[1];
def filtered = ((wvf[1] >= upperBand1[1] or wvf[1] >= rangeHigh[1]) and (wvf < upperBand1 and wvf < rangeHigh));
def filtered_Aggr = (wvf[1] >= upperBand1[1] or wvf[1] >= rangeHigh[1]);
def alert4 = upRange_Aggr and close > close[str] and (close < close[ltLB] or close < close[mtLB]) and filtered_Aggr;
def alert4close = if alert4 then close else 0;
def crossmade = if (madebad < masterEMADLine) and crossmadeup then 1 else if (madebad > masterEMADLine) and crossmadedn then -1 else 0;
def madedn = (madebad > masterEMADLine);
def madeup = (madebad < masterEMADLine);
def made2 = madebadavg;
def made3 = if !madedn and (made2 <= zerolinedata) then madebadavg else double.nan;
def made4 = if !madeup and (made2 >= zerolinedata) then madebadavg else double.nan;
def madecrossupavg = if made2 crosses below masterEMADLine then 1 else 0;
def madecrossdownavg = if made2 crosses above masterEMADLine then 1 else 0;
def crossmadelogicup = if madecrossupavg and !madecrossupavg[1] then 1 else 0;
def crossmadelogicdown = if madecrossdownavg and !madecrossdownavg[1] then 1 else 0;
def crossmademorelogicup = if crossmadelogicup and crosslinelogic and emadup[1] then 1 else 0;
def crossmademorelogicdown = if crossmadelogicdown and !crosslinelogic and emaddown[1] then 1 else 0;
def EmaPushStepUp = if topBandStepUp and EmadUp and (((upperEMADLine) - bottomband) == 0) then 1 else 0;;
def EmaPushStepDown = if bottomBandStepDown and EmadDown and (((lowerEMADLine) - bottomband) == 0) then 1 else 0;
def HLFilter = if HL[1] < HL then 1 else 0;
def LHFilter = if LH[1] > LH then 1 else 0;
def HLFilter2 = if HL[2] < HL[1] then 1 else 0;
def LHFilter2 = if LH[2] > LH[1] then 1 else 0;
#####################################################
##                                                 ##
#####################################################
def ValueUp_lookback = fold index1 = 1 to filterBounceArrows with x1 do x1 + absvalue(valueUp)[index1];
def ValueDown_lookback = fold index2 = 1 to filterBounceArrows with x2 do x2 + absvalue(valueDown)[index2];
def topBandStepDown_lookback = fold index3 = 1 to Steplookback with x3 do x3 + topBandStepDown[index3];
def topBandStepUp_lookback = fold index4 = 1 to Steplookback with x4 do x4 + topBandStepUp[index4];
def bottomBandStepDown_lookback = fold index5 = 1 to Steplookback with x5 do x5 + bottomBandStepDown[index5];
def bottomBandStepUp_lookback = fold index6 = 1 to Steplookback with x6 do x6 + bottomBandStepUp[index6];
def bothBandsDown_lookback = fold index7 = 1 to filterBounceArrows with x7 do x7 + bothBandsDown[index7];
def bothBandsUp_lookback = fold index8 = 1 to filterBounceArrows with x8 do x8 + bothBandsUp[index8];
def bullBias_lookback = fold index9 = 1 to filterBounceArrows with x9 do x9 + bullBias[index9];
def bearBias_lookback = fold index10 = 1 to filterBounceArrows with x10 do x10 + bearBias[index10];
def crossesUpZeroline_lookback = fold index11 = 1 to filterZeroline with x11 do x11 + crossesUpZeroline[index11];
def crossesDownZeroline_lookback = fold index12 = 1 to filterZeroline with x12 do x12 + crossesDownZeroline[index12];
def crossesUpBottomline_lookback = fold index13 = 1 to filterBounceArrows with x13 do x13 + crossesUpline[index13];
def crossesDownTopline_lookback = fold index14 = 1 to filterBounceArrows with x14 do x14 + crossesDownline[index14];
def CrossedUPaboveZero_lookback = fold index15 = 1 to crossabovebelowzero with x15 do x15 + crossesUpZeroline[index15];
def CrossedDOWNbelowZero_lookback = fold index16 = 1 to crossabovebelowzero with x16 do x16 + crossesDownZeroline[index16];
def HL_lookback = fold index17 = 1 to LHHL_Lookback with x17 do x17 + HL[index17];
def LH_lookback = fold index18 = 1 to LHHL_Lookback with x18 do x18 + LH[index18];
def upabovezero_lookback = fold index19 = 1 to crossabovebelowzero with x19 do x19 + HL[index19];
def downbelowzero_lookback = fold index20 = 1 to crossabovebelowzero with x20 do x20 + LH[index20];
def PriceMonitor = fold index21 = 1 to crossabovebelowzero with x21 do x21 + HL[index21];
def ExtremeBuy1_lookback = fold index24 = 1 to filter_3x with x24 do x24 + ExtremeBuy1[index24];
def ExtremeSell1_lookback = fold index25 = 1 to filter_3x with x25 do x25 + ExtremeSell1[index25];
def RegularSell1_lookback = fold index26 = 1 to filter_3x with x26 do x26 + RegularSell1[index26];
def RegularBuy1_lookback = fold index27 = 1 to filter_3x with x27 do x27 + RegularBuy1[index27];
def Squeeze_lookback = fold index28 = 1 to SqueezeLook with x28 do x28 + Squeeze_Alert_1[index28];
def ElCrossDN_lookback = fold index29 = 1 to filterBounceArrows with x29 do x29 + ElCrossDN[index29];
def ElCrossUP_lookback = fold index30 = 1 to filterBounceArrows with x30 do x30 + ElCrossUP[index30];
def bearBias2_lookback = fold index31 = 1 to filterBounceArrows with x31 do x31 + bearBias2[index31];
def bullBias2_lookback = fold index32 = 1 to filterBounceArrows with x32 do x32 + bullBias2[index32];
def crossmade0_lookback = fold index33 = 1 to cloudlinelook with x33 do x33 + crossmade0[index33];
def alert4_lookback = fold index34 = 1 to alert4lookback with x34 do x34 + alert4close[index34];
#####################################################
##                                                 ##
#####################################################
def bubblehidertopdown = topBandStepDown_lookback > PreviousStepsDown;
def bubblehidertopup = topBandStepup_lookback > PreviousStepsUp;
def bubblehiderbottomdown = bottomBandStepDown_lookback > PreviousStepsDown;
def bubblehiderbottomup = bottomBandStepup_lookback > PreviousStepsUp;
def UP1 = if marketopen and (!bubblehidertopdown or !bubblehiderbottomdown) and !EmaPushStepDown and crossmademorelogicup then midBand else double.nan;
def DOWN1 = if marketopen and (!bubblehidertopup or !bubblehiderbottomup) and !EmaPushStepUp and crossmademorelogicdown then midBand else double.nan;
#####################################################
##                                                 ##
#####################################################
plot zeroLine = zerolinedata;
plot Squeeze_Alert = if sqzLevel then (upperEMADLine + lowerEMADLine) / 2 else (upperEMADLine + lowerEMADLine) / 2 ;
plot ExtremeBuy = if showTripleExh and sellerExtreme[1] and !sellerExtreme then midband else Double.NaN;
plot ExtremeSell = if showTripleExh and buyerExtreme[1] and !buyerExtreme then midband else Double.NaN;
plot RegularSell = if showTripleExh and buyerRegular[1] and !buyerRegular then midband else Double.NaN;
plot RegularBuy = if showTripleExh and sellerRegular[1] and !sellerRegular then midband else Double.NaN;
plot topBandPlot = topBand;
plot bottomBandPlot = bottomBand;
plot upperEMADLinePlot = upperEMADLine;
plot lowerEMADLinePlot = lowerEMADLine;
plot masterEMADLinePlot2 = (upperEMADLine + lowerEMADLine) / 2;
plot masterEMADLinePlot = ((upperEMADLinePlot + lowerEMADLinePlot) / 2);
plot made1 = made4;
plot made = made3;
plot UP = UP1;
plot DOWN = DOWN1;
plot firstHL = if showHLLH and trackCrUp and !trackCrUp[1] then lowerEMADLine else double.nan;
plot firstLH = if showHLLH and trackCrDn and !trackCrDn[1] then lowerEMADLine else double.nan;
plot secondHL = if showHLLH and trackCrUp2 and !trackCrUp2[1] and !crossesUpline then lowerEMADLine else double.nan;
plot secondLH = if showHLLH and trackCrDn2 and !trackCrDn2[1] and !crossesDownline then lowerEMADLine else double.nan;
#####################################################
##                                                 ##
#####################################################
def firstHL2 = if trackCrUp and !trackCrUp[1] then 1 else 0;
def firstLH2 = if trackCrDn and !trackCrDn[1] then 1 else 0;
def HLBuy = if firstHL2 and regularsell1 or extremesell1 then 1 else 0;
def LHSell = if firstHL2 and regularbuy1 or extremebuy1 then 1 else 0;
#####################################################
##                                                 ##
#####################################################
UP.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
UP.SetLineWeight(1);
UP.SetDefaultColor(Color.white);
UP.HideBubble();
UP.HideTitle();
#####################################################
##                                                 ##
#####################################################
DOWN.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
DOWN.SetLineWeight(1);
DOWN.SetDefaultColor(Color.white);
DOWN.HideBubble();
DOWN.HideTitle();
#####################################################
##                                                 ##
#####################################################
made1.AssignValueColor(
     if crossmade2 == 1 then color.dark_green
else if crossmade2 == -1 then color.dark_red
else if crossmade0_lookback > 1 and crosslinelogic then Color.gray
else color.dark_red);
#####################################################
##                                                 ##
#####################################################
made.AssignValueColor(
     if crossmade2 == 1 then color.dark_green
else if crossmade2 == -1 then color.dark_red
else if crossmade0_lookback > 1 and crosslinelogic then Color.gray
else color.dark_red);
#####################################################
##                                                 ##
#####################################################
Squeeze_Alert.SetPaintingStrategy(PaintingStrategy.line);
Squeeze_Alert.SetLineWeight(2);
Squeeze_Alert.SetDefaultColor(Color.YELLOW);
#####################################################
##                                                 ##
#####################################################
RegularBuy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
ExtremeBuy.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
RegularSell.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
ExtremeSell.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
#####################################################
##                                                 ##
#####################################################
RegularBuy.SetLineWeight((1));
ExtremeBuy.SetLineWeight((1));
RegularSell.SetLineWeight((1));
ExtremeSell.SetLineWeight((1));
#####################################################
##                                                 ##
#####################################################
ExtremeSell.SetDefaultColor((Color.WHITE));
ExtremeBuy.SetDefaultColor((Color.WHITE));
RegularBuy.SetDefaultColor((Color.white));
RegularSell.SetDefaultColor((Color.white));
#####################################################
##                                                 ##
#####################################################
firstHL.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
firstHL.SetLineWeight(1);
firstHL.SetDefaultColor(Color.blue);
firstHL.HideBubble();
firstHL.HideTitle();
#####################################################
##                                                 ##
#####################################################
firstLH.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
firstLH.SetLineWeight(1);
firstLH.SetDefaultColor(Color.blue);
firstLH.HideBubble();
firstLH.HideTitle();
#####################################################
##                                                 ##
#####################################################
secondHL.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
secondHL.SetLineWeight(1);
secondHL.SetDefaultColor(Color.CYAN);
secondHL.HideBubble();
secondHL.HideTitle();
#####################################################
##                                                 ##
#####################################################
secondLH.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
secondLH.SetLineWeight(1);
secondLH.SetDefaultColor(Color.CYAN);
secondLH.HideBubble();
secondLH.HideTitle();
#####################################################
##                                                 ##
#####################################################
masterEMADLinePlot.SetPaintingStrategy(PaintingStrategy.histogram);
masterEMADLinePlot.HideBubble();
masterEMADLinePlot.SetLineWeight(1);
masterEMADLinePlot.AssignValueColor(
     if alert4 then color.cyan
else if HLBuy then color.light_green
else if LHSell then color.light_red
else if crossmade2up then Color.dark_green
else if crossmade2dn then color.dark_red
else if crossmade0_lookback > 1 and crosslinelogic then Color.dark_gray
else color.dark_red
);
DefineGlobalColor("G0", CreateColor(0, 255, 0));  #Green
DefineGlobalColor("G1", CreateColor(0, 229, 0));  #Green
DefineGlobalColor("G2", CreateColor(0, 206, 0));  #Green
DefineGlobalColor("G3", CreateColor(0, 186, 0));  #Green
DefineGlobalColor("G4", CreateColor(0, 167, 0));  #Green
DefineGlobalColor("G5", CreateColor(0, 151, 0));  #Green
DefineGlobalColor("G6", CreateColor(0, 136, 0));  #Green
DefineGlobalColor("G7", CreateColor(0, 122, 0));  #Green
DefineGlobalColor("G8", CreateColor(0, 109, 0));  #Green
DefineGlobalColor("G9", CreateColor(0, 98, 0));  #Green
DefineGlobalColor("R0", CreateColor(255, 0, 0));  #Red
DefineGlobalColor("R1", CreateColor(224, 0, 0));  #Red
DefineGlobalColor("R2", CreateColor(197, 0, 0));  #Red
DefineGlobalColor("R3", CreateColor(174, 0, 0));  #Red
DefineGlobalColor("R4", CreateColor(153, 0, 0));  #Red
DefineGlobalColor("R5", CreateColor(135, 0, 0));  #Red
DefineGlobalColor("R6", CreateColor(118, 0, 0));  #Red
DefineGlobalColor("R7", CreateColor(104, 0, 0));  #Red
DefineGlobalColor("R8", CreateColor(92, 0, 0));  #Red
DefineGlobalColor("R9", CreateColor(81, 0, 0));  #Red

upperEMADLinePlot.HideTitle();
upperEMADLinePlot.HideBubble();
upperEMADLinePlot.AssignValueColor(
    if (lowerEMADLinePlot > upperEMADLinePlot) then createcolor(153, 0, 0)
    else if (lowerEMADLinePlot < upperEMADLinePlot) then createcolor(0, 167, 0)
    else GlobalColor("Gray")
);
lowerEMADLinePlot.HideTitle();
lowerEMADLinePlot.HideBubble();
lowerEMADLinePlot.AssignValueColor(
    if (lowerEMADLinePlot > upperEMADLinePlot) then Color.red
    else if (lowerEMADLinePlot < upperEMADLinePlot) then Color.green
    else GlobalColor("Gray")
);
masterEMADLinePlot2.HideTitle();
masterEMADLinePlot2.HideBubble();
masterEMADLinePlot2.SetLineWeight(emadLineWeight);
masterEMADLinePlot2.AssignValueColor(
    if masterEMADLinePlot > masterEMADLinePlot[2] then createColor(0, 186, 0)
    else if masterEMADLinePlot < masterEMADLinePlot[2] then createColor(174, 0, 0)
    else GlobalColor("Gray")
);
zeroLine.HideTitle();
zeroLine.HideBubble();
zeroLine.AssignValueColor(
    if (upperEMADLinePlot > zeroLine) then  Color.green
    else if (upperEMADLinePlot < zeroLine) then  Color.red
    else GlobalColor("Yellow")
);
topBandPlot.HideTitle();
topBandPlot.HideBubble();
topBandPlot.AssignValueColor(
    if bothBandsDown then Color.dark_red
    else if bothBandsUp then color.Dark_green
    else if topBandStepUp then Color.green
    else if topBandStepDown then Color.red
    else if bearBias then  Color.yellow
    else GlobalColor("Gray")
);
bottomBandPlot.HideTitle();
bottomBandPlot.HideBubble();
bottomBandPlot.AssignValueColor(
    if bothBandsDown then Color.dark_red
    else if bothBandsUp then color.Dark_green
    else if bottomBandStepUp then Color.green
    else if bottomBandStepDown then Color.red
    else if bullBias then Color.yellow
    else  GlobalColor("Gray")
);
AddLabel(yes, " EMAD RANGE V1000 ", color.WHITE);
AddLabel(ShowColorCodeLabel,
    if  showHowToLabel then " Bullish: Observe cloud prior to reversal " else " Bullish ", color.dark_green);   
AddLabel(ShowColorCodeLabel,
    if  showHowToLabel then " Bearish: Observe cloud prior to reversal " else " Bearish ", color.dark_red);     
AddLabel(ShowColorCodeLabel,
    if  showHowToLabel then " Vix Alert4: Bounce incoming " else " Vix Alert4 ", color.cyan);   
AddLabel(ShowColorCodeLabel,
    if  showHowToLabel then " Seller Exhaustion: Watch for pullback / reversal when exhaustion ends " else " Seller Exhaustion ",  color.light_red);
AddLabel(ShowColorCodeLabel,
    if  showHowToLabel then " Seller Exhaustion: Watch for pullback / reversal when exhaustion ends " else " Buyer Exhaustion ",  color.light_green);
AddLabel(ShowColorCodeLabel,
    if  showHowToLabel then " Neutral: Direction not confirmed " else " Neutral ",  color.gray);
AddLabel(ShowColorCodeLabel,
    if  showHowToLabel then " Squeeze: (non-directional) potential strong move incoming " else " Squeeze ",  color.yellow);
#####################################################
##                                                 ##
#####################################################
AddCloud(if showEMACloud and (made1 > masterEMADLinePlot) then made1 else Double.NaN, masterEMADLinePlot, Color.dark_red, Color.gray);
AddCloud(if showEMACloud and (masterEMADLinePlot >= made) then masterEMADLinePlot else Double.NaN, made,  Color.dark_green, Color.gray);
#####################################################
##                                                 ##
#####################################################
AddChartBubble(showBubbles and crossesUpline and crossesUpline_filter, midBand, "Wait for HL", GlobalColor("Green"), no);
AddChartBubble(showBubbles and crossesDownline and crossesDownline_filter, midBand,"Wait for LH" , GlobalColor("Red"), yes);
#####################################################
##                                                 ##
#####################################################
AddVerticalLine(showVerticalline and crossesUpline and crossesUpline_filter, "", GlobalColor("Green"), no);
AddVerticalLine(showVerticalline and crossesDownline and crossesDownline_filter,"" , GlobalColor("Red"), yes);



2yQCwUI.png


The EMAD Lower V2 predicts where future bounce / pullback may occur. The EMAD EMA’s represent price within the range determined by the levels at which previous bounce or pullback occurred
  • EMAD EMA direction represents the short term trend bias
  • EMAD EMAs above or below the Zero Line represent the (slightly) longer term trend bias
While it is possible to change the length of the averages in settings it is not recommended.
  • Show Bubbles set to “yes” indicates that the EMAD EMA’s have bounced off the top or bottom line (see EMAD entry method)
Screenshots
1oHIiHw.png


Code:
#EMAD Range by @ Christopher84
#EMAD V2 - added line color conditions HODL

#DECLARATIONS
declare lower;


#USER INPUTS
## Upper and Lower EMAD Lines
input fastLength = 10;
input slowLength = 35;
input smoothLength = 12;
input smoothLength2 = 14;
input priceType = close;
input emadLineWeight = 2;
input showEMACloud = yes;
input showBubbles = yes;
input averageType = AverageType.WILDERS;


## Upper and Lower Band Lines
input bandLength = 100;
input bandLength2 = 200;


#GLOBAL COLOR DEFINITIONS
DefineGlobalColor("Green", CreateColor(0, 155, 0));
DefineGlobalColor("Red", CreateColor(225, 105, 105));
DefineGlobalColor("Gray", CreateColor(192, 192, 192));
DefineGlobalColor("Yellow", CreateColor(231, 190, 0));


#DEFINITIONS / CALCULATIONS

## UPPER EMAD LINE
def fastExpAvg = ExpAverage(priceType, fastLength);
def slowExpAvg = ExpAverage(priceType, slowLength);
def EMAD = (priceType - fastExpAvg);
def EMAD2 = (priceType - slowExpAvg);
def EMADAvg = (EMAD + EMAD2) / 2;
def upperEMADLine = ExpAverage(EMADAvg, smoothLength);

## LOWER EMAD LINE
def emadOpen = (upperEMADLine + upperEMADLine[1]) / 2;
def emadHigh = Max(upperEMADLine, upperEMADLine[1]);
def emadLow = Min(upperEMADLine, upperEMADLine[1]);
def emadClose = upperEMADLine;
def bottom = Min(emadClose[1], emadLow);
def tr = TrueRange(emadHigh, emadClose, emadLow);
def ptr = tr / (bottom + tr / 2);
def APTR = MovingAverage(averageType, ptr, smoothLength2);
def upperBand = emadClose[1] + (APTR * emadOpen);
def lowerBand = emadClose[1] - (APTR * emadOpen);
def lowerEMADLine = (upperBand + lowerBand) / 2;

## TOP AND BOTTOM BANDS
def zeroLineData = if IsNaN(close) then Double.NaN else 0;
def EMADSUp = upperEMADLine > zeroLineData;
def EMADSDown = upperEMADLine < zeroLineData;
def EMADdown = (lowerEMADLine > upperEMADLine);
def EMADup = (upperEMADLine >= lowerEMADLine);
def topBand = Highest(lowerEMADLine, bandLength);
def bottomBand = Lowest(lowerEMADLine, bandLength);


## BAND DIRECTION (USED ONLY FOR COLORING - NOT USED FOR PLOTS)
def topBandStepDown = if topBand < topBand[1] then 1 else 0;
def topBandStepUp = if topBand > topBand[1] then 1 else 0;
def bottomBandStepDown = if bottomBand < bottomBand[1] then 1 else 0;
def bottomBandStepUp = if bottomBand > bottomBand[1] then 1 else 0;
def bothBandsDown = bottomBandStepDown and topBandStepDown;
def bothBandsUp = bottomBandStepUp and topBandStepUp;
def bullBias = (bottomBand > zeroLineData);
def bearBias = (topBand < zeroLineData);


## BUBBLE CALCULATIONS (USED ONLY FOR BUBBLES)
def midBand = (upperBand + lowerBand) / 2;
def crossesUp = if (midBand[1] > upperEMADLine[1])and(midBand < upperEMADLine) then 1 else 0;
def crossesDown = if (upperEMADLine[1] > midBand[1])and(upperEMADLine < midBand) then 1 else 0;
def valueUp = if crossesUp then midBand else 0;
def valueDown = if crossesDown then midBand else 0;
def crossesUpline = if (valueUp - bottomBand) == 0 then 1 else 0;
def crossesDownline = if (valueDown - topBand) == 0 then 1 else 0;
def crossesUpline_filter = if crossesUpline and (crossesUpline[1] or crossesUpline[2]  or crossesUpline[3]   or crossesUpline[4])then 0 else 1;
def crossesDownline_filter = if crossesDownline and (crossesDownline[1] or crossesDownline[2]  or crossesDownline[3]   or crossesDownline[4])then 0 else 1;


#PLOTS
plot zeroLine = zeroLineData;
plot upperEMADLinePlot = upperEMADLine;
plot lowerEMADLinePlot = lowerEMADLine;
plot masterEMADLinePlot = (upperEMADLinePlot + lowerEMADLinePlot) / 2;
plot topBandPlot = topBand;
plot bottomBandPlot = bottomBand;


#FORMATTING
upperEMADLinePlot.HideTitle();
upperEMADLinePlot.HideBubble();
upperEMADLinePlot.AssignValueColor(
    if (lowerEMADLinePlot > upperEMADLinePlot) then Color.red
    else if (lowerEMADLinePlot < upperEMADLinePlot) then Color.green
    else GlobalColor("Gray")
);
lowerEMADLinePlot.HideTitle();
lowerEMADLinePlot.HideBubble();
lowerEMADLinePlot.AssignValueColor(
    if (lowerEMADLinePlot > upperEMADLinePlot) then Color.red
    else if (lowerEMADLinePlot < upperEMADLinePlot) then Color.green
    else GlobalColor("Gray")
);
masterEMADLinePlot.HideTitle();
masterEMADLinePlot.HideBubble();
masterEMADLinePlot.SetLineWeight(emadLineWeight);
masterEMADLinePlot.AssignValueColor(
    if masterEMADLinePlot > masterEMADLinePlot[2] then Color.green
    else if masterEMADLinePlot < masterEMADLinePlot[2] then Color.red
    else GlobalColor("Gray")
);
zeroLine.HideTitle();
zeroLine.HideBubble();
zeroLine.AssignValueColor(
    if (upperEMADLinePlot > zeroLine) then  Color.green
    else if (upperEMADLinePlot < zeroLine) then  Color.red
    else GlobalColor("Yellow")
);
topBandPlot.HideTitle();
topBandPlot.HideBubble();
topBandPlot.AssignValueColor(
    if bothBandsDown then Color.dark_red
    else if bothBandsUp then color.Dark_green
    else if topBandStepUp then Color.green
    else if topBandStepDown then Color.red
    else if bearBias then  Color.yellow
    else GlobalColor("Gray")
);
bottomBandPlot.HideTitle();
bottomBandPlot.HideBubble();
bottomBandPlot.AssignValueColor(
    if bothBandsDown then Color.dark_red
    else if bothBandsUp then color.Dark_green
    else if bottomBandStepUp then Color.green
    else if bottomBandStepDown then Color.red
    else if bullBias then Color.yellow
    else  GlobalColor("Gray")
);


#CLOUDS
AddCloud(if showEMACloud and (lowerEMADLinePlot > upperEMADLinePlot) then lowerEMADLinePlot else Double.NaN, upperEMADLinePlot, GlobalColor("Red"), Color.CURRENT);
AddCloud(if showEMACloud and (upperEMADLinePlot >= lowerEMADLinePlot) then upperEMADLinePlot else Double.NaN, lowerEMADLinePlot, GlobalColor("Green"), Color.CURRENT);


#BUBBLES
AddChartBubble(showBubbles and crossesUpline and crossesUpline_filter, midBand, "Wait for HL", GlobalColor("Green"), no);
AddChartBubble(showBubbles and crossesDownline and crossesDownline_filter, midBand,"Wait for LH" , GlobalColor("Red"), yes);

#
 
Last edited:
PTwbFRZ.png


Study link: https://tos.mx/WJZDjWz (will update image with the need to know soon!)

Y2lxxl7.png


uxDOKa6.png



Study Share Link - http://tos.mx/geFQR8E (4/25/23)

Screenshots

2KXy11w.png


Code:
# Volume Buy Sell Pressure with Hot Percent for ThinkorSwim
# Show total volume in gray.  Buying volume in green.  Sell Volume in red.
# Volume average is gray line.
# Specified percent over average volume is cyan triangles.
# Horserider 12/30/2019 derived from some already existing studies.


declare lower;

#Inputs
input showmarket = yes;
input Show30DayAvg = no;
input ShowTodayVolume =  no;
input ShowPercentOf30DayAvg = yes;
input UnusualVolumePercent = 200;
input Show30BarAvg = no;
input ShowCurrentBar = yes;
input ShowPercentOf30BarAvg = yes;
input ShowSellVolumePercent = yes;

def O = open;
def H = high;
def C = close;
def L = low;
def V = volume;
def buying = V*(C-L)/(H-L);
def selling = V*(H-C)/(H-L);

# Selling Volume

Plot SellVol = selling;
SellVol.setPaintingStrategy(PaintingStrategy.Histogram);
SellVol.SetDefaultColor(Color.Red);
SellVol.HideTitle();
SellVol.HideBubble();
SellVol.SetLineWeight(1);

# Total Volume

# Note that Selling + Buying Volume = Volume.
plot TV =  volume;

TV.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
TV.SetDefaultColor(Color.GRAY);
#TV.HideTitle();
#TV.HideBubble();
TV.SetLineWeight(1);

Plot BuyVol = buying;
BuyVol.setPaintingStrategy(PaintingStrategy.Histogram);
BuyVol.SetDefaultColor(Color.Green);
BuyVol.HideTitle();
BuyVol.HideBubble();
BuyVol.SetLineWeight(5);

#Volume Data

def volLast30DayAvg = (volume(period = "DAY")[1] + volume(period = "DAY")[2] + volume(period = "DAY")[3] + volume(period = "DAY")[4] + volume(period = "DAY")[5] + volume(period = "DAY")[6] + volume(period = "DAY")[7] + volume(period = "DAY")[8] + volume(period = "DAY")[9] + volume(period = "DAY")[10] + volume(period = "DAY")[11] + volume(period = "DAY")[12] + volume(period = "DAY")[13] + volume(period = "DAY")[14] + volume(period = "DAY")[15] + volume(period = "DAY")[16] + volume(period = "DAY")[17] + volume(period = "DAY")[18] + volume(period = "DAY")[19] + volume(period = "DAY")[20] + volume(period = "DAY")[21] + volume(period = "DAY")[22] + volume(period = "DAY")[23] + volume(period = "DAY")[24] + volume(period = "DAY")[25] + volume(period = "DAY")[26] + volume(period = "DAY")[27] + volume(period = "DAY")[28] + volume(period = "DAY")[29] + volume(period = "DAY")[30]) / 30;
def today = volume(period = "DAY");
def percentOf30Day = Round((today / volLast30DayAvg) * 100, 0);
def avg30Bars = (volume[1] + volume[2] + volume[3] + volume[4] + volume[5] + volume[6] + volume[7] + volume[8] + volume[9] + volume[10] + volume[11] + volume[12] + volume[13] + volume[14] + volume[15] + volume[16] + volume[17] + volume[18] + volume[19] + volume[20] + volume[21] + volume[22] + volume[23] + volume[24] + volume[25] + volume[26] + volume[27] + volume[28] + volume[29] + volume[30]) / 30;
def curVolume = volume;
def percentOf30Bar = Round((curVolume / avg30Bars) * 100, 0);
def SellVolPercent = Round((Selling / Volume) * 100, 0);
def BuyVolPercent = Round((buying / Volume) * 100, 0);

# Labels
AddLabel(ShowTodayVolume, "Today: " + today, (if percentOf30Day >= UnusualVolumePercent then Color.GREEN else if percentOf30Day >= 100 then Color.ORANGE else Color.LIGHT_GRAY));

AddLabel(Show30DayAvg, "Avg 30 Days: " + Round(volLast30DayAvg, 0), Color.LIGHT_GRAY);

AddLabel(ShowPercentOf30DayAvg, percentOf30Day +"%", (if percentOf30Day >= UnusualVolumePercent then Color.GREEN else if percentOf30Day >= 100 then Color.ORANGE else Color.WHITE) );

AddLabel(Show30BarAvg, "Avg 30 Bars: " + Round(avg30Bars, 0), Color.LIGHT_GRAY);

AddLabel(ShowPercentOf30BarAvg, PercentOf30Bar + "%", (if PercentOf30Bar >= UnusualVolumePercent then Color.GREEN else if PercentOf30Bar >= 100 then Color.ORANGE else Color.WHITE) );

AddLabel(ShowCurrentBar, "Current Bar: " + curVolume, (if percentOf30Bar >= UnusualVolumePercent then Color.GREEN else if PercentOf30Bar >= 100 then Color.ORANGE else Color.LIGHT_GRAY));

AddLabel(ShowSellVolumePercent, "Selling Pressure: "+SellVolPercent + "%", (if SellVolPercent > 51 then Color.RED else if SellVolPercent < 49 then Color.GREEN else Color.ORANGE));

AddLabel(ShowSellVolumePercent,"Buying Pressure: "+ BuyVolPercent + "%", (if BuyVolPercent > 51 then Color.Green else if SellVolPercent < 49 then Color.red else Color.ORANGE));

input length = 21;
input length2 = 21;

plot VolAvg = Average(volume, length);
#plot VolAvg1= Average(volume, length2);

VolAvg.Setdefaultcolor(Color.Gray);


#def crossover = if (VolAvg2 crosses below VolAvg4) then 1 else 0;
#def crossunder = if (VolAvg2 crosses above VolAvg4) and (volume<volavg) then 1 else 0;
#AddVerticalLine(if crossover ==1 then 1 else 0,"",color.cyan);
#AddVerticalLine(if crossunder ==1 then 1 else 0);


# hiVolume indicator
# source: http://tinboot.blogspot.com
# author: allen everhart


input type = { default SMP, EXP } ;
input length_HV = 20 ;
input HotPct = 100.0 ;

def MA =
if type == type.SMP then
SimpleMovingAvg(volume, length_HV)
else
MovAvgExponential(volume, length_HV);

plot HV =
if 100 * ((volume / ma) - 1) >= hotPct then
ma
else
Double.NaN;

hv.SetDefaultColor( Color.CYAN);
hv.SetLineWeight(1) ;
hv.SetPaintingStrategy( PaintingStrategy.TRIANGLES);

# Market Breath Ratios
# Paris (based on an earlier idea from ESP)
# 11.02.2015
# One Note Download

def UVOL   = close(“$UVOL”);
def DVOL   = close(“$DVOL”);

def UVOLD  = close(“$UVOLI”);
def DVOLD  = close(“$DVOLI”);

def UVOLS  = close(“$UVOLSP”);
def DVOLS  = close(“$DVOLSP”);

def UVOLN  = close(“$UVOL/Q”);
def DVOLN  = close(“$DVOL/Q”);

def UVOLR  = close(“$UVOLRL”);
def DVOLR  = close(“$DVOLRL”);

#addLabel(showmarket, "Broad Mkt Ratios -->", Color.Light_Gray);

def SPYRatio = if (UVOLS >= DVOLS) then (UVOLS / DVOLS) else -(DVOLS / UVOLS);
AddLabel(showmarket, "S&P500: " + Concat(Round(SPYRatio, 2), ” :1”), if SPYRatio >= 0 then Color.UPTICK else Color.DOWNTICK);

def DJIRatio =  if (UVOLD >= DVOLD) then (UVOLD / DVOLD) else -(DVOLD / UVOLD);
AddLabel(showmarket, "DJI: " + Concat(Round(DJIRatio, 2), ” :1”), if DJIRatio >= 0 then Color.UPTICK else Color.DOWNTICK);

def NDXRatio =  if  (UVOLN >= DVOLN) then (UVOLN / DVOLN) else -(DVOLN / UVOLN);
AddLabel(showmarket, "QQQ: " + Concat(Round(NDXRatio, 2), ” :1”), if NDXRatio >= 0 then Color.UPTICK else Color.DOWNTICK);

def RUTRatio =  if (UVOLR >= DVOLR) then (UVOLR / DVOLR) else -(DVOLR / UVOLR);
AddLabel(showmarket, "R2000: " + Concat(Round(RUTRatio, 2), ” :1”), if RUTRatio >= 0 then Color.UPTICK else Color.DOWNTICK);

def NYSERatio =  if (UVOL >= DVOL) then (UVOL / DVOL) else -(DVOL / UVOL);
AddLabel(showmarket, "NYSE: " + Concat(Round(NYSERatio, 2), ” :1”), if NYSERatio >= 0 then Color.UPTICK else Color.DOWNTICK);
 
Last edited:
f5mkFh1.png


This post will provide recommended settings adjustments and limitations for users interested in a similar chart style in ThinkOrSwim mobile.

TOS Mobile Screenshot (4/26/23)

C3_Max_Spark_Filtered

Mobile setup
For use with TOS mobile C3_Max_Spark_Filtered necessary settings adjustments are the following:
  • Turn off all plots named “AvgExp
  • Change size and color of “RegularBuy”, “ExtremeBuy”, “RegularSell”, “ExtremeSell
  • Change “YHextlineOB” to short dashed
  • Change “YHextlineOS” to short dashed

Notice the left side text “Draw as”, “Style”, etc.

EMAD_Lower_V2

Mobile setup
The line colors in the EMAD Lower plots on mobile are all the same. The colors will not change, as they do on a PC, because TOS mobile does not enable that function.
  • Change all plot colors
  • Change line weights

Horserider_Volume

Mobile setup
For reasons unknown the Horserider_Volume bars do not show the 3 separate colors for 3 separate volume bars to appear as it does on a PC.
  • Change “SellVol” from histogram to solid and set line weight to 3
  • Change “Hv” size to 3
  • Change colors
 
Last edited:
v967Xl1.png


This post will provide links and explanations various watchlist columns related to studies within the Confirmation Trend Chart Style (though some are not named directly their code is within one of the aforementioned studies).


ZDFVf1h.png


Share link - https://tos.mx/cn1MD6S

Zf2N0VH.png

Code:
#Big_4 watchlist column

#######################################
##  Create Labels
#######################################
input showtitle = no;
input showlabels = yes;
def AutoAgg = yes;
def AutoAgg2 = yes;

def ag_skip = no;
def ag_skip2 = no;
def ag_skip_lbl = no;

def agperiod1 = GetAggregationPeriod();
 
input timeframe = aggregationperiod.DAY;

input length = 10;
input length2 = 20;

def Vol = volume(period = timeframe);
def at_High = high(period = timeframe);
def at_Open = open(period = timeframe);
def at_Close = close(period = timeframe);
def at_Low = low(period = timeframe);
def Vol1 = volume(period = timeframe);
def at_High1 = high(period = timeframe);
def at_Open1 = open(period = timeframe);
def at_Close1 = close(period = timeframe);
def at_Low1 = low(period = timeframe);

# Buy_Volume forumla is volume * (close_price minus low_price) / (High_price minus low_price)
def Buy_Volume = RoundUp(Vol * (at_Close - at_Low) / (at_High - at_Low));
def Buy_percent = RoundUp((Buy_Volume / Vol) * 100);
#Buy_percent.SetPaintingStrategy(PaintingStrategy.LINE);
#Buy_percent.SetLineWeight(1);
#Buy_percent.SetDefaultColor(Color.GREEN);

#Sell_Volume forumla is  volume * (High_price minus Close_price) / (High_price minus Low_price)
def Sell_Volume = RoundDown(Vol1 * (at_High1 - at_Close1) / (at_High1 - at_Low1));
def Sell_percent = RoundUp((Sell_Volume / Vol1) * 100);
#input price = close;
input length_BB = 10;
input length_BB2 = 20;
plot avg = ExpAverage(close(period = agperiod1), length_BB);
#plot avg = ExpAverage((price), length);
def height = avg - avg[length];
avg.SetStyle(Curve.SHORT_DASH);
avg.SetLineWeight(1);

AddLabel(showtitle, " Big_6: ", Color.Light_gray);

# AK Trend

def aktrend_input1 = 3;
def aktrend_input2 = 8;
def aktrend_price = close;

def aktrend_fastmaa = MovAvgExponential(aktrend_price, aktrend_input1);
def aktrend_fastmab = MovAvgExponential(aktrend_price, aktrend_input2);
def aktrend_bspread = (aktrend_fastmaa - aktrend_fastmab) * 1.001;

def cond1_UP = if aktrend_bspread > 0 then 1 else 0;
def cond1_DN = if aktrend_bspread <= 0 then -1 else 0;

# ZSCORE

def zscore_price = close;
def zscore_length = 20;
def zscore_ZavgLength = 20;

def zscore_oneSD = StDev(zscore_price, zscore_length);
def zscore_avgClose = SimpleMovingAvg(zscore_price, zscore_length);
def zscore_ofoneSD = zscore_oneSD * zscore_price[1];
def zscore_Zscorevalue = ((zscore_price - zscore_avgClose) / zscore_oneSD);
def zscore_avgZv = Average(zscore_Zscorevalue, 20);
def zscore_Zscore = ((zscore_price - zscore_avgClose) / zscore_oneSD);
def zscore_avgZscore = Average(zscore_Zscorevalue, zscore_ZavgLength);

def cond2_UP = if zscore_Zscore > 0 then 1 else 0;
def cond2_DN = if zscore_Zscore <= 0 then -1 else 0;

# Ehlers

def ehlers_length = 34;

def ehlers_price = (high + low) / 2;
def ehlers_coeff = ehlers_length * ehlers_price * ehlers_price - 2 * ehlers_price * Sum(ehlers_price, ehlers_length)[1] + Sum(ehlers_price * ehlers_price, ehlers_length)[1];
def ehlers_Ehlers = Sum(ehlers_coeff * ehlers_price, ehlers_length) / Sum(ehlers_coeff, ehlers_length);

def cond3_UP = if close > ehlers_Ehlers then 1 else 0;
def cond3_DN = if close <= ehlers_Ehlers then -1 else 0;

# Anchored Momentum

def amom_src = close;
def amom_MomentumPeriod = 10;
def amom_SignalPeriod = 8;
def amom_SmoothMomentum = no;
def amom_SmoothingPeriod = 7;

def amom_p = 2 * amom_MomentumPeriod + 1;
def amom_t_amom = if amom_SmoothMomentum == yes then ExpAverage(amom_src, amom_SmoothingPeriod) else amom_src;
def amom_amom = 100 * ( (amom_t_amom / ( Average(amom_src, amom_p)) - 1));
def amom_amoms = Average(amom_amom, amom_SignalPeriod);


def cond4_UP = if amom_amom > 0 then 1 else 0;
def cond4_DN = if amom_amom <= 0 then -1 else 0;

# TMO

def tmo_length = 30; #def 14
def tmo_calcLength = 6; #def 5
def tmo_smoothLength = 6; #def 3

def tmo_data = fold i = 0 to tmo_length with s do s + (if close > GetValue(open, i) then 1 else if close < GetValue(open, i) then - 1 else 0);
def tmo_EMA5 = ExpAverage(tmo_data, tmo_calcLength);
def tmo_Main = ExpAverage(tmo_EMA5, tmo_smoothLength);
def tmo_Signal = ExpAverage(tmo_Main, tmo_smoothLength);
def tmo_color = if tmo_Main > tmo_Signal then 1 else -1;

def cond5_UP = if tmo_Main <= 0 then 1 else 0;
def cond5_DN = if tmo_Main >= 0 then -1 else 0;

# Strategy

input Strategy_Confirmation_Factor = 4;
input Strategy_FilterWithTMO = no;
input Strategy_FilterWithTMO_arrows = yes;
input Strategy_ColoredCandlesOn = yes;
input Strategy_VerticalLinesOn = no;
input Strategy_HoldTrend = no;

def cond_UP = cond1_UP + cond2_UP + cond3_UP + cond4_UP;
def cond_DN = cond1_DN + cond2_DN + cond3_DN + cond4_DN;

def direction = if cond_UP >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_UP) then 1
                else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_DN) then -1
                else if !Strategy_HoldTrend and direction[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
                else if !Strategy_HoldTrend and direction[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0
                else direction[1];

def direction2 = if cond_UP >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_UP) then 1
                else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_DN) then -1
                else if !Strategy_HoldTrend and direction2[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
                else if !Strategy_HoldTrend and direction2[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0
                else direction2[1];

def signal_up = direction2 == 1 and direction2[1] < 1;


def signal_dn = direction2 == -1 and direction2[1] > -1;


addlabel(yes, if signal_up then "👍" else if signal_dn then "👎" else "  ", color.black);
Assignbackgroundcolor(if direction == 1 then Color.dark_GREEN
else if direction == -1 then Color.RED
else Color.gray);

K8p4YMB.png


Watchlist Column Share Link - http://tos.mx/SD7Fqm7 (4/25/23)

Description
The watchlist column for TS_V9 is from the original study code not the filtered code as watchlist columns do not support more than one aggregation.
  • Signals present within 3 bars indicate “Buy” or “Sell”
  • Signals not present within 3 bars indicate the most recent signal “Last Buy” or “Last Sell”
Code:
#TS_V9 Watchlist Column - HODL - 4/25/23 
#TS Strategy_V9 Created by Christopher84 08/10/2021
#Modified 05/23/2022 to include Chart Bubbles and Labels.
#Modified 05/25/2022 to include Targets and Stoplosses.
#Modified 05/26/2022 to include Line Labels by Dcstocks
#Modified 05/27/2022 to include target 7.

input trailType = {default modified, unmodified};
input ATRPeriod = 11;
input ATRFactor = 2.2;
input firstTrade = {default long, short};
input averageType = AverageType.SIMPLE;
input price = close;
input coloredCandlesOn = yes;
input LabelsOn = yes;

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);

def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);

def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;
    }
}
#def isnan = double.nan;
def bn = barnumber();
def TrailingStop = trail;
def LongEnter = (price crosses above TrailingStop) within 3 bars;
def LongEnterbn = if longenter then bn else longenterbn[1];

def LongExit = (price crosses below TrailingStop)within 3 bars;
def LongExitbn = if LongExit then bn else LongExitbn[1];

def Hold_signal = if LongEnterbn > LongExitbn then 1 else 0;
#plot value = if LongEnter then 1 else if LongExit then 0 else double.nan;


AssignbackgroundColor( if longenter then color.Dark_Green 
else if !longenter and (Hold_signal == 1) then Color.green 
else if longexit then Color.Dark_Red 
else if !longexit and (Hold_signal == 0) then Color.Red 
else color.dark_Gray);
AddLabel(yes, if (longenter) then "TS_1H"
else if !longenter and (Hold_signal == 1) then "Last: BUY"
else if (longexit) then "TS_1H"
else if !longexit and (Hold_signal == 0) then "Last: SELL"
else "  ", if longenter then color.white
else if !longenter and (Hold_signal == 1) then Color.black
else if longexit then Color.white
else if !longexit and (Hold_signal == 0) then Color.black
else color.dark_Gray);


#AddLabel(yes, if (price crosses above TrailingStop) then "Long"
#else if (price crosses below TrailingStop) then "Short"
##else "NO BREAK", if conditionBD then Color.RED 
##else if conditionBO then Color.GREEN 
#else "  ");


#AssignvalueColor(if coloredCandlesOn and ((price > TrailingStop)) then Color.GREEN else if coloredCandlesOn and ((price < TrailingStop)) then Color.RED else Color.GRAY);


#def upsignal = (price crosses above TrailingStop);

#def downsignal = (price crosses below TrailingStop);



###------------------------------------------------------------------------------------------
# Profit and Loss Labels
#
# Fill in the 0>0 in the Create Signals section below to match your buy and sell signal conditions
#
# When using large amounts of hisorical data, P/L may take time to calculate
###------------------------------------------------------------------------------------------

05P3m4P.png


EMAD Watchlist Column Share Link - http://

Description
The EMAD watchlist column indicates the location of the EMAs within the range and changes colors accordingly.
  • Above or below zero line
  • EMA cross up or down off line
Code:
code

FqzAaTd.png


Volume_%_30Bar Watchlist Column Share Link - http://tos.mx/u3K4CTM

Description
The volume percent 30 bar watchlist column shows the percent value of 30 bars of volume

Code:
#Volume Buy Sell Pressure with Hot Percent for ThinkorSwim
# Show total volume in gray.  Buying volume in green.  Sell Volume in red.
# Volume average is gray line.
# Specified percent over average volume is cyan triangles.
# Horserider 12/30/2019 derived from some already existing studies.


declare lower;

#Inputs

input Show30DayAvg = yes;
input ShowTodayVolume =  yes;
input ShowPercentOf30DayAvg = yes;
input UnusualVolumePercent = 200;
input Show30BarAvg = yes;
input ShowCurrentBar = yes;
input ShowPercentOf30BarAvg = yes;
input ShowSellVolumePercent = yes;

def O = open;
def H = high;
def C = close;
def L = low;
def V = volume;
def buying = V*(C-L)/(H-L);
def selling = V*(H-C)/(H-L);

# Selling Volume

Plot SellVol = selling;
SellVol.setPaintingStrategy(PaintingStrategy.Histogram);
SellVol.SetDefaultColor(Color.Red);
SellVol.HideTitle();
SellVol.HideBubble();
SellVol.SetLineWeight(1);

# Total Volume

# Note that Selling + Buying Volume = Volume.
plot TV =  volume;

TV.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
TV.SetDefaultColor(Color.GRAY);
#TV.HideTitle();
#TV.HideBubble();
TV.SetLineWeight(1);

Plot BuyVol = buying;
BuyVol.setPaintingStrategy(PaintingStrategy.Histogram);
BuyVol.SetDefaultColor(Color.Green);
BuyVol.HideTitle();
BuyVol.HideBubble();
BuyVol.SetLineWeight(5);

#Volume Data

def volLast30DayAvg = (volume(period = "DAY")[1] + volume(period = "DAY")[2] + volume(period = "DAY")[3] + volume(period = "DAY")[4] + volume(period = "DAY")[5] + volume(period = "DAY")[6] + volume(period = "DAY")[7] + volume(period = "DAY")[8] + volume(period = "DAY")[9] + volume(period = "DAY")[10] + volume(period = "DAY")[11] + volume(period = "DAY")[12] + volume(period = "DAY")[13] + volume(period = "DAY")[14] + volume(period = "DAY")[15] + volume(period = "DAY")[16] + volume(period = "DAY")[17] + volume(period = "DAY")[18] + volume(period = "DAY")[19] + volume(period = "DAY")[20] + volume(period = "DAY")[21] + volume(period = "DAY")[22] + volume(period = "DAY")[23] + volume(period = "DAY")[24] + volume(period = "DAY")[25] + volume(period = "DAY")[26] + volume(period = "DAY")[27] + volume(period = "DAY")[28] + volume(period = "DAY")[29] + volume(period = "DAY")[30]) / 30;
def today = volume(period = "DAY");
def percentOf30Day = Round((today / volLast30DayAvg) * 100, 0);
def avg30Bars = (volume[1] + volume[2] + volume[3] + volume[4] + volume[5] + volume[6] + volume[7] + volume[8] + volume[9] + volume[10] + volume[11] + volume[12] + volume[13] + volume[14] + volume[15] + volume[16] + volume[17] + volume[18] + volume[19] + volume[20] + volume[21] + volume[22] + volume[23] + volume[24] + volume[25] + volume[26] + volume[27] + volume[28] + volume[29] + volume[30]) / 30;
def curVolume = volume;
def percentOf30Bar = Round((curVolume / avg30Bars) * 100, 0);
def SellVolPercent = Round((Selling / Volume) * 100, 0);

# Labels



#AddLabel(Show30BarAvg, "30 Bar: " + Round(avg30Bars, 0), Color.white);

#AddLabel(ShowCurrentBar, "Cur Bar: " + curVolume, (if percentOf30Bar >= UnusualVolumePercent then Color.GREEN else if PercentOf30Bar >= 100 then Color.ORANGE else Color.LIGHT_GRAY));

#AddLabel(ShowPercentOf30BarAvg, PercentOf30Bar + "%", (if PercentOf30Bar >= UnusualVolumePercent then Color.GREEN else if PercentOf30Bar >= 100 then Color.Light_Green else Color.WHITE) );

assignBackgroundColor(if PercentOf30Bar >= UnusualVolumePercent then color.GREEN else if  PercentOf30Bar >= 100 then color.RED else color.white);
AddLabel(ShowPercentOf30BarAvg, PercentOf30Bar + "%",Color.Black);
#AddLabel(buying >= selling, ""+BuyVolPercent, color.black);
#AddLabel(ShowSellVolumePercent, "Cur Bar Sell %: " + SellVolPercent, (if SellVolPercent > 51 then Color.RED else if SellVolPercent < 49 then Color.GREEN else Color.ORANGE));

#input length = 21;
#input length2 = 21;

#plot VolAvg = Average(volume, length);
#plot VolAvg1= Average(volume, length2);

#VolAvg.SetDefaultColor(GetColor(1));
#VolAvg1.SetDefaultColor(GetColor(3));


#def crossover = if (VolAvg2 crosses below VolAvg4) then 1 else 0;
#def crossunder = if (VolAvg2 crosses above VolAvg4) and (volume<volavg) then 1 else 0;
#AddVerticalLine(if crossover ==1 then 1 else 0,"",color.cyan);
#AddVerticalLine(if crossunder ==1 then 1 else 0);


# hiVolume indicator
# source: http://tinboot.blogspot.com
# author: allen everhart


#input type = { default SMP, EXP } ;
#input length_HV = 20 ;
#input HotPct = 100.0 ;


#def MA =
#if type == type.SMP then
#SimpleMovingAvg(volume, length_HV)
#else
#MovAvgExponential(volume, length_HV);

#plot HV =
##ma
#else
#Double.NaN;

#hv.SetDefaultColor( Color.CYAN);
#hv.SetLineWeight(1) ;
#hv.SetPaintingStrategy( PaintingStrategy.TRIANGLES);

8uY4FIc.png


Vix_Alert4 Watchlist Column Share Link - http://tos.mx/qmsqFqB (4/25/23)

Description
The Vix Alert 4 indicates a potential reversal.
  • Colors cell if condition exists within 3 bars
Code:
# Source?
# VixAlert4 WL Column - HODL
# Williams Vix Fix Formula
input pd = 22;
input bbl = 20;
input mult = 2.0;
input lb = 50;
input ph = 0.85;
input pl = 1.01;

# Downtrend Criteria

input ltLB = 40;
input mtLB = 14;
input str = 3;

def wvf = ((highest(close, pd) - low) / (highest(close, pd))) * 100;
def sDev = mult * stdev(wvf, bbl);
def midLine = SimpleMovingAvg(wvf, bbl);
def lowerBand = midLine - sDev;
def upperBand = midLine + sDev;
def rangeHigh = (highest(wvf, lb)) * ph;

#  Filtered Bar Criteria

def upRange = low > low[1] and close > high[1];
def upRange_Aggr = close > close[1] and close > open[1];

#  Filtered Criteria

def filtered = ((wvf[1] >= upperBand[1] or wvf[1] >= rangeHigh[1]) and(wvf<upperBand and wvf<rangeHigh));
def filtered_Aggr = (wvf[1] >= upperBand[1] or wvf[1] >= rangeHigh[1]);

# Alerts Criteria

def alert1 = wvf >= upperBand or wvf >= rangeHigh;
def alert2 = (wvf[1] >= upperBand[1] or wvf[1] >= rangeHigh[1]) and (wvf < upperBand and wvf < rangeHigh);
def alert3 = upRange and close > close[str] and (close < close[ltLB] or close < close[mtLB]) and filtered;
def alert4 = upRange_Aggr and close > close[str] and (close < close[ltLB] or close < close[mtLB]) and filtered_Aggr;

AssignbackgroundColor(if alert4 within 2 bars then color.orange else color.Dark_Gray);

AddLabel(yes, if (Alert4) within 2 bars  then "Alert 4 Day" + " "
else " ", color.black);

yEHgW4k.png


Blast_Off Watchlist Column Share Link - http://tos.mx/gVd03PO (4/25/23)

Description
Code:
# Blast Off Indicator
# Should use on the Daily chart
# Assembled by BenTen at useThinkScript.com
# Converted from https://www.tradingview.com/script/V9Mi6eOO-CM-Blast-Off-V1-Alerts-Ready/

input trig = 20;
input paintbar = yes;

def val = AbsValue(close - open);
def range = high - low;
def blastOffVal = (val / range) * 100;
def trigger = trig;
def alert1 = blastOffVal < trig;
def col = blastOffVal < trig;

plot value = if col then 1 else 0;
addlabel(yes, "Blast Off ", if value == 1 then color.black else color.Dark_Gray);
AssignBackgroundColor(if col then Color.orange else Color.Dark_GRAY);

SsLV9nt.png


Triple_Exhaustion Watchlist Column Share Link - http://tos.mx/L4uOP8M

Description
The Triple Exhaustion watchlist column indicates the end of exhaustion.
  • Color changes green or red when condition exists within 3 bars
  • If you so choose change the number "3" to any number (I added within x bars bc there were few indications for the current bar)
Code:
## Triple Exhaustion Watchlist Column
##
##
## CREDITS
## Requested by @Chence27 from criteria listed here https://usethinkscript.com/threads/triple-exhaustion-indicator.9001/
##
##
## Removing the header Credit credits and description is not permitted, any modification needs to be shared.
##
## V 1.0 :    @cos251 - Initial release per request from www.usethinkscript.com forum thread:
##       :    https://usethinkscript.com/threads/triple-exhaustion-indicator.9001/
##
##
##



# --- Inputs
input over_bought = 80;
input over_sold = 20;
input KPeriod = 10;
input DPeriod = 10;
input priceH = high;
input priceL = low;
input priceC = close;
input averageType = AverageType.SIMPLE;
input length = 1000;
input paintBars = yes;
input showLabels = yes;


# --- Indicators - StochasticSlow / MACD / MACD StDev / DMI+/-
def SlowK = reference StochasticFull(over_bought, over_sold, KPeriod, DPeriod, priceH, priceL, priceC, 3, averageType).FullK;
def MACD = reference MACD()."Value";
def priceMean = Average(MACD, length);
def MACD_stdev =  (MACD - priceMean) / StDev(MACD, length);
def dPlus = reference DMI()."DI+";
def dMinus = reference DMI()."DI-";
# --- End Indicators

# --- Conditions
def sellerRegular = SlowK < 20 and MACD_stdev < -1 and dPlus < 15;
def sellerExtreme = SlowK < 20 and MACD_stdev < -2 and dPlus < 15;
def buyerRegular = SlowK > 80 and MACD_stdev > 1 and dMinus < 15;
def buyerExtreme = SlowK > 80 and MACD_stdev > 2 and dMinus < 15;
# --- End Conditions

# -- Price Color
AssignPriceColor( if paintBars and sellerExtreme then Color.CYAN else if buyerExtreme and paintBars then Color.GREEN else if paintBars and sellerRegular then Color.YELLOW else if buyerRegular and paintBars then Color.DARK_GREEN else if paintBars then Color.GRAY else Color.Current);

# --- Arrows/Triggers
plot RegularBuy = if sellerRegular[1] and !sellerRegular then 1 else 0;
plot ExtremeBuy = if sellerExtreme[1] and !sellerExtreme  then 1 else 0;
RegularBuy.SetPaintingStrategy(PaintingSTrategy.ARROW_UP);
ExtremeBuy.SetPaintingSTrategy(paintingSTrategy.Arrow_UP);
RegularBuy.SetDefaultColor(Color.green);
ExtremeBuy.SetDefaultColor(Color.Dark_GREEN);

plot RegularSell = if buyerRegular[1] and !buyerRegular  then 1 else 0;
plot ExtremeSell = if buyerExtreme[1] and !buyerExtreme  then 1 else 0;
RegularSell.SetPaintingStrategy(PaintingSTrategy.ARROW_down);
ExtremeSell.SetPaintingSTrategy(paintingSTrategy.Arrow_DOWN);
RegularSell.SetDefaultColor(Color.red);
ExtremeSell.SetDefaultColor(Color.Dark_red);


# --- Labels#
#AddLabel(showLabels,"SellerRegular",Color.YELLOW);
#AddLabel(showLabels,"SellerExtreme",Color.CYAN);
#AddLabel(showLabels,"BuyerRegular",Color.DARK_GREEN);
#AddLabel(showLabels,"BuyerExtreme",Color.GREEN);
#Addlabel (yes,  "3X EXH:", Color.Gray);
#Addlabel (yes, if sellerExtreme then "  " else
 #              if buyerExtreme then "  " else
 #              if sellerRegular then "  " else
 #              if buyerRegular then "  " else
 #              if sellerExtreme then "  " else "  ",
 #              if buyerExtreme then Color.MAGENTA else
 #              if sellerRegular then Color.GREEN else
 #              if buyerRegular then Color.RED else
 #              if sellerExtreme then Color.Cyan else
 #              Color.yellow);
#Addlabel (yes, " 3X ARW: ", Color.Gray);
addLabel (yes, if extremeSell within 3 bars then "3X" else
               if extremebuy within 3 bars then "3X" else
               if regularsell within 3 bars then "3XT" else
               if regularbuy within 3 bars then "3XT" else "  ");

AssignbackgroundColor(
               if extremeSell within 3 bars then Color.Dark_red else
               if extremebuy  within 3 bars then  Color.Dark_green else
               if regularsell within 3 bars then Color.dark_red else
               if regularbuy  within 3 bars then  Color.dark_green else
                  Color.dark_gray);


lNSxdDF.png


MAMA Watchlist Column Share Link - http://tos.mx/AvGKZ10 (4/25/23)

Description
The MAMA watchlist column indicates bullish or bearish price action which (I believe - will verify) is based on the agreement level between 16 different indicators
  • Green = bullish
  • Red = bearish
Code:
#Ehler's MAMA Watchlist Column
#Created by Christopher84 10/10/2022
 
script WMA_Smooth {
    input price = hl2;
    plot smooth = (4 * price
+ 3 * price[1]
+ 2 * price[2]
+ price[3]) / 10;
}

input showcloud = no;

script Phase_Accumulation {
# This is Ehler's Phase Accumulation code. It has a full cycle delay.
# However, it computes the correction factor to a very high degree.
#
    input price = hl2;

    rec Smooth;
    rec Detrender;
    rec Period;
    rec Q1;
    rec I1;
    rec I1p;
    rec Q1p;
    rec Phase1;
    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase1;
    rec InstPeriod1;
    rec InstPeriod;
    def CorrectionFactor;

    if BarNumber() <= 5
    then {
        Period = 0;
        Smooth = 0;
        Detrender = 0;
        CorrectionFactor = 0;
        Q1 = 0;
        I1 = 0;
        Q1p = 0;
        I1p = 0;
        Phase = 0;
        Phase1 = 0;
        DeltaPhase1 = 0;
        DeltaPhase = 0;
        InstPeriod = 0;
        InstPeriod1 = 0;
    } else {
        CorrectionFactor = 0.075 * Period[1] + 0.54;
 
# Smooth and detrend my smoothed signal:
        Smooth = WMA_Smooth(price);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;
 
# Compute Quadrature and Phase of Detrended signal:
        Q1p = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1p = Detrender[3];
 
# Smooth out Quadrature and Phase:
        I1 = 0.15 * I1p + 0.85 * I1p[1];
        Q1 = 0.15 * Q1p + 0.85 * Q1p[1];
 
# Determine Phase
        if I1 != 0
        then {
# Normally, ATAN gives results from -pi/2 to pi/2.
# We need to map this to circular coordinates 0 to 2pi

            if Q1 >= 0 and I1 > 0
            then { # Quarant 1
                Phase1 = ATan(AbsValue(Q1 / I1));
            } else if Q1 >= 0 and I1 < 0
            then { # Quadrant 2
                Phase1 = Double.Pi - ATan(AbsValue(Q1 / I1));
            } else if Q1 < 0 and I1 < 0
            then { # Quadrant 3
                Phase1 = Double.Pi + ATan(AbsValue(Q1 / I1));
            } else { # Quadrant 4
                Phase1 = 2 * Double.Pi - ATan(AbsValue(Q1 / I1));
            }
        } else if Q1 > 0
        then { # I1 == 0, Q1 is positive
            Phase1 = Double.Pi / 2;
        } else if Q1 < 0
        then { # I1 == 0, Q1 is negative
            Phase1 = 3 * Double.Pi / 2;
        } else { # I1 and Q1 == 0
            Phase1 = 0;
        }
 
# Convert phase to degrees
        Phase = Phase1 * 180 / Double.Pi;

        if Phase[1] < 90 and Phase > 270
        then {
# This occurs when there is a big jump from 360-0
            DeltaPhase1 = 360 + Phase[1] - Phase;
        } else {
            DeltaPhase1 = Phase[1] - Phase;
        }
 
# Limit our delta phases between 7 and 60
        if DeltaPhase1 < 7
        then {
            DeltaPhase = 7;
        } else if DeltaPhase1 > 60
        then {
            DeltaPhase = 60;
        } else {
            DeltaPhase = DeltaPhase1;
        }
 
# Determine Instantaneous period:
        InstPeriod1 =
-1 * (fold i = 0 to 40 with v=0 do
if v < 0 then
v
else if v > 360 then
-i
else
v + GetValue(DeltaPhase, i, 41)
);

        if InstPeriod1 <= 0
        then {
            InstPeriod = InstPeriod[1];
        } else {
            InstPeriod = InstPeriod1;
        }

        Period = 0.25 * InstPeriod + 0.75 * Period[1];
    }
    plot DC = Period;
}

script Ehler_MAMA {
    input price = hl2;
    input FastLimit = 0.5;
    input SlowLimit = 0.05;


    rec Period;
    rec Period_raw;
    rec Period_cap;
    rec Period_lim;

    rec Smooth;
    rec Detrender;
    rec I1;
    rec Q1;
    rec jI;
    rec jQ;
    rec I2;
    rec Q2;
    rec I2_raw;
    rec Q2_raw;

    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase_raw;
    rec alpha;
    rec alpha_raw;

    rec Re;
    rec Im;
    rec Re_raw;
    rec Im_raw;

    rec SmoothPeriod;
    rec vmama;
    rec vfama;

    def CorrectionFactor = Phase_Accumulation(price).CorrectionFactor;

    if BarNumber() <= 5
    then {
        Smooth = 0;
        Detrender = 0;

        Period = 0;
        Period_raw = 0;
        Period_cap = 0;
        Period_lim = 0;
        I1 = 0;
        Q1 = 0;
        I2 = 0;
        Q2 = 0;
        jI = 0;
        jQ = 0;
        I2_raw = 0;
        Q2_raw = 0;
        Re = 0;
        Im = 0;
        Re_raw = 0;
        Im_raw = 0;
        SmoothPeriod = 0;
        Phase = 0;
        DeltaPhase = 0;
        DeltaPhase_raw = 0;
        alpha = 0;
        alpha_raw = 0;
        vmama = 0;
        vfama = 0;
    } else {
# Smooth and detrend my smoothed signal:
        Smooth = WMA_Smooth(price);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

        Q1 = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1 = Detrender[3];

        jI = ( 0.0962 * I1
+ 0.5769 * I1[2]
- 0.5769 * I1[4]
- 0.0962 * I1[6] ) * CorrectionFactor;

        jQ = ( 0.0962 * Q1
+ 0.5769 * Q1[2]
- 0.5769 * Q1[4]
- 0.0962 * Q1[6] ) * CorrectionFactor;
 
# This is the complex conjugate
        I2_raw = I1 - jQ;
        Q2_raw = Q1 + jI;

        I2 = 0.2 * I2_raw + 0.8 * I2_raw[1];
        Q2 = 0.2 * Q2_raw + 0.8 * Q2_raw[1];

        Re_raw = I2 * I2[1] + Q2 * Q2[1];
        Im_raw = I2 * Q2[1] - Q2 * I2[1];

        Re = 0.2 * Re_raw + 0.8 * Re_raw[1];
        Im = 0.2 * Im_raw + 0.8 * Im_raw[1];
 
# Compute the phase
        if Re != 0 and Im != 0
        then {
            Period_raw = 2 * Double.Pi / ATan(Im / Re);
        } else {
            Period_raw = 0;
        }

        if Period_raw > 1.5 * Period_raw[1]
        then {
            Period_cap = 1.5 * Period_raw[1];
        } else if Period_raw < 0.67 * Period_raw[1] {
            Period_cap = 0.67 * Period_raw[1];
        } else {
            Period_cap = Period_raw;
        }

        if Period_cap < 6
        then {
            Period_lim = 6;
        } else if Period_cap > 50
        then {
            Period_lim = 50;
        } else {
            Period_lim = Period_cap;
        }

        Period = 0.2 * Period_lim + 0.8 * Period_lim[1];
        SmoothPeriod = 0.33 * Period + 0.67 * SmoothPeriod[1];

        if I1 != 0
        then {
            Phase = ATan(Q1 / I1);
        } else if Q1 > 0
        then { # Quadrant 1:
            Phase = Double.Pi / 2;
        } else if Q1 < 0
        then { # Quadrant 4:
            Phase = -Double.Pi / 2;
        } else { # Both numerator and denominator are 0.
            Phase = 0;
        }

        DeltaPhase_raw = Phase[1] - Phase;
        if DeltaPhase_raw < 1
        then {
            DeltaPhase = 1;
        } else {
            DeltaPhase = DeltaPhase_raw;
        }

        alpha_raw = FastLimit / DeltaPhase;
        if alpha_raw < SlowLimit
        then {
            alpha = SlowLimit;
        } else {
            alpha = alpha_raw;
        }
        vmama = alpha * price + (1 - alpha) * vmama[1];
        vfama = 0.5 * alpha * vmama + (1 - 0.5 * alpha) * vfama[1];
    }

    plot MAMA = vmama;
    plot FAMA = vfama;

}

declare upper;
input price = hl2;
input FastLimit = 0.5;
input SlowLimit = 0.05;
DefineGlobalColor("Pre_Cyan", CreateColor(50, 200, 255)) ;
DefineGlobalColor("LabelGreen",  CreateColor(0, 165, 0)) ;
DefineGlobalColor("LabelRed",  CreateColor(225, 0, 0)) ;

plot MAMA = Ehler_MAMA(price, FastLimit, SlowLimit).MAMA;

def UP = price > MAMA;
def DOWN = price < MAMA;

addlabel(yes, if UP then "👍 1H" else if Down then "👎 1H" else "  ", color.white);
AssignBackgroundColor(if DOWN then color.dark_RED else if UP then color.dark_green else color.black);
#"👍" else if Down then "👎"

FCc9xdp.png


8heyvSb.png


EMAD Watchlist Column: https://tos.mx/gHABnff

Code:
#EMAD_Range Created by Christopher84 01/05/2022
#EMAD Watchlist column HODL

declare lower;
input length8 = 10;
input length9 = 35;
input length10 = 12;
input show_ema_cloud = yes;
input price1 = close;
input coloredCandlesOn = no;
def showBreakoutSignals = no;
def displace = 0;
def bn = barnumber();
def AvgExp8 = ExpAverage(price1[-displace], length8);
def UPD = AvgExp8[1] < AvgExp8;
#AvgExp8.SetStyle(Curve.SHORT_DASH);
#AvgExp8.SetLineWeight(1);

def AvgExp9 = ExpAverage(price1[-displace], length9);
def UPW = AvgExp9[1] < AvgExp9;
#AvgExp9.SetStyle(Curve.SHORT_DASH);
#AvgExp9.SetLineWeight(1);

def Below = AvgExp8 < AvgExp9;
def Spark = UPD + UPW + Below;

def UPEMA = AvgExp8[1] < AvgExp8;
def DOWNEMA = AvgExp8[1] > AvgExp8;
#AvgExp8.AssignValueColor(if UPEMA then Color.LIGHT_GREEN else if DOWNEMA then Color.RED else Color.YELLOW);

def UPEMA2 = AvgExp9[1] < AvgExp9;
def DOWNEMA2 = AvgExp9[1] > AvgExp9;
#AvgExp9.AssignValueColor(if UPEMA2 then Color.LIGHT_GREEN else if DOWNEMA2 then Color.RED else Color.YELLOW);

def EMAD = (price1 - AvgExp8);
def UPEMAD = EMAD >= EMAD[1];
def DOWNEMAD = EMAD < EMAD[1];
#EMAD.AssignValueColor(if UPEMAD then Color.LIGHT_GREEN else if DOWNEMAD then Color.RED else Color.GRAY);

def EMAD2 = (price1 - AvgExp9);
def UPEMAD2 = EMAD2 >= EMAD2[1];
def DOWNEMAD2 = EMAD2 < EMAD2[1];
#EMAD2.AssignValueColor(if UPEMAD2 then Color.White else if DOWNEMAD2 then Color.BLUE else Color.GRAY);

def EMADAvg = (EMAD + EMAD2) / 2;
def UPEMADAvg = EMADAvg >= EMADAvg[1];
def DOWNEMADAvg = EMADAvg < EMADAvg[1];
#EMADAvg.AssignValueColor(if UPEMADAvg then Color.LIGHT_GREEN else if DOWNEMADAvg then Color.RED else Color.GRAY);

plot EMADSmooth = ExpAverage(EMADAvg[-displace], length10);


#########################################
input length = 14;
input averageType = AverageType.WILDERS;
def price = EMADSmooth;
#def bottom = Min(close[1], low);
input agperiod1 = AggregationPeriod.DAY;

def o = (EMADSmooth + EMADSmooth[1]) / 2;

def h = Max(EMADSmooth, EMADSmooth[1]);

def l = Min(EMADSmooth, EMADSmooth[1]);

def c = EMADSmooth;

#def open = open(period = agperiod1);
#def high = high(period = agperiod1);
#def low = low(period = agperiod1);
#def close = close(period = agperiod1);
def bottom = Min(c[1], l);
def tr = TrueRange(h, c, l);

def ptr = tr / (bottom + tr / 2);

def APTR = MovingAverage(averageType, ptr, length);
#APTR.SetDefaultColor(GetColor(8));
def UpperBand = c[1] + (APTR * o);
#UpperBand.SetDefaultColor(Color.GRAY);

def LowerBand = c[1] - (APTR * o);
#LowerBand.SetDefaultColor(Color.GRAY);

def MidBand = (UpperBand + LowerBand) / 2;

def BulgeLength = 100;
def SqueezeLength = 100;
def BulgeLength2 = 200;
def SqueezeLength2 = 200;
#Top Line
def Bulge = Highest(MidBand, BulgeLength);
#Bottom Line
def Squeeze = Lowest(MidBand, SqueezeLength);
#MidBand.AssignValueColor(if (MidBand > EMADSmooth) then Color.RED else if (MidBand < #EMADSmooth) then Color.GREEN else Color.GRAY);
#EMADSmooth.AssignValueColor(if (MidBand > EMADSmooth) then Color.RED else if (MidBand < #EMADSmooth) then Color.GREEN else Color.GRAY);

#AddCloud(if show_ema_cloud and (MidBand > EMADSmooth) then MidBand else Double.NaN, #EMADSmooth, Color.RED, Color.CURRENT);
#AddCloud(if show_ema_cloud and (EMADSmooth >= MidBand) then EMADSmooth else Double.NaN, #MidBand, Color.GREEN, Color.CURRENT);



def ZeroLine = 0;
def NearZeroAbove = (EMADSmooth > 0) and (EMADSmooth < 1);
def NearZeroBelow = (EMADSmooth < 0) and (EMADSmooth > -1);

#ZeroLine.AssignValueColor(if (EMADSmooth > ZeroLine) then Color.GREEN else if #(EMADSmooth < ZeroLine) then Color.RED else Color.YELLOW);

def EMADSUp = EMADSmooth > ZeroLine;
def EMADSDown = EMADSmooth < ZeroLine;

#Top line moving
def bulge_Step_DN = if Bulge < Bulge[1] then 1 else 0;
def bulge_Step_UP = if Bulge > Bulge[1] then 1 else 0;

#Bottom line moving
def Squeeze_Step_DN = if Squeeze < Squeeze[1] then 1 else 0;
def Squeeze_Step_UP = if Squeeze > Squeeze[1] then 1 else 0;

#Ema <> zeroline

def EMADSUP_bn = if EMADSUP then bn else EMADSUP_bn[1];

def EMADSDown_bn = if EMADSDown then bn else EMADSDown_bn[1];
#Ema direction
def EMADdown = (MidBand > EMADSmooth);
def EMADup = (EMADSmooth >= MidBand);

#Cross
def CrossUP = if (MidBand[1] > EMADSmooth[1])and(MidBand < EMADSmooth) then 1 else 0;
def CrossDOWN = if (EMADSmooth[1] > MidBand[1])and(EMADSmooth < MidBand) then 1 else 0;

#value at cross
Def ValueUP = if crossup then midband else 0;
Def ValueDown = if crossdown then midband else 0;

#determine if cross touching line
def CrossUPline = if (ValueUP - squeeze) == 0 then 1 else 0;
def CrossDownline = if (ValueDown - bulge) == 0 then 1 else 0;

#bar number at cross
def CrossUPline_bn = if CrossUPline then bn else CrossUPline_bn[1];
def CrossDownline_bn = if CrossDownline then bn else CrossDownline_bn[1];

#which cross at line is most recent
def Last_Cross_Up = CrossUPline_bn > CrossDownline_bn ;
def Last_Cross_Down = CrossDownline_bn > CrossUPline_bn ;

def crossupline_filter = if crossupline and (crossupline[1] or crossupline[2]  or crossupline[3]   or crossupline[4])then 0 else 1;
def crossdownline_filter = if Crossdownline and (Crossdownline[1] or Crossdownline[2]  or Crossdownline[3]   or Crossdownline[4])then 0 else 1;


#addLabel (yes, if EMADSmooth > ZeroLine then "EMAD" else
#if EMADSmooth < ZeroLine then "EMAD" else "EMAD");
addLabel (yes,( if (CrossUPline) then "Cross Up - Line"
else if (EMADSDown) and (MidBand > EMADSmooth) then "EMA DN < 0"
else if (CrossDOWNline) then "Cross Down - Line"
else if (EMADSUp) and(EMADSmooth >= MidBand) then "EMA UP > 0"
else if (EMADSUp) and (MidBand > EMADSmooth) then "EMA DN > 0"
else if (EMADSDown) and (EMADSmooth >= MidBand) then  "EMA UP < 0"
else  ""),
     if (CrossUPline) then Color.black
else if (EMADSDown) and (MidBand > EMADSmooth) then color.white
else if (CrossDOWNline) then Color.black
else if (EMADSUp) and(EMADSmooth >= MidBand) then color.white
else if (EMADSUp) and (MidBand > EMADSmooth) then color.black
else if (EMADSDown) and (EMADSmooth >= MidBand) then Color.black
else Color.black);
AssignBackgroundColor(
if (CrossUPline) then Color.red
else if (EMADSDown)and (MidBand > EMADSmooth) then Color.dark_RED
else if (CrossDOWNline) then Color.green
else if (EMADSUp) and(EMADSmooth >= MidBand) then Color.Dark_GREEN
else if (EMADSUp) and (MidBand > EMADSmooth) then Color.yellow
else if (EMADSDown) and (EMADSmooth >= MidBand) then Color.orange
else Color.dark_GRAY);

#else if (NearZeroAbove) then Color.GREEN
#else if (NearZeroBelow) then Color.Dark_red else Color.GRAY);


#Vertical Line
AddVerticalLine(( GetDay() <> GetDay()[1]), "", Color.Dark_Gray, Curve.SHORT_DASH);

#plot Bulge = Highest(MidBand, BulgeLength);
#Bulge.SetDefaultColor(Color.WHITE);
#plot Squeeze = Lowest(MidBand, SqueezeLength);
#Squeeze.SetDefaultColor(Color.WHITE);


#Label
#Addlabel (yes," EMAD: ", Color.Gray);
#addLabel (yes, if EMADSmooth > ZeroLine then "  " else
#if EMADSmooth < ZeroLine then "  " else " ",
 #              if EMADSmooth > ZeroLine then Color.Green else
              # if EMADSmooth < ZeroLine then Color.Red else
              # Color.CURRENT);
 
Last edited:

Alternate Versions | Styles & Studies

This post will provide links to alternate versions of chart styles and studies related to the Confirmation Trend Chart Style. The following studies may be in various stages of development and or require backtesting while others are complete though no longer in use for reasons noted in the description.

TS_V9_Spark_Filter
Style & Study
TS_V9_Spark_Filter Study - https://tos.mx/JjV5zo6
TS_V9_Spark_Filter Style- https://tos.mx/yioyc2k

Description
This is a single aggregation variation of TS_V9 Filtered where the C3_Max_Spark_Filtered Arrows are referenced as the filter for TS_V9 signals

* Note: The screenshot below shows white arrows (from the TS_V9 Spark Filter) and the cyan arrows from the TS_V9_Filtered study (the cyan arrows will plot on top of some of the white arrows but I wanted to use it as a reference. Seems to work well on higher timeframes the short amount of time I have looked at it... Let me know what you think *

cLBwBu4.png


This is the study on its own (the spark up and down arrows can also be turned on in settings)
ppoxYZN.png


MTF Version
Style & Study
C3_Max_Spark_MTF Chart Style - https://tos.mx/MvgNxaz

Description
This is the multi timeframe version of C3_Max_Spark as the name implies though the MTF functionality is only applied to the labels. Unfortunately 4 aggregations cause a very noticeable lag. The lower indicator with horizontal lines (over the top of the EMAD Lower…) is 4 aggregations of Vix Alert 4 and Triple Exhaustion.

Future development
In the near future only a second aggregation for the more useful label(s) will be utilized in order to minimize lag if possible.

oU2cKzn.png


Code:
   ##########################################################################################
   ##########################################################################################
   ###                                                                                    ###
   ###       #############################           #########               #########    ###
   ###     #################################         #########               #########    ###
   ###    ####################################       #########               #########    ###                                                                                                 
   ###   ########                     #########      #########               #########    ###
   ###   ########    C3_MAX_SPARK     #########      #########               #########    ###                                                                                                
   ###   ########         MTF         #########      #########               #########    ###
   ###   ########   @Christopher84    #########      #########               #########    ###
   ###   ########                     #########      #########               #########    ###
   ###   ######################################      ##################################   ###
   ###    ####################################       ##################################   ###
   ###     #################################         ##################################   ###
   ###    ####################################       ##################################   ###
   ###   ########                     #########                              #########    ###
   ###   ########     @Horserider     #########                              #########    ###                                                                                                     
   ###   ########  HORSERIDER VOLUME  #########                              #########    ###   
   ###   ########  TRIPLE EXHAUSTION  #########                              #########    ###
   ###   ########      @chence27      #########                              #########    ###    
   ###   ########                     #########                              #########    ###
   ###    ####################################                               #########    ###
   ###     ##################################                                #########    ###
   ###      ###############################                                  #########    ###
   ###                                                                                    ###
   ##########################################################################################
   ##########################################################################################




#TS Strategy_V9 Created by Christopher84 08/10/2021
#Modified 05/23/2022 to include Chart Bubbles and Labels.
#Modified 05/25/2022 to include Targets and Stoplosses.
#Modified 05/26/2022 to include Line Labels by Dcstocks
#Modified 05/27/2022 to include target 7.
                          
# Created by Christopher84 06/30/2022                                                                                                  
# Based off of the Confirmation Candles Study. Main difference is that CC Candles weigh factors of positive                                                                                              
# and negative price movement to create the Consensus_Level. The Consensus_Level is considered positive if                                                                                              
# above zero and negative if below zero.                                                                                              
                              
# --- HORSERIDER VOLUME --- #                                                                                              
                              
# Show total volume in gray.  Buying volume in green.  Sell Volume in red.                                                                                              
# Volume average is gray line.                                                                                              
# Specified percent over average volume is cyan triangles.                                                                                              
# Horserider 12/30/2019 derived from some already existing studies.                                                                                              
# hiVolume indicator                                                                                              
# source: http://tinboot.blogspot.com                                                                                              
# author: allen everhart                                                                                                                                      
# --- TRIPLE EXHAUSTION --- #                                                                                                                                  
# Requested by @Chence27 from criteria listed here https://usethinkscript.com/threads/triple-exhaustion-indicator.9001/                                                                                              
# Removing the header Credit credits and description is not permitted, any modification needs to be shared.                                                                                              
# V 1.0 :    @cos251 - Initial release per request from www.usethinkscript.com forum thread:                                                                                              
#       :    https://usethinkscript.com/threads/triple-exhaustion-indicator.9001/                                                                                              
# V 1.1 : @chence27 - modifcations to better approximate original study                                                                                              


declare upper;

#input ShowBroadMkt = yes;


#AssignPriceColor(if ColoredCandlesOn and (priceColor_V5 == 1) then Color.GREEN else if ColoredCandlesOn and (priceColor_V5 == -1) then Color.RED else Color.GRAY);                             
                              
# --- C3 MAX ---                                                                                         
#####################################################################################################################################################
input agperiod1 = {"1 min", "2 min", "3 min", default "5 min", "10 min", "15 min", "30 min", "1 hour", "2 hours", "4 hours", "Day", "Week", "Month"};
input agperiod2 = {"1 min", "2 min", "3 min", "5 min",default "10 min", "15 min", "30 min", "1 hour", "2 hours", "4 hours", "Day", "Week", "Month"};
input agperiod3 = {"1 min", "2 min", "3 min", "5 min", "10 min", "15 min", "30 min",default "1 hour", "2 hours", "4 hours", "Day", "Week", "Month"};
                             
input Price = CLOSE;                                                                                              
input ShortLength1 = 5;                                                                                              
input ShortLength2 = 14;                                                                                              
input ShortLength3 = 5;                                                                                              
input LongLength1 = 12;                                                                                              
input LongLength2 = 55;                                                                                              
input LongLength3 = 7;                                                                                              
input Color_Candles = yes;                                                                                              
                                                                                                                                            
# --- HORSERIDER Volume ---                                                                                              

input Show30DayAvg = no;
input ShowTodayVolume =  no;
input ShowPercentOf30DayAvg = yes;
input UnusualVolumePercent = 200;
input Show30BarAvg = no;
input ShowCurrentBar = yes;
input ShowPercentOf30BarAvg = yes;
input ShowSellVolumePercent = yes;
def length_3 = 20;
input type_HV = { default SMP, EXP } ;
input length1_3 = 20 ;
input hotPct = 100.0;                                                                                                                                                                                                  

def O_3 = open;
def H_3 = high;
def C_3 = close;
def L_3 = low;
def V_3 = volume;
def buying =  V_3 * (C_3 - L_3) / (H_3 - L_3);
def selling = V_3 * (H_3 - C_3) / (H_3 - L_3);

def volLast30DayAvg = (volume(period =
"DAY")[1]  + volume(period = "DAY")[2]  + volume(period = "DAY")[3]  + volume(period =
"DAY")[4]  + volume(period = "DAY")[5]  + volume(period = "DAY")[6]  + volume(period =
"DAY")[7]  + volume(period = "DAY")[8]  + volume(period = "DAY")[9]  + volume(period =
"DAY")[10] + volume(period = "DAY")[11] + volume(period = "DAY")[12] + volume(period =
"DAY")[13] + volume(period = "DAY")[14] + volume(period = "DAY")[15] + volume(period =
"DAY")[16] + volume(period = "DAY")[17] + volume(period = "DAY")[18] + volume(period =
"DAY")[19] + volume(period = "DAY")[20] + volume(period = "DAY")[21] + volume(period =
"DAY")[22] + volume(period = "DAY")[23] + volume(period = "DAY")[24] + volume(period =
"DAY")[25] + volume(period = "DAY")[26] + volume(period = "DAY")[27] + volume(period =
"DAY")[28] + volume(period = "DAY")[29] + volume(period = "DAY")[30]) / 30;

def today = volume(period = "DAY");
def percentOf30Day = Round((today / volLast30DayAvg) * 100, 0);

def avg30Bars = (volume[1]  + volume[2]  + volume[3]  + volume[4]  + volume[5]  + volume[6]
  + volume[7]  + volume[8]  + volume[9]  + volume[10] + volume[11] + volume[12] + volume[13]
  + volume[14] + volume[15] + volume[16] + volume[17] + volume[18] + volume[19] + volume[20]
  + volume[21] + volume[22] + volume[23] + volume[24] + volume[25] + volume[26] + volume[27]
  + volume[28] + volume[29] + volume[30]) / 30;

def curVolume = volume;
def percentOf30Bar = Round((curVolume / avg30Bars) * 100, 0);
def SellVolPercent = Round((selling / volume) * 100, 0);
def ma = if type_HV == type_HV.SMP then SimpleMovingAvg(volume, length_3) else MovAvgExponential(volume, length_3);                                                                  
                              
# --- TRIPLE EXHAUSTION ---
                                                                                                                                             
input averageType_3x = AverageType.SIMPLE;
input length_3x = 1000;

def over_bought_3x = 80;
def over_sold_3x = 20;
def KPeriod_3x = 10;
def DPeriod_3x = 10;
def priceH_3x = high;
def priceL_3x = low;
def priceC_3x = close;                                                                                                                                                          
                                                                                          
# --- TRIPLE EXHAUSTION INDICATORS - StochasticSlow / MACD / MACD StDev / DMI+/-                                                                                       

def SlowK_3x = reference StochasticFull(over_bought_3x, over_sold_3x, KPeriod_3x, DPeriod_3x, priceH_3x, priceL_3x, priceC_3x, 3, averageType_3x).FullK;
def MACD_3x = reference MACD()."Value";
def priceMean_3x = Average(MACD_3x, length_3x);
def MACD_stdev_3x =  (MACD_3x - priceMean_3x) / StDev(MACD_3x, length_3x);
def dPlus_3x = reference DMI()."DI+";
def dMinus_3x = reference DMI()."DI-";

def sellerRegular = SlowK_3x < 20 and MACD_stdev_3x < -1 and dPlus_3x < 15;
def sellerExtreme = SlowK_3x < 20 and MACD_stdev_3x < -2 and dPlus_3x < 15;

def buyerRegular = SlowK_3x > 80 and MACD_stdev_3x > 1 and dMinus_3x < 15;
def buyerExtreme = SlowK_3x > 80 and MACD_stdev_3x > 2 and dMinus_3x < 15;
                                                                                                                                                    
# --- Arrows/Triggers                                                  

plot RegularBuy = if sellerRegular[1] and !sellerRegular then low else Double.NaN;
plot ExtremeBuy = if sellerExtreme[1] and !sellerExtreme then low else Double.NaN;

plot RegularSell = if buyerRegular[1] and !buyerRegular then high else Double.NaN;
plot ExtremeSell = if buyerExtreme[1] and !buyerExtreme then high else Double.NaN;

RegularBuy.SetPaintingStrategy(PaintingStrategy.POINTS);
ExtremeBuy.SetPaintingStrategy(PaintingStrategy.POINTS);
RegularSell.SetPaintingStrategy(PaintingStrategy.POINTS);
ExtremeSell.SetPaintingStrategy(PaintingStrategy.POINTS);

input point_size_3x = 5;

RegularBuy.SetLineWeight((point_size_3x));
ExtremeBuy.SetLineWeight((point_size_3x));
RegularSell.SetLineWeight((point_size_3x));
ExtremeSell.SetLineWeight((point_size_3x));

RegularBuy.SetDefaultColor((Color.GREEN));
ExtremeBuy.SetDefaultColor((Color.WHITE));
RegularSell.SetDefaultColor((Color.RED));
ExtremeSell.SetDefaultColor((Color.WHITE));                                                                                                   
                              
# --- C3 MAX --- #                                                                                              
                              
# Momentum Oscillators                                                                                              

def MS = Average(Average(price, ShortLength1) - Average(price, ShortLength2), ShortLength3);
def MS2 = Average(Average(price, LongLength1) - Average(price, LongLength2), LongLength3);                                                                                              
                              
# Wave A                                                                                              

def MSGreens = If (MS >= 0, MS, 0);
def MSReds = If (MS < 0, MS, 0);                                                                                              
                              
# Wave C                                                                                              

def MS2Blues = If (MS2 >= 0, MS2, 0);
def MS2Yellows = If (MS2 < 0, MS2, 0);
def MayhemBullish = MSGreens > MSGreens[1] and  MS2Blues > MS2Blues[1];
def MayhemBearish =  MSReds < MSReds[1] and  MS2Yellows < MS2Yellows[1];
def MS_Pos = MSGreens;
def MS_Neg = MSReds;
def MS2_Pos = MS2Blues;
def MS2_Neg = MS2Yellows;                                                                                              
                              
# Squeeze Indicator                                                                                                                                                                                                   

def length = 20;
def nK = 1.5;
def nBB = 2.0;
def BBHalfWidth = StDev(price, length);
def KCHalfWidth = nK * Average(TrueRange(high,  close,  low),  length);
def isSqueezed = nBB * BBHalfWidth / KCHalfWidth < 1;
def BBS_Ind = If(isSqueezed, 0, Double.NaN);                                                                                              
                              
# Bollinger Resolution                                                                                              

def BBSMA = Average(price, length);
def BBSMAL = BBSMA + (-nBB * BBHalfWidth);
def BBSMAU = BBSMA + (nBB * BBHalfWidth);
def PerB = RoundUp((price - BBSMAL) / (BBSMAU - BBSMAL) * 100, 0);
      
# Parabolic SAR Signal                                                                                              

input accelerationFactor = 0.0275;
input accelerationLimit = 0.2;

def SAR = ParabolicSAR(accelerationFactor = accelerationFactor, accelerationLimit = accelerationLimit);
def bearishCross = Crosses(SAR, price, CrossingDirection.ABOVE);
def signalDown = bearishCross;#If(bearishCross, 0, Double.NaN);                                                                                              
def bullishCross = Crosses(SAR, price, CrossingDirection.BELOW);
def signalUp =  bullishCross;#If(bullishCross, 0, Double.NaN);                                                                                              
def UP = bullishCross;
def DOWN = bearishCross;
def priceColor = if UP then 1 else if DOWN then -1 else priceColor[1];                                                                                              
                              
# OB_OS_Levels_v5 by Christopher84 12/10/2021                                                                                              

input BarsUsedForRange = 2;
input BarsRequiredToRemainInRange = 2;
input ColorPrice = YES;
input HideTargets = no;
input HideBalance = no;
input HideBoxLines = no;
input HideCloud = no;
input HideLabels = no;                                                                                                                                                                                                   
                              
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                              

def ATRPeriod = 5;
def ATRFactor = 2.0;

def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1] then high - close[1] else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1] then close[1] - low else (close[1] - low) - 0.5 * (low[1] - high);

input trailType = {default modified, unmodified};
def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}

input averageType = AverageType.SIMPLE;
input firstTrade = {default long, short};

def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);
def state = {default init, long, short};

def trail;

switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
case long:
        state = state.long;
        trail =  close - loss;
case short:
        state = state.short;
        trail = close + loss;}
    } else {
        state = state.init;
        trail = Double.NaN;}
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;}
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;}}

def TrailingStop = trail;
def H = Highest(TrailingStop, 12);
def L = Lowest(TrailingStop, 12);
def BulgeLengthPrice = 100;
def SqueezeLengthPrice = 100;
def BandwidthC3 = (H - L);
def IntermResistance2 = Highest(BandwidthC3, BulgeLengthPrice);
def IntermSupport2 = Lowest(BandwidthC3, SqueezeLengthPrice);
def sqzTrigger = BandwidthC3 <= IntermSupport2;
def sqzLevel = if !sqzTrigger[1] and sqzTrigger then hl2                                                                                              
               else if !sqzTrigger then Double.NaN                                                                                              
               else sqzLevel[1];

plot Squeeze_Alert = sqzLevel;
Squeeze_Alert.SetPaintingStrategy(PaintingStrategy.POINTS);
Squeeze_Alert.SetLineWeight(3);
Squeeze_Alert.SetDefaultColor(Color.YELLOW);                                                                                              
                              
#-----------------------------                                                                                              
#Yellow Candle_height (OB_OS)                                                                                              
#-----------------------------                                                                                              

def displace = 0;
def factorK2 = 3.25;
def lengthK2 = 20;
def price1 = open;
def trueRangeAverageType = AverageType.SIMPLE;
def ATR_length = 15;
def SMA_lengthS = 6;                                                                                              
input ATRPeriod2 = 5;                                                                                              
input ATRFactor2 = 1.5;                                                                                              
                              
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                              

#def ATRPeriod2 = 5;
#def ATRFactor2 = 1.5;

def HiLo2 = Min(high - low, 1.5 * Average(high - low, ATRPeriod));

def HRef2 = if (low <= high[1]) then (high - close[1]) else
               (high - close[1]) - 0.5 * (low - high[1]);

def LRef2 = if (high >= low[1]) then (close[1] - low) else
               (close[1] - low) - 0.5 * (low[1] - high);

def loss2 = ATRFactor2 * MovingAverage(averageType, trueRange, ATRPeriod2);
def multiplier_factor = 1.25;
def valS = Average(price, SMA_lengthS);
def average_true_range = Average(TrueRange(high, close, low), length = ATR_length);
def Upper_BandS = valS[-displace] + multiplier_factor * average_true_range[-displace];
def Middle_BandS = valS[-displace];
def Lower_BandS = valS[-displace] - multiplier_factor * average_true_range[-displace];
def shiftK2 = factorK2 * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK2);
def averageK2 = MovingAverage(averageType, price, lengthK2);
def AvgK2 = averageK2[-displace];
def Upper_BandK2 = averageK2[-displace] + shiftK2[-displace];
def Lower_BandK2 = averageK2[-displace] - shiftK2[-displace];
def condition_BandRevDn = (Upper_BandS > Upper_BandK2);
def condition_BandRevUp = (Lower_BandS < Lower_BandK2);
input fastLength = 12;
input slowLength = 26;
input MACDLength = 9;

input MACD_AverageType = {SMA, default EMA};

def fastEMA = ExpAverage(price, fastLength);
def slowEMA = ExpAverage(price, slowLength);
def Value;
def Avg1;

switch (MACD_AverageType) {
case SMA:
    Value = Average(price, fastLength) - Average(price, slowLength);
    Avg1 = Average(Value, MACDLength);
case EMA:
    Value = fastEMA - slowEMA;
    Avg1 = ExpAverage(Value, MACDLength);}

def Diff = Value - Avg1;
def MACDLevel = 0.0;
def Level = MACDLevel;
def condition1 = Value[1] <= Value;
def condition1D = Value[1] > Value;                                                                                              
                              
#RSI                                                                                              

def RSI_length = 14;
def RSI_AverageType = AverageType.WILDERS;
def RSI_OB = 70;
def RSI_OS = 30;

def NetChgAvg = MovingAverage(RSI_AverageType, price - price[1], RSI_length);
def TotChgAvg = MovingAverage(RSI_AverageType, AbsValue(price - price[1]), RSI_length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;
def RSI = 50 * (ChgRatio + 1);

def condition2 = (RSI[3] < RSI) is true or (RSI >= 80) is true;
def condition2D = (RSI[3] > RSI) is true or (RSI < 20) is true;
def conditionOB1 = RSI > RSI_OB;
def conditionOS1 = RSI < RSI_OS;                                                                                              
                              
#MFI                                                                                              

def MFI_Length = 14;
def MFIover_Sold = 20;
def MFIover_Bought = 80;
def movingAvgLength = 1;
def MoneyFlowIndex = Average(MoneyFlow(high, close, low, volume, MFI_Length), movingAvgLength);
def MFIOverBought = MFIover_Bought;
def MFIOverSold = MFIover_Sold;

def condition3 = (MoneyFlowIndex[2] < MoneyFlowIndex) is true or (MoneyFlowIndex > 85) is true;
def condition3D = (MoneyFlowIndex[2] > MoneyFlowIndex) is true or (MoneyFlowIndex < 20) is true;
def conditionOB2 = MoneyFlowIndex > MFIover_Bought;
def conditionOS2 = MoneyFlowIndex < MFIover_Sold;                                                                                              
                              
#Forecast                                                                                              

def na = Double.NaN;
def MidLine = 50;
def Momentum = MarketForecast().Momentum;
def NearT =  MarketForecast().NearTerm;
def Intermed = MarketForecast().Intermediate;
def FOB = 80;
def FOS = 20;
def upperLine = 110;

def condition4 = (Intermed[1] <= Intermed) or (NearT >= MidLine);
def condition4D = (Intermed[1] > Intermed) or (NearT < MidLine);
def conditionOB3 = Intermed > FOB;
def conditionOS3 = Intermed < FOS;
def conditionOB4 = NearT > FOB;
def conditionOS4 = NearT < FOS;                                                                                              
                              
#Change in Price                                                                                              

def lengthCIP = 5;
def CIP = (price - price[1]);
def AvgCIP = ExpAverage(CIP[-displace], lengthCIP);
def CIP_UP = AvgCIP > AvgCIP[1];
def CIP_DOWN = AvgCIP < AvgCIP[1];
def condition5 = CIP_UP;
def condition5D = CIP_DOWN;                                                                                              
                              
#EMA_1                                                                                              

def EMA_length = 8;
def AvgExp = ExpAverage(price[-displace], EMA_length);
def condition6 = (price >= AvgExp) and (AvgExp[2] <= AvgExp);
def condition6D = (price < AvgExp) and (AvgExp[2] > AvgExp);                                                                                              
                              
#EMA_2                                                                                              

def EMA_2length = 20;
def displace2 = 0;
def AvgExp2 = ExpAverage(price[-displace2], EMA_2length);
def condition7 = (price >= AvgExp2) and (AvgExp2[2] <= AvgExp);
def condition7D = (price < AvgExp2) and (AvgExp2[2] > AvgExp);                                                                                              
                              
#DMI Oscillator                                                                                              

def DMI_length = 5;#Typically set to 10                                                                                              
input DMI_averageType = AverageType.WILDERS;
def diPlus = DMI(DMI_length, DMI_averageType)."DI+";
def diMinus = DMI(DMI_length, DMI_averageType)."DI-";
def Osc = diPlus - diMinus;
def Hist = Osc;
def ZeroLine = 0;
def condition8 = Osc >= ZeroLine;
def condition8D = Osc < ZeroLine;                                                                                              
                              
#Trend_Periods                                                                                              

def TP_fastLength = 3;#Typically 7                                                                                              
def TP_slowLength = 4;#Typically 15                                                                                              
def Periods = Sign(ExpAverage(close, TP_fastLength) - ExpAverage(close, TP_slowLength));
def condition9 = Periods > 0;
def condition9D = Periods < 0;                                                                                              
                              
#Polarized Fractal Efficiency                                                                                              

def PFE_length = 5;#Typically 10                                                                                              
def smoothingLength = 2.5;#Typically 5                                                                                              
def PFE_diff = close - close[PFE_length - 1];
def val = 100 * Sqrt(Sqr(PFE_diff) + Sqr(PFE_length)) / Sum(Sqrt(1 + Sqr(close - close[1])), PFE_length - 1);
def PFE = ExpAverage(if PFE_diff > 0 then val else -val, smoothingLength);
def UpperLevel = 50;
def LowerLevel = -50;
def condition10 = PFE > 0;
def condition10D = PFE < 0;
def conditionOB5 = PFE > UpperLevel;
def conditionOS5 = PFE < LowerLevel;                                                                                              
                              
#Bollinger Bands Percent_B                                                                                              

input BBPB_averageType = AverageType.SIMPLE;
def BBPB_length = 20;#Typically 20                                                                                              
def Num_Dev_Dn = -2.0;
def Num_Dev_up = 2.0;
def BBPB_OB = 100;
def BBPB_OS = 0;
def upperBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, BBPB_averageType).UpperBand;
def lowerBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, BBPB_averageType).LowerBand;
def PercentB = (price - lowerBand) / (upperBand - lowerBand) * 100;
def HalfLine = 50;
def UnitLine = 100;
def condition11 = PercentB > HalfLine;
def condition11D = PercentB < HalfLine;
def conditionOB6 = PercentB > BBPB_OB;
def conditionOS6 = PercentB < BBPB_OS;
def condition12 = (Upper_BandS[1] <= Upper_BandS) and (Lower_BandS[1] <= Lower_BandS);
def condition12D = (Upper_BandS[1] > Upper_BandS) and (Lower_BandS[1] > Lower_BandS);                                                                                              
                              
#Klinger Histogram                                                                                              

def Klinger_Length = 13;
def KVOsc = KlingerOscillator(Klinger_Length).KVOsc;
def KVOH = KVOsc - Average(KVOsc, Klinger_Length);
def condition13 = (KVOH > 0);
def condition13D = (KVOH < 0);                                                                                              
                              
#Projection Oscillator                                                                                              

def ProjectionOsc_length = 30;#Typically 10                                                                                              
def MaxBound = HighestWeighted(high, ProjectionOsc_length, LinearRegressionSlope(price = high, length = ProjectionOsc_length));
def MinBound = LowestWeighted(low, ProjectionOsc_length, LinearRegressionSlope(price = low, length = ProjectionOsc_length));
def ProjectionOsc_diff = MaxBound - MinBound;
def PROSC = if ProjectionOsc_diff != 0 then 100 * (close - MinBound) / ProjectionOsc_diff else 0;
def PROSC_OB = 80;
def PROSC_OS = 20;
def condition14 = PROSC > 50;
def condition14D = PROSC < 50;
def conditionOB7 = PROSC > PROSC_OB;
def conditionOS7 = PROSC < PROSC_OS;                                                                                              
                              
#Trend Confirmation Calculator                                                                                              
#Confirmation_Factor range 1-15.                                                                                              

input Confirmation_Factor = 7;                                                                                              
#Use for testing conditions individually. Remove # from line below and change Confirmation_Factor to 1.                                                                                              
#def Agreement_Level = condition1;                                                                                              

def Agreement_LevelOB = 12;
def Agreement_LevelOS = 2;
def factorK = 2.0;

#Spark 1
def lengthK = 20;
def shift = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK);
def shift1 = factorK * MovingAverage(trueRangeAverageType, TrueRange(high(period = agperiod1), close(period = agperiod1), low(period = agperiod1)), lengthK);
def shift2= factorK * MovingAverage(trueRangeAverageType, TrueRange(high(period = agperiod2), close(period = agperiod2), low(period = agperiod2)), lengthK);
def shift3 = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK);


def averageK = MovingAverage(averageType, price, lengthK);
def averageK_A1 = MovingAverage(averageType,close(period = agperiod1), lengthK);
def averageK_A2 = MovingAverage(averageType,close(period = agperiod2), lengthK);
def averageK_A3 = MovingAverage(averageType,close(period = agperiod3), lengthK);

def AvgK = averageK[-displace];
def AvgK_A1 = averageK_A1[-displace];
def AvgK_A2 = averageK_A2[-displace];
def AvgK_A3 = averageK_A3[-displace];

def Upper_BandK = averageK[-displace] + shift[-displace];
def Upper_BandK_A1 = averageK_A1[-displace] + shift[-displace];
def Upper_BandK_A2 = averageK_A2[-displace] + shift[-displace];
def Upper_BandK_A3 = averageK_A3[-displace] + shift[-displace];

def Lower_BandK = averageK[-displace] - shift[-displace];
def Lower_BandK_A1 = averageK_A1[-displace] - shift[-displace];
def Lower_BandK_A2 = averageK_A2[-displace] - shift[-displace];
def Lower_BandK_A3 = averageK_A3[-displace] - shift[-displace];



def conditionK1UP = price >= Upper_BandK;
def conditionK2UP = (Upper_BandK[1] < Upper_BandK) and (Lower_BandK[1] < Lower_BandK);
def conditionK2UP_A1 = (Upper_BandK_A1[1] < Upper_BandK_A1) and (Lower_BandK_A1[1] < Lower_BandK_A1);
def conditionK2UP_A2 = (Upper_BandK_A2[1] < Upper_BandK_A2) and (Lower_BandK_A2[1] < Lower_BandK_A2);
def conditionK2UP_A3 = (Upper_BandK_A3[1] < Upper_BandK_A3) and (Lower_BandK_A3[1] < Lower_BandK_A3);

def conditionK3DN = (Upper_BandK[1] > Upper_BandK) and (Lower_BandK[1] > Lower_BandK);
def conditionK4DN = price < Lower_BandK;
def Agreement_Level =   condition1 + condition2 + condition3 + condition4 + condition5 +
                        condition6 + condition7 + condition8 + condition9 + condition10 +
                        condition11 + condition12 + condition13 + condition14 + conditionK1UP +
                        conditionK2UP;
def Agreement_LevelD = (condition1D + condition2D + condition3D + condition4D + condition5D +
                        condition6D + condition7D + condition8D + condition9D + condition10D +
                        condition11D + condition12D + condition13D + condition14D + conditionK3DN +
                        conditionK4DN);
def Consensus_Level = Agreement_Level - Agreement_LevelD;
def UP2 = Consensus_Level >= 10;
def DOWN2 = Consensus_Level < -10;
def priceColor2 = if UP2 then 1                                                                                              
                 else if DOWN2 then -1                                                                                              
                 else priceColor2[1];
def Consensus_Level_OB = 10;
def Consensus_Level_OS = -10;                                                                                              
                              
#Super_OB/OS Signal                                                                                              

def OB_Level = conditionOB1 + conditionOB2 + conditionOB3 + conditionOB4 + conditionOB5 + conditionOB6 + conditionOB7;
def OS_Level = conditionOS1 + conditionOS2 + conditionOS3 + conditionOS4 + conditionOS5 + conditionOS6 + conditionOS7;
def Consensus_Line = OB_Level - OS_Level;
def Zero_Line = 0;
def Super_OB = 4;
def Super_OS = -4;
def DOWN_OB = (Agreement_Level > Agreement_LevelOB) and (Consensus_Line > Super_OB) and (Consensus_Level > Consensus_Level_OB);
def UP_OS = (Agreement_Level < Agreement_LevelOS) and (Consensus_Line < Super_OS) and (Consensus_Level < Consensus_Level_OS);
def OS_Buy = UP_OS;
def OB_Sell = DOWN_OB;
def neutral = Consensus_Line < Super_OB and Consensus_Line > Super_OS;

input use_line_limits = yes;#Yes, plots line from/to; No, plot line across entire chart                                                                                              
input linefrom = 100;#Hint linefrom: limits how far line plots in candle area                                                                                              
input lineto   = 12;#Hint lineto: limits how far into expansion the line will plot                                                                                              

def YHOB = if Color_Candles and ((price1 > Upper_BandS) and (condition_BandRevDn)) then high else Double.NaN;
def YHOS = if Color_Candles and ((price1 < Lower_BandS) and (condition_BandRevUp)) then high else Double.NaN;
def YLOB = if Color_Candles and ((price1 > Upper_BandS) and (condition_BandRevDn)) then low else Double.NaN;
def YLOS = if Color_Candles and ((price1 < Lower_BandS) and (condition_BandRevUp)) then low else Double.NaN;                                                                                              
                              
#extend midline of yellow candle                                                                                              

plot YCOB = if !IsNaN(YHOB) then hl2 else Double.NaN;
YCOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOB.SetDefaultColor(Color.GREEN);
def YHextOB = if IsNaN(YCOB) then YHextOB[1] else YCOB;

plot YHextlineOB = YHextOB;
YHextlineOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOB.SetDefaultColor(Color.ORANGE);
YHextlineOB.SetLineWeight(2);

plot YCOS = if !IsNaN(YHOS) then hl2 else Double.NaN;
YCOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOS.SetDefaultColor(Color.GREEN);
def YHextOS = if IsNaN(YCOS) then YHextOS[1] else YCOS;

plot YHextlineOS = YHextOS;
YHextlineOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOS.SetDefaultColor(Color.LIGHT_GREEN);
YHextlineOS.SetLineWeight(2);

def YC = Color_Candles and priceColor2 == 1 and price1 > Upper_BandS and condition_BandRevDn;                                                                                              
                              
#Additional Signals                                                                                              

input showCloud = yes;                                                                                              
#AddCloud(if showCloud and condition_BandRevUp then Lower_BandK2 else Double.NaN,  Lower_BandS,  Color.LIGHT_GREEN,  Color.CURRENT);                                                                                              
#AddCloud(if showCloud and condition_BandRevDn then Upper_BandS else Double.NaN,  Upper_BandK2,  Color.LIGHT_RED,  Color.CURRENT);                                                                                              
                              
# Identify Consolidation                                                                                              

def HH = Highest(high[1], BarsUsedForRange);
def LL = Lowest(low[1], BarsUsedForRange);
def maxH = Highest(HH, BarsRequiredToRemainInRange);
def maxL = Lowest(LL, BarsRequiredToRemainInRange);
def HHn = if maxH == maxH[1] or maxL == maxL then maxH else HHn[1];
def LLn = if maxH == maxH[1] or maxL == maxL then maxL else LLn[1];
def Bh = if high <= HHn and HHn == HHn[1] then HHn else Double.NaN;
def Bl = if low >= LLn and LLn == LLn[1] then LLn else Double.NaN;
def CountH = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountH[1] + 1;
def CountL = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountL[1] + 1;

def ExpH = if BarNumber() == 1 then Double.NaN else                                                                                              
           if CountH[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then HHn[-BarsRequiredToRemainInRange] else                                                                                              
           if high <= ExpH[1] then ExpH[1] else Double.NaN;

def ExpL = if BarNumber() == 1 then Double.NaN else                                                                                              
           if CountL[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then LLn[-BarsRequiredToRemainInRange] else                                                                                              
           if low >= ExpL[1] then ExpL[1] else Double.NaN;                                                                                              
                              
# Plot the High and Low of the Box; Paint Cloud                                                                                              

def BoxHigh = if ((DOWN_OB) or (Upper_BandS crosses above Upper_BandK2)
                            or (condition_BandRevDn) and (high > high[1]) and ((price > Upper_BandK2)
                            or (price > Upper_BandS))) then Highest(ExpH) else Double.NaN;              

def BoxLow = if (DOWN_OB) or ((Upper_BandS crosses above Upper_BandK2)) then Lowest(low) else Double.NaN;                                                                     
def BoxHigh2 = if ((UP_OS) or ((Lower_BandS crosses below Lower_BandK2))) then Highest(ExpH) else Double.NaN;
def BH2 = if !IsNaN(BoxHigh2) then high else Double.NaN;
def BH2ext = if IsNaN(BH2) then BH2ext[1] else BH2;
def BH2extline = BH2ext;

plot H_BH2extline = Lowest(BH2extline, 1);
H_BH2extline.SetDefaultColor(Color.GREEN);

def BoxLow2 = if ((UP_OS) or (Lower_BandS crosses below Lower_BandK2)
                          or (condition_BandRevUp) and (low < low[1]) and ((price < Lower_BandK2)
                          or (price < Lower_BandS))) or ((UP_OS[1]) and (low < low[1])) then Lowest(low) else Double.NaN;
                              
# extend the current YCHigh line to the right edge of the chart                                                                                              

def BH1 = if !IsNaN(BoxHigh) then high else Double.NaN;
def BH1ext = if IsNaN(BH1) then BH1ext[1] else BH1;
def BH1extline = BH1ext;
def BL1 = if !IsNaN(BoxLow) then low else Double.NaN;
def BL1ext = if IsNaN(BL1) then BL1ext[1] else BL1;

plot BL1extline = BL1ext;
BL1extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL1extline.SetDefaultColor(Color.RED);
BL1extline.SetLineWeight(1);

def BL2 = if !IsNaN(BoxLow2) then low else Double.NaN;
def BL2ext = if IsNaN(BL2) then BL2ext[1] else BL2;

plot BL2extline = BL2ext;
BL2extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL2extline.SetDefaultColor(Color.GREEN);
BL2extline.SetLineWeight(1);

plot H_BH1extline = Highest(BH1extline, 1);
H_BH1extline.SetDefaultColor(Color.RED);

plot L_BL1extline = Highest(BL1extline, 1);
L_BL1extline.SetDefaultColor(Color.RED);

plot L_BL2extline = Lowest(BL2extline, 1);
L_BL2extline.SetDefaultColor(Color.GREEN);                                                                                                                                                                                                                                              
AddCloud(if !HideCloud then BH1extline else Double.NaN, BL1extline, Color.RED, Color.GRAY);
AddCloud(if !HideCloud then BH2extline else Double.NaN, BL2extline, Color.GREEN, Color.GRAY);



script WMA_Smooth {
    input price_WMA = hl2;
    plot smooth = (4 * price_WMA
+ 3 * price_WMA[1]
+ 2 * price_WMA[2]
+ price_WMA[3]) / 10;
}

script Phase_Accumulation {

# This is Ehler's Phase Accumulation code. It has a full cycle delay.
# However, it computes the correction factor to a very high degree.

    input price_WMA = hl2;

    rec Smooth;
    rec Detrender;
    rec Period;
    rec Q1;
    rec I1;
    rec I1p;
    rec Q1p;
    rec Phase1;
    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase1;
    rec InstPeriod1;
    rec InstPeriod;
    def CorrectionFactor;

    if BarNumber() <= 5
    then {
        Period = 0;
        Smooth = 0;
        Detrender = 0;
        CorrectionFactor = 0;
        Q1 = 0;
        I1 = 0;
        Q1p = 0;
        I1p = 0;
        Phase = 0;
        Phase1 = 0;
        DeltaPhase1 = 0;
        DeltaPhase = 0;
        InstPeriod = 0;
        InstPeriod1 = 0;
    } else {
        CorrectionFactor = 0.075 * Period[1] + 0.54;

# Smooth and detrend my smoothed signal:

        Smooth = WMA_Smooth(price_WMA);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

# Compute Quadrature and Phase of Detrended signal:

        Q1p = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1p = Detrender[3];

# Smooth out Quadrature and Phase:

        I1 = 0.15 * I1p + 0.85 * I1p[1];
        Q1 = 0.15 * Q1p + 0.85 * Q1p[1];

# Determine Phase

        if I1 != 0
        then {

# Normally, ATAN gives results from -pi/2 to pi/2.
# We need to map this to circular coordinates 0 to 2pi

            if Q1 >= 0 and I1 > 0
            then { # Quarant 1
                Phase1 = ATan(AbsValue(Q1 / I1));
            } else if Q1 >= 0 and I1 < 0
            then { # Quadrant 2
                Phase1 = Double.Pi - ATan(AbsValue(Q1 / I1));
            } else if Q1 < 0 and I1 < 0
            then { # Quadrant 3
                Phase1 = Double.Pi + ATan(AbsValue(Q1 / I1));
            } else { # Quadrant 4
                Phase1 = 2 * Double.Pi - ATan(AbsValue(Q1 / I1));
            }
        } else if Q1 > 0
        then { # I1 == 0, Q1 is positive
            Phase1 = Double.Pi / 2;
        } else if Q1 < 0
        then { # I1 == 0, Q1 is negative
            Phase1 = 3 * Double.Pi / 2;
        } else { # I1 and Q1 == 0
            Phase1 = 0;
        }

# Convert phase to degrees

        Phase = Phase1 * 180 / Double.Pi;

        if Phase[1] < 90 and Phase > 270
        then {
# This occurs when there is a big jump from 360-0

            DeltaPhase1 = 360 + Phase[1] - Phase;
        } else {
            DeltaPhase1 = Phase[1] - Phase;
        }

# Limit our delta phases between 7 and 60

        if DeltaPhase1 < 7
        then {
            DeltaPhase = 7;
        } else if DeltaPhase1 > 60
        then {
            DeltaPhase = 60;
        } else {
            DeltaPhase = DeltaPhase1;
        }

# Determine Instantaneous period:

        InstPeriod1 =
-1 * (fold i = 0 to 40 with v=0 do
if v < 0 then
v
else if v > 360 then
-i
else
v + GetValue(DeltaPhase, i, 41));

        if InstPeriod1 <= 0
        then {
            InstPeriod = InstPeriod[1];
        } else {
            InstPeriod = InstPeriod1;
        }

        Period = 0.25 * InstPeriod + 0.75 * Period[1];
    }
    plot DC = Period;
}

script Ehler_MAMA {
    input price_WMA = hl2;
    input FastLimit = 0.5;
    input SlowLimit = 0.05;


    rec Period;
    rec Period_raw;
    rec Period_cap;
    rec Period_lim;

    rec Smooth;
    rec Detrender;
    rec I1;
    rec Q1;
    rec jI;
    rec jQ;
    rec I2;
    rec Q2;
    rec I2_raw;
    rec Q2_raw;

    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase_raw;
    rec alpha;
    rec alpha_raw;

    rec Re;
    rec Im;
    rec Re_raw;
    rec Im_raw;

    rec SmoothPeriod;
    rec vmama;
    rec vfama;

    def CorrectionFactor = Phase_Accumulation(price_WMA).CorrectionFactor;

    if BarNumber() <= 5
    then {
        Smooth = 0;
        Detrender = 0;

        Period = 0;
        Period_raw = 0;
        Period_cap = 0;
        Period_lim = 0;
        I1 = 0;
        Q1 = 0;
        I2 = 0;
        Q2 = 0;
        jI = 0;
        jQ = 0;
        I2_raw = 0;
        Q2_raw = 0;
        Re = 0;
        Im = 0;
        Re_raw = 0;
        Im_raw = 0;
        SmoothPeriod = 0;
        Phase = 0;
        DeltaPhase = 0;
        DeltaPhase_raw = 0;
        alpha = 0;
        alpha_raw = 0;
        vmama = 0;
        vfama = 0;
    } else {

# Smooth and detrend my smoothed signal:

        Smooth = WMA_Smooth(price_WMA);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

        Q1 = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1 = Detrender[3];

        jI = ( 0.0962 * I1
+ 0.5769 * I1[2]
- 0.5769 * I1[4]
- 0.0962 * I1[6] ) * CorrectionFactor;

        jQ = ( 0.0962 * Q1
+ 0.5769 * Q1[2]
- 0.5769 * Q1[4]
- 0.0962 * Q1[6] ) * CorrectionFactor;

# This is the complex conjugate

        I2_raw = I1 - jQ;
        Q2_raw = Q1 + jI;

        I2 = 0.2 * I2_raw + 0.8 * I2_raw[1];
        Q2 = 0.2 * Q2_raw + 0.8 * Q2_raw[1];

        Re_raw = I2 * I2[1] + Q2 * Q2[1];
        Im_raw = I2 * Q2[1] - Q2 * I2[1];

        Re = 0.2 * Re_raw + 0.8 * Re_raw[1];
        Im = 0.2 * Im_raw + 0.8 * Im_raw[1];

# Compute the phase

        if Re != 0 and Im != 0
        then {
            Period_raw = 2 * Double.Pi / ATan(Im / Re);
        } else {
            Period_raw = 0;
        }

        if Period_raw > 1.5 * Period_raw[1]
        then {
            Period_cap = 1.5 * Period_raw[1];
        } else if Period_raw < 0.67 * Period_raw[1] {
            Period_cap = 0.67 * Period_raw[1];
        } else {
            Period_cap = Period_raw;
        }

        if Period_cap < 6
        then {
            Period_lim = 6;
        } else if Period_cap > 50
        then {
            Period_lim = 50;
        } else {
            Period_lim = Period_cap;
        }

        Period = 0.2 * Period_lim + 0.8 * Period_lim[1];
        SmoothPeriod = 0.33 * Period + 0.67 * SmoothPeriod[1];

        if I1 != 0
        then {
            Phase = ATan(Q1 / I1);
        } else if Q1 > 0
        then { # Quadrant 1:
            Phase = Double.Pi / 2;
        } else if Q1 < 0
        then { # Quadrant 4:
            Phase = -Double.Pi / 2;
        } else { # Both numerator and denominator are 0.
            Phase = 0;
        }

        DeltaPhase_raw = Phase[1] - Phase;
        if DeltaPhase_raw < 1
        then {
            DeltaPhase = 1;
        } else {
            DeltaPhase = DeltaPhase_raw;
        }

        alpha_raw = FastLimit / DeltaPhase;
        if alpha_raw < SlowLimit
        then {
            alpha = SlowLimit;
        } else {
            alpha = alpha_raw;
        }
        vmama = alpha * price_WMA + (1 - alpha) * vmama[1];
        vfama = 0.5 * alpha * vmama + (1 - 0.5 * alpha) * vfama[1];
    }

    plot MAMA = vmama;
    plot FAMA = vfama;
}

input price2 = hl2;
input FastLimit = 0.5;
input SlowLimit = 0.05;

def MAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).MAMA;
def FAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).FAMA;

def Crossing = Crosses((MAMA < FAMA), yes);

def Crossing1 = Crosses((MAMA > FAMA), yes);

# --- C3 MAX --- LABELS ---

AddLabel(yes, Concat("MAMA", Concat("",
if MAMA > FAMA then "" else "")),
if MAMA > FAMA then Color.LIGHT_GREEN else Color.LIGHT_RED);


def MF_UP = FAMA < MAMA;
def MF_DN = FAMA > MAMA;
def priceColor10 = if MF_UP then 1
                 else if MF_DN then -1
                 else priceColor10[1];

input extension_length_limited_to = 10;
def lastbar = if IsNaN(close[-1]) and !IsNaN(close) then BarNumber() else Double.NaN;


####################################################################################################################################################


#EMA_Candles / Spark
#Created by Christopher84 11/30/2021

input showBreakoutSignals = no;

#Spark1 (1min chart)
input length8 = 10;
input length9 = 35;

input show_ema_cloud = yes;
input opacity = 50;


#Spark1
plot AvgExp8 = ExpAverage(price[-displace], length8);
def UPD = AvgExp8[1] < AvgExp8;
AvgExp8.SetStyle(Curve.SHORT_DASH);

plot AvgExp9 = ExpAverage(price[-displace], length9);
def UPW = AvgExp9[1] < AvgExp9;
AvgExp9.SetStyle(Curve.SHORT_DASH);

#Spark2
plot AvgExp8_S2 = ExpAverage(close(period = agperiod1)[-displace], length8);
def UPD_S2 = AvgExp8_S2 [1] < AvgExp8_S2 ;
AvgExp8_S2.SetStyle(Curve.SHORT_DASH);

plot AvgExp9_S2 = ExpAverage(close(period = agperiod1)[-displace], Length9);
def UPW_S2 = AvgExp9_S2[1] < AvgExp9_S2;
AvgExp9_S2.SetStyle(Curve.SHORT_DASH);

#Spark3
plot AvgExp8_S3 = ExpAverage(close(period = agperiod2)[-displace], length8);
def UPD_S3 = AvgExp8_S3 [1] < AvgExp8_S3 ;
AvgExp8_S3.SetStyle(Curve.SHORT_DASH);

plot AvgExp9_S3 = ExpAverage(close(period = agperiod2)[-displace], Length9);
def UPW_S3 = AvgExp9_S3[1] < AvgExp9_S3;
AvgExp9_S3.SetStyle(Curve.SHORT_DASH);

#Spark4
plot AvgExp8_S4 = ExpAverage(close(period = agperiod3)[-displace], length8);
def UPD_S4 = AvgExp8_S4[1] < AvgExp8_S4 ;
AvgExp8_S4.SetStyle(Curve.SHORT_DASH);

plot AvgExp9_S4 = ExpAverage(close(period = agperiod3)[-displace], Length9);
def UPW_S4 = AvgExp9_S4[1] < AvgExp9_S4;
AvgExp9_S4.SetStyle(Curve.SHORT_DASH);



###################################################################################################################################################################
#SPARK#
###################################################################################################################################################

#Spark 1
def Below = AvgExp8 < AvgExp9;
def Spark = UPD + UPW + Below;

def UPEMA = AvgExp8[1] < AvgExp8;
def DOWNEMA = AvgExp8[1] > AvgExp8;

#Spark 2
def Below_Spark_2 = AvgExp8_S2 < AvgExp9_S2;
def Spark_2  = UPD_S2 + UPW_S2 + Below_Spark_2;

def UPEMA_S2  = AvgExp8_S2[1] < AvgExp8_S2;
def DOWNEMA_S2  = AvgExp8_S2[1] > AvgExp8_S2;

#Spark 3
def Below_Spark_3 = AvgExp8_S3 < AvgExp9_S3;
def Spark_3  = UPD_S3 + UPW_S3 + Below_Spark_3;

def UPEMA_S3  = AvgExp8_S3[1] < AvgExp8_S3;
def DOWNEMA_S3  = AvgExp8_S3[1] > AvgExp8_S3;

#Spark 4
def Below_Spark_4 = AvgExp8_S4 < AvgExp9_S4;
def Spark_4  = UPD_S4 + UPW_S4 + Below_Spark_4;

def UPEMA_S4  = AvgExp8_S4[1] < AvgExp8_S4;
def DOWNEMA_S4  = AvgExp8_S4[1] > AvgExp8_S4;

AvgExp8.AssignValueColor(if UPEMA then Color.LIGHT_GREEN else if DOWNEMA then Color.RED else Color.YELLOW);

#Spark 1
def UPEMA2 = AvgExp9[1] < AvgExp9;
def DOWNEMA2 = AvgExp9[1] > AvgExp9;

#Spark 2
def UPEMA2_S2  = AvgExp9_S2[1] < AvgExp9_S2;
def DOWNEMA2_S2  = AvgExp9_S2[1] > AvgExp9_S2;

#Spark 3
def UPEMA2_S3  = AvgExp9_S3 [1] < AvgExp9_S3;
def DOWNEMA2_S3  = AvgExp9_S3 [1] > AvgExp9_S3;

#Spark 4
def UPEMA2_S4  = AvgExp9_S4 [1] < AvgExp9_S4;
def DOWNEMA2_S4  = AvgExp9_S4 [1] > AvgExp9_S4;

AvgExp9.AssignValueColor(if UPEMA2 then Color.LIGHT_GREEN else if DOWNEMA2 then Color.RED else Color.YELLOW);

AddCloud(if show_ema_cloud and (AvgExp9 > AvgExp8) then AvgExp9 else Double.NaN, AvgExp8, Color.LIGHT_RED, Color.CURRENT);
AddCloud(if show_ema_cloud and (AvgExp8 > AvgExp9) then AvgExp8 else Double.NaN,  AvgExp9,  Color.LIGHT_GREEN, Color.CURRENT);

#Spark 1
def UP8 = UPEMA and UPEMA2;
def DOWN8 = DOWNEMA and DOWNEMA2;
def priceColor8 = if UP8 then 1
                 else if DOWN8 then -1
                 else 0;
def UP11 = UPEMA;
def DOWN11 = DOWNEMA;
def priceColor11 = if UP11 then 1
                 else if DOWN11 then -1
                 else 0;
def UP12 = UPEMA2;
def DOWN12 = DOWNEMA2;
def priceColor12 = if UP12 then 1
                 else if DOWN12 then -1
                 else 0;


#Spark 2
def UP8_S2 = UPEMA_S2  and UPEMA2_S2;
def DOWN8_S2 = DOWNEMA_S2  and DOWNEMA2_S2 ;
def priceColor8_S2 = if UP8_S2  then 1
                 else if DOWN8_S2  then -1
                 else 0;
def UP11_S2 = UPEMA_S2 ;
def DOWN11_S2 = DOWNEMA_S2 ;
def priceColor11_S2 = if UP11_S2 then 1
                 else if DOWN11_S2 then -1
                 else 0;
def UP12_S2 = UPEMA2_S2;
def DOWN12_S2 = DOWNEMA2_S2;
def priceColor12_S2 = if UP12_S2 then 1
                 else if DOWN12_S2 then -1
                 else 0;

#Spark 3
def UP8_S3 = UPEMA_S3  and UPEMA2_S3;
def DOWN8_S3 = DOWNEMA_S3  and DOWNEMA2_S3 ;
def priceColor8_S3 = if UP8_S3  then 1
                 else if DOWN8_S3  then -1
                 else 0;
def UP11_S3 = UPEMA_S3 ;
def DOWN11_S3 = DOWNEMA_S3 ;
def priceColor11_S3 = if UP11_S3 then 1
                 else if DOWN11_S2 then -1
                 else 0;
def UP12_S3 = UPEMA2_S3;
def DOWN12_S3 = DOWNEMA2_S3;
def priceColor12_S3 = if UP12_S3 then 1
                 else if DOWN12_S3 then -1
                 else 0;

#Spark 4
def UP8_S4 = UPEMA_S4  and UPEMA2_S4;
def DOWN8_S4 = DOWNEMA_S4  and DOWNEMA2_S4 ;
def priceColor8_S4 = if UP8_S4  then 1
                 else if DOWN8_S4  then -1
                 else 0;
def UP11_S4 = UPEMA_S4 ;
def DOWN11_S4 = DOWNEMA_S4 ;
def priceColor11_S4 = if UP11_S4 then 1
                 else if DOWN11_S2 then -1
                 else 0;
def UP12_S4 = UPEMA2_S4;
def DOWN12_S4 = DOWNEMA2_S4;
def priceColor12_S4 = if UP12_S4 then 1
                 else if DOWN12_S4 then -1
                 else 0;


###################################################################


def UpCalc =  (priceColor == 1) + (priceColor2 == 1) + (priceColor8 == 1) + (priceColor10 == 1);
def StrongUpCalc =  (priceColor == 1) + (priceColor2 == 1)  + (priceColor10 == 1);

#Spark 1
def CandleColor = if (priceColor2 == 1) and (priceColor12 == 1) and (Spark >= 2) then 1 else
                 if (priceColor2 == -1) and (Spark < 1) then -1 else 0;

#Spark 2
def CandleColor_S2 = if (priceColor12_S2 == 1) and (Spark_2 >= 2) then 1 else
                  if (Spark_2 < 1)  then -1 else 0;

#Spark 3
def CandleColor_S3 = if (priceColor12_S3 == 1) and (Spark_3 >= 2) then 1 else
                  if (Spark_3 < 1)  then -1 else 0;

#Spark 4
def CandleColor_S4 = if (priceColor12_S4 == 1) and (Spark_4 >= 2) then 1 else
                  if  (Spark_4 < 1)  then -1 else 0;


#Spark 1
plot SparkUP = (Spark == 3) and (CandleColor == 1);
SparkUP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SparkUP.AssignValueColor(Color.LIGHT_GREEN);

plot SparkDN = (Spark == 0) and (CandleColor == -1);
SparkDN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SparkDN.AssignValueColor(Color.RED);

#Spark 2
plot SparkUP2 = (Spark_2 == 3) and (CandleColor_S2 == 1);
SparkUP2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SparkUP2.AssignValueColor(Color.white);

plot SparkDN2 = (Spark_2  == 0) and (CandleColor_S2  == -1);
SparkDN2.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SparkDN2.AssignValueColor(Color.white);

#Spark 3
plot SparkUP3 = (Spark_3  == 3) and (CandleColor_S3 == 1);
SparkUP3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SparkUP3.AssignValueColor(Color.blue);

plot SparkDN3 = (Spark_3  == 0) and (CandleColor_S3 == -1);
SparkDN3.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SparkDN3.AssignValueColor(Color.blue);

#Spark 4
plot SparkUP4 = (Spark_4  == 3) and (CandleColor_S4 == 1);
SparkUP4.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SparkUP4.AssignValueColor(Color.yellow);

plot SparkDN4 = (Spark_4  == 0) and (CandleColor_S4 == -1);
SparkDN4.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SparkDN4.AssignValueColor(Color.yellow);


##########################################################################################################################################################


##################################################################################                              
                              
                               
 
def Buy = UP_OS;
def Sell = DOWN_OB;
def conditionLTB = (conditionK2UP and (Consensus_Level < 0));
def conditionLTS = (conditionK3DN and (Consensus_Level > 0));

def conditionBO = ((Upper_BandS[1] < Upper_BandS))
              and ((Lower_BandS[1] < Lower_BandS))
              and ((Upper_BandK[1] < Upper_BandK))
              and ((Lower_BandK[1] < Lower_BandK));

def conditionBD = ((Upper_BandS[1] > Upper_BandS))
              and ((Lower_BandS[1] > Lower_BandS))
              and ((Upper_BandK[1] > Upper_BandK))
              and ((Lower_BandK[1] > Lower_BandK));

def MomentumUP = Consensus_Level[1] < Consensus_Level;
def MomentumDOWN = Consensus_Level[1] > Consensus_Level;
def Squeeze_Signal = !IsNaN(Squeeze_Alert);
def conditionOB = (Consensus_Level >= 12) and (Consensus_Line >= 4);
def conditionOS = (Consensus_Level <= -12) and (Consensus_Line <= -3);


# --- C3 LABELS ---

AddLabel(yes, if conditionLTB then "BULL LTB"
         else if conditionLTS then "BEAR LTS"
         else if conditionK2UP then "TREND: BULL"
         else if conditionK3DN then "TREND: BEAR" else "TREND: CONSOLIDATION",
              if conditionLTB then Color.GREEN
         else if conditionLTS then Color.RED
         else if conditionK2UP then Color.LIGHT_GREEN
         else if conditionK3DN then Color.LIGHT_RED else Color.GRAY);

AddLabel(yes, if conditionBD then "BREAKDOWN"
         else if conditionBO then "BREAKOUT" else "NO BREAK",
              if conditionBD then Color.RED
         else if conditionBO then Color.GREEN else Color.GRAY);
input Spark_1_label = yes;
input Spark_2_label = yes;
input Spark_3_label = yes;
input Spark_4_label = yes;



#Spark 1
AddLabel(Spark_1_label, if (Spark == 3) then "SPARK: " + Round(Spark, 1)
         else if (Spark == 0) then  "SPARK: " + Round(Spark, 1) else "SPARK: " + Round(Spark, 1),
              if (Spark == 3) then Color.YELLOW
         else if (Spark == 2) then Color.GREEN
         else if (Spark == 0) then Color.RED else Color.GRAY);

#Spark 2
AddLabel(Spark_2_label, if (Spark_2 == 3) then "2nd SPARK: " + Round(Spark_2, 1)
         else if (Spark_2 == 0) then  "2nd SPARK: " + Round(Spark_2, 1) else "2nd SPARK: " + Round(Spark_2, 1),
              if (Spark_2 == 3) then Color.YELLOW
         else if (Spark_2 == 2) then Color.GREEN
         else if (Spark_2 == 0) then Color.RED else Color.GRAY);

#Spark 3
AddLabel(Spark_3_label, if (Spark_3 == 3) then "3rd SPARK: " + Round(Spark_3, 1)
         else if (Spark_3 == 0) then  "3rd SPARK: " + Round(Spark_3, 1) else "3rd SPARK: " + Round(Spark_3, 1),
              if (Spark_3 == 3) then Color.YELLOW
         else if (Spark_3 == 2) then Color.GREEN
         else if (Spark_3 == 0) then Color.RED else Color.GRAY);

#Spark 4
AddLabel(Spark_4_label, if (Spark_4 == 3) then "4th SPARK: " + Round(Spark_4, 1)
         else if (Spark_4 == 0) then  "4th SPARK: " + Round(Spark_4, 1) else "4th SPARK: " + Round(Spark_4, 1),
              if (Spark_4 == 3) then Color.YELLOW
         else if (Spark_4 == 2) then Color.GREEN
         else if (Spark_4 == 0) then Color.RED else Color.GRAY);

AddLabel(yes, "SQZ!", if Squeeze_Signal then Color.YELLOW else Color.GRAY);

AddLabel(yes, if MomentumUP then "CSNS UP: " + Round(Consensus_Level, 1)
         else if MomentumUP or MomentumDOWN and conditionOB then "CSNS OB: " + Round(Consensus_Level, 1)
         else if MomentumDOWN then  "CSNS DOWN:" + Round(Consensus_Level, 1)
         else if MomentumUP or MomentumDOWN and conditionOS then "CSNS OS: " + Round(Consensus_Level, 1) else "CSNS = " + Round(Consensus_Level, 1),
              if conditionOB then Color.RED else
              if conditionOS then Color.GREEN else Color.GRAY);

AddLabel(yes, Concat("BAND%: ", PerB), if PerB < 0 then Color.YELLOW else if PerB > 0 and PerB[1] < 0 then Color.GREEN else Color.WHITE);                                                                                              


#--- END ---
input hideverticalline = no;
AddVerticalLine(hideverticalline and( GetDay() <> GetDay()[1]), "", Color.Light_gray, Curve.SHORT_DASH);

#--- END ---


Breakouts Version

Study
C3_Max_Spark_Breakouts Study- http://tos.mx/WNBp8BI

Description
This is the breakout version of C3_Max_Spark. The breakout code plots an indication when the wick, body, or close of a candle crosses any level plotted by C3_Max_Spark, and then the opposite cross occurs within x bars. The code is functional and complete, although backtesting with different settings on various timeframes was challenging, thus could not be used to increase the probability of a successful trade.

Future development
In the future the breakouts portion of the code will be (if possible) further developed in order to signal the zone breakout pullback entry method as seen in the “Application” post (#10).

Note
If you… yes YOU! are using this version please provide feedback including preferred settings, and an example of how you are putting it to use.

Screenshots
otrGmTn.png


ntmiKBL.png


Code:
#--- C4_MAX_BREAKOUTS_V5 --- #                                                                                           
#--- C3_MAX_SPARK --- #                                                                                           
                            
# Created by Christopher84 06/30/2022                                                                                               
# Based off of the Confirmation Candles Study. Main difference is that CC Candles weigh factors of positive                                                                                           
# and negative price movement to create the Consensus_Level. The Consensus_Level is considered positive if                                                                                           
# above zero and negative if below zero.                                                                                           
                            
# --- HORSERIDER VOLUME --- #                                                                                           
                            
# Show total volume in gray.  Buying volume in green.  Sell Volume in red.                                                                                           
# Volume average is gray line.                                                                                           
# Specified percent over average volume is cyan triangles.                                                                                           
# Horserider 12/30/2019 derived from some already existing studies.                                                                                           
# hiVolume indicator                                                                                           
# source: http://tinboot.blogspot.com                                                                                           
# author: allen everhart                                                                                           
                            
# --- TRIPLE EXHAUSTION --- #                                                                                           
                            
# Requested by @Chence27 from criteria listed here https://usethinkscript.com/threads/triple-exhaustion-indicator.9001/                                                                                           
# Removing the header Credit credits and description is not permitted, any modification needs to be shared.                                                                                           
# V 1.0 :    @cos251 - Initial release per request from www.usethinkscript.com forum thread:                                                                                           
#       :    https://usethinkscript.com/threads/triple-exhaustion-indicator.9001/                                                                                           
# V 1.1 : @chence27 - modifcations to better approximate original study                                                                                           
# --- BULL_BEAR V5 --- #

#Bull_Bear_Candles+Label Created by Christopher84
#Created 10/21/2022
# Show SELL and BUY Volume and percentage.
# Referencing credit to Horserider script at https://usethinkscript.com/threads/volume-buy-sell-indicator-with-hot-percent-for-thinkorswim.389/
# Nomak 02/21/2020

declare upper;

input timeframe = AggregationPeriod.Day;
input ColoredCandlesOn = yes;
input BulgeLengthV = 20;
input SqueezeLengthV = 20;
input BulgeLengthV2 = 20;
input SqueezeLengthV2 = 20;

def Vol = volume(period = timeframe);
def at_High = high(period = timeframe);
def at_Open = open(period = timeframe);
def at_Close = close(period = timeframe);
def at_Low = low(period = timeframe);
def Vol1 = volume(period = timeframe);
def at_High1 = high(period = timeframe);
def at_Open1 = open(period = timeframe);
def at_Close1 = close(period = timeframe);
def at_Low1 = low(period = timeframe);

# Buy_Volume forumla is volume * (close_price minus low_price) / (High_price minus low_price)
def Buy_Volume = RoundUp(Vol * (at_Close - at_Low) / (at_High - at_Low));
def Buy_percent = RoundUp((Buy_Volume / Vol) * 100);
#Buy_percent.SetPaintingStrategy(PaintingStrategy.LINE);
#Buy_percent.SetLineWeight(1);
#Buy_percent.SetDefaultColor(Color.GREEN);

#Sell_Volume forumla is  volume * (High_price minus Close_price) / (High_price minus Low_price)
def Sell_Volume = RoundDown(Vol1 * (at_High1 - at_Close1) / (at_High1 - at_Low1));
def Sell_percent = RoundUp((Sell_Volume / Vol1) * 100);
#Sell_percent.SetPaintingStrategy(PaintingStrategy.LINE);
#Sell_percent.SetLineWeight(1);
#Sell_percent.SetDefaultColor(Color.RED);


AddLabel(yes, "BuyVol " + Buy_Volume, Color.GREEN);
AddLabel(yes, "SellVol " + Sell_Volume, Color.RED);
AddLabel(yes, "Buy % " + Buy_percent, Color.GREEN);
AddLabel(yes, "Sell % " + Sell_percent, Color.RED);

#################################################################################

input price = close;
input length_V5 = 10;
input agperiod1 = {"1 min", "2 min", "3 min", default "5 min", "10 min", "15 min", "30 min", "1 hour", "2 hours", "4 hours", "Day", "Week", "Month"};
input agperiod2 = {"1 min", "2 min", "3 min", "5 min",default "10 min", "15 min", "30 min", "1 hour", "2 hours", "4 hours", "Day", "Week", "Month"};

plot avg = ExpAverage(close(period = agperiod1), length_V5);
def height = avg - avg[length_V5];
avg.SetStyle(Curve.SHORT_DASH);
avg.SetLineWeight(1);

def UP_V5 = avg[1] < avg;
def DOWN_V5 = avg[1] > avg;
Avg.AssignValueColor(if UP_V5 then Color.LIGHT_GREEN else if DOWN_V5 then Color.RED else Color.YELLOW);

plot avg2 = ExpAverage(close(period = agperiod2), length_V5);
def height2 = avg2 - avg2[length_V5];
avg2.SetStyle(Curve.SHORT_DASH);
avg2.SetLineWeight(1);

def UP2_V5 = avg2[1] < avg2;
def DOWN2_V5 = avg2[1] > avg2;
Avg2.AssignValueColor(if UP2_V5 then Color.LIGHT_GREEN else if DOWN2_V5 then Color.RED else Color.YELLOW);

#AddCloud(avg2, avg, Color.LIGHT_RED, Color.CURRENT);
#AddCloud(avg, avg2, Color.LIGHT_GREEN, Color.CURRENT);

def Condition1UP = avg > avg2;
def Condition1DN = avg < avg2;

def Condition2UP = Buy_percent > 50;
def Condition2DN = Buy_percent < 50;

def BullUP = Condition1UP + Condition2UP;
def BearDN = Condition1DN + Condition2DN;

def Bull_Bear = if Condition1UP==1 and Condition2UP == 1 then 1 else if Condition1DN == 1 and Condition2DN == 1 then -1 else 0;

def priceColor_V5 = if ((avg[1]<avg) and (avg2[1]<avg2)) then 1
                 else if((avg[1]>avg) and (avg2[1]>avg2)) then -1
                 else priceColor_V5[1];

AssignPriceColor(if ColoredCandlesOn and (priceColor_V5==1) then Color.GREEN else if ColoredCandlesOn and (priceColor_V5==-1) then Color.RED else Color.Gray);                           
                            
# --- C3 MAX INPUTS --- #                                                                                           
                            
#input Price = CLOSE;                                                                                           
#input ShortLength1 = 5;                                                                                           
#input ShortLength2 = 14;                                                                                           
#input ShortLength3 = 5;                                                                                           
#input LongLength1 = 12;                                                                                           
#input LongLength2 = 55;                                                                                           
#input LongLength3 = 7;                                                                                           
input Color_Candles = yes;                                                                                           
                            
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                           
                            
def ShortLength1 = 5;                                                                                           
def ShortLength2 = 14;                                                                                           
def ShortLength3 = 5;                                                                                           
def LongLength1 = 12;                                                                                               
def LongLength2 = 55;                                                                                           
def LongLength3 = 7;                                                                                           
                            
# --- HORSERIDER VOLUME INPUTS ---                                                                                           
                            
input Show30DayAvg = no;                                                                                           
input ShowTodayVolume =  no;                                                                                           
input ShowPercentOf30DayAvg = yes;                                                                                           
input UnusualVolumePercent = 200;                                                                                           
input Show30BarAvg = no;                                                                                           
input ShowCurrentBar = yes;                                                                                           
input ShowPercentOf30BarAvg = yes;                                                                                           
input ShowSellVolumePercent = yes;                                                                                           
def length_3 = 20;                                                                                           
input type_HV = { default SMP, EXP } ;                                                                                           
input length1_3 = 20 ;                                                                                           
input hotPct = 100.0 ;                                                                                           
                            
# --- HORSERIDER DEF ---                                                                                           
                            
def O_3 = open;                                                                                           
def H_3 = high;                                                                                           
def C_3 = close;                                                                                           
def L_3 = low;                                                                                           
def V_3 = volume;                                                                                           
def buying = V_3 * (C_3 - L_3) / (H_3 - L_3);                                                                                           
def selling = V_3 * (H_3 - C_3) / (H_3 - L_3);                                                                                           
def volLast30DayAvg = (volume(period = "DAY")[1] + volume(period = "DAY")[2] + volume(period = "DAY")[3] + volume(period = "DAY")[4] + volume(period = "DAY")[5] + volume(period = "DAY")[6] + volume(period = "DAY")[7] + volume(period = "DAY")[8] + volume(period = "DAY")[9] + volume(period = "DAY")[10] + volume(period = "DAY")[11] + volume(period = "DAY")[12] + volume(period = "DAY")[13] + volume(period = "DAY")[14] + volume(period = "DAY")[15] + volume(period = "DAY")[16] + volume(period = "DAY")[17] + volume(period = "DAY")[18] + volume(period = "DAY")[19] + volume(period = "DAY")[20] + volume(period = "DAY")[21] + volume(period = "DAY")[22] + volume(period = "DAY")[23] + volume(period = "DAY")[24] + volume(period = "DAY")[25] + volume(period = "DAY")[26] + volume(period = "DAY")[27] + volume(period = "DAY")[28] + volume(period = "DAY")[29] + volume(period = "DAY")[30]) / 30;                                                                                           
def today = volume(period = "DAY");                                                                                           
def percentOf30Day = Round((today / volLast30DayAvg) * 100, 0);                                                                                           
def avg30Bars = (volume[1] + volume[2] + volume[3] + volume[4] + volume[5] + volume[6] + volume[7] + volume[8] + volume[9] + volume[10] + volume[11] + volume[12] + volume[13] + volume[14] + volume[15] + volume[16] + volume[17] + volume[18] + volume[19] + volume[20] + volume[21] + volume[22] + volume[23] + volume[24] + volume[25] + volume[26] + volume[27] + volume[28] + volume[29] + volume[30]) / 30;                                                                                           
def curVolume = volume;                                                                                           
def percentOf30Bar = Round((curVolume / avg30Bars) * 100, 0);                                                                                           
def SellVolPercent = Round((selling / volume) * 100, 0);                                                                                           
def ma = if type_HV == type_HV.SMP then SimpleMovingAvg(volume, length_3) else MovAvgExponential(volume, length_3);                                                                                           
                            
# --- HORSERIDER STUDY --- LABELS ---                                                                                           
                            
AddLabel(Show30DayAvg, "30 Day Avg: " + Round(volLast30DayAvg, 0), Color.LIGHT_GRAY);                                                                                           
AddLabel(ShowTodayVolume, "Day: " + today, (if percentOf30Day >= UnusualVolumePercent then Color.GREEN else if percentOf30Day >= 100 then Color.ORANGE else Color.LIGHT_GRAY));                                                                                           
AddLabel(ShowPercentOf30DayAvg, percentOf30Day + "%", (if percentOf30Day >= UnusualVolumePercent then Color.GREEN else if percentOf30Day >= 100 then Color.ORANGE else Color.WHITE) );                                                                                           
AddLabel(Show30BarAvg, "30 Bar Avg: " + Round(avg30Bars, 0), Color.LIGHT_GRAY);                                                                                           
AddLabel(ShowCurrentBar, "1 Bar: " + curVolume, (if percentOf30Bar >= UnusualVolumePercent then Color.GREEN else if percentOf30Bar >= 100 then Color.ORANGE else Color.LIGHT_GRAY));                                                                                           
AddLabel(ShowPercentOf30BarAvg, percentOf30Bar + "%", (if percentOf30Bar >= UnusualVolumePercent then Color.GREEN else if percentOf30Bar >= 100 then Color.ORANGE else Color.WHITE) );                                                                                           
AddLabel(ShowSellVolumePercent, "1 Bar Sell %: " + SellVolPercent, (if SellVolPercent > 51 then Color.RED else if SellVolPercent < 49 then Color.GREEN else Color.ORANGE));                                                                                           
                            
# --- TRIPLE EXHAUSTION STUDY --- INPUTS ---                                                                                           
                            
#input over_bought_3x = 80;                                                                                           
#input over_sold_3x = 20;                                                                                           
#input KPeriod_3x = 10;                                                                                           
#input DPeriod_3x = 10;                                                                                           
#input priceH_3x = high;                                                                                           
#input priceL_3x = low;                                                                                           
#input priceC_3x = close;                                                                                           
input averageType_3x = AverageType.SIMPLE;                                                                                           
input length_3x = 1000;                                                                                           
#input paintBars_3x = no;                                                                                           
#input showLabels_3x = no;                                                                                           
                            
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                           
                            
def over_bought_3x = 80;                                                                                           
def over_sold_3x = 20;                                                                                           
def KPeriod_3x = 10;                                                                                           
def DPeriod_3x = 10;                                                                                           
def priceH_3x = high;                                                                                           
def priceL_3x = low;                                                                                           
def priceC_3x = close;                                                                                           
                            
# --- TRIPLE EXHAUSTION STUDY --- DEF --- INDICATORS - StochasticSlow / MACD / MACD StDev / DMI+/-                                                                                           
                            
def SlowK_3x = reference StochasticFull(over_bought_3x, over_sold_3x, KPeriod_3x, DPeriod_3x, priceH_3x, priceL_3x, priceC_3x, 3, averageType_3x).FullK;                                                                                           
def MACD_3x = reference MACD()."Value";                                                                                           
def priceMean_3x = Average(MACD_3x, length_3x);                                                                                           
def MACD_stdev_3x =  (MACD_3x - priceMean_3x) / StDev(MACD_3x, length_3x);                                                                                           
def dPlus_3x = reference DMI()."DI+";                                                                                           
def dMinus_3x = reference DMI()."DI-";
                                                                                      
def sellerRegular = SlowK_3x < 20 and MACD_stdev_3x < -1 and dPlus_3x < 15;                                                                                           
def sellerExtreme = SlowK_3x < 20 and MACD_stdev_3x < -2 and dPlus_3x < 15;                                                                                           
def buyerRegular = SlowK_3x > 80 and MACD_stdev_3x > 1 and dMinus_3x < 15;                                                                                           
def buyerExtreme = SlowK_3x > 80 and MACD_stdev_3x > 2 and dMinus_3x < 15;                                                                                           
                            
# --- TRIPLE EXHAUSTION STUDY --- ARROWS ---                                                                                                                                                   
                                                                                                                                  
# --- Arrows/Triggers
plot RegularBuy = if sellerRegular[1] and !sellerRegular then low else Double.NaN;
plot ExtremeBuy = if sellerExtreme[1] and !sellerExtreme then low else Double.NaN;
RegularBuy.SetPaintingStrategy(PaintingSTrategy.Points);
ExtremeBuy.SetPaintingSTrategy(paintingSTrategy.Points);
RegularBuy.SetDefaultColor(Color.yellow);
ExtremeBuy.SetDefaultColor(Color.GREEN);

plot RegularSell = if buyerRegular[1] and !buyerRegular then high else Double.NaN;
plot ExtremeSell = if buyerExtreme[1] and !buyerExtreme then high else Double.NaN;
RegularSell.SetPaintingStrategy(PaintingSTrategy.Points);
ExtremeSell.SetPaintingSTrategy(paintingSTrategy.Points);
RegularSell.SetDefaultColor(Color.yellow);
ExtremeSell.SetDefaultColor(Color.RED);

#Addverticalline ((Regularsell),"",Color.red);                                                                                           
#Addverticalline ((Regularbuy),"", Color.Green);                                                                                           
                            
                            
# --- PLD STUDY --- #                                                                                           
                            
# --- PLD STUDY INPUTS ---                                                                                           
#input price = close;               
input length_PLD = 5;                                                                                           
input displace_PLD = -11;                                                                                           
input showBreakoutSignals_PLD = no;                                                                                           
input ColoredCandlesOn_PLD = no;                                                                                           
input BulgeLengthPrice_PLD = 5;                                                                                           
input SqueezeLengthPrice_PLD = 5;                                                                                           
                            
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                           
                            
#def BulgeLengthPrice_PLD = 5;                                                                                           
#def SqueezeLengthPrice_PLD = 5;                                                                                           
                            
# --- PLD DEF --- #                                                                                           

                
plot PLD = ExpAverage(Price[-displace_PLD], length_PLD);                                                                                           
def UpperBand_PLD = Highest(PLD, BulgeLengthPrice_PLD);                                                                                           
def LowerBand_PLD = Lowest(PLD, SqueezeLengthPrice_PLD);                                                                                           
plot UpSignal_PLD = Price crosses above UpperBand_PLD;                                                                                           
plot DownSignal_PLD = Price crosses below LowerBand_PLD;                                                                                           
UpSignal_PLD.SetHiding(!showBreakoutSignals_PLD);                                                                                           
DownSignal_PLD.SetHiding(!showBreakoutSignals_PLD);                                                                                           
PLD.SetDefaultColor(GetColor(1));                                                                                           
UpSignal_PLD.SetDefaultColor(Color.UPTICK);                                                                                           
UpSignal_PLD.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);                                                                                           
DownSignal_PLD.SetDefaultColor(Color.DOWNTICK);                                                                                           
DownSignal_PLD.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);                                                                                           
def LongEnter = (Price crosses above UpperBand_PLD);                                                                                           
def LongExit = (Price crosses below LowerBand_PLD);                                                                                           
                            
# --- CONFIRMATION NEAR TERM LEVELS STUDY ---                                                                                           
                            
def displace2_2 = 0;                                                                                           
def factorK2_2 = 2.0;                                                                                           
def lengthK2_2 = 20;                                                                                           
input averageType2_2 = AverageType.SIMPLE;                                                                                           
def trueRangeAverageType2_2 = AverageType.SIMPLE;                                                                                           
def BulgeLengthPrice2 = 20;                                                                                           
def SqueezeLengthPrice2 = 20;                                                                                           
def shift2_2 = factorK2_2  * MovingAverage(trueRangeAverageType2_2 , TrueRange(high, close, low), lengthK2_2 );                                                                                           
def averageK2_2 = MovingAverage(averageType2_2 , Price , lengthK2_2 );                                                                                           
def Upper_BandK2_2  = averageK2_2 [-displace2_2 ] + shift2_2 [-displace2_2 ];                                                                                           
def Lower_BandK2_2  = averageK2_2 [-displace2_2 ] - shift2_2 [-displace2_2 ];                                                                                           
def conditionK2 = (Upper_BandK2_2 [1] < Upper_BandK2_2 ) and (Lower_BandK2_2 [1] < Lower_BandK2_2 );                                                                                           
def conditionK3 = (Upper_BandK2_2 [1] > Upper_BandK2_2 ) and (Lower_BandK2_2 [1] > Lower_BandK2_2 );                                                                                           
                            
# --- C3 MAX STUDY --- #                                                                                           
                            
# Momentum Oscillators                                                                                           
                            
def MS = Average(Average(Price, ShortLength1) - Average(Price, ShortLength2), ShortLength3);                                                                                           
def MS2 = Average(Average(Price, LongLength1) - Average(Price, LongLength2), LongLength3);                                                                                           
                            
# Wave A                                                                                           
                            
def MSGreens = If (MS >= 0, MS, 0);                                                                                           
def MSReds = If (MS < 0, MS, 0);                                                                                           
                            
# Wave C                                                                                           
                            
def MS2Blues = If (MS2 >= 0, MS2, 0);                                                                                           
def MS2Yellows = If (MS2 < 0, MS2, 0);                                                                                           
def MayhemBullish = MSGreens > MSGreens[1] and  MS2Blues > MS2Blues[1];                                                                                           
def MayhemBearish =  MSReds < MSReds[1] and  MS2Yellows < MS2Yellows[1];                                                                                           
def MS_Pos = MSGreens;                                                                                           
def MS_Neg = MSReds;                                                                                           
def MS2_Pos = MS2Blues;                                                                                           
def MS2_Neg = MS2Yellows;                                                                                           
                            
# Squeeze Indicator                                                                                           
                            
#input length = 20;                                                                                           
#input nK = 1.5;                                                                                           
#input nBB = 2.0;                                                                                           
                            
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                           
                            
def length = 20;                                                                                           
def nK = 1.5;                                                                                           
def nBB = 2.0;                                                                                           
                            
def BBHalfWidth = StDev(Price, length);                                                                                           
def KCHalfWidth = nK * Average(TrueRange(high,  close,  low),  length);                                                                                           
def isSqueezed = nBB * BBHalfWidth / KCHalfWidth < 1;                                                                                           
def BBS_Ind = If(isSqueezed, 0, Double.NaN);                                                                                           
                            
# Bollinger Resolution                                                                                           
                            
def BBSMA = Average(Price, length);                                                                                           
def BBSMAL = BBSMA + (-nBB * BBHalfWidth);                                                                                           
def BBSMAU = BBSMA + (nBB * BBHalfWidth);                                                                                           
def PerB = RoundUp((Price - BBSMAL) / (BBSMAU - BBSMAL) * 100, 0);                                                                                           
AddLabel(yes, Concat("%B: ", PerB), if PerB < 0 then Color.YELLOW else if PerB > 0 and PerB[1] < 0 then Color.GREEN else Color.WHITE);                                                                                           
                            
# Parabolic SAR Signal                                                                                           
                            
input accelerationFactor = 0.0275;                                                                                           
input accelerationLimit = 0.2;                                                                                           
                            
def SAR = ParabolicSAR(accelerationFactor = accelerationFactor, accelerationLimit = accelerationLimit);                                                                                           
def bearishCross = Crosses(SAR, Price, CrossingDirection.ABOVE);                                                                                           
def signalDown = bearishCross;#If(bearishCross, 0, Double.NaN);                                                                                           
def bullishCross = Crosses(SAR, Price, CrossingDirection.BELOW);                                                                                           
def signalUp =  bullishCross;#If(bullishCross, 0, Double.NaN);                                                                                           
def UP = bullishCross;                                                                                           
def DOWN = bearishCross;                                                                                           
def priceColor = if UP then 1 else if DOWN then -1 else priceColor[1];                                                                                           
                            
# OB_OS_Levels_v5 by Christopher84 12/10/2021                                                                                           
                            
input BarsUsedForRange = 2;                                                                                           
input BarsRequiredToRemainInRange = 2;                                                                                           
input TargetMultiple = 0.5;                                                                                           
input ColorPrice = yes;                                                                                           
input HideTargets = no;                                                                                           
input HideBalance = no;                                                                                           
input HideBoxLines = no;                                                                                           
input HideCloud = no;                                                                                           
input HideLabels = no;                                                                                           
                            
#Squeeze Dots Created 04/28/2021 by Christopher84                                                                                           
                            
#input ATRPeriod = 5;                                                                                           
#input ATRFactor = 2.0;                                                                                           
                            
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                           
                            
def ATRPeriod = 5;                                                                                           
def ATRFactor = 2.0;                                                                                           
                            
def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));                                                                                           
def HRef = if low <= high[1] then high - close[1] else (high - close[1]) - 0.5 * (low - high[1]);                                                                                           
def LRef = if high >= low[1] then close[1] - low else (close[1] - low) - 0.5 * (low[1] - high);                                                                                           
                            
input trailType = {default modified, unmodified};                                                                                           
def trueRange;                                                                                           
switch (trailType) {                                                                                           
case modified:                                                                                           
    trueRange = Max(HiLo, Max(HRef, LRef));                                                                                           
case unmodified:                                                                                           
    trueRange = TrueRange(high, close, low);                                                                                           
}                                                                                           
                            
input averageType = AverageType.SIMPLE;                                                                                           
input firstTrade = {default long, short};                                                                                           
                            
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);                                                                                           
def state = {default init, long, short};                                                                                           
def trail;                                                                                           
switch (state[1]) {                                                                                           
case init:                                                                                           
    if (!IsNaN(loss)) {                                                                                           
        switch (firstTrade) {                                                                                           
        case long:                                                                                           
            state = state.long;                                                                                           
            trail =  close - loss;                                                                                           
        case short:                                                                                           
            state = state.short;                                                                                           
            trail = close + loss;                                                                                           
    }                                                                                           
    } else {                                                                                           
        state = state.init;                                                                                           
        trail = Double.NaN;                                                                                           
    }                                                                                           
case long:                                                                                           
    if (close > trail[1]) {                                                                                           
        state = state.long;                                                                                           
        trail = Max(trail[1], close - loss);                                                                                           
    } else {                                                                                           
        state = state.short;                                                                                           
        trail = close + loss;                                                                                           
    }                                                                                           
case short:                                                                                           
    if (close < trail[1]) {                                                                                           
        state = state.short;                                                                                           
        trail = Min(trail[1], close + loss);                                                                                           
    } else {                                                                                           
        state = state.long;                                                                                           
        trail =  close - loss;                                                                                           
    }                                                                                           
}                                                                                           
                            
def TrailingStop = trail;                                                                                           
def H = Highest(TrailingStop, 12);                                                                                           
def L = Lowest(TrailingStop, 12);                                                                                           
def BulgeLengthPrice = 100;                                                                                           
def SqueezeLengthPrice = 100;                                                                                           
def BandwidthC3 = (H - L);                                                                                           
def IntermResistance2 = Highest(BandwidthC3, BulgeLengthPrice);                                                                                           
def IntermSupport2 = Lowest(BandwidthC3, SqueezeLengthPrice);                                                                                           
def sqzTrigger = BandwidthC3 <= IntermSupport2;                                                                                           
def sqzLevel = if !sqzTrigger[1] and sqzTrigger then hl2                                                                                           
               else if !sqzTrigger then Double.NaN                                                                                           
               else sqzLevel[1];                                                                                           
                            
plot Squeeze_Alert = sqzLevel;                                                                                           
Squeeze_Alert.SetPaintingStrategy(PaintingStrategy.POINTS);                                                                                           
Squeeze_Alert.SetLineWeight(3);                                                                                           
Squeeze_Alert.SetDefaultColor(Color.YELLOW);                                                                                           
                            
#-----------------------------                                                                                           
#Yellow Candle_height (OB_OS)                                                                                           
#-----------------------------                                                                                           
                            
def displace = 0;                                                                                           
def factorK2 = 3.25;                                                                                           
def lengthK2 = 20;                                                                                           
def price1 = open;                                                                                           
def trueRangeAverageType = AverageType.SIMPLE;                                                                                           
def ATR_length = 15;                                                                                           
def SMA_lengthS = 6;                                                                                           
#input ATRPeriod2 = 5;                                                                                           
#input ATRFactor2 = 1.5;                                                                                           
                            
# --- Changed Inputs to "def" so they will not show in settings ---                                                                                           
                            
def ATRPeriod2 = 5;                                                                                           
def ATRFactor2 = 1.5;                                                                                           
                            
def HiLo2 = Min(high - low, 1.5 * Average(high - low, ATRPeriod));                                                                                           
def HRef2 = if low <= high[1]                                                                                           
    then high - close[1]                                                                                           
    else (high - close[1]) - 0.5 * (low - high[1]);                                                                                           
def LRef2 = if high >= low[1]                                                                                           
    then close[1] - low                                                                                           
    else (close[1] - low) - 0.5 * (low[1] - high);                                                                                           
def loss2 = ATRFactor2 * MovingAverage(averageType, trueRange, ATRPeriod2);                                                                                           
def multiplier_factor = 1.25;                                                                                           
def valS = Average(Price, SMA_lengthS);                                                                                           
def average_true_range = Average(TrueRange(high, close, low), length = ATR_length);                                                                                           
def Upper_BandS = valS[-displace] + multiplier_factor * average_true_range[-displace];                                                                                           
def Middle_BandS = valS[-displace];                                                                                           
def Lower_BandS = valS[-displace] - multiplier_factor * average_true_range[-displace];                                                                                           
                            
def shiftK2 = factorK2 * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK2);                                                                                           
def averageK2 = MovingAverage(averageType, Price, lengthK2);                                                                                           
def AvgK2 = averageK2[-displace];                                                                                           
def Upper_BandK2 = averageK2[-displace] + shiftK2[-displace];                                                                                           
def Lower_BandK2 = averageK2[-displace] - shiftK2[-displace];                                                                                           
def condition_BandRevDn = (Upper_BandS > Upper_BandK2);                                                                                           
def condition_BandRevUp = (Lower_BandS < Lower_BandK2);                                                                                           
def fastLength = 12;                                                                                           
def slowLength = 26;                                                                                           
def MACDLength = 9;                                                                                           
input MACD_AverageType = {SMA, default EMA};                                                                                           
def fastEMA = ExpAverage(Price, fastLength);                                                                                           
def slowEMA = ExpAverage(Price, slowLength);                                                                                           
def Value;                                                                                           
def Avg1;                                                                                           
switch (MACD_AverageType) {                                                                                           
case SMA:                                                                                           
    Value = Average(Price, fastLength) - Average(Price, slowLength);                                                                                           
    Avg1 = Average(Value, MACDLength);                                                                                           
case EMA:                                                                                           
    Value = fastEMA - slowEMA;                                                                                           
    Avg1 = ExpAverage(Value, MACDLength);                                                                                           
}                                                                                           
                            
def Diff = Value - Avg1;                                                                                           
def MACDLevel = 0.0;                                                                                           
def Level = MACDLevel;                                                                                           
def condition1 = Value[1] <= Value;                                                                                           
def condition1D = Value[1] > Value;                                                                                           
                            
#RSI                                                                                           
                            
def RSI_length = 14;                                                                                           
def RSI_AverageType = AverageType.WILDERS;                                                                                           
def RSI_OB = 70;                                                                                           
def RSI_OS = 30;                                                                                           
                            
def NetChgAvg = MovingAverage(RSI_AverageType, Price - Price[1], RSI_length);                                                                                           
def TotChgAvg = MovingAverage(RSI_AverageType, AbsValue(Price - Price[1]), RSI_length);                                                                                           
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;                                                                                           
def RSI = 50 * (ChgRatio + 1);                                                                                           
                            
def condition2 = (RSI[3] < RSI) is true or (RSI >= 80) is true;                                                                                           
def condition2D = (RSI[3] > RSI) is true or (RSI < 20) is true;                                                                                           
def conditionOB1 = RSI > RSI_OB;                                                                                           
def conditionOS1 = RSI < RSI_OS;                                                                                           
                            
#MFI                                                                                           
                            
def MFI_Length = 14;                                                                                           
def MFIover_Sold = 20;                                                                                           
def MFIover_Bought = 80;                                                                                           
def movingAvgLength = 1;                                                                                           
def MoneyFlowIndex = Average(MoneyFlow(high, close, low, volume, MFI_Length), movingAvgLength);                                                                                           
def MFIOverBought = MFIover_Bought;                                                                                           
def MFIOverSold = MFIover_Sold;                                                                                           
                            
def condition3 = (MoneyFlowIndex[2] < MoneyFlowIndex) is true or (MoneyFlowIndex > 85) is true;                                                                                           
def condition3D = (MoneyFlowIndex[2] > MoneyFlowIndex) is true or (MoneyFlowIndex < 20) is true;                                                                                           
def conditionOB2 = MoneyFlowIndex > MFIover_Bought;                                                                                           
def conditionOS2 = MoneyFlowIndex < MFIover_Sold;                                                                                           
                            
#Forecast                                                                                           
                            
def na = Double.NaN;                                                                                           
def MidLine = 50;                                                                                           
def Momentum = MarketForecast().Momentum;                                                                                           
def NearT =  MarketForecast().NearTerm;                                                                                           
def Intermed = MarketForecast().Intermediate;                                                                                           
def FOB = 80;                                                                                           
def FOS = 20;                                                                                           
def upperLine = 110;                                                                                           
                            
def condition4 = (Intermed[1] <= Intermed) or (NearT >= MidLine);                                                                                           
def condition4D = (Intermed[1] > Intermed) or (NearT < MidLine);                                                                                           
def conditionOB3 = Intermed > FOB;                                                                                           
def conditionOS3 = Intermed < FOS;                                                                                           
def conditionOB4 = NearT > FOB;                                                                                           
def conditionOS4 = NearT < FOS;                                                                                           
                            
#Change in Price                                                                                           
                            
def lengthCIP = 5;                                                                                           
def CIP = (Price - Price[1]);                                                                                           
def AvgCIP = ExpAverage(CIP[-displace], lengthCIP);                                                                                           
def CIP_UP = AvgCIP > AvgCIP[1];                                                                                           
def CIP_DOWN = AvgCIP < AvgCIP[1];                                                                                           
def condition5 = CIP_UP;                                                                                           
def condition5D = CIP_DOWN;                                                                                           
                            
#EMA_1                                                                                           
                            
def EMA_length = 8;                                                                                           
def AvgExp = ExpAverage(Price[-displace], EMA_length);                                                                                           
def condition6 = (Price >= AvgExp) and (AvgExp[2] <= AvgExp);                                                                                           
def condition6D = (Price < AvgExp) and (AvgExp[2] > AvgExp);                                                                                           
                            
#EMA_2                                                                                           
                            
def EMA_2length = 20;                                                                                           
def displace2 = 0;                                                                                           
def AvgExp2 = ExpAverage(Price[-displace2], EMA_2length);                                                                                           
def condition7 = (Price >= AvgExp2) and (AvgExp2[2] <= AvgExp);                                                                                           
def condition7D = (Price < AvgExp2) and (AvgExp2[2] > AvgExp);                                                                                           
                            
#DMI Oscillator                                                                                           
                            
def DMI_length = 5;#Typically set to 10                                                                                           
input DMI_averageType = AverageType.WILDERS;                                                                                           
def diPlus = DMI(DMI_length, DMI_averageType)."DI+";                                                                                           
def diMinus = DMI(DMI_length, DMI_averageType)."DI-";                                                                                           
def Osc = diPlus - diMinus;                                                                                           
def Hist = Osc;                                                                                           
def ZeroLine = 0;                                                                                           
def condition8 = Osc >= ZeroLine;                                                                                           
def condition8D = Osc < ZeroLine;                                                                                           
                            
#Trend_Periods                                                                                           
                            
def TP_fastLength = 3;#Typically 7                                                                                           
def TP_slowLength = 4;#Typically 15                                                                                           
def Periods = Sign(ExpAverage(close, TP_fastLength) - ExpAverage(close, TP_slowLength));                                                                                           
def condition9 = Periods > 0;                                                                                           
def condition9D = Periods < 0;                                                                                           
                            
#Polarized Fractal Efficiency                                                                                           
                            
def PFE_length = 5;#Typically 10                                                                                           
def smoothingLength = 2.5;#Typically 5                                                                                           
def PFE_diff = close - close[PFE_length - 1];                                                                                           
def val = 100 * Sqrt(Sqr(PFE_diff) + Sqr(PFE_length)) / Sum(Sqrt(1 + Sqr(close - close[1])), PFE_length - 1);                                                                                           
def PFE = ExpAverage(if PFE_diff > 0 then val else -val, smoothingLength);                                                                                           
def UpperLevel = 50;                                                                                           
def LowerLevel = -50;                                                                                           
def condition10 = PFE > 0;                                                                                           
def condition10D = PFE < 0;                                                                                           
def conditionOB5 = PFE > UpperLevel;                                                                                           
def conditionOS5 = PFE < LowerLevel;                                                                                           
                            
#Bollinger Bands Percent_B                                                                                           
                            
input BBPB_averageType = AverageType.SIMPLE;                                                                                           
def BBPB_length = 20;#Typically 20                                                                                           
def Num_Dev_Dn = -2.0;                                                                                           
def Num_Dev_up = 2.0;                                                                                           
def BBPB_OB = 100;                                                                                           
def BBPB_OS = 0;                                                                                           
def upperBand = BollingerBands(Price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, BBPB_averageType).UpperBand;                                                                                           
def lowerBand = BollingerBands(Price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, BBPB_averageType).LowerBand;                                                                                           
def PercentB = (Price - lowerBand) / (upperBand - lowerBand) * 100;                                                                                           
def HalfLine = 50;                                                                                           
def UnitLine = 100;                                                                                           
def condition11 = PercentB > HalfLine;                                                                                           
def condition11D = PercentB < HalfLine;                                                                                           
def conditionOB6 = PercentB > BBPB_OB;                                                                                           
def conditionOS6 = PercentB < BBPB_OS;                                                                                           
def condition12 = (Upper_BandS[1] <= Upper_BandS) and (Lower_BandS[1] <= Lower_BandS);                                                                                           
def condition12D = (Upper_BandS[1] > Upper_BandS) and (Lower_BandS[1] > Lower_BandS);                                                                                           
                            
#Klinger Histogram                                                                                           
                            
def Klinger_Length = 13;                                                                                           
def KVOsc = KlingerOscillator(Klinger_Length).KVOsc;                                                                                           
def KVOH = KVOsc - Average(KVOsc, Klinger_Length);                                                                                           
def condition13 = (KVOH > 0);                                                                                           
def condition13D = (KVOH < 0);                                                                                           
                            
#Projection Oscillator                                                                                           
                            
def ProjectionOsc_length = 30;#Typically 10                                                                                           
def MaxBound = HighestWeighted(high, ProjectionOsc_length, LinearRegressionSlope(price = high, length = ProjectionOsc_length));                                                                                           
def MinBound = LowestWeighted(low, ProjectionOsc_length, LinearRegressionSlope(price = low, length = ProjectionOsc_length));                                                                                           
def ProjectionOsc_diff = MaxBound - MinBound;                                                                                           
def PROSC = if ProjectionOsc_diff != 0 then 100 * (close - MinBound) / ProjectionOsc_diff else 0;                                                                                           
def PROSC_OB = 80;                                                                                           
def PROSC_OS = 20;                                                                                           
def condition14 = PROSC > 50;                                                                                           
def condition14D = PROSC < 50;                                                                                           
def conditionOB7 = PROSC > PROSC_OB;                                                                                           
def conditionOS7 = PROSC < PROSC_OS;                                                                                           
                            
#Trend Confirmation Calculator                                                                                           
#Confirmation_Factor range 1-15.                                                                                           
                            
input Confirmation_Factor = 7;                                                                                           
#Use for testing conditions individually. Remove # from line below and change Confirmation_Factor to 1.                                                                                           
#def Agreement_Level = condition1;                                                                                           
                            
def Agreement_LevelOB = 12;                                                                                           
def Agreement_LevelOS = 2;                                                                                           
def factorK = 2.0;                                                                                           
def lengthK = 20;                                                                                           
def shift = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK);                                                                                           
def averageK = MovingAverage(averageType, Price, lengthK);                                                                                           
def AvgK = averageK[-displace];                                                                                           
def Upper_BandK = averageK[-displace] + shift[-displace];                                                                                           
def Lower_BandK = averageK[-displace] - shift[-displace];                                                                                           
def conditionK1UP = Price >= Upper_BandK;                                                                                           
def conditionK2UP = (Upper_BandK[1] < Upper_BandK) and (Lower_BandK[1] < Lower_BandK);                                                                                           
def conditionK3DN = (Upper_BandK[1] > Upper_BandK) and (Lower_BandK[1] > Lower_BandK);                                                                                           
def conditionK4DN = Price < Lower_BandK;                                                                                           
def Agreement_Level = condition1 + condition2 + condition3 + condition4 + condition5 + condition6 + condition7 + condition8 + condition9 +          condition10 + condition11 + condition12 + condition13 + condition14 + conditionK1UP + conditionK2UP;                                                                                           
def Agreement_LevelD = (condition1D + condition2D + condition3D + condition4D + condition5D + condition6D + condition7D + condition8D + condition9D + condition10D + condition11D + condition12D + condition13D + condition14D + conditionK3DN + conditionK4DN);                                                                                           
def Consensus_Level = Agreement_Level - Agreement_LevelD;                                                                                           
def UP2 = Consensus_Level >= 10;                                                                                           
def DOWN2 = Consensus_Level < -10;                                                                                           
def priceColor2 = if UP2 then 1                                                                                           
                 else if DOWN2 then -1                                                                                           
                 else priceColor2[1];                                                                                           
def Consensus_Level_OB = 10;                                                                                           
def Consensus_Level_OS = -10;                                                                                           
                            
#Super_OB/OS Signal                                                                                           
                            
def OB_Level = conditionOB1 + conditionOB2 + conditionOB3 + conditionOB4 + conditionOB5 + conditionOB6 + conditionOB7;                                                                                           
def OS_Level = conditionOS1 + conditionOS2 + conditionOS3 + conditionOS4 + conditionOS5 + conditionOS6 + conditionOS7;                                                                                           
def Consensus_Line = OB_Level - OS_Level;                                                                                           
def Zero_Line = 0;                                                                                           
def Super_OB = 4;                                                                                           
def Super_OS = -4;                                                                                           
def DOWN_OB = (Agreement_Level > Agreement_LevelOB) and (Consensus_Line > Super_OB) and (Consensus_Level > Consensus_Level_OB);                                                                                           
def UP_OS = (Agreement_Level < Agreement_LevelOS) and (Consensus_Line < Super_OS) and (Consensus_Level < Consensus_Level_OS);                                                                                           
def OS_Buy = UP_OS;                                                                                           
def OB_Sell = DOWN_OB;                                                                                           
def neutral = Consensus_Line < Super_OB and Consensus_Line > Super_OS;                                                                                           
input use_line_limits = yes;#Yes, plots line from/to; No, plot line across entire chart                                                                                           
input linefrom = 100;#Hint linefrom: limits how far line plots in candle area                                                                                           
input lineto   = 12;#Hint lineto: limits how far into expansion the line will plot                                                                                           
def YHOB = if Color_Candles and ((price1 > Upper_BandS) and (condition_BandRevDn)) then high else Double.NaN;                                                                                           
def YHOS = if Color_Candles and ((price1 < Lower_BandS) and (condition_BandRevUp)) then high else Double.NaN;                                                                                           
def YLOB = if Color_Candles and ((price1 > Upper_BandS) and (condition_BandRevDn)) then low else Double.NaN;                                                                                           
def YLOS = if Color_Candles and ((price1 < Lower_BandS) and (condition_BandRevUp)) then low else Double.NaN;                                                                                           
                            
#extend midline of yellow candle                                                                                           
                            
plot YCOB = if !IsNaN(YHOB) then hl2 else Double.NaN;                                                                                           
YCOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);                                                                                           
YCOB.SetDefaultColor(Color.GREEN);                                                                                           
def YHextOB = if IsNaN(YCOB) then YHextOB[1] else YCOB;                                                                                           
plot YHextlineOB = YHextOB;                                                                                           
YHextlineOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);                                                                                           
YHextlineOB.SetDefaultColor(Color.ORANGE);                                                                                           
YHextlineOB.SetLineWeight(2);                                                                                           
plot YCOS = if !IsNaN(YHOS) then hl2 else Double.NaN;                                                                                           
YCOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);                                                                                           
YCOS.SetDefaultColor(Color.GREEN);                                                                                           
def YHextOS = if IsNaN(YCOS) then YHextOS[1] else YCOS;                                                                                           
plot YHextlineOS = YHextOS;                                                                                           
YHextlineOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);                                                                                           
YHextlineOS.SetDefaultColor(Color.LIGHT_GREEN);                                                                                           
YHextlineOS.SetLineWeight(2);                                                                                           
                            
def YC = Color_Candles and priceColor2 == 1 and price1 > Upper_BandS and condition_BandRevDn;                                                                                           
                            
#Additional Signals                                                                                           
                            
input showCloud = yes;                                                                                           
#AddCloud(if showCloud and condition_BandRevUp then Lower_BandK2 else Double.NaN,  Lower_BandS,  Color.LIGHT_GREEN,  Color.CURRENT);                                                                                           
#AddCloud(if showCloud and condition_BandRevDn then Upper_BandS else Double.NaN,  Upper_BandK2,  Color.LIGHT_RED,  Color.CURRENT);                                                                                           
                            
# Identify Consolidation                                                                                           
                            
def HH = Highest(high[1], BarsUsedForRange);                                                                                           
def LL = Lowest(low[1], BarsUsedForRange);                                                                                           
def maxH = Highest(HH, BarsRequiredToRemainInRange);                                                                                           
def maxL = Lowest(LL, BarsRequiredToRemainInRange);                                                                                           
def HHn = if maxH == maxH[1] or maxL == maxL then maxH else HHn[1];                                                                                           
def LLn = if maxH == maxH[1] or maxL == maxL then maxL else LLn[1];                                                                                           
def Bh = if high <= HHn and HHn == HHn[1] then HHn else Double.NaN;                                                                                           
def Bl = if low >= LLn and LLn == LLn[1] then LLn else Double.NaN;                                                                                           
def CountH = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountH[1] + 1;                                                                                           
def CountL = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountL[1] + 1;                                                                                           
def ExpH = if BarNumber() == 1 then Double.NaN else                                                                                           
            if CountH[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then HHn[-BarsRequiredToRemainInRange] else                                                                                           
            if high <= ExpH[1] then ExpH[1] else Double.NaN;                                                                                           
def ExpL = if BarNumber() == 1 then Double.NaN else                                                                                           
            if CountL[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then LLn[-BarsRequiredToRemainInRange] else                                                                                           
            if low >= ExpL[1] then ExpL[1] else Double.NaN;                                                                                           
                            
# Plot the High and Low of the Box; Paint Cloud                                                                                           
                            
def BoxHigh = if ((DOWN_OB) or (Upper_BandS crosses above Upper_BandK2) or (condition_BandRevDn) and (high > high[1]) and ((Price > Upper_BandK2) or (Price > Upper_BandS))) then Highest(ExpH) else Double.NaN;#if (DOWN_OB > 3) then Highest(ExpH) else if (Condition_BandRevDn and (price > AvgExp) and (High > High[1])) then Highest(ExpH) else Double.NaN;                                                                                           
def BoxLow = if (DOWN_OB) or ((Upper_BandS crosses above Upper_BandK2)) then Lowest(low) else Double.NaN;#if (DOWN_OB crosses above 3) then Lowest(low) else if ((Upper_BandS crosses above Upper_BandK2)) then Lowest(ExpH) else Double.NaN;#if ((DOWN_OB) or (Condition_BandRevDn and (price < price[1]))) then Highest(ExpL) else Double.NaN;                                                                                           
def BoxHigh2 = if ((UP_OS) or ((Lower_BandS crosses below Lower_BandK2))) then Highest(ExpH) else Double.NaN; #if (UP_OS) then Highest(ExpH) else if ((Lower_BandS crosses below Lower_BandK2)) then Highest(ExpH) else Double.NaN;                                                                                           
def BH2 = if !IsNaN(BoxHigh2) then high else Double.NaN;                                                                                           
def BH2ext = if IsNaN(BH2) then BH2ext[1] else BH2;                                                                                           
def BH2extline = BH2ext;                                                                                           
plot H_BH2extline = Lowest(BH2extline, 1);                                                                                           
H_BH2extline.SetDefaultColor(Color.GREEN);                                                                                           
def BoxLow2 = if ((UP_OS) or (Lower_BandS crosses below Lower_BandK2) or (condition_BandRevUp) and (low < low[1]) and ((Price < Lower_BandK2) or (Price < Lower_BandS))) or ((UP_OS[1]) and (low < low[1])) then Lowest(low) else Double.NaN;#if (UP_OS) then Lowest(low) else if (Condition_BandRevUp and (price < AvgExp) and (Low < Low[1])) then Lowest(low) else Double.NaN;                                                                                           
                            
# extend the current YCHigh line to the right edge of the chart                                                                                           
                            
def BH1 = if !IsNaN(BoxHigh) then high else Double.NaN;                                                                                           
def BH1ext = if IsNaN(BH1) then BH1ext[1] else BH1;                                                                                           
def BH1extline = BH1ext;                                                                                           
def BL1 = if !IsNaN(BoxLow) then low else Double.NaN;                                                                                           
def BL1ext = if IsNaN(BL1) then BL1ext[1] else BL1;                                                                                           
                            
plot BL1extline = BL1ext;                                                                                           
BL1extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);                                                                                           
BL1extline.SetDefaultColor(Color.RED);                                                                                           
BL1extline.SetLineWeight(1);                                                                                           
def BL2 = if !IsNaN(BoxLow2) then low else Double.NaN;                                                                                           
def BL2ext = if IsNaN(BL2) then BL2ext[1] else BL2;                                                                                           
plot BL2extline = BL2ext;                                                                                           
BL2extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);                                                                                           
BL2extline.SetDefaultColor(Color.GREEN);                                                                                           
BL2extline.SetLineWeight(1);                                                                                           
plot H_BH1extline = Highest(BH1extline, 1);                                                                                           
H_BH1extline.SetDefaultColor(Color.RED);                                                                                           
plot L_BL1extline = Highest(BL1extline, 1);                                                                                           
L_BL1extline.SetDefaultColor(Color.RED);                                                                                           
plot L_BL2extline = Lowest(BL2extline, 1);                                                                                           
L_BL2extline.SetDefaultColor(Color.GREEN);                                                                                           
                            
###################### --- BREAKOUT CODE --- ######################                                                                           
                            
# Price crosses level and the opposite crossing happend within x number of bars                                                                                           
                            
def bn = BarNumber();                                                                                           
def na_1 = Double.NaN;                                                                                           
                            
input bars_back_OS = 5;                           
input bars_back_OB = 5;                           
                            
input bars_back_H_BH1 = 5;                           
input bars_back_H_BH2 = 5;                           
                            
input bars_back_L_BL1 = 5;                                                                                           
input bars_back_L_BL2 = 5;                           
                            
# def support = ... some price level                           
                                                                                            
def Y_Line_OS = YHextlineOS;                                                                                           
def LG_Line_OB = YHextlineOB;                                                                                           
                            
def High_BH1_Red = H_BH1EXTLINE;                                                                                           
def Low_BL1_Red = L_BL1EXTLINE;                                                                                           
                            
def High_BH2_Grn = H_BH2EXTLINE;                                                                                           
def Low_BL2_Grn = L_BL2EXTLINE;                                                                                           
                            
############# INPUT FOR TESTING ONLY ##############                                                                                           
                            
input support_level = 50;                                                                                           
                            
########### CONVERT CONSTANT TO VAR ############                                                                                                                                                   
                            
input show_ref_line = no;                                                                                           
                            
# plot y = if show_ref_line then support else na_1;                                                                                                                                           
                            
########### CHOOSE WICK, BODY, or CLOSE ###########                                                                                           
                            
input OB_Candle = {default "wick" , "body" , "close"};                                                                                           
def High_OB;                                                                                           
def Low_OB;                                                                                           
switch (OB_Candle) {                                                                                           
case "wick":                                                                                           
    High_OB = high;                                                                                           
    Low_OB = low;                                                                                           
case "body":                                                                                           
    High_OB = Max(open, close);                                                                                           
    Low_OB = Min(open, close);                                                                                           
case "close":                                                                                           
    High_OB = close;                                                                                           
    Low_OB = close;                                                                                           
}                                                                                           
                            
input OS_Candle = {default "wick" , "body" , "close"};                                                                                           
def High_OS;                                                                                           
def Low_OS;                                                                                           
switch (OS_Candle) {                                                                                           
case "wick":                                                                                           
    High_OS = high;                                                                                           
    Low_OS = low;                                                                                           
case "body":                                                                                           
    High_OS = Max(open, close);                                                                                           
    Low_OS = Min(open, close);                                                                                           
case "close":                                                                                           
    High_OS = close;                                                                                           
    Low_OS = close;                                                                                           
}                                                                                           
                            
input H_BH1_Candle = {default "wick" , "body" , "close"};                                                                                           
def High_H_BH1;                                                                                           
def Low_H_BH1;                                                                                           
switch (H_BH1_Candle) {                                                                                           
case "wick":                                                                                           
    High_H_BH1 = high;                                                                                           
    Low_H_BH1 = low;                                                                                           
case "body":                                                                                           
    High_H_BH1 = Max(open, close);                                                                                           
    Low_H_BH1 = Min(open, close);                                                                                           
case "close":                                                                                           
    High_H_BH1 = close;                                                                                           
    Low_H_BH1 = close;                                                                                           
}                                                                                           
                            
input H_BH2_Candle = {default "wick" , "body" , "close"};                                                                                           
def High_H_BH2;                                                                                           
def Low_H_BH2;                                                                                           
switch (H_BH2_Candle) {                                                                                           
case "wick":                                                                                           
    High_H_BH2 = high;                                                                                           
    Low_H_BH2 = low;                                                                                           
case "body":                                                                                           
    High_H_BH2 = Max(open, close);                                                                                           
    Low_H_BH2 = Min(open, close);                                                                                           
case "close":                                                                                           
    High_H_BH2 = close;                                                                                           
    Low_H_BH2 = close;                                                                                           
}                                                                                           
                            
input L_BL1_Candle = {default "wick" , "body" , "close"};                                                                                           
def High_L_BL1;                                                                                           
def Low_L_BL1;                                                                                           
switch (L_BL1_Candle) {                                                                                           
case "wick":                                                                                           
    High_L_BL1 = high;                                                                                           
    Low_L_BL1 = low;                                                                                           
case "body":                                                                                           
    High_L_BL1 = Max(open, close);                                                                                           
    Low_L_BL1 = Min(open, close);                                                                                           
case "close":                                                                                           
    High_L_BL1 = close;                                                                                           
    Low_L_BL1 = close;                                                                                           
}                                                                                           
                            
input L_BL2_Candle = {default "wick" , "body" , "close"};                                                                                           
def High_L_BL2;                                                                                           
def Low_L_BL2;                                                                                           
switch (L_BL2_Candle) {                                                                                           
case "wick":                                                                                           
    High_L_BL2 = high;                                                                                           
    Low_L_BL2 = low;                                                                                           
case "body":                                                                                           
    High_L_BL2 = Max(open, close);                                                                                           
    Low_L_BL2 = Min(open, close);                                                                                           
case "close":                                                                                           
    High_L_BL2 = close;                                                                                           
    Low_L_BL2 = close;                                                                                           
}                                                                                           
                            
########### LABELS ############                                                                           
                            
#AddLabel(1, "Crossing Levels OS " + OS_Candle , Color.YELLOW);                           
                                                                                            
#AddLabel(1, "Bars Back OS" + bars_back_OS , Color.YELLOW);                           
                                                                                            
#AddLabel(1, "Crossing Levels OB " + OB_Candle , Color.YELLOW);                           
                                                                                            
#AddLabel(1, "Bars Back OB " + bars_back_OB , Color.YELLOW);                                   
                                                                                    
#AddLabel(1, "Crossing Levels H_BH1 " + H_BH1_Candle , Color.YELLOW);                                   
                                                                                    
#AddLabel(1, "Bars Back H_BH1 " + bars_back_H_BH1, Color.YELLOW);                                   
                            
#AddLabel(1, "Crossing Levels H_BH2 " + H_BH2_Candle , Color.YELLOW);                                   
                                                                                    
#AddLabel(1, "Bars Back H_BH2 " + bars_back_H_BH2, Color.YELLOW);                                   
                            
#AddLabel(1, "Crossing Levels L_BL1 " + L_BL1_Candle , Color.YELLOW);                                   
                                                                                    
#AddLabel(1, "Bars Back L_BL1 " + bars_back_L_BL1, Color.YELLOW);                                   
                            
#AddLabel(1, "Crossing Levels L_BL2 " + L_BL2_Candle , Color.YELLOW);                                   
                                                                                    
#AddLabel(1, "Bars Back L_BL2 " + bars_back_L_BL2, Color.YELLOW);                                   
                            
                            
########## CROSSING UP / DOWN ###########                                                                                   
                            
def OS_Down_Bn = if bn == 1 then 0 else if High_OS[1] > Y_Line_OS[1] and Low_OS < Y_Line_OS then bn else OS_Down_Bn[1];                                                                                           
def OS_Up_Bn = if bn == 1 then 0 else if Low_OS[1] < Y_Line_OS[1] and High_OS > Y_Line_OS then bn else OS_Up_Bn[1];                                                                                           
                            
def OB_Down_Bn = if bn == 1 then 0 else if High_OB[1] > LG_Line_OB[1] and Low_OB < LG_Line_OB then bn else OB_Down_Bn[1];                                                                                           
def OB_Up_Bn = if bn == 1 then 0 else if Low_OB[1] < LG_Line_OB[1] and High_OB > LG_Line_OB then bn else OB_Up_Bn[1];                                                                                           
                            
def H_BH1_Down_Bn = if bn == 1 then 0 else if High_H_BH1[1] > High_BH1_Red[1] and Low_H_BH1 < High_BH1_Red then bn else H_BH1_Down_Bn[1];                                                                                           
def H_BH1_Up_Bn = if bn == 1 then 0 else if Low_H_BH1[1] < High_BH1_Red[1] and High_H_BH1 > High_BH1_Red then bn else H_BH1_Down_Bn[1];                                                                                           
                            
def H_BH2_Down_Bn = if bn == 1 then 0 else if High_H_BH2[1] > High_BH2_Grn[1] and Low_H_BH2 < High_BH2_Grn then bn else H_BH2_Down_Bn[1];                                                                           
def H_BH2_Up_Bn = if bn == 1 then 0 else if Low_H_BH2[1] < High_BH2_Grn[1] and High_H_BH2 > High_BH2_Grn then bn else H_BH2_Up_Bn[1];                                                                                           
                            
def L_BL1_Down_Bn = if bn == 1 then 0 else if High_L_BL1[1] > Low_BL1_Red[1] and Low_L_BL1 < Low_BL1_Red then bn else L_BL1_Down_Bn[1];                                                                                           
def L_BL1_Up_Bn = if bn == 1 then 0 else if Low_L_BL1[1] < Low_BL1_Red[1] and High_L_BL1 > Low_BL1_Red then bn else L_BL1_Up_Bn[1];                                                                                           
                            
def L_BL2_Down_Bn = if bn == 1 then 0 else if High_L_BL2[1] > Low_BL2_Grn[1] and Low_L_BL2 < Low_BL2_Grn then bn else L_BL2_Down_Bn[1];                                                                                           
def L_BL2_Up_Bn = if bn == 1 then 0 else if Low_L_BL2[1] < Low_BL2_Grn[1] and High_L_BL2 > Low_BL2_Grn then bn else L_BL2_Up_Bn[1];                                                                                           
                            
########### GETTIN CROSSED-UP ###########                                                                                           
                            
# dip then rise, within len bars                                                                                                        #TEST#
                            
def OS_Up_0 = if                                                                                           
bn > bars_back_OS                                                                                         
and                                                                                           
( (OS_Up_Bn - OS_Down_Bn) <= bars_back_OS and (OS_Up_Bn - OS_Down_Bn) > 0 )                                                                                           
and                                                                                           
OS_Up_Bn == bn                                                                                           
and                                                                                           
Sum(OS_Up_0[1], (bars_back_OS - 1)) == 0                                                                                           
then 1 else 0;                                                                                           
                            
def OS_Down_0 = if                                                                                           
bn > bars_back_OS                                                                                           
and                                                                                           
( (OS_Down_Bn - OS_Up_Bn) <= bars_back_OS and (OS_Down_Bn - OS_Up_Bn) > 0 )                                                                                           
and                                                                                           
OS_Down_Bn == bn                                                                                           
and                                                                                           
Sum(OS_Down_0[1], (bars_back_OS - 1)) == 0                                                                                           
then 1 else 0;                                                                                           
                            
def OB_Up_0 = if                                                                                           
bn > bars_back_OS                                                                                           
and                                                                                           
( (OB_Up_Bn - OB_Down_Bn) <= bars_back_OB and (OB_Up_Bn - OB_Down_Bn) > 0 )                                                                                           
and                                                                                           
OB_Up_Bn == bn                                                                                           
and                                                                                           
Sum(OB_Up_0[1], (bars_back_OB - 1)) == 0                                                                                           
then 1 else 0;                                                                                           
                            
def OB_Down_0 = if                                                                                           
bn > bars_back_OB                                                                                           
and                                                                                           
( (OB_Down_Bn - OB_Up_Bn) <= bars_back_OB and (OB_Down_Bn - OB_Up_Bn) > 0 )                                                                                           
and                                                                                           
OB_Down_Bn == bn                                                                                           
and                                                                                           
Sum(OB_Down_0[1], (bars_back_OB - 1)) == 0                                                                                           
then 1 else 0;                                                                                           
                            
def H_BH1_Up_0 = if                                                                                           
bn > bars_back_H_BH1                                                                                           
and                                                                                           
( (H_BH1_Up_Bn - H_BH1_Down_Bn) <= bars_back_H_BH1 and (H_BH1_Up_Bn - H_BH1_Down_Bn) > 0 )                                                                                           
and                                                                                           
H_BH1_Up_Bn == bn                                                                                           
and                                                                                           
Sum(H_BH1_Up_0[1], (bars_back_H_BH1 - 1)) == 0                                                                                         
then 1 else 0;                                                                                           
                            
def H_BH1_Down_0 = if                                                                                           
bn > bars_back_H_BH1                                                                                           
and                                                                                           
( (H_BH1_Down_Bn - H_BH1_Up_Bn) <= bars_back_H_BH1 and (H_BH1_Down_Bn - H_BH1_Up_Bn) > 0 )                                                                                           
and                                                                                           
H_BH1_Down_Bn == bn                                                                                           
and                                                                                           
Sum(H_BH1_Down_0[1], (bars_back_H_BH1 - 1)) == 0                                                                                           
then 1 else 0;                                                                                           
                            
def L_BL1_Up_0 = if                                                                                           
bn > bars_back_L_BL1                                                                                         
and                                                                                           
( (L_BL1_Up_Bn - L_BL1_Down_Bn) <= bars_back_L_BL1 and (L_BL1_Up_Bn - L_BL1_Down_Bn) > 0 )                                                                                           
and                                                                                           
L_BL1_Up_Bn == bn                                                                                           
and                                                                                           
Sum(L_BL1_Up_0[1], (bars_back_L_BL1 - 1)) == 0                                                                                           
then 1 else 0;                                                                                           
                            
def L_BL1_Down_0 = if                                                                                           
bn > bars_back_L_BL1                                                                                           
and                                                                                           
( (L_BL1_Down_Bn - L_BL1_Up_Bn) <= bars_back_L_BL1 and (L_BL1_Down_Bn - L_BL1_Up_Bn) > 0 )                                                                                           
and                                                                                           
L_BL1_Down_Bn == bn                                                                                           
and                                                                                           
Sum(L_BL1_Down_0[1], (bars_back_L_BL1 - 1)) == 0                                                                                           
then 1 else 0;                                                                                           
                            
def H_BH2_Up_0 = if                                                                                           
bn > bars_back_H_BH2                                                                                           
and                                                                                           
( (H_BH2_Up_Bn - H_BH2_Down_Bn) <= bars_back_H_BH2 and (H_BH2_Up_Bn - H_BH2_Down_Bn) > 0 )                                                                                           
and                                                                                           
H_BH2_Up_Bn == bn                                                                                           
and                                                                                           
Sum(H_BH2_Up_0[1], (bars_back_H_BH2 - 1)) == 0                                                                                           
then 1 else 0;                                                                                           
                            
def H_BH2_Down_0 = if                                                                                           
bn > bars_back_H_BH2                                                                                           
and                                                                                           
( (H_BH2_Down_Bn - H_BH2_Up_Bn) <= bars_back_H_BH2 and (H_BH2_Down_Bn - H_BH2_Up_Bn) > 0 )                                                                                           
and                                                                                           
H_BH2_Down_Bn == bn                                                                                           
and                                                                                           
Sum(H_BH2_Down_0[1], (bars_back_H_BH2 - 1)) == 0                                                                                           
then 1 else 0;                                                                                           
                            
def L_BL2_Up_0 = if                                                                                           
bn > bars_back_L_BL2                                                                                           
and                                                                                           
( (L_BL2_Up_Bn - L_BL2_Down_Bn) <= bars_back_L_BL2 and (L_BL2_Up_Bn - L_BL2_Down_Bn) > 0 )                                                                                           
and                                                                                           
L_BL2_Up_Bn == bn                                                                                           
and                                                                                           
Sum(L_BL2_Up_0[1], (bars_back_L_BL2 - 1)) == 0                                                                                           
then 1 else 0;                                                                                       
                            
def L_BL2_Down_0 = if                                                                                           
bn > bars_back_L_BL2                                                                                           
and                                                                                           
( (L_BL2_Down_Bn - L_BL2_Up_Bn) <= bars_back_L_BL2 and (L_BL2_Down_Bn - L_BL2_Up_Bn) > 0 )                                                                                           
and                                                                                           
L_BL2_Down_Bn == bn                                                                                           
and                                                                                           
Sum(L_BL2_Down_0[1], (bars_back_L_BL2 - 1)) == 0                                                                                           
then 1 else 0;

############## --- CROSSOVER TEST(s) --- ###############

def OS_Up_2 = if                                                                                           
bn > bars_back_OS                                                                                         
and                                                                                           
( (OS_Up_Bn - OS_Down_Bn) <= bars_back_OS and (OS_Up_Bn - OS_Down_Bn) > 0 )                                                                                           
and                                                                                           
OS_Up_Bn == bn                                                                                           
and                                                                                           
Sum(OS_Up_0[1], (bars_back_OS - 1)) == 0                                                                                           
and                                                                                                                                                                                                       ( (OS_Up_Bn - OS_Down_Bn) <= bars_back_OS and (OS_Up_Bn - OS_Down_Bn) > 0 )                                                                                           
and                                                                                           
OS_Up_Bn == bn                                                                                           
and                                                                                           
Sum(OS_Up_0[1], (bars_back_OS - 1)) == 0                                                                                           
then 1 else 0;       



                                            
                            
########### ARROWS ###########                                                                                           
                            
input arrow_size = 1;

plot OS_Up_22 = OS_Up_2;                                                                                           
OS_Up_22.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);                                                                                           
OS_Up_22.SetDefaultColor(Color.White);                                                                                           
OS_Up_22.SetLineWeight(arrow_size);

plot OS_Up = OS_Up_0;                                                                                           
OS_Up.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);                                                                                           
OS_Up.SetDefaultColor(Color.White);                                                                                           
OS_Up.SetLineWeight(arrow_size);                                                                                           
                            
plot OS_Down = OS_Down_0;                                                                                           
OS_Down.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);                                                                                           
OS_Down.SetDefaultColor(Color.White);                                                                                           
OS_Down.SetLineWeight(arrow_size);                                                                                           
                            
plot OB_Up = OB_Up_0;                                                                                           
OB_Up.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);                                                                                           
OB_Up.SetDefaultColor(Color.White);                                                                                           
OB_Up.SetLineWeight(arrow_size);                                                                                           
                            
plot OB_Down = OB_Down_0;                                                                                           
OB_Down.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);                                                                                           
OB_Down.SetDefaultColor(Color.White);                                                                                           
OB_Down.SetLineWeight(arrow_size);                                                                                           
                            
plot H_BH1_Up = H_BH1_Up_0;                                                                                           
H_BH1_Up.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);                                                                                           
H_BH1_Up.SetDefaultColor(Color.White);                                                                                           
H_BH1_Up.SetLineWeight(arrow_size);                                                                                           
                            
plot H_BH1_Down = H_BH1_Down_0;                                                                                           
H_BH1_Down.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);                                                                                           
H_BH1_Down.SetDefaultColor(Color.White);                                                                                           
H_BH1_Down.SetLineWeight(arrow_size);                                                                                           
                            
plot L_BL1_Up = L_BL1_Up_0;                                                                                           
L_BL1_Up.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);                                                                                           
L_BL1_Up.SetDefaultColor(Color.White);                                                                                           
L_BL1_Up.SetLineWeight(arrow_size);                                                                                           
                            
plot L_BL1_Down = L_BL1_Down_0;                                                                                           
L_BL1_Down.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);                                                                                           
L_BL1_Down.SetDefaultColor(Color.White);                                                                                           
L_BL1_Down.SetLineWeight(arrow_size);                                                                                           
                            
plot H_BH2_Up = H_BH2_Up_0;                                                                                           
H_BH2_Up.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);                                                                                           
H_BH2_Up.SetDefaultColor(Color.White);                                                                                           
H_BH2_Up.SetLineWeight(arrow_size);                                                                                           
                            
plot H_BH2_Down = H_BH1_Down_0;                                                                                           
H_BH2_Down.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);                                                                                           
H_BH2_Down.SetDefaultColor(Color.BLUE);                                                                                           
H_BH2_Down.SetLineWeight(arrow_size);                                                                                           
                            
plot L_BL2_Up = L_BL2_Up_0;                                                                                           
L_BL2_Up.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);                                                                                           
L_BL2_Up.SetDefaultColor(Color.LIGHT_GREEN);                                                                                           
L_BL2_Up.SetLineWeight(arrow_size);                                                                                           
                            
plot L_BL2_Down = L_BL2_Down_0;                                                                                           
L_BL2_Down.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);                                                                                           
L_BL2_Down.SetDefaultColor(Color.WHITE);                                                                                           
L_BL2_Down.SetLineWeight(arrow_size);                                                                                           
                            
                            
########### TEST VARIABLES ###########                                                                                           
                            
input test_crossing_bubbles = no;                                                                                           
                            
AddChartBubble(test_crossing_bubbles and OS_Down_Bn == bn, high, bn, Color.RED, no);                                                                                           
AddChartBubble(test_crossing_bubbles and OS_Up_Bn == bn, low, bn, Color.GREEN, yes);                                                                                           
                            
AddChartBubble(test_crossing_bubbles and OB_Down_Bn == bn, high, bn, Color.RED, no);                                                                                           
AddChartBubble(test_crossing_bubbles and OB_Up_Bn == bn, low, bn, Color.GREEN, yes);                                   
                            
AddChartBubble(test_crossing_bubbles and H_BH1_Down_Bn == bn, high, bn, Color.RED, no);                                                                                           
AddChartBubble(test_crossing_bubbles and H_BH1_Up_Bn == bn, low, bn, Color.GREEN, yes);                                   
                            
AddChartBubble(test_crossing_bubbles and H_BH2_Down_Bn == bn, high, bn, Color.RED, no);                                                                                           
AddChartBubble(test_crossing_bubbles and H_BH2_Up_Bn == bn, low, bn, Color.GREEN, yes);                                   
                            
AddChartBubble(test_crossing_bubbles and L_BL1_Down_Bn == bn, high, bn, Color.RED, no);                                                                                           
AddChartBubble(test_crossing_bubbles and L_BL1_Up_Bn == bn, low, bn, Color.GREEN, yes);                                   
                            
AddChartBubble(test_crossing_bubbles and L_BL2_Down_Bn == bn, high, bn, Color.RED, no);                                                                                           
AddChartBubble(test_crossing_bubbles and L_BL2_Up_Bn == bn, low, bn, Color.GREEN, yes);                                   
                            
##################################################################################                           
                            
                            
                            
                            
                            
                            
##################################################################################                           
                            
AddCloud(if !HideCloud then BH1extline else Double.NaN, BL1extline, Color.RED, Color.GRAY);
AddCloud(if !HideCloud then BH2extline else Double.NaN, BL2extline, Color.GREEN, Color.GRAY);

script WMA_Smooth {
    input price_WMA = hl2;
    plot smooth = (4 * price_WMA
+ 3 * price_WMA[1]
+ 2 * price_WMA[2]
+ price_WMA[3]) / 10;}

script Phase_Accumulation {

# This is Ehler's Phase Accumulation code. It has a full cycle delay.
# However, it computes the correction factor to a very high degree.

    input price_WMA = hl2;

    rec Smooth;
    rec Detrender;
    rec Period;
    rec Q1;
    rec I1;
    rec I1p;
    rec Q1p;
    rec Phase1;
    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase1;
    rec InstPeriod1;
    rec InstPeriod;
    def CorrectionFactor;

    if BarNumber() <= 5
    then {
        Period = 0;
        Smooth = 0;
        Detrender = 0;
        CorrectionFactor = 0;
        Q1 = 0;
        I1 = 0;
        Q1p = 0;
        I1p = 0;
        Phase = 0;
        Phase1 = 0;
        DeltaPhase1 = 0;
        DeltaPhase = 0;
        InstPeriod = 0;
        InstPeriod1 = 0;
    } else {
        CorrectionFactor = 0.075 * Period[1] + 0.54;

# Smooth and detrend my smoothed signal:

        Smooth = WMA_Smooth(price_WMA);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

# Compute Quadrature and Phase of Detrended signal:

        Q1p = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1p = Detrender[3];

# Smooth out Quadrature and Phase:

        I1 = 0.15 * I1p + 0.85 * I1p[1];
        Q1 = 0.15 * Q1p + 0.85 * Q1p[1];

# Determine Phase

        if I1 != 0
        then {

# Normally, ATAN gives results from -pi/2 to pi/2.
# We need to map this to circular coordinates 0 to 2pi

            if Q1 >= 0 and I1 > 0
            then { # Quarant 1
                Phase1 = ATan(AbsValue(Q1 / I1));
            } else if Q1 >= 0 and I1 < 0
            then { # Quadrant 2
                Phase1 = Double.Pi - ATan(AbsValue(Q1 / I1));
            } else if Q1 < 0 and I1 < 0
            then { # Quadrant 3
                Phase1 = Double.Pi + ATan(AbsValue(Q1 / I1));
            } else { # Quadrant 4
                Phase1 = 2 * Double.Pi - ATan(AbsValue(Q1 / I1));
            }
        } else if Q1 > 0
        then { # I1 == 0, Q1 is positive
            Phase1 = Double.Pi / 2;
        } else if Q1 < 0
        then { # I1 == 0, Q1 is negative
            Phase1 = 3 * Double.Pi / 2;
        } else { # I1 and Q1 == 0
            Phase1 = 0;
        }

# Convert phase to degrees

        Phase = Phase1 * 180 / Double.Pi;

        if Phase[1] < 90 and Phase > 270
        then {
# This occurs when there is a big jump from 360-0

            DeltaPhase1 = 360 + Phase[1] - Phase;
        } else {
            DeltaPhase1 = Phase[1] - Phase;
        }

# Limit our delta phases between 7 and 60

        if DeltaPhase1 < 7
        then {
            DeltaPhase = 7;
        } else if DeltaPhase1 > 60
        then {
            DeltaPhase = 60;
        } else {
            DeltaPhase = DeltaPhase1;
        }

# Determine Instantaneous period:

        InstPeriod1 =
-1 * (fold i = 0 to 40 with v=0 do
if v < 0 then
v
else if v > 360 then
-i
else
v + GetValue(DeltaPhase, i, 41));

        if InstPeriod1 <= 0
        then {
            InstPeriod = InstPeriod[1];
        } else {
            InstPeriod = InstPeriod1;
        }

        Period = 0.25 * InstPeriod + 0.75 * Period[1];
    }
    plot DC = Period;}

script Ehler_MAMA {
    input price_WMA = hl2;
    input FastLimit = 0.5;
    input SlowLimit = 0.05;


    rec Period;
    rec Period_raw;
    rec Period_cap;
    rec Period_lim;

    rec Smooth;
    rec Detrender;
    rec I1;
    rec Q1;
    rec jI;
    rec jQ;
    rec I2;
    rec Q2;
    rec I2_raw;
    rec Q2_raw;

    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase_raw;
    rec alpha;
    rec alpha_raw;

    rec Re;
    rec Im;
    rec Re_raw;
    rec Im_raw;

    rec SmoothPeriod;
    rec vmama;
    rec vfama;

    def CorrectionFactor = Phase_Accumulation(price_WMA).CorrectionFactor;

    if BarNumber() <= 5
    then {
        Smooth = 0;
        Detrender = 0;

        Period = 0;
        Period_raw = 0;
        Period_cap = 0;
        Period_lim = 0;
        I1 = 0;
        Q1 = 0;
        I2 = 0;
        Q2 = 0;
        jI = 0;
        jQ = 0;
        I2_raw = 0;
        Q2_raw = 0;
        Re = 0;
        Im = 0;
        Re_raw = 0;
        Im_raw = 0;
        SmoothPeriod = 0;
        Phase = 0;
        DeltaPhase = 0;
        DeltaPhase_raw = 0;
        alpha = 0;
        alpha_raw = 0;
        vmama = 0;
        vfama = 0;
    } else {

# Smooth and detrend my smoothed signal:

        Smooth = WMA_Smooth(price_WMA);
        Detrender = ( 0.0962 * Smooth
+ 0.5769 * Smooth[2]
- 0.5769 * Smooth[4]
- 0.0962 * Smooth[6] ) * CorrectionFactor;

        Q1 = ( 0.0962 * Detrender
+ 0.5769 * Detrender[2]
- 0.5769 * Detrender[4]
- 0.0962 * Detrender[6] ) * CorrectionFactor;
        I1 = Detrender[3];

        jI = ( 0.0962 * I1
+ 0.5769 * I1[2]
- 0.5769 * I1[4]
- 0.0962 * I1[6] ) * CorrectionFactor;

        jQ = ( 0.0962 * Q1
+ 0.5769 * Q1[2]
- 0.5769 * Q1[4]
- 0.0962 * Q1[6] ) * CorrectionFactor;

# This is the complex conjugate

        I2_raw = I1 - jQ;
        Q2_raw = Q1 + jI;

        I2 = 0.2 * I2_raw + 0.8 * I2_raw[1];
        Q2 = 0.2 * Q2_raw + 0.8 * Q2_raw[1];

        Re_raw = I2 * I2[1] + Q2 * Q2[1];
        Im_raw = I2 * Q2[1] - Q2 * I2[1];

        Re = 0.2 * Re_raw + 0.8 * Re_raw[1];
        Im = 0.2 * Im_raw + 0.8 * Im_raw[1];

# Compute the phase

        if Re != 0 and Im != 0
        then {
            Period_raw = 2 * Double.Pi / ATan(Im / Re);
        } else {
            Period_raw = 0;
        }

        if Period_raw > 1.5 * Period_raw[1]
        then {
            Period_cap = 1.5 * Period_raw[1];
        } else if Period_raw < 0.67 * Period_raw[1] {
            Period_cap = 0.67 * Period_raw[1];
        } else {
            Period_cap = Period_raw;
        }

        if Period_cap < 6
        then {
            Period_lim = 6;
        } else if Period_cap > 50
        then {
            Period_lim = 50;
        } else {
            Period_lim = Period_cap;
        }

        Period = 0.2 * Period_lim + 0.8 * Period_lim[1];
        SmoothPeriod = 0.33 * Period + 0.67 * SmoothPeriod[1];

        if I1 != 0
        then {
            Phase = ATan(Q1 / I1);
        } else if Q1 > 0
        then { # Quadrant 1:
            Phase = Double.Pi / 2;
        } else if Q1 < 0
        then { # Quadrant 4:
            Phase = -Double.Pi / 2;
        } else { # Both numerator and denominator are 0.
            Phase = 0;
        }

        DeltaPhase_raw = Phase[1] - Phase;
        if DeltaPhase_raw < 1
        then {
            DeltaPhase = 1;
        } else {
            DeltaPhase = DeltaPhase_raw;
        }

        alpha_raw = FastLimit / DeltaPhase;
        if alpha_raw < SlowLimit
        then {
            alpha = SlowLimit;
        } else {
            alpha = alpha_raw;
        }
        vmama = alpha * price_WMA + (1 - alpha) * vmama[1];
        vfama = 0.5 * alpha * vmama + (1 - 0.5 * alpha) * vfama[1];}

    plot MAMA = vmama;
    plot FAMA = vfama;}

input price2 = hl2;
input FastLimit = 0.5;
input SlowLimit = 0.05;

def MAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).MAMA;
def FAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).FAMA;

def Crossing = Crosses((MAMA < FAMA), yes);
#Crossing.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

def Crossing1 = Crosses((MAMA > FAMA), yes);
#Crossing1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);

# --- C3 MAX --- LABELS ---

AddLabel(yes, Concat("MAMA: ", Concat("",
if MAMA > FAMA then "Bull" else "Bear")),
if MAMA > FAMA then Color.GREEN else Color.RED);

# --- C3 MAX --- C3 MF LINE ---

#plot C3_MF_Line = (MAMA + FAMA) / 2;
#C3_MF_Line.SetPaintingStrategy(PaintingStrategy.LINE);
#C3_MF_Line.SetLineWeight(3);
#C3_MF_Line.AssignValueColor(if Color_Candles and ((priceColor2 == 1) and (price1 > Upper_BandS) and (condition_BandRevDn)) then Color.YELLOW else if Color_Candles and ((priceColor2 == -1) and (price1 < Lower_BandS) and (condition_BandRevUp)) then Color.YELLOW else if Color_Candles and priceColor2 == -1 then Color.RED  else if Color_Candles and (priceColor2 == 1) then Color.GREEN else Color.CURRENT);

#def C3_MF_UP = C3_MF_Line > C3_MF_Line[1];
#def C3_MF_DN = C3_MF_Line < C3_MF_Line[1];
#def priceColor9 = if C3_MF_UP then 1
#                 else if C3_MF_DN then -1
#                 else priceColor9[1];

def MF_UP = FAMA < MAMA;
def MF_DN = FAMA > MAMA;
def priceColor10 = if MF_UP then 1
                 else if MF_DN then -1
                 else priceColor10[1];

input extension_length_limited_to = 10;
def lastbar = if IsNaN(close[-1]) and !IsNaN(close) then BarNumber() else Double.NaN;
#def inertline = InertiaAll(C3_MF_Line, 2);
#def EXT_C3_MF = if !IsNaN(close()) then inertline else EXT_C3_MF[1] + ((EXT_C3_MF[1] - EXT_C3_MF[2]) / (2 - 1));
#plot extension = if BarNumber() <= HighestAll(lastbar) + extension_length_limited_to then EXT_C3_MF else Double.NaN;
#extension.SetDefaultColor(Color.WHITE);
####################################################################################################################################################

#EMA_Candles
#Created by Christopher84 11/30/2021

input showBreakoutSignals = no;
input length8 = 10;
input length9 = 35;
input show_ema_cloud = yes;

plot AvgExp8 = ExpAverage(price[-displace], length8);

def UPD = AvgExp8[1] < AvgExp8;
AvgExp8.SetStyle(Curve.SHORT_DASH);

plot AvgExp9 = ExpAverage(price[-displace], length9);

def UPW = AvgExp9[1] < AvgExp9;
AvgExp9.SetStyle(Curve.short_dash);
def Below = AvgExp8 < AvgExp9;
def Spark = UPD + UPW + Below;
def UPEMA = AvgExp8[1] < AvgExp8;
def DOWNEMA = AvgExp8[1] > AvgExp8;
AvgExp8.AssignValueColor(if UPEMA then Color.LIGHT_GREEN else if DOWNEMA then Color.RED else Color.YELLOW);
def UPEMA2 = AvgExp9[1] < AvgExp9;
def DOWNEMA2 = AvgExp9[1] > AvgExp9;
AvgExp9.AssignValueColor(if UPEMA2 then Color.LIGHT_GREEN else if DOWNEMA2 then Color.RED else Color.YELLOW);

AddCloud(if show_ema_cloud and (AvgExp9 > AvgExp8) then AvgExp9 else Double.NaN, AvgExp8, Color.light_RED, Color.CURRENT);
AddCloud(if show_ema_cloud and (AvgExp8 > AvgExp9) then AvgExp8 else Double.NaN, AvgExp9, Color.light_GREEN, Color.CURRENT);

def UP8 = UPEMA and UPEMA2;
def DOWN8 = DOWNEMA and DOWNEMA2;
def priceColor8 = if UP8 then 1
                 else if DOWN8 then -1
                 else 0;

def UP11 = UPEMA;
def DOWN11 = DOWNEMA;
def priceColor11 = if UP11 then 1
                 else if DOWN11 then -1
                 else 0;
def UP12 = UPEMA2;
def DOWN12 = DOWNEMA2;
def priceColor12 = if UP12 then 1
                 else if DOWN12 then -1
                 else 0;

def UpCalc =  (priceColor == 1) + (priceColor2 == 1) + (priceColor8 == 1) + (priceColor10 == 1);
def StrongUpCalc =  (priceColor == 1) + (priceColor2 == 1)  + (priceColor10 == 1) + (priceColor12 == 1);# + (priceColor12 == 1);
def CandleColor = if (priceColor2 == 1) and (Spark >= 2) then 1
                 else if (priceColor2 == -1) and (Spark < 2) then -1
                 #else if ((PriceColor8[2] == 1) and (PriceColor8 == 1)) then 1
                 #else if ((PriceColor8[2] == -1) and (PriceColor8 == -1))then -1
                 #else if (priceColor2 == 1) then 1
                 #else if (priceColor2 == -1) then -1
                 else 0;
#AssignPriceColor(if Color_Candles and (CandleColor == 1) then Color.GREEN else if Color_Candles and (CandleColor == -1) then Color.RED else Color.GRAY);
plot SparkUP = (Spark == 3) and (CandleColor == 1);
SparkUP.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
SparkUP.AssignValueColor(Color.LIGHT_GREEN);
plot SparkDN = (Spark == 0) and (CandleColor == -1);
SparkDN.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
SparkDN.AssignValueColor(Color.RED);

#--- CONFIRMATION LEVELS --- PLOT ---

plot NearTResistance = Highest(price, BulgeLengthPrice2);
NearTResistance.AssignValueColor(if (conditionK2) then Color.GREEN else if (conditionK3) then Color.RED else Color.GRAY);
NearTResistance.SetStyle(Curve.SHORT_DASH);
plot NearTSupport = Lowest(price, SqueezeLengthPrice2);
NearTSupport.AssignValueColor(if (conditionK2) then Color.GREEN else if (conditionK3) then Color.RED else Color.GRAY);
NearTSupport.SetStyle(Curve.SHORT_DASH);

#--- CONFIRMATION LEVELS --- DEF ---

def Buy = UP_OS;
def Sell = DOWN_OB;
def conditionLTB = (conditionK2UP and (Consensus_Level < 0));
def conditionLTS = (conditionK3DN and (Consensus_Level > 0));
def conditionBO = ((Upper_BandS[1] < Upper_BandS) and (Lower_BandS[1] < Lower_BandS)) and ((Upper_BandK[1] < Upper_BandK) and (Lower_BandK[1] < Lower_BandK));
def conditionBD = ((Upper_BandS[1] > Upper_BandS) and (Lower_BandS[1] > Lower_BandS) and (Upper_BandK[1] > Upper_BandK) and (Lower_BandK[1] > Lower_BandK));
def MomentumUP = Consensus_Level[1] < Consensus_Level;
def MomentumDOWN = Consensus_Level[1] > Consensus_Level;
def Squeeze_Signal = !IsNaN(Squeeze_Alert);
def conditionOB = (Consensus_Level >= 12) and (Consensus_Line >= 4);
def conditionOS = (Consensus_Level <= -12) and (Consensus_Line <= -3);

AddLabel(yes, if conditionLTB then "BULLISH LTB" else if conditionLTS then "BEARISH LTS" else if conditionK2UP then "TREND_BULLISH" else if conditionK3DN then "TREND_BEARISH" else "TREND_CONSOLIDATION", if conditionLTB then Color.GREEN else if conditionLTS then Color.RED else if conditionK2UP then Color.WHITE else if conditionK3DN then Color.DARK_GRAY else Color.GRAY);
AddLabel(yes, if conditionBD then "BREAKDOWN" else if conditionBO then "BREAKOUT" else "NO_BREAK", if conditionBD then Color.RED else if conditionBO then Color.GREEN else Color.GRAY);
AddLabel(yes, if (Spark == 3) then "SPARK UP = " + Round(Spark, 1) else if (Spark == 0) then  "SPARK DOWN = " + Round(Spark, 1) else "SPARK = " + Round(Spark, 1), if (Spark == 3) then Color.YELLOW else if (Spark == 2) then Color.GREEN else if (Spark == 0) then Color.RED else Color.GRAY);
AddLabel(yes, "SQUEEZE ALERT", if Squeeze_Signal then Color.YELLOW else Color.GRAY);
AddLabel(yes, if MomentumUP then "Consensus_Increasing = " + Round(Consensus_Level, 1) else if MomentumUP or MomentumDOWN and conditionOB then "Consensus_OVERBOUGHT = " + Round(Consensus_Level, 1) else if MomentumDOWN then  "Consensus_Decreasing = " + Round(Consensus_Level, 1) else if MomentumUP or MomentumDOWN and conditionOS then "Consensus_OVERSOLD = " + Round(Consensus_Level, 1) else "Consensus = " + Round(Consensus_Level, 1), if conditionOB then Color.RED else if conditionOS then Color.GREEN else Color.GRAY);

# --- VERTICLE LINE DAILY ---

AddVerticalLine(( GetDay() <> GetDay()[1]), "", Color.DARK_GRAY, Curve.SHORT_DASH);

#--- END ---
 
Last edited by a moderator:
@HODL-Lay-HE-hoo! Here is some positive feedback on this strategy. I have been using Hamiltonian Monte Carlo for back-testing over the past few days. C3_Max_Spark worked surprisingly well on SPY Weekly options. I bought it at the first Buy signal at market open, sold it the next day and the Weeklys quadrupled in value with less than 8% drawdown. It's exceptional!

O2awl6B.png
 
Last edited:
@quantum My goodness sir. Great to hear!

Questions:
  1. Do you have “Show higher ag” set to yes or no? (In settings)
  2. Are you using a hard stop or are you extremely disciplined to cut your losses like an emotionless robot? (or was it paper?)
  3. Through what means are you executing Hamiltonian Monte Carlo backtesting??
 
Last edited:
@quantum My goodness sir. Great to hear!

Questions:
  1. Do you have “Show higher ag” set to yes or no? (In settings)
  2. Are you using a hard stop or are you extremely disciplined to cut your losses like an emotionless robot? (or was it paper?)
  3. Through what means are you executing Hamiltonian Monte Carlo backtesting??

@HODL-Lay-HE-hoo!

1. Higher ag is set to yes
2. I use trailing stop loss to exit the trades
[My risk management is overkill honestly, but I do it anyway because I learned my lesson the very very very hard way :)
--> First, I use HMC to calculate equity curves, max drawdowns and sortino ratios.
--> Then, I combine it with VIX and GEX to approximate my position sizing and risk to reward ratios
--> Finally, I use an approximate HMC-factor x ATR in my trailing stop loss to ride the trend and exit when stop loss gets hit]
3. I use MATLAB for HMC computations
 
Status
Not open for further replies.

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
194 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