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

Status
Not open for further replies.
I highly appreciate taking the time to make this! I was wondering what the arrows and their corresponding colors mean in the EMAD lower study?

Awesome stuff!
No problem, The white arrows are meant to be higher lows and lower highs... however.... seeing as the EMAD EMAs and cross ten ways from Sunday within a short period of time it made for too many inaccurate signals when defined as the following:

HL = (EMA > Zeroline) and (EMA Cross down) and (EMA is not crossing down while touching the Top band)
LH = (EMA < Zeroline) and (EMA Cross Up) and (EMA is not crossing Up while touching the Bottom band)

Therefore I added another moving average which attempts to locate HL and LH (the line that has a cloud and turns green red or gray)... long story short when the "MADE" moving average (dont ask me why I called it that I have no idea) crosses the EMAD EMAs an arrow plots....

The cyan arrows are the same thing but I added a condition to color it cyan when "Alert4" (from Vix Fix) is true (only use it for up signals)

To be honest I dont really care about all the arrows on EMAD because I know what I am looking for and can do so better than what I just explained (which is simply the EMAD Entry Method on page 1)

You will notice in settings there are two more arrows "First HL" "Second HL" and the same for LH which was an attempt to filter out false signals by a good Samaritan a while back... the code is still used I just dont use the arrows.

Hope that clears up some confusion.
 

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

No problem, The white arrows are meant to be higher lows and lower highs... however.... seeing as the EMAD EMAs and cross ten ways from Sunday within a short period of time it made for too many inaccurate signals when defined as the following:

HL = (EMA > Zeroline) and (EMA Cross down) and (EMA is not crossing down while touching the Top band)
LH = (EMA < Zeroline) and (EMA Cross Up) and (EMA is not crossing Up while touching the Bottom band)

Therefore I added another moving average which attempts to locate HL and LH (the line that has a cloud and turns green red or gray)... long story short when the "MADE" moving average (dont ask me why I called it that I have no idea) crosses the EMAD EMAs an arrow plots....

The cyan arrows are the same thing but I added a condition to color it cyan when "Alert4" (from Vix Fix) is true (only use it for up signals)

To be honest I dont really care about all the arrows on EMAD because I know what I am looking for and can do so better than what I just explained (which is simply the EMAD Entry Method on page 1)

You will notice in settings there are two more arrows "First HL" "Second HL" and the same for LH which was an attempt to filter out false signals by a good Samaritan a while back... the code is still used I just dont use the arrows.

Hope that clears up some confusion.

Thanks! I'm still studying the method and the screenshots to get an understanding of how to read the EMAD lower study. Takes some getting used to, to wrap my head around it. I was just noticing the arrows did indeed happen at some of the HL and LH points. Wanted to clear that up.
 
@HODL-Lay-HE-hoo! Is it possible for the c3 zone to paint properly on a tick chart? or is that just a ToS oopsie that can't be fixed?
Because tick/renko/range charts have no concept of time and because there are some time references in this script; it is unlikely that you will be able to get the C3 to display correctly on a tick chart.

If you are having issues with other studies on your tick charts, please note that some members have had some success with fixing tick chart display by enabling extended hours.
 
Good people...

Here is the long awaited... highly anticipated... (possibly useless)... C3 BIG MAX Consensus Histogram (Lower)

There are (at this time) 43 up and down conditions including the 14 C3 consensus conditions and the 6 (or 7) C3 OB/OS conditions... plus the BIG 4 conditions, EMAD condtions, Ehlers crossovers, Market phases, etc.

The Zeroline is currently set to change from green to red based on the average amount of up signals being greater or less that down signals at the user input length.

* Added input to adjust the high and low limits and points when crossed*


study: https://tos.mx/UENGBNM (Link updated)

f7jgDtc.png


L3fblEZ.png


bP20Dnj.png


(I need to do housekeeping on the code fyi)

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

declare lower;

#####################################################
##                                                 ##
#####################################################
input High_Limit = 33;
input Low_Limit = -33;
input Average_Length = 21;
def X_Signal_Bars = 5; #hint Signals within x bars = true
input showbubbles = no;
input Color_EMAD_Candles = no;
input TradeDaytimeOnly = no; #hint tradeDaytimeOnly: (IntraDay Only) Only perform trades during hours stated
input OpenTime = 0730; #hint OpenTime: Opening time of market hides arrows
input CloseTime = 1800; #hint CloseTime: Closing time of market hides arrows
input Ehlers_Avg_Length = 9;
input Ehlers_Length = 34;
input ATR_Period_TSV9 = 11;
input ATR_Factor_TSV9 = 2.2;
input Filter_OG_Signals = {EMAD_Filter, Phase_Filter, default No_Filter};
input FirstTrade_Squeeze = {default long, short};
input TrailType = {default modified, unmodified};
input FirstTrade = {default long, short};
input MACD_AverageType = {SMA, default EMA};
input DMI_averageType = AverageType.WILDERS;
input AvgType = AverageType.HULL;
input AverageType_BB = AverageType.SIMPLE;
input type_HV = { default SMP, EXP };
input Candle = {default "wick" , "body" , "close"}; #hint when this part of the candle crosses the POBOS lines (for arrow)
########################################################
## 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));
########################################################
## HEIKIN ASHI                                        ##
########################################################
def Zone_Span = .5;
def Use_Clouds_Before_Filter = no; #hint Effects "combined signals" the violet arrows
def CVD_Length_avg = 9;
def Flat_Earth_Bars = 10;
def Flat_Earth_Controller = 10;
def Above_X_Levels = 5;
def Below_X_Levels = 1;
def BG_Bars = 5;
def Color_HIZ_Candles = no;
def Color_HIZ_Candles2 = no;
def hiz_Length = 9;
def Color_Ehlers_Candles = no;
def Show_HLLH_Color = yes;
def X_Upcolor1_Bars  = 5;
def Clouds_before = 5;
def X_Green_Clouds = 1;
def X_Red_Clouds = 1;
def hidecloud = no;
def Show_CVD_Cloud = yes;
def Show_EMAD_Cloud = yes;
def Show_Phase_Cloud = yes;
def X_Signal_Bars_2 = 3; #hint Signals within x bars = true
def Show_Signal_Bubbles = no;
def Signal_UP_Agreement = 1; #hint Agreement: if greater than this number of signals are true within x bars
def Signal_DOWN_Agreement = 1; #hint Agreement: if greater than this number of signals are true within x bars;
def Show_C3_Labels = yes;
def Show_OG_Filter_label = no;
def Show_Combined_Filter_label = no;
def Show_Combined_Signals = yes;
def Show_Alert4_Signals = no;
def Show_EMAD_Signals = no;
def Show_EMAD_HLLH_Signals = no;
def Show_Triple_Exh_Signals = no;
def Show_TS_Signals = no;
def Show_Spark_Signals = no;
def Show_Big4_Signals = no;
def X_Keylevel_Bars = 10; #hint Signals within x bars = true
def bn = barnumber();
def AllAvgINC_Length = 5;
def Low_Volume = 5;
def lengthVolAvgPlotselling = 9;
def lengthVolAvgPlotbuying = 9;
def Crossed_Consensus_UP = 6;
def Crossed_Consensus_DOWN = -6;
def Show_C3_Levels = no;
def Buy_Sell_Avg_Length = 20;
def OBOS_Compression = 0.2;
def EMAD_Zero_Compression = 0.1;
def X_InKey_Bars = 5;
def X_Zone_bars = 5;
def X_Zone_Cloud_Bars = 10;
def X_Alert4_Bars = 10; #hint Signals within x bars = true
def Length_HV = 20;
def Hot_Percent_HV = 110.0; #hint total volume of bar greater than hotpct = cyan triangle
def Big4_Confirmation_Factor = 4; #hint Big4
def EMAD_Cloud_Lookback = 100;
def Hide_Consecutive = yes; #hint Combined Signals: Hidden if within 5 bars of signals in the same direction
def Compression_Span_Low = 1;
def Zone_Average_length = 21;
def Zone_Percent_Diff = .5;
########################################################
##                                                    ##
########################################################
def haClose = (open + high + low + close) / 4;
def haOpen = if IsNaN(haOpen[1]) then (open + close) / 2 else (haOpen[1] + haClose[1]) / 2;
def haHigh = Max(high, Max(haClose, haOpen));
def haLow = Min(low, Min(haClose, haOpen));
########################################################
## HA WICK, BODY, CLOSE OF CANDLE FOR BREAKOUTS       ##
########################################################
def High_Levels;
def Low_Levels;
switch (Candle) {
case "wick":
    High_Levels = haHigh;
    Low_Levels = haLow;
case "body":
    High_Levels = Max(haOpen, haClose);
    Low_Levels = Min(haOpen, haClose);
case "close":
    High_Levels = haClose;
    Low_Levels = haClose;
}
#// This source code is subject to the terms of the Mozilla Public License 2.0 at #https://mozilla.org/MPL/2.0/
#// © blackcat1402
#https://www.tradingview.com/script/bhdaBHlg-blackcat-L2-KDJ-with-Whale-Pump-and-Oust/
#study("[blackcat] L2 KDJ with Whale Pump and Oust"
# Converted by Sam4Cok@Samer800 - 08/2022

#//inputs
input ShowBubble     = yes;
input ShowBubble2    = no;

input ShowHistogram  = yes;
input BuyAlertLimit  = 0;   # "BuyAlertLimit"
input SellAlertLimit =100; # "SellAlertLimit"
input Period = 18;
input SignalK = 4;
input SignalD = 4;

#//functions
def na2 = Double.NaN;
script nz {
    input data  = 1;
    input repl  = 0;
    def ret_val = if IsNaN(data) then repl else data;
    plot return = ret_val;
}
#xrf(values, length) =>
script xrf {
    input values = close;
    input length = 0;
    def r_val;
    r_val = if length >= 1 then
        fold i = 0 to length
            with p do
            if IsNaN(r_val[1]) or !IsNaN(values[i]) then values[i] else r_val[1] else Double.NaN;
    plot return =  r_val;
}
#xsa(src,len,wei) =>
script xsa {
    input src = close;
    input len = 0;
    input wei = 0;
    def sumf;
    def ma;
    def out;
    sumf =  nz(sumf[1]) - nz(src[len]) + src;
    ma   =  if IsNaN(src[len]) then Double.NaN else sumf / len;
    out  =  if IsNaN(out[1]) then ma else (src * wei + out[1] * (len - wei)) / len;
    plot return = out;
}
#alma(series, length, offset, sigma, floor)
script ALMA {
input series = close;
input windowsize = 9;
input Offset = 0.85;
input Sigma = 6;
def m = Offset * (windowsize - 1);
def s = windowsize/Sigma;
def Sum = fold i = 0 to windowsize with WS do
           WS + Exp(-1 * (sqr(i-m))/(2*sqr(s))) * getValue(series, windowsize - i - 1);
def norm = fold j = 0 to windowsize with CW do
           CW + Exp(-1 * (sqr(j-m))/(2*sqr(s)));
plot ALMA = sum / norm;
}
#//algorithm for whale pump an oust-----
    def var1 = xrf(ohlc4,1)[1];
    def var2 = xsa(AbsValue(low - var1), 13, 1) / xsa(Max(low - var1, 0), 10, 1);
    def var3 = ExpAverage(var2, 10);
    def var4 = Lowest(low, 33);
    def var5 = ExpAverage(If(low <= var4, var3, 0), 3);

#//define KDJ
def rsv = (close-lowest(low,Period))/(highest(high,Period)-lowest(low,Period))*100;
def k2 = alma(xsa(rsv,SignalK,1),3,0.85,6);
def d = alma(xsa(k2,SignalD,1),3,0.85,6);
def j = alma(3*k2-2*d,3, 0.85,6);

########
#// plot signal
#    plot kLine = k2;
#    kLine.SetDefaultColor(Color.WHITE);
#    plot dLine = d;
#    dLine.SetDefaultColor(Color.ORANGE);
#    plot jLine = j;
#    jLine.AssignValueColor( CreateColor(17, 118, 242));
#    jLine.SetLineWeight(2);

def KJD_Cross_Down = (d > k2) and (k2 > j);
def KJD_Down = KJD_Cross_Down[1] and  KJD_Cross_Down[2] and  KJD_Cross_Down[3] and KJD_Cross_Down;
def KJD_Cross_Up = (d < k2) and (k2 < j);
def KJD_Up = KJD_Cross_Up[1] and KJD_Cross_Up[2] and KJD_Cross_Up[3] and KJD_Cross_Up;

#//plot whale buy histograms

    def bgcolor = if j crosses above BuyAlertLimit then 1 else
                  if j crosses below SellAlertLimit then -1 else 0;

def BGcolor_UP = if j crosses above BuyAlertLimit then 1 else 0;
def BGcolor_DN =  if j crosses below SellAlertLimit then 1 else 0;
def BGcolor_UP_bn = if BGcolor_UP then bn else BGcolor_UP_bn[1];
def BGcolor_DN_bn = if BGcolor_DN then bn else BGcolor_DN_bn[1];
def BGcolor_Last = BGcolor_UP_bn > BGcolor_DN_bn;
#//whale pump candles
#    plot OustHist = var5;
#    OustHist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
#    OustHist.SetHiding(!ShowHistogram);
#    OustHist.AssignValueColor(if var5 > var5[1] then CreateColor(38,166,154) else
#                          if var5 < var5[1] then Color.PINK else Color.GRAY);
#//Add Bubble
def plothighz = if (j crosses above BuyAlertLimit) then halow else if (j crosses below SellAlertLimit) then hahigh else plothighz[1];
def hiz = plothighz;

def plothighz2 = average(plothighz, hiz_Length);
def hiz2 = plothighz2;

#//define bottom zone threshold values
def h1 = 99;
def h2 = 2;
def h3 = 0;
def h4 = 100;
#AddCloud(h2, h3, Color.DARK_GREEN, Color.DARK_GREEN, yes);
#AddCloud(h1, h4, CreateColor(255, 102, 255),  CreateColor(255, 102, 255), yes);

########################################################
##                                                    ##
########################################################
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;
def LongTrades = yes; #hint LongTrades: perform long
def ShortTrades = yes; #hint ShortTrades: perform short trades
def useStops = no;     #hint useStops: use stop orders
def useAlerts = no;    #hint useAlerts: use alerts on signals
#####################################################
## FIRST BAR                                       ##
#####################################################
def lastbar = HighestAll(if IsNaN(close[-1]) then bn else 0);
def Firstbar = SecondsFromTime(OpenTime)[1] < 0 and SecondsFromTime(OpenTime) >= 0;
def FirstBar_number = if Firstbar then bn else FirstBar_number[1];
def Bars_From_First = bn - FirstBar_number;
def Within_Range = Bars_From_First < EMAD_Cloud_Lookback;
#####################################################
## HORSERIDER VOLUME                               ##
#####################################################
def buying = volume * (close - low) / (high - low);
def selling = volume * (high - close) / (high - low);
def MA = if type_HV == type_HV.SMP then SimpleMovingAvg(volume, Length_HV) else MovAvgExponential(volume, Length_HV);
def HV = if (100 * ((volume / MA) - 1) >= Hot_Percent_HV) then 1 else 0;
def VolAvg1 = Average(volume, Buy_Sell_Avg_Length);
def VolAvgsell1 = Average(selling, Buy_Sell_Avg_Length);
def VolAvgbuy1 = Average(buying, Buy_Sell_Avg_Length);
def sellgoingup = VolAvgsell1 > VolAvgsell1[1];
def buygoingup = VolAvgbuy1 > VolAvgbuy1[1];
def Avggoingup = VolAvg1 > VolAvg1[1];
def selling_low = selling < Low_Volume;
def buying_low = buying < Low_Volume;
def Buy_Up_Sell_Up = sellgoingup and buygoingup;
def Buy_Up_Sell_Down = !sellgoingup and buygoingup;
def Buy_Down_Sell_Down = !sellgoingup and !buygoingup;
def Sell_Up_Buy_Down = sellgoingup and !buygoingup;
def sell_Abv_Avg =  VolAvgsell1 > VolAvg1;
def Buy_Abv_Avg =  VolAvgbuy1 > VolAvg1;
def bothup = sellgoingup and buygoingup;
def Volume_BiasBull = (VolAvgsell1 >= VolAvgbuy1);
def Volume_BiasBear = (VolAvgsell1 < VolAvgbuy1);
def Volume_Crossover_Bull = Volume_BiasBull and !Volume_BiasBull[1];
def Volume_Crossover_Bear = Volume_BiasBull and !Volume_BiasBull[1];
def sell_below_Avg =  VolAvgsell1 < VolAvg1;
def Buy_below_Avg =  VolAvgbuy1 < VolAvg1;
def buy_avg_above_sell = VolAvgbuy1 > VolAvgsell1;
def Sell_avg_above_buy = VolAvgsell1 > VolAvgbuy1;
def Buy_crosses_sell_avg = !buy_avg_above_sell[1] and buy_avg_above_sell;
def Buy_crosses_sell_avg_Down = buy_avg_above_sell[1] and !buy_avg_above_sell;
def Sell_crosses_buy_avg = !Sell_avg_above_buy[1] and Sell_avg_above_buy;
def Sell_crosses_buy_avg_Down = Sell_avg_above_buy[1] and !Sell_avg_above_buy;
def Buy_crosses_avg = !Buy_Abv_Avg[1] and Buy_Abv_Avg;
def Buy_crosses_avg_Down = Buy_Abv_Avg[1] and !Buy_Abv_Avg;
def Sell_crosses_avg = !sell_Abv_Avg[1] and sell_Abv_Avg;
def Sell_crosses_avg_Down = sell_Abv_Avg[1] and !sell_Abv_Avg;
def Selling_Then_Buying = (selling[1] > VolAvg1[1]) and (Buying > VolAvg1);
def Buying_Then_Selling = (Buying[1] > VolAvg1[1]) and (selling > VolAvg1);
def Bull_Volume_Inc_Avg = Selling_Then_Buying and Avggoingup;
def Bear_Volume_Inc_Avg = Buying_Then_Selling and Avggoingup;
#####################################################
## UPPER EMA                                       ##
#####################################################
def Cloud_Lookback = 20;
def HL_LH_Lookback = 20;
def Previous_Steps_Down = 2; #hint filter for hiding arrows
def Previous_Steps_Up = 2; #hint filter for hiding arrows
def Length_MAD = 4;
def Band_Length = 100;
def Smooth_Length = 12;
def Smooth_Length_2 = 14;
def Fast_Length = 10;
def Slow_Length = 35;
def Made_Avg_Length = 3;
def ATR_Period_Squeeze = 5;
def ATR_Factor_Squeeze = 2.0;
def Length_3x = 1000;
def AverageType = AverageType.WILDERS;
def AverageType_Squeeze = AverageType.SIMPLE;
def EMAD_EMA_lineweight = 2;
def Step_lookback = 10;
def FastExpAvg = ExpAverage(close, Fast_Length);
def SlowExpAvg = ExpAverage(close, Slow_Length);
def EMAD_Fast = (close - FastExpAvg);
def EMAD_Slow = (close - SlowExpAvg);
def EMAD_Avg = (EMAD_Fast + EMAD_Slow) / 2;
#####################################################
## UPPER EMA                                       ##
#####################################################
def Upper_EMAD_EMA = ExpAverage(EMAD_Avg, Smooth_Length);
def EMAD_Open = (Upper_EMAD_EMA + Upper_EMAD_EMA[1]) / 2;
def EMAD_High = Max(Upper_EMAD_EMA, Upper_EMAD_EMA[1]);
def EMAD_Low = Min(Upper_EMAD_EMA, Upper_EMAD_EMA[1]);
def EMAD_Close = Upper_EMAD_EMA;
def Bottom = Min(EMAD_Close[1], EMAD_Low);
def TR = TrueRange(EMAD_High, EMAD_Close, EMAD_Low);
def PTR = TR / (Bottom + TR / 2);
def APTR = MovingAverage(AverageType, PTR, Smooth_Length_2);
def UpperBand = EMAD_Close[1] + (APTR * EMAD_Open);
def LowerBand = EMAD_Close[1] - (APTR * EMAD_Open);
#####################################################
## LOWER EMA                                       ##
#####################################################
def Lower_EMAD_EMA = (UpperBand + LowerBand) / 2;
#####################################################
## TOP BAND                                        ##
#####################################################
def TopBand = Highest(Lower_EMAD_EMA, Band_Length);
#####################################################
## BOTTOM BAND                                     ##
#####################################################
def BottomBand = Lowest(Lower_EMAD_EMA, Band_Length);
#####################################################
## ZERO LINE                                       ##
#####################################################
def ZeroLineData = if IsNaN(close) then Double.NaN else 0;
def EMAD_Above_Zero = Upper_EMAD_EMA > ZeroLineData;
def EMAD_Below_Zero = Upper_EMAD_EMA < ZeroLineData;
def EMAD_Above_Zero_1 = if EMAD_Above_Zero then 1 else 0;
def EMAD_Below_Zero_1 = if EMAD_Below_Zero then 1 else 0;
def EMAD_EMA_down = (Lower_EMAD_EMA > Upper_EMAD_EMA);
def EMAD_EMA_up = (Upper_EMAD_EMA >= Lower_EMAD_EMA);
#####################################################
## MASTER EMA                                      ##
#####################################################
def Master_EMAD_EMA = (Upper_EMAD_EMA + Lower_EMAD_EMA) / 2;
def TopBand_StepDown = if TopBand < TopBand[1] then 1 else 0;
def TopBand_StepUp = if TopBand > TopBand[1] then 1 else 0;
def BottomBand_StepDown = if BottomBand < BottomBand[1] then 1 else 0;
def BottomBand_StepUp = if BottomBand > BottomBand[1] then 1 else 0;
def BothBands_Down = BottomBand_StepDown and TopBand_StepDown;
def BothBands_Up = BottomBand_StepUp and TopBand_StepUp;
def BottomBand_Above_Zero = (BottomBand > ZeroLineData);
def TopBand_below_Zero = (TopBand < ZeroLineData);
def TopBand_PushUp =  Master_EMAD_EMA >= TopBand;
def BottomBand_PushDown = Master_EMAD_EMA <= BottomBand;
def MidBand = (UpperBand + LowerBand) / 2;
def EMA_CrossUp = if (midBand[1] > Upper_EMAD_EMA[1]) and (midBand < Upper_EMAD_EMA) then 1 else 0;
def EMA_CrossUp_bn = if EMA_CrossUp then bn else EMA_CrossUp_bn[1];
def EMA_CrossDown = if (Upper_EMAD_EMA[1] > midBand[1]) and (Upper_EMAD_EMA < midBand) then 1 else 0;
def EMA_CrossDown_bn = if EMA_CrossDown then bn else EMA_CrossDown_bn[1];
def EMA_Last_Cross = EMA_CrossUp_bn > EMA_CrossDown_bn;
#####################################################
## VALUE                                           ##
#####################################################
def Value_At_CrossUp = if EMA_CrossUp then midBand else Value_At_CrossUp[1];
def Value_At_CrossDown = if EMA_CrossDown then midBand else Value_At_CrossDown[1];
#####################################################
## CROSS AT BAND                                   ##
#####################################################
def CrossUp_BottomBand = if (Value_At_CrossUp - bottomBand) == 0 then 1 else 0;
def CrossDown_TopBand = if (Value_At_CrossDown - topBand) == 0 then 1 else 0;
def CrossUp_BottomBand_1 =  !CrossUp_BottomBand[1] and CrossUp_BottomBand;
def CrossDown_TopBand_1 = !CrossDown_TopBand[1] and CrossDown_TopBand;
def CrossUp_BottomBand_1_bn = if CrossUp_Bottomband_1 then bn else CrossUp_Bottomband_1_bn[1];
def CrossDown_TopBand_1_bn = if CrossDown_topband_1 then bn else CrossDown_TopBand_1_bn[1];
#####################################################
## CROSS AT ZERO                                   ##
#####################################################
def CrossUp_Zeroline = if (Value_At_CrossUp) == 0 then 1 else 0;#THIS IS NOT GOOD FIX IT
def CrossDown_Zeroline = if (Value_At_CrossDown) == 0 then 1 else 0;
def Band_Crossed_First = CrossUp_Bottomband_1_bn > CrossDown_TopBand_1_bn;
#####################################################
## TEST CONDITIONS                                 ##
#####################################################
def CrossUp_BottomBand_Midband = if CrossUp_BottomBand_1 then round(absvalue(midBand),2) else CrossUp_BottomBand_Midband[1];
def CrossDOWN_TopBand_Midband = if CrossDOWN_TopBand_1 then round(absvalue(midBand),2) else CrossDOWN_TopBand_Midband[1];
def UP_Condition_HL = (Marketopen and EMAD_Below_Zero and EMA_CrossUp and !CrossUp_BottomBand_1);
def UP_Condition_HL_bn = if UP_Condition_HL then bn else UP_Condition_HL_bn[1];
def UP_Condition_HL_Midband = if UP_Condition_HL then round(absvalue(midBand),2) else UP_Condition_HL_Midband[1];
def UP_Condition_HL_2 = UP_Condition_HL and (UP_Condition_HL_bn > CrossUp_BottomBand_1_bn);
def UP_Condition_Is_HL = UP_Condition_HL and (UP_Condition_HL_Midband < UP_Condition_HL_Midband[1]);
def UP_Condition_4 = UP_Condition_HL_Midband < CrossUp_BottomBand_Midband[1];
def UP_Condition_4_1 = !UP_Condition_4[1] and UP_Condition_4;
def DOWN_Condition_LH = (Marketopen and EMAD_Above_Zero and EMA_CrossDOWN and !CrossDOWN_TopBand_1);
def DOWN_Condition_LH_bn = if DOWN_Condition_LH then bn else DOWN_Condition_LH_bn[1];
def DOWN_Condition_LH_Midband = if DOWN_Condition_LH then round(absvalue(midBand),2) else DOWN_Condition_LH_Midband[1];
def DOWN_Condition_LH_2 = DOWN_Condition_LH and (DOWN_Condition_LH_bn > CrossDOWN_TopBand_1_bn);
def DOWN_Condition_Is_LH = DOWN_Condition_LH and (DOWN_Condition_LH_Midband < DOWN_Condition_LH_Midband[1]);
def DOWN_Condition_4 = DOWN_Condition_LH_Midband < CrossDOWN_TopBand_Midband[1];
def DOWN_Condition_4_1 = !DOWN_Condition_4[1] and DOWN_Condition_4;
input EMAD_HL_LH_Sum_Length = 120;
def UPHL = UP_Condition_Is_HL and UP_Condition_4 ;
def DOWNLH = DOWN_Condition_Is_LH and DOWN_Condition_4;
def totalHL = sum(UPHL, EMAD_HL_LH_Sum_Length);
def totalLH = sum(DownLH, EMAD_HL_LH_Sum_Length);
def EMAD_Controller = totalHL > totalLH;
#####################################################
##                                                 ##
#####################################################
def Topband_Compression = absvalue(topband) < EMAD_Zero_Compression;
def Bottomband_Compression = absvalue(bottomband) < EMAD_Zero_Compression;
#####################################################
## EMAD CLOUD CONDITIONS                           ##
#####################################################
def EMAD_Green_Cloud_1 = if TopBand_StepUp and TopBand_PushUp and !TopBand_below_Zero then 1 else 0;
def EMAD_Green_Cloud_2 = if BottomBand_StepUp and EMAD_EMA_up and !EMAD_Below_Zero then 1 else 0;
def EMAD_Green_Cloud_3 = if (EMAD_Green_Cloud_1 or EMAD_Green_Cloud_2) then 1 else 0;
def EMAD_Red_Cloud_1 = if BottomBand_StepDown and BottomBand_PushDown and !BottomBand_Above_Zero then 1 else 0;
def EMAD_Red_Cloud_2 = if TopBand_StepDown and EMAD_EMA_down and !EMAD_Above_Zero then 1 else 0;
def EMAD_Red_Cloud_3 = if (EMAD_Red_Cloud_1 or EMAD_Red_Cloud_2) then 1 else 0;
def EMAD_Gray_Cloud_1 = if BottomBand_Above_Zero and !TopBand_PushUp then 1 else 0;
def EMAD_Gray_Cloud_2 = if TopBand_below_Zero and !BottomBand_PushDown then 1 else 0;
#####################################################
## TEST CONDITIONS FOR LEVELS                      ##
#####################################################
def EMAD_Green_Cloud_4 = if MarketOpen and EMAD_EMA_up and (!EMAD_Green_Cloud_3[1] and EMAD_Green_Cloud_3) then 1 else 0;
def EMAD_Red_Cloud_4 = if MarketOpen and EMAD_EMA_down and (!EMAD_Red_Cloud_3[1] and EMAD_Red_Cloud_3) then 1 else 0;
#####################################################
## TEST CONDITIONS FOR LEVELS                      ##
#####################################################
def EMAD_Green_Cloud_4_bn = if EMAD_Green_Cloud_4 then bn else EMAD_Green_Cloud_4_bn[1];
def EMAD_Red_Cloud_4_bn = if EMAD_Red_Cloud_4 then bn else EMAD_Red_Cloud_4_bn[1];
def cloudgreenbarsback = bn - EMAD_Green_Cloud_4_bn;
def cloudredbarsback = bn - EMAD_Red_Cloud_4_bn;
#####################################################
## LAST CLOUD COLOR                                ##
#####################################################
def Last_Cloud = if (cloudredbarsback > cloudgreenbarsback) then 1 else if  (cloudredbarsback < cloudgreenbarsback) then -1 else 0; # 1=green 0=red
def Last_Cloud_Green = if (cloudredbarsback > cloudgreenbarsback) then 1 else 0; # 1=green 0=red
def Last_Cloud_Red = if (cloudredbarsback < cloudgreenbarsback) then 1 else 0; # 1=red 0=green
#####################################################
## COUNT CLOUDS                                    ##
#####################################################
def Last_Red_Green = if Last_Cloud_Red[1] and EMAD_Green_Cloud_4 then 1 else 0;
def LastRG_Bn = if Last_Red_Green then bn else LastRG_Bn[1];
def Last_Green_Red = if Last_Cloud_Red[1] and EMAD_Red_Cloud_4 then 1 else 0;
def LastGR_Bn = if Last_Green_Red then bn else LastGR_Bn[1];
def dynamic_length_green = if !Last_Red_Green then Bars_From_First else if Last_Red_Green then bn - LastRG_Bn else Double.NaN;
def dynamic_length_red = if !Last_Green_Red then Bars_From_First else if Last_Green_Red then bn - LastGR_Bn else Double.NaN;
#####################################################
## COUNT                                           ##
#####################################################
def EMAD_Green_Cloud_lookback = fold index10 = 0 to EMAD_Cloud_Lookback with x10 do x10 + EMAD_Green_Cloud_4[index10];
def EMAD_Red_Cloud_lookback = fold index11 = 0 to EMAD_Cloud_Lookback with x11 do x11 + EMAD_Red_Cloud_4[index11];
#####################################################
## ALTERNATE COUNT METHOD                          ##
#####################################################
def count_window_length = EMAD_Cloud_Lookback;
def conditiongreen = EMAD_Green_Cloud_4; #ex. green cloud then red cloud then green: if lastcloudred[1] and green cloud then counter
def conditionred = EMAD_Red_Cloud_4; #ex. green cloud then red cloud then green: if lastcloudred[1] and green cloud then counter
def counter_green_V2 = Sum(conditiongreen, EMAD_Cloud_Lookback);
def counter_red_V2 = Sum(conditionred, EMAD_Cloud_Lookback);
#####################################################
## TESTING                                         ##
#####################################################
def New_count_green = if Last_Cloud_Green[1] and conditiongreen then (counter_green_V2[1] + 1) else counter_green_V2[1];
def New_count_red = if Last_Cloud_Red[1] and conditionred then (counter_red_V2[1] + 1) else counter_red_V2[1];
def Bubble_green = if !Last_Cloud_Green[1] and conditiongreen then New_count_green - New_count_green[1] else New_count_green;
def Bubble_red = if !Last_Cloud_Red[1] and conditionred then New_count_red - New_count_red[1] else New_count_red;
#####################################################
## CLOUDS BEFORE SIGNAL                            ##
#####################################################
def Green_Clouds_Before = EMAD_Green_Cloud_lookback > X_Green_Clouds;
def Red_Clouds_Before = EMAD_Red_Cloud_lookback > X_Red_Clouds;
#####################################################
## HIGHER LOW - LOWER HIGH                         ##
#####################################################
def HL = CrossUp_BottomBand == 0 and CrossDown_TopBand == 0 and Upper_EMAD_EMA crosses above Lower_EMAD_EMA; #Normal HL LH condition
def LH = CrossDown_TopBand == 0 and CrossUp_BottomBand == 0 and Upper_EMAD_EMA crosses below Lower_EMAD_EMA; #Normal HL LH condition
def bounceUpOnce = CrossUp_BottomBand <> CrossUp_BottomBand[1]; #XUpBtm happened previous bar or on current bar (<> = is NOT equal to)
def bounceDnOnce = CrossDown_TopBand <> CrossDown_TopBand[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];
def HLalready = if trackCrUp and !trackCrUp[1] then 1 else 0;
def LHalready = if trackCrDn and !trackCrDn[1] then 1 else 0;
def HL2_EMAD = HLalready == 0 and Upper_EMAD_EMA crosses above Lower_EMAD_EMA;
def LH2_EMAD  = LHalready == 0 and Upper_EMAD_EMA crosses below Lower_EMAD_EMA;
def crossedUpOnce = HLalready <> HLalready[1];
def crossedDnOnce = LHalready <> LHalready[1];
def trackCrUp2 = if crossedUpOnce then 0 else if HL2_EMAD then 1 else trackCrUp2[1];
def trackCrDn2 = if crossedDnOnce then 0 else if LH2_EMAD then 1 else trackCrDn2[1];
#####################################################
## SQUEEZE                                         ##
#####################################################
def HiLo_Squeeze = Min(high - low, 1.5 * Average(high - low, ATR_Period_Squeeze));
def HRef_Squeeze = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef_Squeeze = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def trueRange_Squeeze;
switch (TrailType) {
case modified:
    trueRange_Squeeze = Max(HiLo_Squeeze, Max(HRef_Squeeze, LRef_Squeeze));
case unmodified:
    trueRange_Squeeze = TrueRange(high, close, low);
}
def loss_Squeeze = ATR_Factor_Squeeze * MovingAverage(AverageType_Squeeze, trueRange_Squeeze, ATR_Period_Squeeze);
def state_Squeeze = {default init, long, short};
def trail_Squeeze;
switch (state_Squeeze[1]) {
case init:
    if (!IsNaN(loss_Squeeze)) {
        switch (FirstTrade) {
        case long:
            state_Squeeze = state_Squeeze.long;
            trail_Squeeze =  close - loss_Squeeze;
        case short:
            state_Squeeze = state_Squeeze.short;
            trail_Squeeze = close + loss_Squeeze;
    }
    } else {
        state_Squeeze = state_Squeeze.init;
        trail_Squeeze = Double.NaN;
    }
case long:
    if (close > trail_Squeeze[1]) {
        state_Squeeze = state_Squeeze.long;
        trail_Squeeze = Max(trail_Squeeze[1], close - loss_Squeeze);
    } else {
        state_Squeeze = state_Squeeze.short;
        trail_Squeeze = close + loss_Squeeze;
    }
case short:
    if (close < trail_Squeeze[1]) {
        state_Squeeze = state_Squeeze.short;
        trail_Squeeze = Min(trail_Squeeze[1], close + loss_Squeeze);
    } else {
        state_Squeeze = state_Squeeze.long;
        trail_Squeeze =  close - loss_Squeeze;
    }
}
def TrailingStop_Squeeze = trail_Squeeze;
def H = Highest(TrailingStop_Squeeze, 12);
def L = Lowest(TrailingStop_Squeeze, 12);
def Bandwidth_Squeeze = (H - L);
def IntermSupport2 = Lowest(Bandwidth_Squeeze, Band_Length);
def Squeeze_Trigger = Bandwidth_Squeeze <= IntermSupport2;
def Squeeze_Level = if !Squeeze_Trigger[1] and Squeeze_Trigger then hl2 else if !Squeeze_Trigger then Double.NaN else Squeeze_Level[1];
def Squeeze_Alert_1 = if Squeeze_Level then (Upper_EMAD_EMA + Lower_EMAD_EMA) / 2 else (Upper_EMAD_EMA + Lower_EMAD_EMA) / 2;
#####################################################
## TS V9                                           ##
#####################################################
def HiLo_TSV9 = Min(high - low, 1.5 * Average(high - low, ATR_Period_TSV9));
def HRef_TSV9 = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef_TSV9 = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def trueRange_TSV9;
switch (TrailType) {
case modified:
    trueRange_TSV9 = Max(HiLo_TSV9, Max(HRef_TSV9, LRef_TSV9));
case unmodified:
    trueRange_TSV9 = TrueRange(high, close, low);
}
def loss_TSV9 = ATR_Factor_TSV9 * MovingAverage(AverageType, trueRange_TSV9, ATR_Period_TSV9);
def state_TSV9 = {default init, long, short};
def trail_TSV9;
switch (state_TSV9[1]) {
case init:
    if (!IsNaN(loss_TSV9)) {
        switch (FirstTrade) {
        case long:
            state_TSV9 = state_TSV9.long;
            trail_TSV9 =  close - loss_TSV9;
        case short:
            state_TSV9 = state_TSV9.short;
            trail_TSV9 = close + loss_TSV9;
    }
    } else {
        state_TSV9 = state_TSV9.init;
        trail_TSV9 = Double.NaN;
    }
case long:
    if (close > trail_TSV9[1]) {
        state_TSV9 = state_TSV9.long;
        trail_TSV9 = Max(trail_TSV9[1], close - loss_TSV9);
    } else {
        state_TSV9 = state_TSV9.short;
        trail_TSV9 = close + loss_TSV9;
    }
case short:
    if (close < trail_TSV9[1]) {
        state_TSV9 = state_TSV9.short;
        trail_TSV9 = Min(trail_TSV9[1], close + loss_TSV9);
    } else {
        state_TSV9 = state_TSV9.long;
        trail_TSV9 =  close - loss_TSV9;
    }
}
def Price = close;
def TrailingStop_TSV9 = trail_TSV9;
def Upsignal = (Price crosses above TrailingStop_TSV9);
def Downsignal = (Price crosses below TrailingStop_TSV9);
def BuySig_TSV9_bn = if Upsignal[1] then bn else BuySig_TSV9_bn[1];
def SellSig_TSV9_bn = if Downsignal[1] then bn else SellSig_TSV9_bn[1];
def TS_Last = if BuySig_TSV9_bn > SellSig_TSV9_bn then 1 else 0;
def cond13_TS_Buy = Upsignal and !Upsignal[1];
def cond13_TS_Sell = Downsignal and !Downsignal[1];
#####################################################
## TRIPLE EXHAUSTION                               ##
#####################################################
def OB_3x = 80;
def OS_3x = 20;
def KPeriod_3x = 10;
def DPeriod_3x = 10;
def SlowK_3x = reference StochasticFull(OB_3x,  OS_3x,  KPeriod_3x,  DPeriod_3x,  EMAD_High, EMAD_Low, EMAD_Close,  3, if (AverageType == 1) then AverageType.SIMPLE else AverageType.EXPONENTIAL).FullK;
def MACD_3x = reference MACD()."Value";
def Price_Avg_3x = Average(MACD_3x, Length_3x);
def MACD_stdev_3x =  (MACD_3x - Price_Avg_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 Extreme_Buy_1 = if SellerExtreme[1] and !SellerExtreme then haLow else Double.NaN;
def Regular_Buy_1 = if SellerRegular[1] and !SellerRegular then haLow else Double.NaN;
def Extreme_Sell_1 = if BuyerExtreme[1] and !BuyerExtreme then haHigh else Double.NaN;
def Regular_Sell_1 = if BuyerRegular[1] and !BuyerRegular then haHigh else Double.NaN;
def Extreme_Buy_2 = if MarketOpen and (SellerExtreme[1] and !SellerExtreme) within X_Signal_Bars bars then 1 else 0;
def Regular_Buy_2 = if MarketOpen and (SellerRegular[1] and !SellerRegular) within X_Signal_Bars bars then 1 else 0;
def Extreme_Sell_2 = if MarketOpen and (BuyerExtreme[1] and !BuyerExtreme) within X_Signal_Bars bars then 1 else 0;
def Regular_Sell_2 = if MarketOpen and (BuyerRegular[1] and !BuyerRegular) within X_Signal_Bars bars then 1 else 0;
def Extreme_Buy_3 = if Extreme_Buy_2 then haLow else Extreme_Buy_3[1];
def Regular_Buy_3 = if Regular_Buy_2 then haLow else Regular_Buy_3[1];
def Extreme_Sell_3 = if Extreme_Sell_2 then haHigh else Extreme_Sell_3[1];
def Regular_Sell_3 = if Regular_Sell_2 then haHigh else Regular_Sell_3[1];
def Extreme_Buy_Line = if MarketOpen and (SellerExtreme[1] and !SellerExtreme) then 1 else 0;
def Regular_Buy_Line = if MarketOpen and (SellerRegular[1] and !SellerRegular) then 1 else 0;
def Extreme_Sell_Line = if MarketOpen and (BuyerExtreme[1] and !BuyerExtreme) then 1 else 0;
def Regular_Sell_Line = if MarketOpen and (BuyerRegular[1] and !BuyerRegular) then 1 else 0;
def Extreme_Buy_bn = if MarketOpen and (SellerExtreme[1] and !SellerExtreme) then bn else Extreme_Buy_bn[1];
def Regular_Buy_bn = if MarketOpen and (SellerRegular[1] and !SellerRegular) then bn else Regular_Buy_bn[1];
def Extreme_Sell_bn = if MarketOpen and (BuyerExtreme[1] and !BuyerExtreme) then bn else Extreme_Sell_bn[1];
def Regular_Sell_bn = if MarketOpen and (BuyerRegular[1] and !BuyerRegular) then bn else Regular_Sell_bn[1];
#####################################################
## C3 MAX YELLOW CANDLE                            ##
#####################################################
def Displace = 0;
def FactorK2 = 3.25;
def LengthK2 = 20;
def TrueRangeAverageType = AverageType.SIMPLE;
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 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_Yellow_Candle = Value[1] <= Value;
def condition1D_Yellow_Candle = 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 = (RSI[3] < RSI) is true or (RSI >= 80) is true;
def condition2D_RSI = (RSI[3] > RSI) is true or (RSI < 20) is true;
def conditionOB1_RSI = RSI > RSI_OB;
def conditionOS1_RSI = RSI < RSI_OS;
#####################################################
## MONEY FLOW INDEX                                ##
#####################################################
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_MFI = (MoneyFlowIndex[2] < MoneyFlowIndex) is true or (MoneyFlowIndex > 85) is true;
def condition3D_MFI = (MoneyFlowIndex[2] > MoneyFlowIndex) is true or (MoneyFlowIndex < 20) is true;
def conditionOB2_MFI = MoneyFlowIndex > MFIover_Bought;
def conditionOS2_MFI = 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_Forcast = (Intermed[1] <= Intermed) or (NearT >= MidLine);
def condition4D_Forcast = (Intermed[1] > Intermed) or (NearT < MidLine);
def conditionOB3_Forcast = Intermed > FOB;
def conditionOS3_Forcast = Intermed < FOS;
def conditionOB4_Forcast = NearT > FOB;
def conditionOS4_Forcast = 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 = CIP_UP;
def condition5D_CIP = CIP_DOWN;
#####################################################
## EMA 1                                           ##
#####################################################
def EMA_length = 8;
def AvgExp = ExpAverage(Price[-Displace], EMA_length);
def condition6_EMA_1 = (Price >= AvgExp) and (AvgExp[2] <= AvgExp);
def condition6D_EMA_1 = (Price < AvgExp) and (AvgExp[2] > AvgExp);
#####################################################
## EMA 2                                           ##
#####################################################
def EMA_2length = 20;
def displace2 = 0;
def AvgExp2 = ExpAverage(Price[-displace2], EMA_2length);
def condition7_EMA_2 = (Price >= AvgExp2) and (AvgExp2[2] <= AvgExp);
def condition7D_EMA_2 = (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_DMI = Osc >= ZeroLine;
def condition8D_DMI = 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_Trend = Periods > 0;
def condition9D_Trend = 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 = PFE > 0;
def condition10D_PFE = PFE < 0;
def conditionOB5_PFE = PFE > UpperLevel;
def conditionOS5_PFE = PFE < LowerLevel;
#####################################################
## BOLLINGER BANDS                                 ##
#####################################################
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_BB = BollingerBands(Price, Displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, AverageType_BB).UpperBand;
def lowerBand_BB = BollingerBands(Price, Displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, AverageType_BB).LowerBand;
def PercentB = (Price - lowerBand_BB) / (upperBand_BB - lowerBand_BB) * 100;
def HalfLine = 50;
def UnitLine = 100;
def condition11_BB = PercentB > HalfLine;
def condition11D_BB = PercentB < HalfLine;
def conditionOB6_BB = PercentB > BBPB_OB;
def conditionOS6_BB = PercentB < BBPB_OS;
def condition12_BB = (Upper_BandS[1] <= Upper_BandS) and (Lower_BandS[1] <= Lower_BandS);
def condition12D_BB = (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_KH = (KVOH > 0);
def condition13D_KH = (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_PO = PROSC > 50;
def condition14D_PO = PROSC < 50;
def conditionOB7_PO = PROSC > PROSC_OB;
def conditionOS7_PO = 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_AK = if aktrend_bspread > 0 then 1 else 0;
def cond1_DN_AK = 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_ZSCORE = if zscore_Zscore > 0 then 1 else 0;
def cond2_DN_ZSCORE = if zscore_Zscore <= 0 then -1 else 0;
#####################################################
## EMAD EHLERS                                     ##
#####################################################
def Price_Ehlers_EMAD = (EMAD_High + EMAD_Low) / 2;
def Coeff = Ehlers_Length * Price_Ehlers_EMAD * Price_Ehlers_EMAD - 2 * Price_Ehlers_EMAD * Sum(Price_Ehlers_EMAD, Ehlers_Length)[1] + Sum(Price_Ehlers_EMAD * Price_Ehlers_EMAD, Ehlers_Length)[1];
def Ehlers_EMAD =  Sum(Coeff * Price_Ehlers_EMAD, Ehlers_Length) / Sum(Coeff, Ehlers_Length);
#####################################################
## EHLERS                                          ##
#####################################################
def Price_Ehlers = (high + low) / 2;
def Ehlers_Coeff = Ehlers_Length * Price_Ehlers * Price_Ehlers - 2 * Price_Ehlers * Sum(Price_Ehlers, Ehlers_Length)[1] + Sum(Price_Ehlers * Price_Ehlers, Ehlers_Length)[1];
def Ehlers = Sum(Ehlers_Coeff * Price_Ehlers, Ehlers_Length) / Sum(Ehlers_Coeff, Ehlers_Length);
def Ehlers_Avg = Average(Ehlers, Ehlers_Avg_Length);
def cond3_UP_Ehlers = if close > Ehlers_Avg then 1 else 0;
def cond3_DN_Ehlers = if close <= Ehlers_Avg 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_AM = if amom_amom > 0 then 1 else 0;
def cond4_DN_AM = 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_TMO = if tmo_Main <= 0 then 1 else 0;
def cond5_DN_TMO = if tmo_Main >= 0 then -1 else 0;
#####################################################
## MADE AVERAGE (EMAD)                             ##
#####################################################
def dataA = Master_EMAD_EMA;
def dataA1 =
    fold aD = 0
    to Length_MAD
    with k = 0  
    do k + dataA[aD];
def MAEMAD = dataA1 / Length_MAD;
def MADehlers = (MAEMAD - Ehlers_EMAD) / 2;
def Madebad = MADehlers + Ehlers_EMAD;
def Madebad_Avg = Average(Madebad, Made_Avg_Length);
def Madebad_CrossUp = if (Madebad < Master_EMAD_EMA) and (Madebad > Madebad[1]) and (EMAD_Above_Zero > 0) then 1 else 0;
def Madebad_CrossDown = if (Madebad > Master_EMAD_EMA) and (Madebad < Madebad[1]) and (EMAD_Below_Zero > 0) then 1 else 0;
def Madebad_CrossCondition = if (Madebad < Master_EMAD_EMA) and (Madebad > Madebad[1]) and (EMAD_Above_Zero > 0) then 1
            else if (Madebad > Master_EMAD_EMA) and (Madebad < Madebad[1]) and (EMAD_Below_Zero > 0) then -1
            else 0;
def Madebad_Condition = if (!Madebad_CrossCondition[1] or !Madebad_CrossCondition[2]) and (Madebad_CrossCondition == 0) then 1 else 0;
#####################################################
## ALERT4                                          ##
#####################################################
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 StDev = MULT * StDev(WVF, BBL);
def MidLine1 = SimpleMovingAvg(WVF, BBL);
def UpperBand1_Alert4 = MidLine1 + StDev;
def Range_High = (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_Alert4[1] or WVF[1] >= Range_High[1]) and (WVF < UpperBand1_Alert4 and WVF < Range_High));
def Filtered_Aggr = (WVF[1] >= UpperBand1_Alert4[1] or WVF[1] >= Range_High[1]);
def Alert4 = UpRange_Aggr and close > close[STR] and (close < close[LTLB] or close < close[MTLB]) and Filtered_Aggr;
def Alert4_1 = if Alert4 then haLow else Double.NaN;
def Alert4_3 = if Alert4 then 1 else 0;
def Alert4_2 = Alert4 within X_Alert4_Bars bars;
#####################################################
## EMAD MADE                                       ##
#####################################################
def Made_Down = (Madebad > Master_EMAD_EMA);
def Made_Up = (Madebad < Master_EMAD_EMA);
def Made_Bottom_MA = if !Made_Down and (Madebad_Avg <= ZeroLineData) then Madebad_Avg else Double.NaN;
def Made_Top_MA = if !Made_Up and (Madebad_Avg >= ZeroLineData) then Madebad_Avg else Double.NaN;
def MadeAvg_Master_Cross_Up = if Madebad_Avg crosses below Master_EMAD_EMA then 1 else 0;
def MadeAvg_Master_Cross_Down = if Madebad_Avg crosses above Master_EMAD_EMA then 1 else 0;
def Cross_Up_MadeAvg_Master = if MadeAvg_Master_Cross_Up and !MadeAvg_Master_Cross_Up[1] then 1 else 0;
def Cross_Down_MadeAvg_Master = if MadeAvg_Master_Cross_Down and !MadeAvg_Master_Cross_Down[1] then 1 else 0;
def MadeAvg_Master_Up_Condition = if Cross_Up_MadeAvg_Master and Band_Crossed_First and EMAD_EMA_up[1] then 1 else 0;
def MadeAvg_Master_Down_Condition = if Cross_Down_MadeAvg_Master and !Band_Crossed_First and EMAD_EMA_down[1] then 1 else 0;
def EMA_Push_StepUp = if TopBand_StepUp and EMAD_EMA_up and (((Upper_EMAD_EMA) - TopBand) == 0) then 1 else 0;
def EMA_Push_StepDown = if BottomBand_StepDown and EMAD_EMA_down and (((Lower_EMAD_EMA) - BottomBand) == 0) then 1 else 0;
def First_HL_1 = if MarketOpen and trackCrUp and !trackCrUp[1] then haLow else Double.NaN;
def First_LH_1 = if MarketOpen and trackCrDn and !trackCrDn[1] then haHigh else Double.NaN;
def Second_HL_1 = if (MarketOpen and trackCrUp2 and !trackCrUp2[1] and !CrossUp_BottomBand) then haLow else Double.NaN;
def Second_LH_1 = if (MarketOpen and trackCrDn2 and !trackCrDn2[1] and !CrossDown_TopBand) then haHigh else Double.NaN;
def First_HL_2 = if (MarketOpen and trackCrUp and !trackCrUp[1]) within X_Signal_Bars bars then 1 else 0;
def First_LH_2 = if (MarketOpen and trackCrDn and !trackCrDn[1]) within X_Signal_Bars bars then 1 else 0;
def Second_HL_2 = if ((MarketOpen and trackCrUp2 and !trackCrUp2[1]) and !CrossUp_BottomBand) within X_Signal_Bars bars then 1 else 0;
def Second_LH_2 = if ((MarketOpen and trackCrDn2 and !trackCrDn2[1]) and !CrossDown_TopBand) within X_Signal_Bars bars then 1 else 0;
def First_HL_3 = if (MarketOpen and trackCrUp and !trackCrUp[1]) within X_Signal_Bars bars then haLow else First_HL_3[1];
def First_LH_3 = if (MarketOpen and trackCrDn and !trackCrDn[1]) within X_Signal_Bars bars then haHigh else First_LH_3[1];
def Second_HL_3 = if ((MarketOpen and trackCrUp2 and !trackCrUp2[1]) and !CrossUp_BottomBand) within X_Signal_Bars bars then haLow else Second_HL_3[1];
def Second_LH_3 = if ((MarketOpen and trackCrDn2 and !trackCrDn2[1]) and !CrossDown_TopBand) within X_Signal_Bars bars then haHigh else Second_LH_3[1];
#####################################################
## FOLD CONDITIONS (EMAD)                          ##
#####################################################
def TopBandStepDown_lookback = fold index1 = 1 to Step_lookback with x1 do x1 + TopBand_StepDown[index1];
def TopBandStepUp_lookback = fold index2 = 1 to Step_lookback with x2 do x2 + TopBand_StepUp[index2];
def BottomBandStepDown_lookback = fold index3 = 1 to Step_lookback with x3 do x3 + BottomBand_StepDown[index3];
def BottomBandStepUp_lookback = fold index4 = 1 to Step_lookback with x4 do x4 + BottomBand_StepUp[index4];
def Madebad_Condition_lookback = fold index5 = 1 to Cloud_Lookback with x5 do x5 + Madebad_Condition[index5];
def HL_lookback = fold index6 = 1 to HL_LH_Lookback with x6 do x6 + First_HL_1[index6];
def LH_lookback = fold index7 = 1 to HL_LH_Lookback with x7 do x7 + First_LH_1[index7];
def HL2_lookback = fold index8 = 1 to HL_LH_Lookback with x8 do x8 + Second_HL_1[index8];
def LH2_lookback = fold index9 = 1 to HL_LH_Lookback with x9 do x9 + Second_LH_1[index9];
#####################################################
## HIDE ARROW CONDITIONS                           ##
#####################################################
def Hide_Arrow_TopBand_StepDown = TopBandStepDown_lookback > Previous_Steps_Down;
def Hide_Arrow_TopBand_StepUp = TopBandStepUp_lookback > Previous_Steps_Up;
def Hide_Arrow_BottomBand_StepDown = BottomBandStepDown_lookback > Previous_Steps_Down;
def Hide_Arrow_BottomBand_StepUp = BottomBandStepUp_lookback > Previous_Steps_Up;
def UP1 = if MarketOpen and (!Hide_Arrow_TopBand_StepDown or !Hide_Arrow_BottomBand_StepDown) and !EMA_Push_StepDown and MadeAvg_Master_Up_Condition then 1 else 0;
def DOWN1 = if MarketOpen and (!Hide_Arrow_TopBand_StepUp or !Hide_Arrow_BottomBand_StepUp) and !EMA_Push_StepUp and MadeAvg_Master_Down_Condition then 1 else 0;
def updown1 = if up1 == 1 then halow else if down1 == 1 then hahigh else updown1[1];
def UP1_1 = if UP1 then haLow else Double.NaN;
def DOWN1_1 = if DOWN1 then haHigh else Double.NaN;
def UP1_2 = if UP1 within X_Signal_Bars bars then 1 else 0;
def DOWN1_2 = if DOWN1 within X_Signal_Bars bars then 1 else 0;
def UP1_3 = if UP1 then haLow else UP1_3[1];
def DOWN1_3 = if DOWN1 then haHigh else DOWN1_3[1];
def UP_1_Price = if (UP1_1 == halow) then (UP1_1 - UP1_1[1]) else double.nan;
def UP_1_increasing = UP_1_Price > 0;
def DOWN_1_Price = if (DOWN1_1 == haHIGH) then (DOWN1_1 - DOWN1_1[1]) else double.nan;
def DOWN_1_increasing = DOWN_1_Price > 0;
def UP1_EMAD_Price = if (UP1_1 == halow) then (EMAD_low[1] - EMAD_low) else double.nan;
def UP_1_EMAD_decreasing = UP1_EMAD_Price > 0;
def DOWN_1_EMAD_Price = if (DOWN1_1 == haHIGH) then (EMAD_high[1] - EMAD_high)else double.nan;
def DOWN_1_EMAD_decreasing = DOWN_1_EMAD_Price > 0;
def EMAD_Divergence_UP = UP_1_EMAD_decreasing and UP_1_increasing;
def EMAD_Divergence_DOWN = DOWN_1_EMAD_decreasing and DOWN_1_increasing;
#####################################################
## MARKET PHASES                                   ##
#####################################################
def Fastavg_Phases = 50;
def Slowavg_Phases = 200;
def Fastsma_Phases = Average( close, Fastavg_Phases);
def Slowsma_Phases = Average(close, Slowavg_Phases);
def Bullphase = Fastsma_Phases > Slowsma_Phases && close > Fastsma_Phases && close > Slowsma_Phases; # Accumulation Phase : close > 50 SMA, close > 200 SMA, 50 SMA < 200 SMA
def Accphase = Fastsma_Phases < Slowsma_Phases && close > Fastsma_Phases && close > Slowsma_Phases;# Recovery Phase : close > 50 SMA, close < 200 SMA, 50 SMA < 200 SMA
def Recphase = Fastsma_Phases < Slowsma_Phases && close < Slowsma_Phases && close > Fastsma_Phases;# Bearish Phase : close < 50 SMA, close < 200 SMA, 50 SMA < 200 SMA
def Bearphase = Fastsma_Phases < Slowsma_Phases && close < Fastsma_Phases && close < Slowsma_Phases;# Distribution Phase : close < 50 SMA, close < 200 SMA, 50 SMA > 200 SMA
def Distphase = Fastsma_Phases > Slowsma_Phases && close < Fastsma_Phases && close < Slowsma_Phases;# Warning Phase : close < 50 SMA, close > 200 SMA, 50 SMA > 200 SMA
def Warnphase = Fastsma_Phases > Slowsma_Phases && close > Slowsma_Phases && close < Fastsma_Phases;
#####################################################
## BIG 4 DIRECTION                                 ##
#####################################################
def Strategy_FilterWithTMO = no;
def Strategy_FilterWithTMO_arrows = yes;
def Strategy_HoldTrend = no;
def Strategy_ColoredCandlesOn = yes;
def coloredCandlesOn = yes;
def cond_UP = cond1_UP_AK + cond2_UP_ZSCORE + cond3_UP_Ehlers + cond4_UP_AM;
def cond_DN = cond1_DN_AK + cond2_DN_ZSCORE + cond3_DN_Ehlers + cond4_DN_AM;
def direction = if cond_UP >= Big4_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_UP_TMO) then 1
else if cond_DN <= - Big4_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_DN_TMO) then -1
    else if !Strategy_HoldTrend and direction[1] == 1 and cond_UP < Big4_Confirmation_Factor and cond_DN > - Big4_Confirmation_Factor then 0
        else if !Strategy_HoldTrend and direction[1] == -1 and cond_DN > -Big4_Confirmation_Factor and cond_UP < Big4_Confirmation_Factor then 0
            else direction[1];
def direction2 = if cond_UP >= Big4_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_UP_TMO) then 1
    else if cond_DN <= - Big4_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_DN_TMO) then -1
        else if !Strategy_HoldTrend and direction2[1] == 1 and cond_UP < Big4_Confirmation_Factor and cond_DN > - Big4_Confirmation_Factor then 0
            else if !Strategy_HoldTrend and direction2[1] == -1 and cond_DN > - Big4_Confirmation_Factor and cond_UP < Big4_Confirmation_Factor then 0
                else direction2[1];
def direction_Equals_zero = direction == 0;
def direction_zero_condition = if direction_Equals_zero and (direction_Equals_zero[1] or direction_Equals_zero[2] or direction_Equals_zero[3] or direction_Equals_zero[4] or direction_Equals_zero[5]) then 0 else 1;
#####################################################
## TREND CONFIRMATION CALCULATOR                   ##
#####################################################
def Confirmation_Factor = 7;
def Agreement_LevelOB = 12;
def Agreement_LevelOS = 2;
def HideBoxLines = no;
#def HideCloud = no;
def HideLabels = no;
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;
#######################################################
## AGREEMENT LEVEL                                   ##
#######################################################
def Agreement_Level = condition1_Yellow_Candle + condition2_RSI + condition3_MFI + condition4_Forcast
                    + condition5_CIP + condition6_EMA_1 + condition7_EMA_2 + condition8_DMI + condition9_Trend
                    + condition10_PFE + condition11_BB + condition12_BB + condition13_KH + condition14_PO
                    + conditionK1UP + conditionK2UP;
def Agreement_LevelD = (condition1D_Yellow_Candle + condition2D_RSI + condition3D_MFI + condition4D_Forcast + condition5D_CIP
                    + condition6D_EMA_1 + condition7D_EMA_2 + condition8D_DMI + condition9D_Trend + condition10D_PFE
                    + condition11D_BB + condition12D_BB + condition13D_KH + condition14D_PO + conditionK3DN
                    + conditionK4DN);
#######################################################
## CONSENSUS LEVEL                                   ##
#######################################################
def Consensus_Level = Agreement_Level - Agreement_LevelD;
def Consensus_UP = 6;
def Consensus_DOWN = -6;
def UP_CL = Consensus_Level >= Consensus_UP;
def DOWN_CL = Consensus_Level < Consensus_DOWN;
def priceColor = if UP_CL then 1 else if DOWN_CL then -1 else priceColor[1];
def Consensus_Level_OB = 14;
def Consensus_Level_OS = -12;
def OB_Level = conditionOB1_RSI + conditionOB2_MFI + conditionOB3_Forcast + conditionOB4_Forcast + conditionOB5_PFE + conditionOB6_BB + conditionOB7_PO;
def OS_Level = conditionOS1_RSI + conditionOS2_MFI + conditionOS3_Forcast + conditionOS4_Forcast + conditionOS5_PFE + conditionOS6_BB + conditionOS7_PO;
def Consensus_Line = OB_Level - OS_Level;
def MomentumUP = Consensus_Level[1] < Consensus_Level;
def MomentumDOWN = Consensus_Level[1] > Consensus_Level;
def conditionOB_CL = (Consensus_Level >= 12) and (Consensus_Line >= 4);
def conditionOS_CL = (Consensus_Level <= -12) and (Consensus_Line <= -3);
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);
#####################################################
## PREVIOUSLY OVERBOUGHT / OVERSOLD LEVELS         ##
#####################################################
def YHOB = if ((open > Upper_BandS) and (Condition_BandRevDn)) then high else Double.NaN;
def YHOS = if ((open < Lower_BandS) and (Condition_BandRevUp)) then high else Double.NaN;
def YLOB = if ((open > Upper_BandS) and (Condition_BandRevDn)) then low else Double.NaN;
def YLOS = if ((open < Lower_BandS) and (Condition_BandRevUp)) then low else Double.NaN;
def YCOB = if !IsNaN(YHOB) then hl2 else Double.NaN;
def YHextOB = if IsNaN(YCOB) then YHextOB[1] else YCOB;
def YHextlineOB = YHextOB;
def YCOS = if !IsNaN(YHOS) then hl2 else Double.NaN;
def YHextOS = if IsNaN(YCOS) then YHextOS[1] else YCOS;
def YHextlineOS = YHextOS;
def HighestPOB = highestAll(YHextlineOB);
def LowestPOS = LowestAll(YHextlineOS);
def HighestPOS = highestAll(YHextlineOS);
def LowestPOB = LowestAll(YHextlineOB);
#####################################################
## OVERBOUGHT / OVERSOLD ZONES                     ##
#####################################################
def BarsUsedForRange = 2;
def BarsRequiredToRemainInRange = 2;
def trig = 20;# for Blast-off candle color
def YC = coloredCandlesOn and priceColor == 1 and open > 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;
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;
def BL2 = if !IsNaN(BoxLow2) then low else Double.NaN;
def BL2ext = if IsNaN(BL2) then BL2ext[1] else BL2;
def BL2extline2 = BL2ext;
#####################################################
## CROSSING LEVELS                                 ##
#####################################################
def Gray_Cloud = (EMAD_Gray_Cloud_1 or EMAD_Gray_Cloud_2) ;
def Green_Cloud = (EMAD_Green_Cloud_1 or EMAD_Green_Cloud_2) ;
def red_Cloud = (EMAD_Red_Cloud_1 or EMAD_Red_Cloud_2) ;# Yellow line
#####################################################
## CROSSING LEVELS CONTINUED                       ##
#####################################################
def Price_X_BL1 = if hl2 > BL1ext then 1 else if hl2 < BL1ext then -1 else 0;
def Price_X_BH1 = if hl2 > BH1ext then 1 else if hl2 < BH1ext then -1 else 0;
def Price_X_BL2 = if hl2 > BL2ext then 1 else if hl2 < BL2ext then -1 else 0;
def Price_X_BH2 = if hl2 > BH2ext then 1 else if hl2 < BH2ext then -1 else 0;
def Price_X_YHextlineOB = if hl2 > YHextlineOB then 1 else if hl2 < YHextlineOB then -1 else 0;
def Price_X_YHextlineOS = if hl2 > YHextlineOS then 1 else if hl2 < YHextlineOS then -1 else 0;
def All_C3_Levels = Price_X_BL1 + Price_X_BH1 + Price_X_BL2 + Price_X_BH2 + Price_X_YHextlineOB + Price_X_YHextlineOS;
def Level_Price_Status = if All_C3_Levels > Above_X_Levels then 1 else if All_C3_Levels < Below_X_Levels then 0 else double.nan;
def Level_Price_Status_Up = if All_C3_Levels > Above_X_Levels then 1 else 0;
def Level_Price_Status_Down = if All_C3_Levels > Below_X_Levels then 1 else 0;
#####################################################
##                                                 ##
#####################################################
def Below_Both_POBOS = ((HL2 < YHextlineOS) and (HL2 < YHextlineOB)) and EMAD_EMA_Down;
def Above_Both_POBOS = ((HL2 > YHextlineOS) and (HL2 > YHextlineOB)) and EMAD_EMA_Up;
#####################################################
## KEY LEVELS                                      ##
#####################################################
def KeylevelOB = if ((BH1ext >= YHextlineOB) and (BL1ext <= YHextlineOB)) then 1 else 0;
def KeylevelOS = if ((BH2ext >= YHextlineOS) and (BL2ext <= YHextlineOS)) then 1 else 0;
def levelOB = if ((BH1ext >= HL2) and (BL1ext <= HL2)) then 1 else 0;
def levelOS = if ((BH2ext >= HL2) and (BL2ext <= HL2)) then 1 else 0;
#####################################################
## OPPOSITE KEY LEVELS                             ##
#####################################################
def Opposite_KeyOS = ((BH1ext >= YHextlineOS) and (BL1ext <= YHextlineOS));
def Opposite_KeyOB = ((BH2ext >= YHextlineOB) and (BL2ext <= YHextlineOB));
def Below_Opposite_KeyOS_Down = Opposite_KeyOS and (HL2 < YHextlineOS);
def Above_Opposite_KeyOS_Up = Opposite_KeyOS and (HL2 > YHextlineOS);
def Below_Opposite_KeyOB_Down = Opposite_KeyOB and (HL2 < YHextlineOB);
def Above_Opposite_KeyOB_Up  = Opposite_KeyOB and (HL2 > YHextlineOB);
def Below_both_OPOBOS = Below_Opposite_KeyOS_Down and (HL2 < YHextlineOB);
def Below_both_OPOBOS2 = Above_Opposite_KeyOS_Up and (HL2 > YHextlineOB);
def Below_both_OPOBOS3 = Below_Opposite_KeyOB_Down and (HL2 < YHextlineOS);
def Below_both_OPOBOS4 = Above_Opposite_KeyOB_Up and (HL2 > YHextlineOS);
#####################################################
## BOTH INSIDE SAME ZONE - KEY LEVELS              ##
#####################################################
def OBOS_Inside_Red = KeylevelOB and Opposite_KeyOS;
def OBOS_Inside_Green = KeylevelOS and Opposite_KeyOB;
#####################################################
## CANDLE INSIDE ZONE                              ##
#####################################################
def keyobpaint = ((hl2 < BH1ext) and (hl2 > BL1ext)) within X_InKey_Bars bars;
def keyospaint = ((hl2 < BH2ext) and (hl2 > BL2ext)) within X_InKey_Bars bars;
#####################################################
## CANDLE INSIDE KEY LEVEL                         ##
#####################################################
def Inside_Key_OB = KeylevelOB and keyobpaint;
def Inside_Key_OS = KeylevelOS and keyospaint;
def In_Key_OB = Inside_Key_OB within X_Keylevel_Bars bars;
def In_Key_OS = Inside_Key_OS within X_Keylevel_Bars bars;
#####################################################
## EMAD CLOUDS IN KEY LEVEL                        ##
#####################################################
def Red_Cloud_in_KeyOS = EMAD_Red_Cloud_3 and In_Key_OS; #bullish
def Green_Cloud_in_KeyOB = EMAD_Green_Cloud_3 and In_Key_OB; #bearish
def Red_Cloud_in_KeyOB = EMAD_Red_Cloud_3 and In_Key_OB;
def Green_Cloud_in_KeyOS = EMAD_Green_Cloud_3 and In_Key_OS;
#####################################################
## PREVIOUS OB / OS ABOVE / BELOW ZONE             ##
#####################################################
def POB_Above_Red_Zone = (YHextlineOB > BH1ext);
def POS_below_Green_Zone = (YHextlineOS < BL2ext);
#####################################################
## PRICE CROSS PREVIOUS OB / OS ABOVE / BELOW ZONE ##
#####################################################
def POB_Abv_Z_Cross = POB_Above_Red_Zone and ((hl2 >=  YHextlineOB) within X_InKey_Bars bars);
def POS_blw_Z_Cross = POS_below_Green_Zone and ((hl2  <= YHextlineOS) within X_InKey_Bars bars);
def POBBCross = !POS_blw_Z_Cross[1] and POS_blw_Z_Cross;
def hidePOBB = if POBBCross[1] or POBBCross[2] or POBBCross[3] or POBBCross[4] or POBBCross[5] or POBBCross[6] or POBBCross[7] then 0 else 1;
def POBLCross = !POB_Abv_Z_Cross[1] and POB_Abv_Z_Cross;
def hidePOBL = if POBLCross[1] or POBLCross[2] or POBLCross[3] or POBLCross[4] or POBLCross[5] or POBLCross[6] or POBLCross[7] then 0 else 1;
def CrossPOB = POBBCross and hidePOBB;
def CrossPOS = POBLCross and hidePOBL;
#####################################################
## ZONE COMPRESSION                                ##
#####################################################
def Zone_Difference = if (BL1ext > BH2ext) then (BL1ext - BH2ext) else Double.NaN;
#addlabel(yes, Zone_Difference , color.yellow);
def Zone_Diff_Percent = (Zone_Difference / hl2) * 100;
#addlabel(yes, Zone_Diff_Percent+"%" , color.yellow);
def Zone_Diff_PerCond = Zone_Diff_Percent < Zone_Percent_Diff;
def Zone_Compression_1 = if (BL1ext < BH2ext) then 1 else 0;
def Zone_Compression_2 = Zone_Difference <= Zone_Span;
#####################################################
## CANDLES BETWEEN ZONES                           ##
#####################################################
def Price_Between_Zones = (Price < BH1ext) and (Price > BL2ext);
def Zone_Compression = if Zone_Compression_1 or  Zone_Compression_2 then 1 else 0;
def Zone_Compression_3 = Zone_Compression and Price_Between_Zones;
def POBOS_Compression = if (YHextlineOB > YHextlineOS) then (YHextlineOB - YHextlineOS) else if (YHextlineOS > YHextlineOB) then (YHextlineOS - YHextlineOB) else double.nan;
#####################################################
## ZONE INCREASING / DECREASING / FLAT / STRETCHED ##
#####################################################
def Zone_Red_Increasing = (BH1ext > BH1ext[1]) or (BL1ext > BL1ext[1]);
def Zone_Red_Decreasing = (BL1ext < BL1ext[1]) or (BH1ext < BH1ext[1]);
def Zone_Red_Flat = (BH1ext == BH1ext[1]) and (BL1ext == BL1ext[1]);
def Zone_Red_Wrapping = (BH1ext > BH1ext[1]) and (BL1ext > BL1ext[1]);
def Zone_Red_Flat_Key = if Zone_Red_Flat and KeylevelOB then 1 else 0;
def Flat_Earth_Bear_1 = sum(Zone_Red_Flat_Key, Flat_Earth_Bars);
#def Flat_Earth_Bear = Zone_Red_Flat_Key and Zone_Red_Flat_Key[1] and Zone_Red_Flat_Key[2] and Zone_Red_Flat_Key[3] and Zone_Red_Flat_Key[4] and Zone_Red_Flat_Key[5];
def Flat_Earth_Bear = Flat_Earth_Bear_1 > Flat_Earth_Controller;
#####################################################
## CANDLE COLOR CONDITIONS                         ##
#####################################################
def Zone_Red_Stretch = (BL1ext < BL1ext[1]) or (BH1ext > BH1ext[1]);
def Zone_Red_Stretch2 = (BL1ext < BL1ext[1]) AND (BH1ext > BH1ext[1]);
def Zone_Red_EMAD_down = (Zone_Red_Stretch within X_Signal_Bars bars) and TopBand_PushUp;
def Zone_Red_Seller_Exh = (Zone_Red_Stretch or Zone_Red_Increasing within X_Zone_bars bars) and (Extreme_Sell_2 or Regular_Sell_2);
def Zone_Red_Seller_Exh_Clouds = Zone_Red_Seller_Exh and Green_Clouds_Before;
#####################################################
## ZONE INCREASING / DECREASING / FLAT / STRETCHED ##
#####################################################
def Zone_Green_Increasing = (BL2ext > BL2ext[1]) or (BH2ext > BH2ext[1]);
def Zone_Green_Decreasing = (BL2ext < BL2ext[1]) or (BH2ext < BH2ext[1]);
def Zone_Green_Flat = (BL2ext == BL2ext[1]) and (BH2ext == BH2ext[1]);
def Zone_Green_Wrapping = (BL2ext < BL2ext[1]) and (BH2ext < BH2ext[1]);
def Zone_Green_Flat_Key = if Zone_Green_Flat and KeylevelOS then 1 else 0;
def Flat_Earth_Bull_1 = sum(Zone_Green_Flat_Key, Flat_Earth_Bars);
#def Flat_Earth_Bull = Zone_Green_Flat_Key and Zone_Green_Flat_Key[1] and Zone_Green_Flat_Key[2] and Zone_Green_Flat_Key[3] and Zone_Green_Flat_Key[4] and Zone_Green_Flat_Key[5];
def Flat_Earth_Bull = Flat_Earth_Bull_1 > Flat_Earth_Controller;
#####################################################
## CANDLE COLOR CONDITIONS                         ##
#####################################################
def Zone_Green_Stretch = (BL2ext < BL2ext[1]) or (BH2ext > BH2ext[1]);
def Zone_Green_EMAD_down = (Zone_Green_Stretch within X_Zone_bars bars) and BottomBand_PushDown;
def Zone_Green_Buyer_Exh = (Zone_Green_Stretch within X_Zone_bars bars) and (Extreme_Buy_2 or Regular_Buy_2);
def Zone_Green_Buyer_Exh_Clouds = Zone_Green_Buyer_Exh and Red_Clouds_Before;
#####################################################
## TEST CONDITIONS FOR LEVELS                      ##
#####################################################
def Zone_Alert4 = (Zone_Green_Stretch within X_Signal_Bars bars) and Alert4_2;
def Zone_Green_Alert4_KEY = In_Key_OS and (Zone_Green_Stretch within X_Zone_bars bars) and Alert4_2;
def Zone_Seller_Exh_KEY = In_Key_OS and (Zone_Green_Stretch within X_Zone_bars bars) and (Extreme_Buy_2 or Regular_Buy_2);
#####################################################
## ZONE OVERLAP                                    ##
#####################################################
def Zone_Overlap = (BH2ext >= BL1ext) and !Zone_Green_Wrapping and !Zone_Green_Decreasing and !Zone_Red_Wrapping and !Zone_Red_Decreasing;
#####################################################
## TEST CONDITIONS FOR LEVELS                      ##
#####################################################
def Zone_Red_Increasing_EMAD = Zone_Red_Increasing and TopBand_PushUp;
def Zone_Green_Decreasing_EMAD = Zone_Green_decreasing and BottomBand_PushDown;
def Green_Cond_1 = Zone_Red_Increasing and Zone_Green_Flat;
def Green_Cond_1_Key = Green_Cond_1 and In_Key_OB;
def Green_Cond_1_3x = (Green_Cond_1 and (Extreme_Sell_2 or Regular_Sell_2)) within X_Signal_Bars bars;
def Green_Cond_2 = Zone_Green_Increasing and Zone_Red_Flat;
def Red_Cond_1 = Zone_Red_Decreasing and Zone_Green_Flat;
def Up_Green_Cond_3 = if Green_Clouds_Before and (!Red_Cond_1 and Red_Cond_1[1]) then 1 else 0;
def Down_Green_Cond_3_Alternate = if Up_Green_Cond_3 and TopBand_PushUp then 1 else 0;
def Alert4_Exhaustion = Alert4_2 and (Extreme_Sell_2 or Regular_Sell_2);
def Green_Cond_3 = Zone_Green_Decreasing and Zone_Red_Flat;
def Down_Green_Cond_3 = if !Green_Cond_1 and Green_Cond_1[1] then 1 else 0;
def Down_Red_Cond_3_Alternate = if Green_Clouds_Before and Down_Green_Cond_3 and TopBand_PushUp then 1 else 0;
def Up_Red_Cond_3 = if !Red_Cond_1 and Red_Cond_1[1] then haLow else Double.NaN;
def Up_Green_Cond_4 = if !Green_Cond_3 and Green_Cond_3[1] then haLow else Double.NaN;
def EMAD_Cloud_Condition_DOWN = (!EMAD_Green_Cloud_1 and EMAD_Green_Cloud_2[1]) or (EMAD_Green_Cloud_1 or EMAD_Green_Cloud_2);
def EMAD_Cloud_Condition_UP = (!EMAD_Red_Cloud_1 and EMAD_Red_Cloud_2[1]) or (EMAD_Red_Cloud_1 or EMAD_Red_Cloud_2);
def Cloud_Zone_Cond_DOWN = if KeylevelOB and (EMAD_Cloud_Condition_DOWN within X_Zone_Cloud_Bars bars) and (Down_Green_Cond_3 within X_Zone_Cloud_Bars bars) then haHigh else Double.NaN;
def Cloud_Zone_Cond_UP = if KeylevelOS and (EMAD_Cloud_Condition_UP within X_Zone_Cloud_Bars bars) and (Up_Red_Cond_3 within X_Zone_Cloud_Bars bars) then haLow else Double.NaN;
#####################################################
## SPARK                                           ##
#####################################################
def Agperiod1 = GetAggregationPeriod();
def timeframe = if Agperiod1 <= AggregationPeriod.DAY then AggregationPeriod.DAY else Agperiod1;
def Length9 = 35;
def Length8 = 10;
def AvgExp8 = ExpAverage(Price[-Displace], Length8);
def UPD = AvgExp8[1] < AvgExp8;
def AvgExp9 = ExpAverage(Price[-Displace], Length9);
def UPW = AvgExp9[1] < AvgExp9;
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;
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 CandleColor = if (priceColor == 1) and (PriceColor12 == 1) and (Spark >= 2) then 1 else if (priceColor == -1) and (Spark < 1) then -1 else 0;
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]) or (BigDN) then 0 else 1;
def Hide_SparkDN = if SparkDN1 and (SparkDN1[1] or SparkDN1[2] or SparkDN1[3] or SparkDN1[4] or SparkDN1[5]) or (BigUP) then 0 else 1;
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 Buy_Volume = RoundUp(Vol * (at_Close - at_Low) / (at_High - at_Low));
def Buy_percent = RoundUp((Buy_Volume / Vol) * 100);
def Sell_Volume = RoundDown(Vol * (at_High - at_Close) / (at_High - at_Low));
def Sell_percent = RoundUp((Sell_Volume / Vol) * 100);
def avg1 = ExpAverage(close(period = Agperiod1), Length8);
def height = avg1 - avg1[Length8];
def avg2 = ExpAverage(close(period = Agperiod1), Length8);    
##C3_MF_Line_v2 Created by Christopher84 03/06/2022  
############################################################
#Keltner Channel
def BulgeLengthPrice2 = 20;
def SqueezeLengthPrice2 = 20;
def BulgeLengthPrice3 = 12;
def SqueezeLengthPrice3 = 12;
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 (open > Upper_BandS) and (condition_BandRevDn)) then 1 else 0;
def C3_Line_2 = if ((priceColor == -1) and (open < Lower_BandS) and (condition_BandRevUp)) then 1 else 0;
def C3_Green =  ((priceColor == 1));
def C3_red =  ((priceColor == 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];
###################################
##Consensus Level & Squeeze Label
###################################
def conditionOB = (Consensus_Level >= 12) and (Consensus_Line >= 4);
def conditionOS = (Consensus_Level <= -12) and (Consensus_Line <= -3);
#####################################################
## LABEL CONDITIONS                                ##
#####################################################                                  
def Condition1UP = avg1 > avg2;
def Condition1DN = avg1 < avg2;
def Condition2UP = Buy_percent > 50;
def Condition2DN = Buy_percent < 50;
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;
#####################################################
## CANDLE COLOR                                    ##
#####################################################
def Red_Wrap_Cond_1 = (Zone_Red_Wrapping or Zone_Red_Increasing) within X_Upcolor1_Bars bars;
def Red_Wrap_Cond_2 = Red_Wrap_Cond_1[1] or Red_Wrap_Cond_1[2] and Zone_Red_Increasing;
def Green_Wrap_Cond_1 = (Zone_Green_Wrapping or Zone_Green_Decreasing) within X_Signal_Bars bars;
def Green_Wrap_Cond_2 = Green_Wrap_Cond_1[1] or Green_Wrap_Cond_1[2] and Zone_Green_decreasing;
#####################################################
## CUMMULATIVE VOLUME DELTA                        ##
#####################################################
input linestyle = {default Candle, Line};
input HeikinAshi = yes; #"Heikin Ashi Candles?")
input maType    =  {default "SMMA", "SMA", "HMA", "EMA", "WMA"};
input maLength  = 9;   #"MA Length"
def BarColor = no;
input BackgroundColor = yes;
def ShowMovAvg = no;
def ShowBand = no;
script nz {
    input data         = 0;
    input replacement  = 0;
    def ret_val = if IsNaN(data) then replacement else data;
    plot return = ret_val;
}
#ma(source, length, type) =>
script ma {
    input source = close;
    input length = 0;
    input type   = "SMA";
    def ma;
ma = if type == "SMA" then SimpleMovingAvg(source, length) else
     if type == "EMA" then ExpAverage(source, length) else
     if type == "WMA" then WMA(source, length) else
     if type == "HMA" then WMA(2 * WMA(source, length / 2) - WMA(source, length), Round(Sqrt(length)))
       else if isNaN(ma[1]) then SimpleMovingAvg(source, length) else
             (ma[1] * (length - 1) + source) / length;
    plot result = ma;
}
#_rate(cond) =>
script _rate {
    input cond = 1;
    def criteria = if cond == 1 then open <= close else open > close;
    def tw = high - Max(open, close) ;
    def bw = Min(open, close) - low;
    def body = AbsValue(close - open);
    def ret  = 0.5 * (tw + bw + (if criteria then 2 * body else 0)) / (tw + bw + body);
    def rate = if nz(ret) == 0 then 0.5 else ret;
    plot Result = rate;
}
def deltaup   = volume * _rate(1);
def deltadown = volume * _rate(0);
def delta     = if close >= open then deltaup else -deltadown;
def cumdelta  = TotalSum(delta);
def o_cd;
def h_cd;
def l_cd;
def c_cd;
def ctl;

if linestyle == linestyle.Candle
then {
    o_cd = cumdelta[1];
    h_cd = Max(cumdelta, cumdelta[1]);
    l_cd = Min(cumdelta, cumdelta[1]);
    c_cd = cumdelta;
    ctl = na;
} else {
    o_cd = na;
    h_cd = na;
    l_cd = na;
    c_cd = na;
    ctl = cumdelta;
}
def LineClose = ExpAverage((cumdelta[1] + Max(cumdelta, cumdelta[1]) + Min(cumdelta, cumdelta[1]) + cumdelta) / 4, 5);
def LineOpen = ExpAverage(if IsNaN(LineOpen[1]) then (cumdelta[1] + cumdelta) / 2 else (LineOpen[1] + LineClose[1]) / 2, 5);
def Line = ctl;
#Line.AssignValueColor( if LineClose >= LineOpen then CreateColor(8,153,129) else if LineClose < LineOpen  then CreateColor(239, 83, 80) else Color.GRAY);
#Line.SetLineWeight(2);
def _Close = (o_cd + h_cd + l_cd + c_cd) / 4;
def _Open = if IsNaN(_Open[1]) then (o_cd + c_cd) / 2 else (_Open[1] + _Close[1]) / 2;
def _High = Max(Max(h_cd, _Open), _Close);
def _Low = Min(Min(l_cd, _Open), _Close);
def haClose_CD = if HeikinAshi then _Close else c_cd;
def haOpen_CD  = if HeikinAshi then _Open  else o_cd;
def haHigh_CD  = if HeikinAshi then _High  else h_cd;
def haLow_CD   = if HeikinAshi then _Low   else l_cd;
def Color = if haClose_CD >= haOpen_CD then 1 else -1;
def UpO;
def UpH;
def UpL;
def UpC;

if Color > 0
then {
    UpO = haOpen_CD ;
    UpH = haHigh_CD ;
    UpL = haLow_CD ;
    UpC = haClose_CD;
} else
{
    UpO = na;
    UpH = na;
    UpL = na;
    UpC = na;
}
# Plot DOWN candle
def DnO;
def DnH;
def DnL;
def DnC;
if Color < 0
then {
    DnO = haOpen_CD ;
    DnH = haHigh_CD ;
    DnL = haLow_CD ;
    DnC = haClose_CD;
} else
{
    DnO = na;
    DnH = na;
    DnL = na;
    DnC = na;
}
def AvgLine = ma(ctl, maLength, maType);
def HaAvgLine = ma(haClose_CD, maLength, maType);
def offs = (1.6185 * stdev(if linestyle == linestyle.Candle then haClose_CD else ctl, maLength));
def upBand = (if linestyle == linestyle.Candle then HaAvgLine else AvgLine) + offs;
def dnBand = (if linestyle == linestyle.Candle then HaAvgLine else AvgLine) - offs;
def BandColor = if (if linestyle == linestyle.Candle then haClose_CD else ctl) > upBand then 1 else if (if linestyle == linestyle.Candle then haClose_CD else ctl) < dnBand then -1 else 0;
def color_1 = if (bandcolor > 0) and (bandcolor[1] < 0) then 1 else 0;
def color_2 = if (bandcolor < 0) and (bandcolor[1] > 0) then 1 else 0;
def Key_Color_1 = In_key_OB and (bandcolor > 0);
def Key_Color_2 = In_key_OB and (bandcolor < 0);
def Key_Color_3 = In_key_OS and (bandcolor > 0);
def Key_Color_4 = In_key_OS and (bandcolor < 0);
#####################################################
## FILTER                                          ##
#####################################################
def Big4_up_1;
def Big4_dn_1;
def TS_UP_1;
def TS_DN_1;
def SparkUP_1;
def SparkDN_1;
switch (Filter_OG_Signals) {
case EMAD_Filter:
    Big4_up_1 = if (MarketOpen and EMAD_Above_Zero and (direction2 == 1 and direction2[1] < 1)) within X_Signal_Bars bars then 1 else 0;
    Big4_dn_1 = if (MarketOpen and EMAD_Below_Zero and (direction2 == -1 and direction2[1] > -1)) within X_Signal_Bars bars then 1 else 0;
    TS_UP_1 = if (MarketOpen and EMAD_Above_Zero and (Upsignal and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    TS_DN_1 = if (MarketOpen and EMAD_Below_Zero and (Downsignal and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    SparkUP_1 = if (MarketOpen and EMAD_Above_Zero and (SparkUP1 and Hide_SparkUP)) within X_Signal_Bars bars then 1 else 0;
    SparkDN_1 = if (MarketOpen and EMAD_Above_Zero and (SparkDN1 and Hide_SparkDN)) within X_Signal_Bars bars then 1 else 0;
case Phase_Filter:
    Big4_up_1 = if (MarketOpen and Bullphase and (direction2 == 1 and direction2[1] < 1)) within X_Signal_Bars bars then 1 else 0;
    Big4_dn_1 = if (MarketOpen and Bearphase and (direction2 == -1 and direction2[1] > -1)) within X_Signal_Bars bars then 1 else 0;
    TS_UP_1 = if ((MarketOpen and Upsignal and Bullphase and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    TS_DN_1 = if ((MarketOpen and Downsignal and Bearphase and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    SparkUP_1 = if (MarketOpen and Bullphase and (SparkUP1 and Hide_SparkUP)) within X_Signal_Bars bars then 1 else 0;
    SparkDN_1 = if (MarketOpen and Bearphase and (SparkDN1 and Hide_SparkDN)) within X_Signal_Bars bars then 1 else 0;
case No_Filter:
    Big4_up_1 = if (MarketOpen and (direction2 == 1 and direction2[1] < 1)) within X_Signal_Bars bars then 1 else 0;
    Big4_dn_1 = if (MarketOpen and (direction2 == -1 and direction2[1] > -1)) within X_Signal_Bars bars then 1 else 0;
    TS_UP_1 = if ((MarketOpen and Upsignal and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    TS_DN_1 = if ((MarketOpen and Downsignal and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    SparkUP_1 = if (MarketOpen and (SparkUP1 and Hide_SparkUP)) within X_Signal_Bars bars then 1 else 0;
    SparkDN_1 = if (MarketOpen and (SparkDN1 and Hide_SparkDN)) within X_Signal_Bars bars then 1 else 0;}
#####################################################
## DIRECTION                                       ##
#####################################################
def Big4_up_bn = if Big4_up_1 then bn else Big4_up_bn[1];
def Big4_dn_bn = if Big4_dn_1 then bn else Big4_dn_bn[1];
def TS_Up_bn = if TS_UP_1 then bn else TS_Up_bn[1];
def TS_Dn_bn = if TS_DN_1 then bn else TS_Dn_bn[1];
def TS_Bars_Back = if TS_Last == 1 then bn - TS_Up_bn else if TS_Last == 0 then bn - TS_Dn_bn else Double.NaN;
def SparkUp_bn = if SparkUP_1 then bn else SparkUp_bn[1];
def SparkDn_bn = if SparkDN_1 then bn else SparkDn_bn[1];
def last_up_bn = if  Big4_up_1 or TS_UP_1 or SparkUP_1 then bn else last_up_bn[1];
def last_dn_bn = if  Big4_dn_1 or TS_DN_1 or SparkDN_1 then bn else last_dn_bn[1];
def Last_Arrow_Up = if last_up_bn > last_dn_bn then 1 else 0;
def Last_Arrow_Down = if last_dn_bn > last_up_bn then 1 else 0;
#####################################################
##                                                 ##
#####################################################
def First_HLLH_3 = if First_HL_2 then Halow else if First_LH_2 then hahigh else First_HLLH_3[1];
def Second_HLLH_3 = if Second_HL_2 then Halow else if Second_LH_2 then hahigh else Second_HLLH_3[1];
def CVD_Cloud_Green = (hl2 > ehlers) and (bandcolor > 0);
def CVD_Cloud_Red = (hl2 < ehlers) and (bandcolor < 0);
def CVD_No_Cloud = !CVD_Cloud_Green and !CVD_Cloud_Red;
def CVD_Green = !CVD_Cloud_Green and CVD_Cloud_Green[1];
def CVD_Green_Bn = if CVD_Green then bn else CVD_Green_Bn[1];
def CVD_Red = !CVD_Cloud_Red and CVD_Cloud_Red[1];
def CVD_Red_bn = if CVD_Red then bn else CVD_Red_bn[1];
def CVD_Last =  (CVD_Green_Bn - CVD_Red_Bn);
def CVD_Last_Green = CVD_Last > 0;
def CVD_Last_Red = CVD_Last < 0;
def countergreen = if CVD_Green and CVD_Last_Green and CVD_No_Cloud then countergreen[1] + 1 else if !CVD_Last_Green then 0 else countergreen[1];
def counterred = if CVD_red and CVD_Last_Red == 1 and CVD_No_Cloud then counterred[1] + 1 else if CVD_Last_Green then 0 else counterred[1];
def countergreen2 = if CVD_Last_Red then 0 else if CVD_Green then (countergreen) else countergreen2[1];
def counterred2 = if CVD_Last_Green then 0 else if CVD_Red then (counterred) else counterred2[1];
def Red_Cloud_Count = CVD_Last_Red and (counterred2 > Clouds_before);
def Green_Cloud_Count = CVD_Last_Green and (countergreen2 > Clouds_before);
def Ehlers_Avg_Length_2 = 120;
def Ehlers_Avg_2 = Average(Ehlers, Ehlers_Avg_Length_2);
#####################################################
##                                                 ##
#####################################################
def EMAD_Controller_1_Down = EMAD_Above_Zero and EMAD_EMA_Down and !EMAD_Controller;
def EMAD_Controller_1_Up = EMAD_Below_Zero and EMAD_EMA_Up and EMAD_Controller;
def EMAD_Controller_1_Down2 = EMAD_Below_Zero and EMAD_EMA_Down and !EMAD_Controller;
def EMAD_Controller_1_Up2 = EMAD_Above_Zero and EMAD_EMA_Up and EMAD_Controller;
#####################################################
##  EMAD CANDLE COLOR DEF                          ##
#####################################################
def CyanCandle = ((warnphase[1] or warnphase[2] or warnphase[3]) and bottomBand_PushDown) or Zone_Green_Wrapping;
def WhiteCandle = ((recphase[1] or recphase[2] or recphase[3]) and TopBand_PushUp) or Zone_Red_Wrapping;
def violetcandle =  EMAD_Controller_1_Up and !TopBand_StepUP and ((bandcolor > 0) within 5 bars);
def magentacandle = EMAD_Controller_1_Down and !bottomBand_StepUP and ((bandcolor < 0) within 5 bars);
def violetcandle2 =  EMAD_Controller_1_Up2 and !TopBand_StepUP and !TopBand_PushUp and ((bandcolor > 0) within 5 bars);
def magentacandle2 = EMAD_Controller_1_Down2 and !bottomBand_StepUP and !bottomBand_PushDown and ((bandcolor < 0) within 5 bars);
def volumecandle_Bull = Bull_Volume_Inc_Avg;
def volumecandle_Bear = Bear_Volume_Inc_Avg;
#####################################################
##                                                 ##
#####################################################
def CyanCandle2 = (!CyanCandle and CyanCandle[1]) Within X_Signal_Bars bars;
def Cyan_bn = if CyanCandle2 then bn else Cyan_bn[1];
def WhiteCandle2 = (!WhiteCandle and WhiteCandle[1]) Within X_Signal_Bars bars;
def white_bn = if whitecandle2 then bn else white_bn[1];
def last_candle_1 = white_bn > Cyan_bn;
def CyanCandle3 = (!CyanCandle2 and CyanCandle2[1]);
def WhiteCandle3 = (!WhiteCandle2 and WhiteCandle2[1]);
def GreenCandle2 = ((hl2 > ehlers) and EMAD_Above_Zero) or topband_PushUp;
def DarkGreenCandle2 = EMAD_EMA_up and bullphase;
def LightGreenCandle2 = EMAD_EMA_down and bullphase;
def RedCandle2 = ((hl2 < ehlers) and EMAD_below_Zero and EMAD_EMA_Down) or bottomband_Pushdown;
def DarkRedCandle2 = (EMAD_EMA_down and bearphase);
def LightRedCandle2 = (EMAD_EMA_up and bearphase) and !In_Key_OS;
def orangecandle2 = topband_compression or bottomband_Compression or Zone_Overlap;
def BlueCandle = (Alert4 or Regular_Sell_Line or Extreme_Sell_Line) and (CyanCandle2 and volumecandle_Bull) Within X_Signal_Bars_2 bars;;
def RedCondition1 = OBOS_Inside_Red and EMAD_EMA_Down and keyobpaint;
def GreenCondition1 =  OBOS_Inside_Green and EMAD_EMA_up and keyospaint;
def hizz1 = hl2 > hiz;
def hizz2 = hl2 < hiz;
def hizz3 = hl2 > hiz2;
def hizz4 = hl2 < hiz2;
def hizz11 = hizz1 and !hizz3;
def hizz111 = hizz1 and hizz3;
def hizz12 = hizz2 and !hizz4;
def hizz122 = hizz2 and hizz4;
def hizz13 = hizz3 and !hizz1;
def hizz14 = hizz4 and !hizz2;
def HIZehlers1 = (Ehlers + plothighz)/2;
def HizEHlers = average(HIZehlers1, hiz_Length);
def flatehlers = HIZEhlers1 == HIZEhlers1[1];
def Alert4_Overlap = Alert4 and orangecandle2;
def Regular_Buy_3X_HL_line = 1;
def CVDLINE = if CVD_Last_Green then halow else if CVD_Last_Red then Hahigh else CVDLINE[1];
def CVDLINEavg = average(cvdline, CVD_Length_avg);
def phaseLINE = if recphase then BH2ext else if warnphase then BL1ext else phaseLINE[1];
def BGbuy = if j crosses above BuyAlertLimit then 1 else 0;
def BGsell = if j crosses below SellAlertLimit then 1 else 0;


def true_count_1 = if condition1_Yellow_Candle then 1 else 0;
def true_count_2 = if condition2_RSI then 1 else 0;
def true_count_3 = if condition3_MFI then 1 else 0;
def true_count_4 = if condition4_Forcast then 1 else 0;
def true_count_5 = if condition5_CIP then 1 else 0;
def true_count_6 = if condition6_EMA_1 then 1 else 0;
def true_count_7 = if condition7_EMA_2 then 1 else 0;
def true_count_8 = if condition8_DMI then 1 else 0;
def true_count_9 = if condition9_Trend then 1 else 0;
def true_count_10 = if condition10_PFE then 1 else 0;
def true_count_11 = if condition11_BB then 1 else 0;
def true_count_12 = if condition12_BB then 1 else 0;
def true_count_13 = if condition13_KH then 1 else 0;
def true_count_14 = if condition14_PO then 1 else 0;
def true_count_15 = if conditionk1UP then 1 else 0;
def true_count_16 = if conditionk2UP then 1 else 0;
def true_count_17 = if conditionob1_RSI then 1 else 0;
def true_count_18 = if conditionob2_MFI then 1 else 0;
def true_count_19 = if conditionob3_Forcast then 1 else 0;
def true_count_20 = if conditionob4_Forcast then 1 else 0;
def true_count_21 = if conditionob5_PFE then 1 else 0;
def true_count_22 = if conditionob6_BB then 1 else 0;
def true_count_23 = if conditionob7_PO then 1 else 0;
def true_count_24 = if UP_OS then 1 else 0;
def true_count_25 = if UP_CL then 1 else 0;
def true_count_26 = if Bullphase then 1 else 0;
def true_count_27 = if direction == 1 then 1 else 0;
def true_count_28 = if EMAD_EMA_UP then 1 else 0;
def true_count_29 = if EMAD_ABOVE_ZERO then 1 else 0;
def true_count_30 = if Green_Cloud_Count then 1 else 0;
def true_count_31 = if Zone_Red_Wrapping then 1 else 0;
def true_count_32 = if Greencandle2 then 1 else 0;
def true_count_33 = if MF_UP then 1 else 0;
def true_count_34 = if upsignal then 1 else 0;
def true_count_35 = if buyerRegular or buyerExtreme then 1 else 0;
def true_count_36 = if HL2 > Ehlers_Avg then 1 else 0;
def true_count_37 = if HL2 > Ehlers_Avg_2 then 1 else 0;
def true_count_38 = if cond1_UP_AK then 1 else 0;
def true_count_39 = if cond2_UP_ZSCORE then 1 else 0;
def true_count_40 = if cond4_UP_AM then 1 else 0;
def true_count_41 = if cond5_UP_TMO then 1 else 0;
def true_count_42 = if BGcolor == 1 then 1 else 0;
def true_count_43 = if BGcolor_Last == 0 then 1 else 0;
def true_count_44 = if topband_Pushup then 1 else 0;

def false_count_1 = if condition1d_Yellow_Candle then 1 else 0;
def false_count_2 = if condition2d_RSI then 1 else 0;
def false_count_3 = if condition3d_MFI then 1 else 0;
def false_count_4 = if condition4d_Forcast then 1 else 0;
def false_count_5 = if condition5d_CIP then 1 else 0;
def false_count_6 = if condition6d_EMA_1 then 1 else 0;
def false_count_7 = if condition7d_EMA_2 then 1 else 0;
def false_count_8 = if condition8d_DMI then 1 else 0;
def false_count_9 = if condition9d_Trend then 1 else 0;
def false_count_10 = if condition10d_PFE then 1 else 0;
def false_count_11 = if condition11d_BB then 1 else 0;
def false_count_12 = if condition12d_BB then 1 else 0;
def false_count_13 = if condition13d_KH then 1 else 0;
def false_count_14 = if condition14d_PO then 1 else 0;
def false_count_15 = if conditionk3DN then 1 else 0;
def false_count_16 = if conditionk4DN then 1 else 0;
def false_count_17 = if conditionos1_RSI then 1 else 0;
def false_count_18 = if conditionOS2_MFI then 1 else 0;
def false_count_19 = if conditionos3_Forcast then 1 else 0;
def false_count_20 = if conditionos4_Forcast then 1 else 0;
def false_count_21 = if conditionos5_PFE then 1 else 0;
def false_count_22 = if conditionos6_BB then 1 else 0;
def false_count_23 = if conditionos7_PO then 1 else 0;
def false_count_24 = if DOWN_OB then 1 else 0;
def false_count_25 = if DOWN_CL then 1 else 0;
def false_count_26 = if Bearphase then 1 else 0;
def false_count_27 = if direction == -1 then 1 else 0;
def false_count_28 = if EMAD_EMA_DOWN then 1 else 0;
def false_count_29 = if EMAD_BELOW_ZERO then 1 else 0;
def false_count_30 = if Red_Cloud_Count then 1 else 0;
def false_count_31 = if Zone_Green_Wrapping then 1 else 0;
def false_count_32 = if Redcandle2 then 1 else 0;
def false_count_33 = if MF_DN then 1 else 0;
def false_count_34 = if Downsignal then 1 else 0;
def false_count_35 = if SellerRegular or SellerExtreme then 1 else 0;
def false_count_36 = if HL2 < Ehlers_Avg then 1 else 0;
def false_count_37 = if HL2 < Ehlers_Avg_2 then 1 else 0;
def false_count_38 = if cond1_DN_AK then 1 else 0;
def false_count_39 = if cond2_DN_ZSCORE then 1 else 0;
def false_count_40 = if cond4_DN_AM then 1 else 0;
def false_count_41 = if cond5_DN_TMO then 1 else 0;
def false_count_42 = if BGcolor == -1 then 1 else 0;
def false_count_43 = if BGcolor_Last == 1 then 1 else 0;
def false_count_44 = if bottomband_PushDown then 1 else 0;

def true_count_sum = true_count_1 + true_count_2 + true_count_3 + true_count_4 + true_count_5 +
                     true_count_6 + true_count_7 + true_count_8 + true_count_9 + true_count_10 +
                     true_count_11 + true_count_12 + true_count_13 + true_count_14 + true_count_15 +
                     true_count_16 + true_count_17 + true_count_18 + true_count_19 + true_count_20 +
                     true_count_21 + true_count_22 + true_count_23 + true_count_24 + true_count_25 +
                     true_count_26 + true_count_27 + true_count_28 + true_count_29 + true_count_30 +
                     true_count_31 + true_count_32 + true_count_33 + true_count_34 + true_count_35 +
                     true_count_36 + true_count_37 + true_count_38 + true_count_39 + true_count_40 +
                     true_count_41 + true_count_42 + true_count_43 + true_count_44;

def false_count_sum = false_count_1 + false_count_2 + false_count_3 + false_count_4 + false_count_5 +
                      false_count_6 + false_count_7 + false_count_8 + false_count_9 + false_count_10 +
                      false_count_11 + false_count_12 + false_count_13 + false_count_14 + false_count_15 +
                      false_count_16 + false_count_17 + false_count_18 + false_count_19 + false_count_20 +
                      false_count_21 + false_count_22 + false_count_23 + false_count_24 + false_count_25 +
                      false_count_26 + false_count_27 + false_count_28 + false_count_29 + false_count_30 +
                      false_count_31 + false_count_32 + false_count_33 + false_count_34 + false_count_35 +
                      false_count_36 + false_count_37 + false_count_38 + false_count_39 + false_count_40 +
                      false_count_41 + false_count_42 + false_count_43 + false_count_44;

def pos_neg_bar = true_count_sum - false_count_sum;
# Calculate average
def num_conditions = 44;
def average_pos_neg_bar = pos_neg_bar / num_conditions;
def average_pos_bar = true_count_sum / num_conditions;
def average_neg_bar = false_count_sum / num_conditions;
def averaged_average_pos = average(true_count_sum, Average_Length);
def averaged_average_neg = average(false_count_sum, Average_Length);
def avg_pos = (averaged_average_pos > averaged_average_neg);
def avg_neg = (averaged_average_pos < averaged_average_neg);
def avg_pos_inc = true_count_sum > true_count_sum[1];
def avg_neg_inc = false_count_sum < false_count_sum[1];

def averaged_average = average(average_pos_neg_bar, Average_Length);
def limit = IsNaN(close) and IsNaN(close[-1] ) && HighestAll(BarNumber());

plot average_line = if !limit then 0 else double.nan;
average_line.assignvaluecolor(if Zone_Overlap then Color.orange else if avg_pos then Color.GREEN  else if avg_neg then Color.Red else color.dark_gray);
average_line.SetLineWeight(2);

plot histogram = pos_neg_bar;
histogram.AssignValueColor(if histogram >= 0 then Color.GREEN else Color.RED);
histogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);

plot high_line = if !limit then High_Limit else double.nan;
high_line.assignvaluecolor(color.dark_gray);
high_line.SetLineWeight(1);

plot low_line = if !limit then Low_Limit else double.nan;
low_line.assignvaluecolor(color.dark_gray);
low_line.SetLineWeight(1);

plot high_line2 = if !limit then 43 else double.nan;
high_line.assignvaluecolor(color.dark_gray);
high_line2.SetLineWeight(2);

plot low_line2 = if !limit then -43 else double.nan;
low_line.assignvaluecolor(color.dark_gray);
low_line2.SetLineWeight(2);

Plot OB = if histogram >= high_line then pos_neg_bar else double.nan;
Plot OS = if histogram <= low_line then pos_neg_bar else double.nan;
#####################################################
##                                                 ##
#####################################################
OB.SetPaintingStrategy(PaintingStrategy.POINTS);
OB.SetLineWeight(3);
OB.assignvaluecolor(color.red);
OS.SetPaintingStrategy(PaintingStrategy.POINTS);
OS.SetLineWeight(3);
OS.assignvaluecolor(color.green);


#####################################################
## ZONE CLOUDS                                     ##
#####################################################
AddCloud(if !HideCloud then low_line else Double.NaN, low_line2, createcolor(60,60,60), createcolor(60,60,60));
AddCloud(if !HideCloud then high_line else Double.NaN, high_line2, createcolor(60,60,60), createcolor(60,60,60));

#FalseHistogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
#FalseHistogram.SetDefaultColor(Color.RED);

Addlabel(yes, " Consensus Level Histogram ", Color.orange);
 
Last edited:
Good people...

Here is the long awaited... highly anticipated... (possibly useless)... C3 BIG MAX Consensus Histogram (Lower)

There are (at this time) 43 up and down conditions including the 14 C3 consensus conditions and the 6 (or 7) C3 OB/OS conditions... plus the BIG 4 conditions, EMAD condtions, Ehlers crossovers, Market phases, etc.

The Zeroline is currently set to change from green to red based on the average amount of up signals being greater or less that down signals at the user input length.


study: https://tos.mx/lXQSaf6

L3fblEZ.png


bP20Dnj.png
---- https://tos.mx/lXQSaf6 ---- Link is not working.
 
Ok I replaced it in the original post
Thanks! The new link isn't working, but I think it's because you recently uploaded it. I'll give it a try later.

I was wondering if you had any updates to the mobile setup? Which versions of the indicators should we use for mobile, as well as settings? Thanks!
 
Thanks! The new link isn't working, but I think it's because you recently uploaded it. I'll give it a try later.

I was wondering if you had any updates to the mobile setup? Which versions of the indicators should we use for mobile, as well as settings? Thanks!
Hmmm weird... yall know that link is a study not a style right? it will not open a window you just have to add it to your chart from your studies.
 
Hmmm weird... yall know that link is a study not a style right? it will not open a window you just have to add it to your chart from your studies.
I'm not sure if the error is simply due to the link being new. Usually takes a bit for links to become active when you open share item.
 
Confirmation Trend Chart 2024

(nothing re-paints / Good for all timeframes)

Chart Style: http://tos.mx/RmujDg2

Disclaimer!
  • There is some unnecessary code that I will remove in time.
  • The white and cyan candles in the screenshots below have been changed to Red and Green.
  • All Arrows are effected by the "Use Clouds Before Filter" status (which I have updated the default settings to show only the "Combined Signals" (violet arrows) when 1 CVD cloud(s) precede the signal ((which is not the same settings pictured below)).
  • I will update the screenshots and whatnot soon.

White Candles Changed to Red / Cyan Candles changed to Green + Observation(s)

dB9RpXb.png


FDfgJQo.png


IPR7fOR.png


Candle Color Code

zzAkrS0.png


Vertical Clouds Between Zones (etc.)

V3xbzrX.png


Lower High Higher Low Candles

ZGW90fV.png


ELhmk6R.png


OB OS Zones Overlap

AhqtjLq.png


Pullbacks / Exhaustion (not triple exhaustion)

JhkCiIC.png

@HODL-Lay-HE-hoo! Awesome update! New candle coloring and clouds make the price action so much clearer, and the combined arrows provide additional confirmation more accurately! 🥳
 
Last edited:
Hello:

This is an awesome chart. When I load it and change to daily/6mos, the prices are a bit off. Is this chart only for use for 1m timeframes?
 
Hello:

This is an awesome chart. When I load it and change to daily/6mos, the prices are a bit off. Is this chart only for use for 1m timeframes?
Hey. Thanks. It works for all timeframes. If your referring to the price bubble I believe that is a function of the candle type.
 
I'm seeing A LOT of arrows and ghost candles and the box lines are confusing without a little shading. Are my settings incorrect? I didn't change anything.

Is there a way to reduce the # of arrows and I read that cyan should be for buying but these are pointing down. Also, the odd ghost candles and it's hard to know if the price is in the box or out without a little shading.
 

Attachments

  • Screenshot 2024-04-12 at 7.02.34 AM.png
    Screenshot 2024-04-12 at 7.02.34 AM.png
    110.4 KB · Views: 424
  • Screenshot 2024-04-12 at 7.02.34 AM.png
    Screenshot 2024-04-12 at 7.02.34 AM.png
    110.4 KB · Views: 414
loads fine

loads fine looks good on the chart seems to be working BUT it cannot be used in a Conditional order . or can it .to complex
To modify chart scripts to work in conditional orders, watchlist custom columns or scans:
1. remove any MTF code as the ToS app does not support secondary aggregations in any of its widgets
2. remove any formatting code as that only applies to charts not to ToS widgets.

The above edits were completed on the above code. Unfortunately, it still remains too complex.

Please note:
While no script is "too complex" to plot on the chart; Schwab does throttle the use of complex scripts in scans, watchlists, and conditional orders to prevent high load runs on the servers.

Many of the more complex scripts found on this forum, can only be used on charts.
They cannot be used in other widgets; such as: scans, watchlists, conditional orders, etc...

Schwab does not currently provide any workarounds.
 
Good people...

Here is the long awaited... highly anticipated... (possibly useless)... C3 BIG MAX Consensus Histogram (Lower)

There are (at this time) 43 up and down conditions including the 14 C3 consensus conditions and the 6 (or 7) C3 OB/OS conditions... plus the BIG 4 conditions, EMAD condtions, Ehlers crossovers, Market phases, etc.

The Zeroline is currently set to change from green to red based on the average amount of up signals being greater or less that down signals at the user input length.

* Added input to adjust the high and low limits and points when crossed*


study: https://tos.mx/UENGBNM (Link updated)

f7jgDtc.png


L3fblEZ.png


bP20Dnj.png


(I need to do housekeeping on the code fyi)

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

declare lower;

#####################################################
##                                                 ##
#####################################################
input High_Limit = 33;
input Low_Limit = -33;
input Average_Length = 21;
def X_Signal_Bars = 5; #hint Signals within x bars = true
input showbubbles = no;
input Color_EMAD_Candles = no;
input TradeDaytimeOnly = no; #hint tradeDaytimeOnly: (IntraDay Only) Only perform trades during hours stated
input OpenTime = 0730; #hint OpenTime: Opening time of market hides arrows
input CloseTime = 1800; #hint CloseTime: Closing time of market hides arrows
input Ehlers_Avg_Length = 9;
input Ehlers_Length = 34;
input ATR_Period_TSV9 = 11;
input ATR_Factor_TSV9 = 2.2;
input Filter_OG_Signals = {EMAD_Filter, Phase_Filter, default No_Filter};
input FirstTrade_Squeeze = {default long, short};
input TrailType = {default modified, unmodified};
input FirstTrade = {default long, short};
input MACD_AverageType = {SMA, default EMA};
input DMI_averageType = AverageType.WILDERS;
input AvgType = AverageType.HULL;
input AverageType_BB = AverageType.SIMPLE;
input type_HV = { default SMP, EXP };
input Candle = {default "wick" , "body" , "close"}; #hint when this part of the candle crosses the POBOS lines (for arrow)
########################################################
## 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));
########################################################
## HEIKIN ASHI                                        ##
########################################################
def Zone_Span = .5;
def Use_Clouds_Before_Filter = no; #hint Effects "combined signals" the violet arrows
def CVD_Length_avg = 9;
def Flat_Earth_Bars = 10;
def Flat_Earth_Controller = 10;
def Above_X_Levels = 5;
def Below_X_Levels = 1;
def BG_Bars = 5;
def Color_HIZ_Candles = no;
def Color_HIZ_Candles2 = no;
def hiz_Length = 9;
def Color_Ehlers_Candles = no;
def Show_HLLH_Color = yes;
def X_Upcolor1_Bars  = 5;
def Clouds_before = 5;
def X_Green_Clouds = 1;
def X_Red_Clouds = 1;
def hidecloud = no;
def Show_CVD_Cloud = yes;
def Show_EMAD_Cloud = yes;
def Show_Phase_Cloud = yes;
def X_Signal_Bars_2 = 3; #hint Signals within x bars = true
def Show_Signal_Bubbles = no;
def Signal_UP_Agreement = 1; #hint Agreement: if greater than this number of signals are true within x bars
def Signal_DOWN_Agreement = 1; #hint Agreement: if greater than this number of signals are true within x bars;
def Show_C3_Labels = yes;
def Show_OG_Filter_label = no;
def Show_Combined_Filter_label = no;
def Show_Combined_Signals = yes;
def Show_Alert4_Signals = no;
def Show_EMAD_Signals = no;
def Show_EMAD_HLLH_Signals = no;
def Show_Triple_Exh_Signals = no;
def Show_TS_Signals = no;
def Show_Spark_Signals = no;
def Show_Big4_Signals = no;
def X_Keylevel_Bars = 10; #hint Signals within x bars = true
def bn = barnumber();
def AllAvgINC_Length = 5;
def Low_Volume = 5;
def lengthVolAvgPlotselling = 9;
def lengthVolAvgPlotbuying = 9;
def Crossed_Consensus_UP = 6;
def Crossed_Consensus_DOWN = -6;
def Show_C3_Levels = no;
def Buy_Sell_Avg_Length = 20;
def OBOS_Compression = 0.2;
def EMAD_Zero_Compression = 0.1;
def X_InKey_Bars = 5;
def X_Zone_bars = 5;
def X_Zone_Cloud_Bars = 10;
def X_Alert4_Bars = 10; #hint Signals within x bars = true
def Length_HV = 20;
def Hot_Percent_HV = 110.0; #hint total volume of bar greater than hotpct = cyan triangle
def Big4_Confirmation_Factor = 4; #hint Big4
def EMAD_Cloud_Lookback = 100;
def Hide_Consecutive = yes; #hint Combined Signals: Hidden if within 5 bars of signals in the same direction
def Compression_Span_Low = 1;
def Zone_Average_length = 21;
def Zone_Percent_Diff = .5;
########################################################
##                                                    ##
########################################################
def haClose = (open + high + low + close) / 4;
def haOpen = if IsNaN(haOpen[1]) then (open + close) / 2 else (haOpen[1] + haClose[1]) / 2;
def haHigh = Max(high, Max(haClose, haOpen));
def haLow = Min(low, Min(haClose, haOpen));
########################################################
## HA WICK, BODY, CLOSE OF CANDLE FOR BREAKOUTS       ##
########################################################
def High_Levels;
def Low_Levels;
switch (Candle) {
case "wick":
    High_Levels = haHigh;
    Low_Levels = haLow;
case "body":
    High_Levels = Max(haOpen, haClose);
    Low_Levels = Min(haOpen, haClose);
case "close":
    High_Levels = haClose;
    Low_Levels = haClose;
}
#// This source code is subject to the terms of the Mozilla Public License 2.0 at #https://mozilla.org/MPL/2.0/
#// © blackcat1402
#https://www.tradingview.com/script/bhdaBHlg-blackcat-L2-KDJ-with-Whale-Pump-and-Oust/
#study("[blackcat] L2 KDJ with Whale Pump and Oust"
# Converted by Sam4Cok@Samer800 - 08/2022

#//inputs
input ShowBubble     = yes;
input ShowBubble2    = no;

input ShowHistogram  = yes;
input BuyAlertLimit  = 0;   # "BuyAlertLimit"
input SellAlertLimit =100; # "SellAlertLimit"
input Period = 18;
input SignalK = 4;
input SignalD = 4;

#//functions
def na2 = Double.NaN;
script nz {
    input data  = 1;
    input repl  = 0;
    def ret_val = if IsNaN(data) then repl else data;
    plot return = ret_val;
}
#xrf(values, length) =>
script xrf {
    input values = close;
    input length = 0;
    def r_val;
    r_val = if length >= 1 then
        fold i = 0 to length
            with p do
            if IsNaN(r_val[1]) or !IsNaN(values[i]) then values[i] else r_val[1] else Double.NaN;
    plot return =  r_val;
}
#xsa(src,len,wei) =>
script xsa {
    input src = close;
    input len = 0;
    input wei = 0;
    def sumf;
    def ma;
    def out;
    sumf =  nz(sumf[1]) - nz(src[len]) + src;
    ma   =  if IsNaN(src[len]) then Double.NaN else sumf / len;
    out  =  if IsNaN(out[1]) then ma else (src * wei + out[1] * (len - wei)) / len;
    plot return = out;
}
#alma(series, length, offset, sigma, floor)
script ALMA {
input series = close;
input windowsize = 9;
input Offset = 0.85;
input Sigma = 6;
def m = Offset * (windowsize - 1);
def s = windowsize/Sigma;
def Sum = fold i = 0 to windowsize with WS do
           WS + Exp(-1 * (sqr(i-m))/(2*sqr(s))) * getValue(series, windowsize - i - 1);
def norm = fold j = 0 to windowsize with CW do
           CW + Exp(-1 * (sqr(j-m))/(2*sqr(s)));
plot ALMA = sum / norm;
}
#//algorithm for whale pump an oust-----
    def var1 = xrf(ohlc4,1)[1];
    def var2 = xsa(AbsValue(low - var1), 13, 1) / xsa(Max(low - var1, 0), 10, 1);
    def var3 = ExpAverage(var2, 10);
    def var4 = Lowest(low, 33);
    def var5 = ExpAverage(If(low <= var4, var3, 0), 3);

#//define KDJ
def rsv = (close-lowest(low,Period))/(highest(high,Period)-lowest(low,Period))*100;
def k2 = alma(xsa(rsv,SignalK,1),3,0.85,6);
def d = alma(xsa(k2,SignalD,1),3,0.85,6);
def j = alma(3*k2-2*d,3, 0.85,6);

########
#// plot signal
#    plot kLine = k2;
#    kLine.SetDefaultColor(Color.WHITE);
#    plot dLine = d;
#    dLine.SetDefaultColor(Color.ORANGE);
#    plot jLine = j;
#    jLine.AssignValueColor( CreateColor(17, 118, 242));
#    jLine.SetLineWeight(2);

def KJD_Cross_Down = (d > k2) and (k2 > j);
def KJD_Down = KJD_Cross_Down[1] and  KJD_Cross_Down[2] and  KJD_Cross_Down[3] and KJD_Cross_Down;
def KJD_Cross_Up = (d < k2) and (k2 < j);
def KJD_Up = KJD_Cross_Up[1] and KJD_Cross_Up[2] and KJD_Cross_Up[3] and KJD_Cross_Up;

#//plot whale buy histograms

    def bgcolor = if j crosses above BuyAlertLimit then 1 else
                  if j crosses below SellAlertLimit then -1 else 0;

def BGcolor_UP = if j crosses above BuyAlertLimit then 1 else 0;
def BGcolor_DN =  if j crosses below SellAlertLimit then 1 else 0;
def BGcolor_UP_bn = if BGcolor_UP then bn else BGcolor_UP_bn[1];
def BGcolor_DN_bn = if BGcolor_DN then bn else BGcolor_DN_bn[1];
def BGcolor_Last = BGcolor_UP_bn > BGcolor_DN_bn;
#//whale pump candles
#    plot OustHist = var5;
#    OustHist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
#    OustHist.SetHiding(!ShowHistogram);
#    OustHist.AssignValueColor(if var5 > var5[1] then CreateColor(38,166,154) else
#                          if var5 < var5[1] then Color.PINK else Color.GRAY);
#//Add Bubble
def plothighz = if (j crosses above BuyAlertLimit) then halow else if (j crosses below SellAlertLimit) then hahigh else plothighz[1];
def hiz = plothighz;

def plothighz2 = average(plothighz, hiz_Length);
def hiz2 = plothighz2;

#//define bottom zone threshold values
def h1 = 99;
def h2 = 2;
def h3 = 0;
def h4 = 100;
#AddCloud(h2, h3, Color.DARK_GREEN, Color.DARK_GREEN, yes);
#AddCloud(h1, h4, CreateColor(255, 102, 255),  CreateColor(255, 102, 255), yes);

########################################################
##                                                    ##
########################################################
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;
def LongTrades = yes; #hint LongTrades: perform long
def ShortTrades = yes; #hint ShortTrades: perform short trades
def useStops = no;     #hint useStops: use stop orders
def useAlerts = no;    #hint useAlerts: use alerts on signals
#####################################################
## FIRST BAR                                       ##
#####################################################
def lastbar = HighestAll(if IsNaN(close[-1]) then bn else 0);
def Firstbar = SecondsFromTime(OpenTime)[1] < 0 and SecondsFromTime(OpenTime) >= 0;
def FirstBar_number = if Firstbar then bn else FirstBar_number[1];
def Bars_From_First = bn - FirstBar_number;
def Within_Range = Bars_From_First < EMAD_Cloud_Lookback;
#####################################################
## HORSERIDER VOLUME                               ##
#####################################################
def buying = volume * (close - low) / (high - low);
def selling = volume * (high - close) / (high - low);
def MA = if type_HV == type_HV.SMP then SimpleMovingAvg(volume, Length_HV) else MovAvgExponential(volume, Length_HV);
def HV = if (100 * ((volume / MA) - 1) >= Hot_Percent_HV) then 1 else 0;
def VolAvg1 = Average(volume, Buy_Sell_Avg_Length);
def VolAvgsell1 = Average(selling, Buy_Sell_Avg_Length);
def VolAvgbuy1 = Average(buying, Buy_Sell_Avg_Length);
def sellgoingup = VolAvgsell1 > VolAvgsell1[1];
def buygoingup = VolAvgbuy1 > VolAvgbuy1[1];
def Avggoingup = VolAvg1 > VolAvg1[1];
def selling_low = selling < Low_Volume;
def buying_low = buying < Low_Volume;
def Buy_Up_Sell_Up = sellgoingup and buygoingup;
def Buy_Up_Sell_Down = !sellgoingup and buygoingup;
def Buy_Down_Sell_Down = !sellgoingup and !buygoingup;
def Sell_Up_Buy_Down = sellgoingup and !buygoingup;
def sell_Abv_Avg =  VolAvgsell1 > VolAvg1;
def Buy_Abv_Avg =  VolAvgbuy1 > VolAvg1;
def bothup = sellgoingup and buygoingup;
def Volume_BiasBull = (VolAvgsell1 >= VolAvgbuy1);
def Volume_BiasBear = (VolAvgsell1 < VolAvgbuy1);
def Volume_Crossover_Bull = Volume_BiasBull and !Volume_BiasBull[1];
def Volume_Crossover_Bear = Volume_BiasBull and !Volume_BiasBull[1];
def sell_below_Avg =  VolAvgsell1 < VolAvg1;
def Buy_below_Avg =  VolAvgbuy1 < VolAvg1;
def buy_avg_above_sell = VolAvgbuy1 > VolAvgsell1;
def Sell_avg_above_buy = VolAvgsell1 > VolAvgbuy1;
def Buy_crosses_sell_avg = !buy_avg_above_sell[1] and buy_avg_above_sell;
def Buy_crosses_sell_avg_Down = buy_avg_above_sell[1] and !buy_avg_above_sell;
def Sell_crosses_buy_avg = !Sell_avg_above_buy[1] and Sell_avg_above_buy;
def Sell_crosses_buy_avg_Down = Sell_avg_above_buy[1] and !Sell_avg_above_buy;
def Buy_crosses_avg = !Buy_Abv_Avg[1] and Buy_Abv_Avg;
def Buy_crosses_avg_Down = Buy_Abv_Avg[1] and !Buy_Abv_Avg;
def Sell_crosses_avg = !sell_Abv_Avg[1] and sell_Abv_Avg;
def Sell_crosses_avg_Down = sell_Abv_Avg[1] and !sell_Abv_Avg;
def Selling_Then_Buying = (selling[1] > VolAvg1[1]) and (Buying > VolAvg1);
def Buying_Then_Selling = (Buying[1] > VolAvg1[1]) and (selling > VolAvg1);
def Bull_Volume_Inc_Avg = Selling_Then_Buying and Avggoingup;
def Bear_Volume_Inc_Avg = Buying_Then_Selling and Avggoingup;
#####################################################
## UPPER EMA                                       ##
#####################################################
def Cloud_Lookback = 20;
def HL_LH_Lookback = 20;
def Previous_Steps_Down = 2; #hint filter for hiding arrows
def Previous_Steps_Up = 2; #hint filter for hiding arrows
def Length_MAD = 4;
def Band_Length = 100;
def Smooth_Length = 12;
def Smooth_Length_2 = 14;
def Fast_Length = 10;
def Slow_Length = 35;
def Made_Avg_Length = 3;
def ATR_Period_Squeeze = 5;
def ATR_Factor_Squeeze = 2.0;
def Length_3x = 1000;
def AverageType = AverageType.WILDERS;
def AverageType_Squeeze = AverageType.SIMPLE;
def EMAD_EMA_lineweight = 2;
def Step_lookback = 10;
def FastExpAvg = ExpAverage(close, Fast_Length);
def SlowExpAvg = ExpAverage(close, Slow_Length);
def EMAD_Fast = (close - FastExpAvg);
def EMAD_Slow = (close - SlowExpAvg);
def EMAD_Avg = (EMAD_Fast + EMAD_Slow) / 2;
#####################################################
## UPPER EMA                                       ##
#####################################################
def Upper_EMAD_EMA = ExpAverage(EMAD_Avg, Smooth_Length);
def EMAD_Open = (Upper_EMAD_EMA + Upper_EMAD_EMA[1]) / 2;
def EMAD_High = Max(Upper_EMAD_EMA, Upper_EMAD_EMA[1]);
def EMAD_Low = Min(Upper_EMAD_EMA, Upper_EMAD_EMA[1]);
def EMAD_Close = Upper_EMAD_EMA;
def Bottom = Min(EMAD_Close[1], EMAD_Low);
def TR = TrueRange(EMAD_High, EMAD_Close, EMAD_Low);
def PTR = TR / (Bottom + TR / 2);
def APTR = MovingAverage(AverageType, PTR, Smooth_Length_2);
def UpperBand = EMAD_Close[1] + (APTR * EMAD_Open);
def LowerBand = EMAD_Close[1] - (APTR * EMAD_Open);
#####################################################
## LOWER EMA                                       ##
#####################################################
def Lower_EMAD_EMA = (UpperBand + LowerBand) / 2;
#####################################################
## TOP BAND                                        ##
#####################################################
def TopBand = Highest(Lower_EMAD_EMA, Band_Length);
#####################################################
## BOTTOM BAND                                     ##
#####################################################
def BottomBand = Lowest(Lower_EMAD_EMA, Band_Length);
#####################################################
## ZERO LINE                                       ##
#####################################################
def ZeroLineData = if IsNaN(close) then Double.NaN else 0;
def EMAD_Above_Zero = Upper_EMAD_EMA > ZeroLineData;
def EMAD_Below_Zero = Upper_EMAD_EMA < ZeroLineData;
def EMAD_Above_Zero_1 = if EMAD_Above_Zero then 1 else 0;
def EMAD_Below_Zero_1 = if EMAD_Below_Zero then 1 else 0;
def EMAD_EMA_down = (Lower_EMAD_EMA > Upper_EMAD_EMA);
def EMAD_EMA_up = (Upper_EMAD_EMA >= Lower_EMAD_EMA);
#####################################################
## MASTER EMA                                      ##
#####################################################
def Master_EMAD_EMA = (Upper_EMAD_EMA + Lower_EMAD_EMA) / 2;
def TopBand_StepDown = if TopBand < TopBand[1] then 1 else 0;
def TopBand_StepUp = if TopBand > TopBand[1] then 1 else 0;
def BottomBand_StepDown = if BottomBand < BottomBand[1] then 1 else 0;
def BottomBand_StepUp = if BottomBand > BottomBand[1] then 1 else 0;
def BothBands_Down = BottomBand_StepDown and TopBand_StepDown;
def BothBands_Up = BottomBand_StepUp and TopBand_StepUp;
def BottomBand_Above_Zero = (BottomBand > ZeroLineData);
def TopBand_below_Zero = (TopBand < ZeroLineData);
def TopBand_PushUp =  Master_EMAD_EMA >= TopBand;
def BottomBand_PushDown = Master_EMAD_EMA <= BottomBand;
def MidBand = (UpperBand + LowerBand) / 2;
def EMA_CrossUp = if (midBand[1] > Upper_EMAD_EMA[1]) and (midBand < Upper_EMAD_EMA) then 1 else 0;
def EMA_CrossUp_bn = if EMA_CrossUp then bn else EMA_CrossUp_bn[1];
def EMA_CrossDown = if (Upper_EMAD_EMA[1] > midBand[1]) and (Upper_EMAD_EMA < midBand) then 1 else 0;
def EMA_CrossDown_bn = if EMA_CrossDown then bn else EMA_CrossDown_bn[1];
def EMA_Last_Cross = EMA_CrossUp_bn > EMA_CrossDown_bn;
#####################################################
## VALUE                                           ##
#####################################################
def Value_At_CrossUp = if EMA_CrossUp then midBand else Value_At_CrossUp[1];
def Value_At_CrossDown = if EMA_CrossDown then midBand else Value_At_CrossDown[1];
#####################################################
## CROSS AT BAND                                   ##
#####################################################
def CrossUp_BottomBand = if (Value_At_CrossUp - bottomBand) == 0 then 1 else 0;
def CrossDown_TopBand = if (Value_At_CrossDown - topBand) == 0 then 1 else 0;
def CrossUp_BottomBand_1 =  !CrossUp_BottomBand[1] and CrossUp_BottomBand;
def CrossDown_TopBand_1 = !CrossDown_TopBand[1] and CrossDown_TopBand;
def CrossUp_BottomBand_1_bn = if CrossUp_Bottomband_1 then bn else CrossUp_Bottomband_1_bn[1];
def CrossDown_TopBand_1_bn = if CrossDown_topband_1 then bn else CrossDown_TopBand_1_bn[1];
#####################################################
## CROSS AT ZERO                                   ##
#####################################################
def CrossUp_Zeroline = if (Value_At_CrossUp) == 0 then 1 else 0;#THIS IS NOT GOOD FIX IT
def CrossDown_Zeroline = if (Value_At_CrossDown) == 0 then 1 else 0;
def Band_Crossed_First = CrossUp_Bottomband_1_bn > CrossDown_TopBand_1_bn;
#####################################################
## TEST CONDITIONS                                 ##
#####################################################
def CrossUp_BottomBand_Midband = if CrossUp_BottomBand_1 then round(absvalue(midBand),2) else CrossUp_BottomBand_Midband[1];
def CrossDOWN_TopBand_Midband = if CrossDOWN_TopBand_1 then round(absvalue(midBand),2) else CrossDOWN_TopBand_Midband[1];
def UP_Condition_HL = (Marketopen and EMAD_Below_Zero and EMA_CrossUp and !CrossUp_BottomBand_1);
def UP_Condition_HL_bn = if UP_Condition_HL then bn else UP_Condition_HL_bn[1];
def UP_Condition_HL_Midband = if UP_Condition_HL then round(absvalue(midBand),2) else UP_Condition_HL_Midband[1];
def UP_Condition_HL_2 = UP_Condition_HL and (UP_Condition_HL_bn > CrossUp_BottomBand_1_bn);
def UP_Condition_Is_HL = UP_Condition_HL and (UP_Condition_HL_Midband < UP_Condition_HL_Midband[1]);
def UP_Condition_4 = UP_Condition_HL_Midband < CrossUp_BottomBand_Midband[1];
def UP_Condition_4_1 = !UP_Condition_4[1] and UP_Condition_4;
def DOWN_Condition_LH = (Marketopen and EMAD_Above_Zero and EMA_CrossDOWN and !CrossDOWN_TopBand_1);
def DOWN_Condition_LH_bn = if DOWN_Condition_LH then bn else DOWN_Condition_LH_bn[1];
def DOWN_Condition_LH_Midband = if DOWN_Condition_LH then round(absvalue(midBand),2) else DOWN_Condition_LH_Midband[1];
def DOWN_Condition_LH_2 = DOWN_Condition_LH and (DOWN_Condition_LH_bn > CrossDOWN_TopBand_1_bn);
def DOWN_Condition_Is_LH = DOWN_Condition_LH and (DOWN_Condition_LH_Midband < DOWN_Condition_LH_Midband[1]);
def DOWN_Condition_4 = DOWN_Condition_LH_Midband < CrossDOWN_TopBand_Midband[1];
def DOWN_Condition_4_1 = !DOWN_Condition_4[1] and DOWN_Condition_4;
input EMAD_HL_LH_Sum_Length = 120;
def UPHL = UP_Condition_Is_HL and UP_Condition_4 ;
def DOWNLH = DOWN_Condition_Is_LH and DOWN_Condition_4;
def totalHL = sum(UPHL, EMAD_HL_LH_Sum_Length);
def totalLH = sum(DownLH, EMAD_HL_LH_Sum_Length);
def EMAD_Controller = totalHL > totalLH;
#####################################################
##                                                 ##
#####################################################
def Topband_Compression = absvalue(topband) < EMAD_Zero_Compression;
def Bottomband_Compression = absvalue(bottomband) < EMAD_Zero_Compression;
#####################################################
## EMAD CLOUD CONDITIONS                           ##
#####################################################
def EMAD_Green_Cloud_1 = if TopBand_StepUp and TopBand_PushUp and !TopBand_below_Zero then 1 else 0;
def EMAD_Green_Cloud_2 = if BottomBand_StepUp and EMAD_EMA_up and !EMAD_Below_Zero then 1 else 0;
def EMAD_Green_Cloud_3 = if (EMAD_Green_Cloud_1 or EMAD_Green_Cloud_2) then 1 else 0;
def EMAD_Red_Cloud_1 = if BottomBand_StepDown and BottomBand_PushDown and !BottomBand_Above_Zero then 1 else 0;
def EMAD_Red_Cloud_2 = if TopBand_StepDown and EMAD_EMA_down and !EMAD_Above_Zero then 1 else 0;
def EMAD_Red_Cloud_3 = if (EMAD_Red_Cloud_1 or EMAD_Red_Cloud_2) then 1 else 0;
def EMAD_Gray_Cloud_1 = if BottomBand_Above_Zero and !TopBand_PushUp then 1 else 0;
def EMAD_Gray_Cloud_2 = if TopBand_below_Zero and !BottomBand_PushDown then 1 else 0;
#####################################################
## TEST CONDITIONS FOR LEVELS                      ##
#####################################################
def EMAD_Green_Cloud_4 = if MarketOpen and EMAD_EMA_up and (!EMAD_Green_Cloud_3[1] and EMAD_Green_Cloud_3) then 1 else 0;
def EMAD_Red_Cloud_4 = if MarketOpen and EMAD_EMA_down and (!EMAD_Red_Cloud_3[1] and EMAD_Red_Cloud_3) then 1 else 0;
#####################################################
## TEST CONDITIONS FOR LEVELS                      ##
#####################################################
def EMAD_Green_Cloud_4_bn = if EMAD_Green_Cloud_4 then bn else EMAD_Green_Cloud_4_bn[1];
def EMAD_Red_Cloud_4_bn = if EMAD_Red_Cloud_4 then bn else EMAD_Red_Cloud_4_bn[1];
def cloudgreenbarsback = bn - EMAD_Green_Cloud_4_bn;
def cloudredbarsback = bn - EMAD_Red_Cloud_4_bn;
#####################################################
## LAST CLOUD COLOR                                ##
#####################################################
def Last_Cloud = if (cloudredbarsback > cloudgreenbarsback) then 1 else if  (cloudredbarsback < cloudgreenbarsback) then -1 else 0; # 1=green 0=red
def Last_Cloud_Green = if (cloudredbarsback > cloudgreenbarsback) then 1 else 0; # 1=green 0=red
def Last_Cloud_Red = if (cloudredbarsback < cloudgreenbarsback) then 1 else 0; # 1=red 0=green
#####################################################
## COUNT CLOUDS                                    ##
#####################################################
def Last_Red_Green = if Last_Cloud_Red[1] and EMAD_Green_Cloud_4 then 1 else 0;
def LastRG_Bn = if Last_Red_Green then bn else LastRG_Bn[1];
def Last_Green_Red = if Last_Cloud_Red[1] and EMAD_Red_Cloud_4 then 1 else 0;
def LastGR_Bn = if Last_Green_Red then bn else LastGR_Bn[1];
def dynamic_length_green = if !Last_Red_Green then Bars_From_First else if Last_Red_Green then bn - LastRG_Bn else Double.NaN;
def dynamic_length_red = if !Last_Green_Red then Bars_From_First else if Last_Green_Red then bn - LastGR_Bn else Double.NaN;
#####################################################
## COUNT                                           ##
#####################################################
def EMAD_Green_Cloud_lookback = fold index10 = 0 to EMAD_Cloud_Lookback with x10 do x10 + EMAD_Green_Cloud_4[index10];
def EMAD_Red_Cloud_lookback = fold index11 = 0 to EMAD_Cloud_Lookback with x11 do x11 + EMAD_Red_Cloud_4[index11];
#####################################################
## ALTERNATE COUNT METHOD                          ##
#####################################################
def count_window_length = EMAD_Cloud_Lookback;
def conditiongreen = EMAD_Green_Cloud_4; #ex. green cloud then red cloud then green: if lastcloudred[1] and green cloud then counter
def conditionred = EMAD_Red_Cloud_4; #ex. green cloud then red cloud then green: if lastcloudred[1] and green cloud then counter
def counter_green_V2 = Sum(conditiongreen, EMAD_Cloud_Lookback);
def counter_red_V2 = Sum(conditionred, EMAD_Cloud_Lookback);
#####################################################
## TESTING                                         ##
#####################################################
def New_count_green = if Last_Cloud_Green[1] and conditiongreen then (counter_green_V2[1] + 1) else counter_green_V2[1];
def New_count_red = if Last_Cloud_Red[1] and conditionred then (counter_red_V2[1] + 1) else counter_red_V2[1];
def Bubble_green = if !Last_Cloud_Green[1] and conditiongreen then New_count_green - New_count_green[1] else New_count_green;
def Bubble_red = if !Last_Cloud_Red[1] and conditionred then New_count_red - New_count_red[1] else New_count_red;
#####################################################
## CLOUDS BEFORE SIGNAL                            ##
#####################################################
def Green_Clouds_Before = EMAD_Green_Cloud_lookback > X_Green_Clouds;
def Red_Clouds_Before = EMAD_Red_Cloud_lookback > X_Red_Clouds;
#####################################################
## HIGHER LOW - LOWER HIGH                         ##
#####################################################
def HL = CrossUp_BottomBand == 0 and CrossDown_TopBand == 0 and Upper_EMAD_EMA crosses above Lower_EMAD_EMA; #Normal HL LH condition
def LH = CrossDown_TopBand == 0 and CrossUp_BottomBand == 0 and Upper_EMAD_EMA crosses below Lower_EMAD_EMA; #Normal HL LH condition
def bounceUpOnce = CrossUp_BottomBand <> CrossUp_BottomBand[1]; #XUpBtm happened previous bar or on current bar (<> = is NOT equal to)
def bounceDnOnce = CrossDown_TopBand <> CrossDown_TopBand[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];
def HLalready = if trackCrUp and !trackCrUp[1] then 1 else 0;
def LHalready = if trackCrDn and !trackCrDn[1] then 1 else 0;
def HL2_EMAD = HLalready == 0 and Upper_EMAD_EMA crosses above Lower_EMAD_EMA;
def LH2_EMAD  = LHalready == 0 and Upper_EMAD_EMA crosses below Lower_EMAD_EMA;
def crossedUpOnce = HLalready <> HLalready[1];
def crossedDnOnce = LHalready <> LHalready[1];
def trackCrUp2 = if crossedUpOnce then 0 else if HL2_EMAD then 1 else trackCrUp2[1];
def trackCrDn2 = if crossedDnOnce then 0 else if LH2_EMAD then 1 else trackCrDn2[1];
#####################################################
## SQUEEZE                                         ##
#####################################################
def HiLo_Squeeze = Min(high - low, 1.5 * Average(high - low, ATR_Period_Squeeze));
def HRef_Squeeze = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef_Squeeze = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def trueRange_Squeeze;
switch (TrailType) {
case modified:
    trueRange_Squeeze = Max(HiLo_Squeeze, Max(HRef_Squeeze, LRef_Squeeze));
case unmodified:
    trueRange_Squeeze = TrueRange(high, close, low);
}
def loss_Squeeze = ATR_Factor_Squeeze * MovingAverage(AverageType_Squeeze, trueRange_Squeeze, ATR_Period_Squeeze);
def state_Squeeze = {default init, long, short};
def trail_Squeeze;
switch (state_Squeeze[1]) {
case init:
    if (!IsNaN(loss_Squeeze)) {
        switch (FirstTrade) {
        case long:
            state_Squeeze = state_Squeeze.long;
            trail_Squeeze =  close - loss_Squeeze;
        case short:
            state_Squeeze = state_Squeeze.short;
            trail_Squeeze = close + loss_Squeeze;
    }
    } else {
        state_Squeeze = state_Squeeze.init;
        trail_Squeeze = Double.NaN;
    }
case long:
    if (close > trail_Squeeze[1]) {
        state_Squeeze = state_Squeeze.long;
        trail_Squeeze = Max(trail_Squeeze[1], close - loss_Squeeze);
    } else {
        state_Squeeze = state_Squeeze.short;
        trail_Squeeze = close + loss_Squeeze;
    }
case short:
    if (close < trail_Squeeze[1]) {
        state_Squeeze = state_Squeeze.short;
        trail_Squeeze = Min(trail_Squeeze[1], close + loss_Squeeze);
    } else {
        state_Squeeze = state_Squeeze.long;
        trail_Squeeze =  close - loss_Squeeze;
    }
}
def TrailingStop_Squeeze = trail_Squeeze;
def H = Highest(TrailingStop_Squeeze, 12);
def L = Lowest(TrailingStop_Squeeze, 12);
def Bandwidth_Squeeze = (H - L);
def IntermSupport2 = Lowest(Bandwidth_Squeeze, Band_Length);
def Squeeze_Trigger = Bandwidth_Squeeze <= IntermSupport2;
def Squeeze_Level = if !Squeeze_Trigger[1] and Squeeze_Trigger then hl2 else if !Squeeze_Trigger then Double.NaN else Squeeze_Level[1];
def Squeeze_Alert_1 = if Squeeze_Level then (Upper_EMAD_EMA + Lower_EMAD_EMA) / 2 else (Upper_EMAD_EMA + Lower_EMAD_EMA) / 2;
#####################################################
## TS V9                                           ##
#####################################################
def HiLo_TSV9 = Min(high - low, 1.5 * Average(high - low, ATR_Period_TSV9));
def HRef_TSV9 = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef_TSV9 = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def trueRange_TSV9;
switch (TrailType) {
case modified:
    trueRange_TSV9 = Max(HiLo_TSV9, Max(HRef_TSV9, LRef_TSV9));
case unmodified:
    trueRange_TSV9 = TrueRange(high, close, low);
}
def loss_TSV9 = ATR_Factor_TSV9 * MovingAverage(AverageType, trueRange_TSV9, ATR_Period_TSV9);
def state_TSV9 = {default init, long, short};
def trail_TSV9;
switch (state_TSV9[1]) {
case init:
    if (!IsNaN(loss_TSV9)) {
        switch (FirstTrade) {
        case long:
            state_TSV9 = state_TSV9.long;
            trail_TSV9 =  close - loss_TSV9;
        case short:
            state_TSV9 = state_TSV9.short;
            trail_TSV9 = close + loss_TSV9;
    }
    } else {
        state_TSV9 = state_TSV9.init;
        trail_TSV9 = Double.NaN;
    }
case long:
    if (close > trail_TSV9[1]) {
        state_TSV9 = state_TSV9.long;
        trail_TSV9 = Max(trail_TSV9[1], close - loss_TSV9);
    } else {
        state_TSV9 = state_TSV9.short;
        trail_TSV9 = close + loss_TSV9;
    }
case short:
    if (close < trail_TSV9[1]) {
        state_TSV9 = state_TSV9.short;
        trail_TSV9 = Min(trail_TSV9[1], close + loss_TSV9);
    } else {
        state_TSV9 = state_TSV9.long;
        trail_TSV9 =  close - loss_TSV9;
    }
}
def Price = close;
def TrailingStop_TSV9 = trail_TSV9;
def Upsignal = (Price crosses above TrailingStop_TSV9);
def Downsignal = (Price crosses below TrailingStop_TSV9);
def BuySig_TSV9_bn = if Upsignal[1] then bn else BuySig_TSV9_bn[1];
def SellSig_TSV9_bn = if Downsignal[1] then bn else SellSig_TSV9_bn[1];
def TS_Last = if BuySig_TSV9_bn > SellSig_TSV9_bn then 1 else 0;
def cond13_TS_Buy = Upsignal and !Upsignal[1];
def cond13_TS_Sell = Downsignal and !Downsignal[1];
#####################################################
## TRIPLE EXHAUSTION                               ##
#####################################################
def OB_3x = 80;
def OS_3x = 20;
def KPeriod_3x = 10;
def DPeriod_3x = 10;
def SlowK_3x = reference StochasticFull(OB_3x,  OS_3x,  KPeriod_3x,  DPeriod_3x,  EMAD_High, EMAD_Low, EMAD_Close,  3, if (AverageType == 1) then AverageType.SIMPLE else AverageType.EXPONENTIAL).FullK;
def MACD_3x = reference MACD()."Value";
def Price_Avg_3x = Average(MACD_3x, Length_3x);
def MACD_stdev_3x =  (MACD_3x - Price_Avg_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 Extreme_Buy_1 = if SellerExtreme[1] and !SellerExtreme then haLow else Double.NaN;
def Regular_Buy_1 = if SellerRegular[1] and !SellerRegular then haLow else Double.NaN;
def Extreme_Sell_1 = if BuyerExtreme[1] and !BuyerExtreme then haHigh else Double.NaN;
def Regular_Sell_1 = if BuyerRegular[1] and !BuyerRegular then haHigh else Double.NaN;
def Extreme_Buy_2 = if MarketOpen and (SellerExtreme[1] and !SellerExtreme) within X_Signal_Bars bars then 1 else 0;
def Regular_Buy_2 = if MarketOpen and (SellerRegular[1] and !SellerRegular) within X_Signal_Bars bars then 1 else 0;
def Extreme_Sell_2 = if MarketOpen and (BuyerExtreme[1] and !BuyerExtreme) within X_Signal_Bars bars then 1 else 0;
def Regular_Sell_2 = if MarketOpen and (BuyerRegular[1] and !BuyerRegular) within X_Signal_Bars bars then 1 else 0;
def Extreme_Buy_3 = if Extreme_Buy_2 then haLow else Extreme_Buy_3[1];
def Regular_Buy_3 = if Regular_Buy_2 then haLow else Regular_Buy_3[1];
def Extreme_Sell_3 = if Extreme_Sell_2 then haHigh else Extreme_Sell_3[1];
def Regular_Sell_3 = if Regular_Sell_2 then haHigh else Regular_Sell_3[1];
def Extreme_Buy_Line = if MarketOpen and (SellerExtreme[1] and !SellerExtreme) then 1 else 0;
def Regular_Buy_Line = if MarketOpen and (SellerRegular[1] and !SellerRegular) then 1 else 0;
def Extreme_Sell_Line = if MarketOpen and (BuyerExtreme[1] and !BuyerExtreme) then 1 else 0;
def Regular_Sell_Line = if MarketOpen and (BuyerRegular[1] and !BuyerRegular) then 1 else 0;
def Extreme_Buy_bn = if MarketOpen and (SellerExtreme[1] and !SellerExtreme) then bn else Extreme_Buy_bn[1];
def Regular_Buy_bn = if MarketOpen and (SellerRegular[1] and !SellerRegular) then bn else Regular_Buy_bn[1];
def Extreme_Sell_bn = if MarketOpen and (BuyerExtreme[1] and !BuyerExtreme) then bn else Extreme_Sell_bn[1];
def Regular_Sell_bn = if MarketOpen and (BuyerRegular[1] and !BuyerRegular) then bn else Regular_Sell_bn[1];
#####################################################
## C3 MAX YELLOW CANDLE                            ##
#####################################################
def Displace = 0;
def FactorK2 = 3.25;
def LengthK2 = 20;
def TrueRangeAverageType = AverageType.SIMPLE;
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 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_Yellow_Candle = Value[1] <= Value;
def condition1D_Yellow_Candle = 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 = (RSI[3] < RSI) is true or (RSI >= 80) is true;
def condition2D_RSI = (RSI[3] > RSI) is true or (RSI < 20) is true;
def conditionOB1_RSI = RSI > RSI_OB;
def conditionOS1_RSI = RSI < RSI_OS;
#####################################################
## MONEY FLOW INDEX                                ##
#####################################################
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_MFI = (MoneyFlowIndex[2] < MoneyFlowIndex) is true or (MoneyFlowIndex > 85) is true;
def condition3D_MFI = (MoneyFlowIndex[2] > MoneyFlowIndex) is true or (MoneyFlowIndex < 20) is true;
def conditionOB2_MFI = MoneyFlowIndex > MFIover_Bought;
def conditionOS2_MFI = 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_Forcast = (Intermed[1] <= Intermed) or (NearT >= MidLine);
def condition4D_Forcast = (Intermed[1] > Intermed) or (NearT < MidLine);
def conditionOB3_Forcast = Intermed > FOB;
def conditionOS3_Forcast = Intermed < FOS;
def conditionOB4_Forcast = NearT > FOB;
def conditionOS4_Forcast = 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 = CIP_UP;
def condition5D_CIP = CIP_DOWN;
#####################################################
## EMA 1                                           ##
#####################################################
def EMA_length = 8;
def AvgExp = ExpAverage(Price[-Displace], EMA_length);
def condition6_EMA_1 = (Price >= AvgExp) and (AvgExp[2] <= AvgExp);
def condition6D_EMA_1 = (Price < AvgExp) and (AvgExp[2] > AvgExp);
#####################################################
## EMA 2                                           ##
#####################################################
def EMA_2length = 20;
def displace2 = 0;
def AvgExp2 = ExpAverage(Price[-displace2], EMA_2length);
def condition7_EMA_2 = (Price >= AvgExp2) and (AvgExp2[2] <= AvgExp);
def condition7D_EMA_2 = (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_DMI = Osc >= ZeroLine;
def condition8D_DMI = 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_Trend = Periods > 0;
def condition9D_Trend = 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 = PFE > 0;
def condition10D_PFE = PFE < 0;
def conditionOB5_PFE = PFE > UpperLevel;
def conditionOS5_PFE = PFE < LowerLevel;
#####################################################
## BOLLINGER BANDS                                 ##
#####################################################
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_BB = BollingerBands(Price, Displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, AverageType_BB).UpperBand;
def lowerBand_BB = BollingerBands(Price, Displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, AverageType_BB).LowerBand;
def PercentB = (Price - lowerBand_BB) / (upperBand_BB - lowerBand_BB) * 100;
def HalfLine = 50;
def UnitLine = 100;
def condition11_BB = PercentB > HalfLine;
def condition11D_BB = PercentB < HalfLine;
def conditionOB6_BB = PercentB > BBPB_OB;
def conditionOS6_BB = PercentB < BBPB_OS;
def condition12_BB = (Upper_BandS[1] <= Upper_BandS) and (Lower_BandS[1] <= Lower_BandS);
def condition12D_BB = (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_KH = (KVOH > 0);
def condition13D_KH = (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_PO = PROSC > 50;
def condition14D_PO = PROSC < 50;
def conditionOB7_PO = PROSC > PROSC_OB;
def conditionOS7_PO = 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_AK = if aktrend_bspread > 0 then 1 else 0;
def cond1_DN_AK = 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_ZSCORE = if zscore_Zscore > 0 then 1 else 0;
def cond2_DN_ZSCORE = if zscore_Zscore <= 0 then -1 else 0;
#####################################################
## EMAD EHLERS                                     ##
#####################################################
def Price_Ehlers_EMAD = (EMAD_High + EMAD_Low) / 2;
def Coeff = Ehlers_Length * Price_Ehlers_EMAD * Price_Ehlers_EMAD - 2 * Price_Ehlers_EMAD * Sum(Price_Ehlers_EMAD, Ehlers_Length)[1] + Sum(Price_Ehlers_EMAD * Price_Ehlers_EMAD, Ehlers_Length)[1];
def Ehlers_EMAD =  Sum(Coeff * Price_Ehlers_EMAD, Ehlers_Length) / Sum(Coeff, Ehlers_Length);
#####################################################
## EHLERS                                          ##
#####################################################
def Price_Ehlers = (high + low) / 2;
def Ehlers_Coeff = Ehlers_Length * Price_Ehlers * Price_Ehlers - 2 * Price_Ehlers * Sum(Price_Ehlers, Ehlers_Length)[1] + Sum(Price_Ehlers * Price_Ehlers, Ehlers_Length)[1];
def Ehlers = Sum(Ehlers_Coeff * Price_Ehlers, Ehlers_Length) / Sum(Ehlers_Coeff, Ehlers_Length);
def Ehlers_Avg = Average(Ehlers, Ehlers_Avg_Length);
def cond3_UP_Ehlers = if close > Ehlers_Avg then 1 else 0;
def cond3_DN_Ehlers = if close <= Ehlers_Avg 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_AM = if amom_amom > 0 then 1 else 0;
def cond4_DN_AM = 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_TMO = if tmo_Main <= 0 then 1 else 0;
def cond5_DN_TMO = if tmo_Main >= 0 then -1 else 0;
#####################################################
## MADE AVERAGE (EMAD)                             ##
#####################################################
def dataA = Master_EMAD_EMA;
def dataA1 =
    fold aD = 0
    to Length_MAD
    with k = 0 
    do k + dataA[aD];
def MAEMAD = dataA1 / Length_MAD;
def MADehlers = (MAEMAD - Ehlers_EMAD) / 2;
def Madebad = MADehlers + Ehlers_EMAD;
def Madebad_Avg = Average(Madebad, Made_Avg_Length);
def Madebad_CrossUp = if (Madebad < Master_EMAD_EMA) and (Madebad > Madebad[1]) and (EMAD_Above_Zero > 0) then 1 else 0;
def Madebad_CrossDown = if (Madebad > Master_EMAD_EMA) and (Madebad < Madebad[1]) and (EMAD_Below_Zero > 0) then 1 else 0;
def Madebad_CrossCondition = if (Madebad < Master_EMAD_EMA) and (Madebad > Madebad[1]) and (EMAD_Above_Zero > 0) then 1
            else if (Madebad > Master_EMAD_EMA) and (Madebad < Madebad[1]) and (EMAD_Below_Zero > 0) then -1
            else 0;
def Madebad_Condition = if (!Madebad_CrossCondition[1] or !Madebad_CrossCondition[2]) and (Madebad_CrossCondition == 0) then 1 else 0;
#####################################################
## ALERT4                                          ##
#####################################################
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 StDev = MULT * StDev(WVF, BBL);
def MidLine1 = SimpleMovingAvg(WVF, BBL);
def UpperBand1_Alert4 = MidLine1 + StDev;
def Range_High = (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_Alert4[1] or WVF[1] >= Range_High[1]) and (WVF < UpperBand1_Alert4 and WVF < Range_High));
def Filtered_Aggr = (WVF[1] >= UpperBand1_Alert4[1] or WVF[1] >= Range_High[1]);
def Alert4 = UpRange_Aggr and close > close[STR] and (close < close[LTLB] or close < close[MTLB]) and Filtered_Aggr;
def Alert4_1 = if Alert4 then haLow else Double.NaN;
def Alert4_3 = if Alert4 then 1 else 0;
def Alert4_2 = Alert4 within X_Alert4_Bars bars;
#####################################################
## EMAD MADE                                       ##
#####################################################
def Made_Down = (Madebad > Master_EMAD_EMA);
def Made_Up = (Madebad < Master_EMAD_EMA);
def Made_Bottom_MA = if !Made_Down and (Madebad_Avg <= ZeroLineData) then Madebad_Avg else Double.NaN;
def Made_Top_MA = if !Made_Up and (Madebad_Avg >= ZeroLineData) then Madebad_Avg else Double.NaN;
def MadeAvg_Master_Cross_Up = if Madebad_Avg crosses below Master_EMAD_EMA then 1 else 0;
def MadeAvg_Master_Cross_Down = if Madebad_Avg crosses above Master_EMAD_EMA then 1 else 0;
def Cross_Up_MadeAvg_Master = if MadeAvg_Master_Cross_Up and !MadeAvg_Master_Cross_Up[1] then 1 else 0;
def Cross_Down_MadeAvg_Master = if MadeAvg_Master_Cross_Down and !MadeAvg_Master_Cross_Down[1] then 1 else 0;
def MadeAvg_Master_Up_Condition = if Cross_Up_MadeAvg_Master and Band_Crossed_First and EMAD_EMA_up[1] then 1 else 0;
def MadeAvg_Master_Down_Condition = if Cross_Down_MadeAvg_Master and !Band_Crossed_First and EMAD_EMA_down[1] then 1 else 0;
def EMA_Push_StepUp = if TopBand_StepUp and EMAD_EMA_up and (((Upper_EMAD_EMA) - TopBand) == 0) then 1 else 0;
def EMA_Push_StepDown = if BottomBand_StepDown and EMAD_EMA_down and (((Lower_EMAD_EMA) - BottomBand) == 0) then 1 else 0;
def First_HL_1 = if MarketOpen and trackCrUp and !trackCrUp[1] then haLow else Double.NaN;
def First_LH_1 = if MarketOpen and trackCrDn and !trackCrDn[1] then haHigh else Double.NaN;
def Second_HL_1 = if (MarketOpen and trackCrUp2 and !trackCrUp2[1] and !CrossUp_BottomBand) then haLow else Double.NaN;
def Second_LH_1 = if (MarketOpen and trackCrDn2 and !trackCrDn2[1] and !CrossDown_TopBand) then haHigh else Double.NaN;
def First_HL_2 = if (MarketOpen and trackCrUp and !trackCrUp[1]) within X_Signal_Bars bars then 1 else 0;
def First_LH_2 = if (MarketOpen and trackCrDn and !trackCrDn[1]) within X_Signal_Bars bars then 1 else 0;
def Second_HL_2 = if ((MarketOpen and trackCrUp2 and !trackCrUp2[1]) and !CrossUp_BottomBand) within X_Signal_Bars bars then 1 else 0;
def Second_LH_2 = if ((MarketOpen and trackCrDn2 and !trackCrDn2[1]) and !CrossDown_TopBand) within X_Signal_Bars bars then 1 else 0;
def First_HL_3 = if (MarketOpen and trackCrUp and !trackCrUp[1]) within X_Signal_Bars bars then haLow else First_HL_3[1];
def First_LH_3 = if (MarketOpen and trackCrDn and !trackCrDn[1]) within X_Signal_Bars bars then haHigh else First_LH_3[1];
def Second_HL_3 = if ((MarketOpen and trackCrUp2 and !trackCrUp2[1]) and !CrossUp_BottomBand) within X_Signal_Bars bars then haLow else Second_HL_3[1];
def Second_LH_3 = if ((MarketOpen and trackCrDn2 and !trackCrDn2[1]) and !CrossDown_TopBand) within X_Signal_Bars bars then haHigh else Second_LH_3[1];
#####################################################
## FOLD CONDITIONS (EMAD)                          ##
#####################################################
def TopBandStepDown_lookback = fold index1 = 1 to Step_lookback with x1 do x1 + TopBand_StepDown[index1];
def TopBandStepUp_lookback = fold index2 = 1 to Step_lookback with x2 do x2 + TopBand_StepUp[index2];
def BottomBandStepDown_lookback = fold index3 = 1 to Step_lookback with x3 do x3 + BottomBand_StepDown[index3];
def BottomBandStepUp_lookback = fold index4 = 1 to Step_lookback with x4 do x4 + BottomBand_StepUp[index4];
def Madebad_Condition_lookback = fold index5 = 1 to Cloud_Lookback with x5 do x5 + Madebad_Condition[index5];
def HL_lookback = fold index6 = 1 to HL_LH_Lookback with x6 do x6 + First_HL_1[index6];
def LH_lookback = fold index7 = 1 to HL_LH_Lookback with x7 do x7 + First_LH_1[index7];
def HL2_lookback = fold index8 = 1 to HL_LH_Lookback with x8 do x8 + Second_HL_1[index8];
def LH2_lookback = fold index9 = 1 to HL_LH_Lookback with x9 do x9 + Second_LH_1[index9];
#####################################################
## HIDE ARROW CONDITIONS                           ##
#####################################################
def Hide_Arrow_TopBand_StepDown = TopBandStepDown_lookback > Previous_Steps_Down;
def Hide_Arrow_TopBand_StepUp = TopBandStepUp_lookback > Previous_Steps_Up;
def Hide_Arrow_BottomBand_StepDown = BottomBandStepDown_lookback > Previous_Steps_Down;
def Hide_Arrow_BottomBand_StepUp = BottomBandStepUp_lookback > Previous_Steps_Up;
def UP1 = if MarketOpen and (!Hide_Arrow_TopBand_StepDown or !Hide_Arrow_BottomBand_StepDown) and !EMA_Push_StepDown and MadeAvg_Master_Up_Condition then 1 else 0;
def DOWN1 = if MarketOpen and (!Hide_Arrow_TopBand_StepUp or !Hide_Arrow_BottomBand_StepUp) and !EMA_Push_StepUp and MadeAvg_Master_Down_Condition then 1 else 0;
def updown1 = if up1 == 1 then halow else if down1 == 1 then hahigh else updown1[1];
def UP1_1 = if UP1 then haLow else Double.NaN;
def DOWN1_1 = if DOWN1 then haHigh else Double.NaN;
def UP1_2 = if UP1 within X_Signal_Bars bars then 1 else 0;
def DOWN1_2 = if DOWN1 within X_Signal_Bars bars then 1 else 0;
def UP1_3 = if UP1 then haLow else UP1_3[1];
def DOWN1_3 = if DOWN1 then haHigh else DOWN1_3[1];
def UP_1_Price = if (UP1_1 == halow) then (UP1_1 - UP1_1[1]) else double.nan;
def UP_1_increasing = UP_1_Price > 0;
def DOWN_1_Price = if (DOWN1_1 == haHIGH) then (DOWN1_1 - DOWN1_1[1]) else double.nan;
def DOWN_1_increasing = DOWN_1_Price > 0;
def UP1_EMAD_Price = if (UP1_1 == halow) then (EMAD_low[1] - EMAD_low) else double.nan;
def UP_1_EMAD_decreasing = UP1_EMAD_Price > 0;
def DOWN_1_EMAD_Price = if (DOWN1_1 == haHIGH) then (EMAD_high[1] - EMAD_high)else double.nan;
def DOWN_1_EMAD_decreasing = DOWN_1_EMAD_Price > 0;
def EMAD_Divergence_UP = UP_1_EMAD_decreasing and UP_1_increasing;
def EMAD_Divergence_DOWN = DOWN_1_EMAD_decreasing and DOWN_1_increasing;
#####################################################
## MARKET PHASES                                   ##
#####################################################
def Fastavg_Phases = 50;
def Slowavg_Phases = 200;
def Fastsma_Phases = Average( close, Fastavg_Phases);
def Slowsma_Phases = Average(close, Slowavg_Phases);
def Bullphase = Fastsma_Phases > Slowsma_Phases && close > Fastsma_Phases && close > Slowsma_Phases; # Accumulation Phase : close > 50 SMA, close > 200 SMA, 50 SMA < 200 SMA
def Accphase = Fastsma_Phases < Slowsma_Phases && close > Fastsma_Phases && close > Slowsma_Phases;# Recovery Phase : close > 50 SMA, close < 200 SMA, 50 SMA < 200 SMA
def Recphase = Fastsma_Phases < Slowsma_Phases && close < Slowsma_Phases && close > Fastsma_Phases;# Bearish Phase : close < 50 SMA, close < 200 SMA, 50 SMA < 200 SMA
def Bearphase = Fastsma_Phases < Slowsma_Phases && close < Fastsma_Phases && close < Slowsma_Phases;# Distribution Phase : close < 50 SMA, close < 200 SMA, 50 SMA > 200 SMA
def Distphase = Fastsma_Phases > Slowsma_Phases && close < Fastsma_Phases && close < Slowsma_Phases;# Warning Phase : close < 50 SMA, close > 200 SMA, 50 SMA > 200 SMA
def Warnphase = Fastsma_Phases > Slowsma_Phases && close > Slowsma_Phases && close < Fastsma_Phases;
#####################################################
## BIG 4 DIRECTION                                 ##
#####################################################
def Strategy_FilterWithTMO = no;
def Strategy_FilterWithTMO_arrows = yes;
def Strategy_HoldTrend = no;
def Strategy_ColoredCandlesOn = yes;
def coloredCandlesOn = yes;
def cond_UP = cond1_UP_AK + cond2_UP_ZSCORE + cond3_UP_Ehlers + cond4_UP_AM;
def cond_DN = cond1_DN_AK + cond2_DN_ZSCORE + cond3_DN_Ehlers + cond4_DN_AM;
def direction = if cond_UP >= Big4_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_UP_TMO) then 1
else if cond_DN <= - Big4_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_DN_TMO) then -1
    else if !Strategy_HoldTrend and direction[1] == 1 and cond_UP < Big4_Confirmation_Factor and cond_DN > - Big4_Confirmation_Factor then 0
        else if !Strategy_HoldTrend and direction[1] == -1 and cond_DN > -Big4_Confirmation_Factor and cond_UP < Big4_Confirmation_Factor then 0
            else direction[1];
def direction2 = if cond_UP >= Big4_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_UP_TMO) then 1
    else if cond_DN <= - Big4_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_DN_TMO) then -1
        else if !Strategy_HoldTrend and direction2[1] == 1 and cond_UP < Big4_Confirmation_Factor and cond_DN > - Big4_Confirmation_Factor then 0
            else if !Strategy_HoldTrend and direction2[1] == -1 and cond_DN > - Big4_Confirmation_Factor and cond_UP < Big4_Confirmation_Factor then 0
                else direction2[1];
def direction_Equals_zero = direction == 0;
def direction_zero_condition = if direction_Equals_zero and (direction_Equals_zero[1] or direction_Equals_zero[2] or direction_Equals_zero[3] or direction_Equals_zero[4] or direction_Equals_zero[5]) then 0 else 1;
#####################################################
## TREND CONFIRMATION CALCULATOR                   ##
#####################################################
def Confirmation_Factor = 7;
def Agreement_LevelOB = 12;
def Agreement_LevelOS = 2;
def HideBoxLines = no;
#def HideCloud = no;
def HideLabels = no;
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;
#######################################################
## AGREEMENT LEVEL                                   ##
#######################################################
def Agreement_Level = condition1_Yellow_Candle + condition2_RSI + condition3_MFI + condition4_Forcast
                    + condition5_CIP + condition6_EMA_1 + condition7_EMA_2 + condition8_DMI + condition9_Trend
                    + condition10_PFE + condition11_BB + condition12_BB + condition13_KH + condition14_PO
                    + conditionK1UP + conditionK2UP;
def Agreement_LevelD = (condition1D_Yellow_Candle + condition2D_RSI + condition3D_MFI + condition4D_Forcast + condition5D_CIP
                    + condition6D_EMA_1 + condition7D_EMA_2 + condition8D_DMI + condition9D_Trend + condition10D_PFE
                    + condition11D_BB + condition12D_BB + condition13D_KH + condition14D_PO + conditionK3DN
                    + conditionK4DN);
#######################################################
## CONSENSUS LEVEL                                   ##
#######################################################
def Consensus_Level = Agreement_Level - Agreement_LevelD;
def Consensus_UP = 6;
def Consensus_DOWN = -6;
def UP_CL = Consensus_Level >= Consensus_UP;
def DOWN_CL = Consensus_Level < Consensus_DOWN;
def priceColor = if UP_CL then 1 else if DOWN_CL then -1 else priceColor[1];
def Consensus_Level_OB = 14;
def Consensus_Level_OS = -12;
def OB_Level = conditionOB1_RSI + conditionOB2_MFI + conditionOB3_Forcast + conditionOB4_Forcast + conditionOB5_PFE + conditionOB6_BB + conditionOB7_PO;
def OS_Level = conditionOS1_RSI + conditionOS2_MFI + conditionOS3_Forcast + conditionOS4_Forcast + conditionOS5_PFE + conditionOS6_BB + conditionOS7_PO;
def Consensus_Line = OB_Level - OS_Level;
def MomentumUP = Consensus_Level[1] < Consensus_Level;
def MomentumDOWN = Consensus_Level[1] > Consensus_Level;
def conditionOB_CL = (Consensus_Level >= 12) and (Consensus_Line >= 4);
def conditionOS_CL = (Consensus_Level <= -12) and (Consensus_Line <= -3);
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);
#####################################################
## PREVIOUSLY OVERBOUGHT / OVERSOLD LEVELS         ##
#####################################################
def YHOB = if ((open > Upper_BandS) and (Condition_BandRevDn)) then high else Double.NaN;
def YHOS = if ((open < Lower_BandS) and (Condition_BandRevUp)) then high else Double.NaN;
def YLOB = if ((open > Upper_BandS) and (Condition_BandRevDn)) then low else Double.NaN;
def YLOS = if ((open < Lower_BandS) and (Condition_BandRevUp)) then low else Double.NaN;
def YCOB = if !IsNaN(YHOB) then hl2 else Double.NaN;
def YHextOB = if IsNaN(YCOB) then YHextOB[1] else YCOB;
def YHextlineOB = YHextOB;
def YCOS = if !IsNaN(YHOS) then hl2 else Double.NaN;
def YHextOS = if IsNaN(YCOS) then YHextOS[1] else YCOS;
def YHextlineOS = YHextOS;
def HighestPOB = highestAll(YHextlineOB);
def LowestPOS = LowestAll(YHextlineOS);
def HighestPOS = highestAll(YHextlineOS);
def LowestPOB = LowestAll(YHextlineOB);
#####################################################
## OVERBOUGHT / OVERSOLD ZONES                     ##
#####################################################
def BarsUsedForRange = 2;
def BarsRequiredToRemainInRange = 2;
def trig = 20;# for Blast-off candle color
def YC = coloredCandlesOn and priceColor == 1 and open > 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;
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;
def BL2 = if !IsNaN(BoxLow2) then low else Double.NaN;
def BL2ext = if IsNaN(BL2) then BL2ext[1] else BL2;
def BL2extline2 = BL2ext;
#####################################################
## CROSSING LEVELS                                 ##
#####################################################
def Gray_Cloud = (EMAD_Gray_Cloud_1 or EMAD_Gray_Cloud_2) ;
def Green_Cloud = (EMAD_Green_Cloud_1 or EMAD_Green_Cloud_2) ;
def red_Cloud = (EMAD_Red_Cloud_1 or EMAD_Red_Cloud_2) ;# Yellow line
#####################################################
## CROSSING LEVELS CONTINUED                       ##
#####################################################
def Price_X_BL1 = if hl2 > BL1ext then 1 else if hl2 < BL1ext then -1 else 0;
def Price_X_BH1 = if hl2 > BH1ext then 1 else if hl2 < BH1ext then -1 else 0;
def Price_X_BL2 = if hl2 > BL2ext then 1 else if hl2 < BL2ext then -1 else 0;
def Price_X_BH2 = if hl2 > BH2ext then 1 else if hl2 < BH2ext then -1 else 0;
def Price_X_YHextlineOB = if hl2 > YHextlineOB then 1 else if hl2 < YHextlineOB then -1 else 0;
def Price_X_YHextlineOS = if hl2 > YHextlineOS then 1 else if hl2 < YHextlineOS then -1 else 0;
def All_C3_Levels = Price_X_BL1 + Price_X_BH1 + Price_X_BL2 + Price_X_BH2 + Price_X_YHextlineOB + Price_X_YHextlineOS;
def Level_Price_Status = if All_C3_Levels > Above_X_Levels then 1 else if All_C3_Levels < Below_X_Levels then 0 else double.nan;
def Level_Price_Status_Up = if All_C3_Levels > Above_X_Levels then 1 else 0;
def Level_Price_Status_Down = if All_C3_Levels > Below_X_Levels then 1 else 0;
#####################################################
##                                                 ##
#####################################################
def Below_Both_POBOS = ((HL2 < YHextlineOS) and (HL2 < YHextlineOB)) and EMAD_EMA_Down;
def Above_Both_POBOS = ((HL2 > YHextlineOS) and (HL2 > YHextlineOB)) and EMAD_EMA_Up;
#####################################################
## KEY LEVELS                                      ##
#####################################################
def KeylevelOB = if ((BH1ext >= YHextlineOB) and (BL1ext <= YHextlineOB)) then 1 else 0;
def KeylevelOS = if ((BH2ext >= YHextlineOS) and (BL2ext <= YHextlineOS)) then 1 else 0;
def levelOB = if ((BH1ext >= HL2) and (BL1ext <= HL2)) then 1 else 0;
def levelOS = if ((BH2ext >= HL2) and (BL2ext <= HL2)) then 1 else 0;
#####################################################
## OPPOSITE KEY LEVELS                             ##
#####################################################
def Opposite_KeyOS = ((BH1ext >= YHextlineOS) and (BL1ext <= YHextlineOS));
def Opposite_KeyOB = ((BH2ext >= YHextlineOB) and (BL2ext <= YHextlineOB));
def Below_Opposite_KeyOS_Down = Opposite_KeyOS and (HL2 < YHextlineOS);
def Above_Opposite_KeyOS_Up = Opposite_KeyOS and (HL2 > YHextlineOS);
def Below_Opposite_KeyOB_Down = Opposite_KeyOB and (HL2 < YHextlineOB);
def Above_Opposite_KeyOB_Up  = Opposite_KeyOB and (HL2 > YHextlineOB);
def Below_both_OPOBOS = Below_Opposite_KeyOS_Down and (HL2 < YHextlineOB);
def Below_both_OPOBOS2 = Above_Opposite_KeyOS_Up and (HL2 > YHextlineOB);
def Below_both_OPOBOS3 = Below_Opposite_KeyOB_Down and (HL2 < YHextlineOS);
def Below_both_OPOBOS4 = Above_Opposite_KeyOB_Up and (HL2 > YHextlineOS);
#####################################################
## BOTH INSIDE SAME ZONE - KEY LEVELS              ##
#####################################################
def OBOS_Inside_Red = KeylevelOB and Opposite_KeyOS;
def OBOS_Inside_Green = KeylevelOS and Opposite_KeyOB;
#####################################################
## CANDLE INSIDE ZONE                              ##
#####################################################
def keyobpaint = ((hl2 < BH1ext) and (hl2 > BL1ext)) within X_InKey_Bars bars;
def keyospaint = ((hl2 < BH2ext) and (hl2 > BL2ext)) within X_InKey_Bars bars;
#####################################################
## CANDLE INSIDE KEY LEVEL                         ##
#####################################################
def Inside_Key_OB = KeylevelOB and keyobpaint;
def Inside_Key_OS = KeylevelOS and keyospaint;
def In_Key_OB = Inside_Key_OB within X_Keylevel_Bars bars;
def In_Key_OS = Inside_Key_OS within X_Keylevel_Bars bars;
#####################################################
## EMAD CLOUDS IN KEY LEVEL                        ##
#####################################################
def Red_Cloud_in_KeyOS = EMAD_Red_Cloud_3 and In_Key_OS; #bullish
def Green_Cloud_in_KeyOB = EMAD_Green_Cloud_3 and In_Key_OB; #bearish
def Red_Cloud_in_KeyOB = EMAD_Red_Cloud_3 and In_Key_OB;
def Green_Cloud_in_KeyOS = EMAD_Green_Cloud_3 and In_Key_OS;
#####################################################
## PREVIOUS OB / OS ABOVE / BELOW ZONE             ##
#####################################################
def POB_Above_Red_Zone = (YHextlineOB > BH1ext);
def POS_below_Green_Zone = (YHextlineOS < BL2ext);
#####################################################
## PRICE CROSS PREVIOUS OB / OS ABOVE / BELOW ZONE ##
#####################################################
def POB_Abv_Z_Cross = POB_Above_Red_Zone and ((hl2 >=  YHextlineOB) within X_InKey_Bars bars);
def POS_blw_Z_Cross = POS_below_Green_Zone and ((hl2  <= YHextlineOS) within X_InKey_Bars bars);
def POBBCross = !POS_blw_Z_Cross[1] and POS_blw_Z_Cross;
def hidePOBB = if POBBCross[1] or POBBCross[2] or POBBCross[3] or POBBCross[4] or POBBCross[5] or POBBCross[6] or POBBCross[7] then 0 else 1;
def POBLCross = !POB_Abv_Z_Cross[1] and POB_Abv_Z_Cross;
def hidePOBL = if POBLCross[1] or POBLCross[2] or POBLCross[3] or POBLCross[4] or POBLCross[5] or POBLCross[6] or POBLCross[7] then 0 else 1;
def CrossPOB = POBBCross and hidePOBB;
def CrossPOS = POBLCross and hidePOBL;
#####################################################
## ZONE COMPRESSION                                ##
#####################################################
def Zone_Difference = if (BL1ext > BH2ext) then (BL1ext - BH2ext) else Double.NaN;
#addlabel(yes, Zone_Difference , color.yellow);
def Zone_Diff_Percent = (Zone_Difference / hl2) * 100;
#addlabel(yes, Zone_Diff_Percent+"%" , color.yellow);
def Zone_Diff_PerCond = Zone_Diff_Percent < Zone_Percent_Diff;
def Zone_Compression_1 = if (BL1ext < BH2ext) then 1 else 0;
def Zone_Compression_2 = Zone_Difference <= Zone_Span;
#####################################################
## CANDLES BETWEEN ZONES                           ##
#####################################################
def Price_Between_Zones = (Price < BH1ext) and (Price > BL2ext);
def Zone_Compression = if Zone_Compression_1 or  Zone_Compression_2 then 1 else 0;
def Zone_Compression_3 = Zone_Compression and Price_Between_Zones;
def POBOS_Compression = if (YHextlineOB > YHextlineOS) then (YHextlineOB - YHextlineOS) else if (YHextlineOS > YHextlineOB) then (YHextlineOS - YHextlineOB) else double.nan;
#####################################################
## ZONE INCREASING / DECREASING / FLAT / STRETCHED ##
#####################################################
def Zone_Red_Increasing = (BH1ext > BH1ext[1]) or (BL1ext > BL1ext[1]);
def Zone_Red_Decreasing = (BL1ext < BL1ext[1]) or (BH1ext < BH1ext[1]);
def Zone_Red_Flat = (BH1ext == BH1ext[1]) and (BL1ext == BL1ext[1]);
def Zone_Red_Wrapping = (BH1ext > BH1ext[1]) and (BL1ext > BL1ext[1]);
def Zone_Red_Flat_Key = if Zone_Red_Flat and KeylevelOB then 1 else 0;
def Flat_Earth_Bear_1 = sum(Zone_Red_Flat_Key, Flat_Earth_Bars);
#def Flat_Earth_Bear = Zone_Red_Flat_Key and Zone_Red_Flat_Key[1] and Zone_Red_Flat_Key[2] and Zone_Red_Flat_Key[3] and Zone_Red_Flat_Key[4] and Zone_Red_Flat_Key[5];
def Flat_Earth_Bear = Flat_Earth_Bear_1 > Flat_Earth_Controller;
#####################################################
## CANDLE COLOR CONDITIONS                         ##
#####################################################
def Zone_Red_Stretch = (BL1ext < BL1ext[1]) or (BH1ext > BH1ext[1]);
def Zone_Red_Stretch2 = (BL1ext < BL1ext[1]) AND (BH1ext > BH1ext[1]);
def Zone_Red_EMAD_down = (Zone_Red_Stretch within X_Signal_Bars bars) and TopBand_PushUp;
def Zone_Red_Seller_Exh = (Zone_Red_Stretch or Zone_Red_Increasing within X_Zone_bars bars) and (Extreme_Sell_2 or Regular_Sell_2);
def Zone_Red_Seller_Exh_Clouds = Zone_Red_Seller_Exh and Green_Clouds_Before;
#####################################################
## ZONE INCREASING / DECREASING / FLAT / STRETCHED ##
#####################################################
def Zone_Green_Increasing = (BL2ext > BL2ext[1]) or (BH2ext > BH2ext[1]);
def Zone_Green_Decreasing = (BL2ext < BL2ext[1]) or (BH2ext < BH2ext[1]);
def Zone_Green_Flat = (BL2ext == BL2ext[1]) and (BH2ext == BH2ext[1]);
def Zone_Green_Wrapping = (BL2ext < BL2ext[1]) and (BH2ext < BH2ext[1]);
def Zone_Green_Flat_Key = if Zone_Green_Flat and KeylevelOS then 1 else 0;
def Flat_Earth_Bull_1 = sum(Zone_Green_Flat_Key, Flat_Earth_Bars);
#def Flat_Earth_Bull = Zone_Green_Flat_Key and Zone_Green_Flat_Key[1] and Zone_Green_Flat_Key[2] and Zone_Green_Flat_Key[3] and Zone_Green_Flat_Key[4] and Zone_Green_Flat_Key[5];
def Flat_Earth_Bull = Flat_Earth_Bull_1 > Flat_Earth_Controller;
#####################################################
## CANDLE COLOR CONDITIONS                         ##
#####################################################
def Zone_Green_Stretch = (BL2ext < BL2ext[1]) or (BH2ext > BH2ext[1]);
def Zone_Green_EMAD_down = (Zone_Green_Stretch within X_Zone_bars bars) and BottomBand_PushDown;
def Zone_Green_Buyer_Exh = (Zone_Green_Stretch within X_Zone_bars bars) and (Extreme_Buy_2 or Regular_Buy_2);
def Zone_Green_Buyer_Exh_Clouds = Zone_Green_Buyer_Exh and Red_Clouds_Before;
#####################################################
## TEST CONDITIONS FOR LEVELS                      ##
#####################################################
def Zone_Alert4 = (Zone_Green_Stretch within X_Signal_Bars bars) and Alert4_2;
def Zone_Green_Alert4_KEY = In_Key_OS and (Zone_Green_Stretch within X_Zone_bars bars) and Alert4_2;
def Zone_Seller_Exh_KEY = In_Key_OS and (Zone_Green_Stretch within X_Zone_bars bars) and (Extreme_Buy_2 or Regular_Buy_2);
#####################################################
## ZONE OVERLAP                                    ##
#####################################################
def Zone_Overlap = (BH2ext >= BL1ext) and !Zone_Green_Wrapping and !Zone_Green_Decreasing and !Zone_Red_Wrapping and !Zone_Red_Decreasing;
#####################################################
## TEST CONDITIONS FOR LEVELS                      ##
#####################################################
def Zone_Red_Increasing_EMAD = Zone_Red_Increasing and TopBand_PushUp;
def Zone_Green_Decreasing_EMAD = Zone_Green_decreasing and BottomBand_PushDown;
def Green_Cond_1 = Zone_Red_Increasing and Zone_Green_Flat;
def Green_Cond_1_Key = Green_Cond_1 and In_Key_OB;
def Green_Cond_1_3x = (Green_Cond_1 and (Extreme_Sell_2 or Regular_Sell_2)) within X_Signal_Bars bars;
def Green_Cond_2 = Zone_Green_Increasing and Zone_Red_Flat;
def Red_Cond_1 = Zone_Red_Decreasing and Zone_Green_Flat;
def Up_Green_Cond_3 = if Green_Clouds_Before and (!Red_Cond_1 and Red_Cond_1[1]) then 1 else 0;
def Down_Green_Cond_3_Alternate = if Up_Green_Cond_3 and TopBand_PushUp then 1 else 0;
def Alert4_Exhaustion = Alert4_2 and (Extreme_Sell_2 or Regular_Sell_2);
def Green_Cond_3 = Zone_Green_Decreasing and Zone_Red_Flat;
def Down_Green_Cond_3 = if !Green_Cond_1 and Green_Cond_1[1] then 1 else 0;
def Down_Red_Cond_3_Alternate = if Green_Clouds_Before and Down_Green_Cond_3 and TopBand_PushUp then 1 else 0;
def Up_Red_Cond_3 = if !Red_Cond_1 and Red_Cond_1[1] then haLow else Double.NaN;
def Up_Green_Cond_4 = if !Green_Cond_3 and Green_Cond_3[1] then haLow else Double.NaN;
def EMAD_Cloud_Condition_DOWN = (!EMAD_Green_Cloud_1 and EMAD_Green_Cloud_2[1]) or (EMAD_Green_Cloud_1 or EMAD_Green_Cloud_2);
def EMAD_Cloud_Condition_UP = (!EMAD_Red_Cloud_1 and EMAD_Red_Cloud_2[1]) or (EMAD_Red_Cloud_1 or EMAD_Red_Cloud_2);
def Cloud_Zone_Cond_DOWN = if KeylevelOB and (EMAD_Cloud_Condition_DOWN within X_Zone_Cloud_Bars bars) and (Down_Green_Cond_3 within X_Zone_Cloud_Bars bars) then haHigh else Double.NaN;
def Cloud_Zone_Cond_UP = if KeylevelOS and (EMAD_Cloud_Condition_UP within X_Zone_Cloud_Bars bars) and (Up_Red_Cond_3 within X_Zone_Cloud_Bars bars) then haLow else Double.NaN;
#####################################################
## SPARK                                           ##
#####################################################
def Agperiod1 = GetAggregationPeriod();
def timeframe = if Agperiod1 <= AggregationPeriod.DAY then AggregationPeriod.DAY else Agperiod1;
def Length9 = 35;
def Length8 = 10;
def AvgExp8 = ExpAverage(Price[-Displace], Length8);
def UPD = AvgExp8[1] < AvgExp8;
def AvgExp9 = ExpAverage(Price[-Displace], Length9);
def UPW = AvgExp9[1] < AvgExp9;
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;
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 CandleColor = if (priceColor == 1) and (PriceColor12 == 1) and (Spark >= 2) then 1 else if (priceColor == -1) and (Spark < 1) then -1 else 0;
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]) or (BigDN) then 0 else 1;
def Hide_SparkDN = if SparkDN1 and (SparkDN1[1] or SparkDN1[2] or SparkDN1[3] or SparkDN1[4] or SparkDN1[5]) or (BigUP) then 0 else 1;
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 Buy_Volume = RoundUp(Vol * (at_Close - at_Low) / (at_High - at_Low));
def Buy_percent = RoundUp((Buy_Volume / Vol) * 100);
def Sell_Volume = RoundDown(Vol * (at_High - at_Close) / (at_High - at_Low));
def Sell_percent = RoundUp((Sell_Volume / Vol) * 100);
def avg1 = ExpAverage(close(period = Agperiod1), Length8);
def height = avg1 - avg1[Length8];
def avg2 = ExpAverage(close(period = Agperiod1), Length8);   
##C3_MF_Line_v2 Created by Christopher84 03/06/2022 
############################################################
#Keltner Channel
def BulgeLengthPrice2 = 20;
def SqueezeLengthPrice2 = 20;
def BulgeLengthPrice3 = 12;
def SqueezeLengthPrice3 = 12;
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 (open > Upper_BandS) and (condition_BandRevDn)) then 1 else 0;
def C3_Line_2 = if ((priceColor == -1) and (open < Lower_BandS) and (condition_BandRevUp)) then 1 else 0;
def C3_Green =  ((priceColor == 1));
def C3_red =  ((priceColor == 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];
###################################
##Consensus Level & Squeeze Label
###################################
def conditionOB = (Consensus_Level >= 12) and (Consensus_Line >= 4);
def conditionOS = (Consensus_Level <= -12) and (Consensus_Line <= -3);
#####################################################
## LABEL CONDITIONS                                ##
#####################################################                                 
def Condition1UP = avg1 > avg2;
def Condition1DN = avg1 < avg2;
def Condition2UP = Buy_percent > 50;
def Condition2DN = Buy_percent < 50;
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;
#####################################################
## CANDLE COLOR                                    ##
#####################################################
def Red_Wrap_Cond_1 = (Zone_Red_Wrapping or Zone_Red_Increasing) within X_Upcolor1_Bars bars;
def Red_Wrap_Cond_2 = Red_Wrap_Cond_1[1] or Red_Wrap_Cond_1[2] and Zone_Red_Increasing;
def Green_Wrap_Cond_1 = (Zone_Green_Wrapping or Zone_Green_Decreasing) within X_Signal_Bars bars;
def Green_Wrap_Cond_2 = Green_Wrap_Cond_1[1] or Green_Wrap_Cond_1[2] and Zone_Green_decreasing;
#####################################################
## CUMMULATIVE VOLUME DELTA                        ##
#####################################################
input linestyle = {default Candle, Line};
input HeikinAshi = yes; #"Heikin Ashi Candles?")
input maType    =  {default "SMMA", "SMA", "HMA", "EMA", "WMA"};
input maLength  = 9;   #"MA Length"
def BarColor = no;
input BackgroundColor = yes;
def ShowMovAvg = no;
def ShowBand = no;
script nz {
    input data         = 0;
    input replacement  = 0;
    def ret_val = if IsNaN(data) then replacement else data;
    plot return = ret_val;
}
#ma(source, length, type) =>
script ma {
    input source = close;
    input length = 0;
    input type   = "SMA";
    def ma;
ma = if type == "SMA" then SimpleMovingAvg(source, length) else
     if type == "EMA" then ExpAverage(source, length) else
     if type == "WMA" then WMA(source, length) else
     if type == "HMA" then WMA(2 * WMA(source, length / 2) - WMA(source, length), Round(Sqrt(length)))
       else if isNaN(ma[1]) then SimpleMovingAvg(source, length) else
             (ma[1] * (length - 1) + source) / length;
    plot result = ma;
}
#_rate(cond) =>
script _rate {
    input cond = 1;
    def criteria = if cond == 1 then open <= close else open > close;
    def tw = high - Max(open, close) ;
    def bw = Min(open, close) - low;
    def body = AbsValue(close - open);
    def ret  = 0.5 * (tw + bw + (if criteria then 2 * body else 0)) / (tw + bw + body);
    def rate = if nz(ret) == 0 then 0.5 else ret;
    plot Result = rate;
}
def deltaup   = volume * _rate(1);
def deltadown = volume * _rate(0);
def delta     = if close >= open then deltaup else -deltadown;
def cumdelta  = TotalSum(delta);
def o_cd;
def h_cd;
def l_cd;
def c_cd;
def ctl;

if linestyle == linestyle.Candle
then {
    o_cd = cumdelta[1];
    h_cd = Max(cumdelta, cumdelta[1]);
    l_cd = Min(cumdelta, cumdelta[1]);
    c_cd = cumdelta;
    ctl = na;
} else {
    o_cd = na;
    h_cd = na;
    l_cd = na;
    c_cd = na;
    ctl = cumdelta;
}
def LineClose = ExpAverage((cumdelta[1] + Max(cumdelta, cumdelta[1]) + Min(cumdelta, cumdelta[1]) + cumdelta) / 4, 5);
def LineOpen = ExpAverage(if IsNaN(LineOpen[1]) then (cumdelta[1] + cumdelta) / 2 else (LineOpen[1] + LineClose[1]) / 2, 5);
def Line = ctl;
#Line.AssignValueColor( if LineClose >= LineOpen then CreateColor(8,153,129) else if LineClose < LineOpen  then CreateColor(239, 83, 80) else Color.GRAY);
#Line.SetLineWeight(2);
def _Close = (o_cd + h_cd + l_cd + c_cd) / 4;
def _Open = if IsNaN(_Open[1]) then (o_cd + c_cd) / 2 else (_Open[1] + _Close[1]) / 2;
def _High = Max(Max(h_cd, _Open), _Close);
def _Low = Min(Min(l_cd, _Open), _Close);
def haClose_CD = if HeikinAshi then _Close else c_cd;
def haOpen_CD  = if HeikinAshi then _Open  else o_cd;
def haHigh_CD  = if HeikinAshi then _High  else h_cd;
def haLow_CD   = if HeikinAshi then _Low   else l_cd;
def Color = if haClose_CD >= haOpen_CD then 1 else -1;
def UpO;
def UpH;
def UpL;
def UpC;

if Color > 0
then {
    UpO = haOpen_CD ;
    UpH = haHigh_CD ;
    UpL = haLow_CD ;
    UpC = haClose_CD;
} else
{
    UpO = na;
    UpH = na;
    UpL = na;
    UpC = na;
}
# Plot DOWN candle
def DnO;
def DnH;
def DnL;
def DnC;
if Color < 0
then {
    DnO = haOpen_CD ;
    DnH = haHigh_CD ;
    DnL = haLow_CD ;
    DnC = haClose_CD;
} else
{
    DnO = na;
    DnH = na;
    DnL = na;
    DnC = na;
}
def AvgLine = ma(ctl, maLength, maType);
def HaAvgLine = ma(haClose_CD, maLength, maType);
def offs = (1.6185 * stdev(if linestyle == linestyle.Candle then haClose_CD else ctl, maLength));
def upBand = (if linestyle == linestyle.Candle then HaAvgLine else AvgLine) + offs;
def dnBand = (if linestyle == linestyle.Candle then HaAvgLine else AvgLine) - offs;
def BandColor = if (if linestyle == linestyle.Candle then haClose_CD else ctl) > upBand then 1 else if (if linestyle == linestyle.Candle then haClose_CD else ctl) < dnBand then -1 else 0;
def color_1 = if (bandcolor > 0) and (bandcolor[1] < 0) then 1 else 0;
def color_2 = if (bandcolor < 0) and (bandcolor[1] > 0) then 1 else 0;
def Key_Color_1 = In_key_OB and (bandcolor > 0);
def Key_Color_2 = In_key_OB and (bandcolor < 0);
def Key_Color_3 = In_key_OS and (bandcolor > 0);
def Key_Color_4 = In_key_OS and (bandcolor < 0);
#####################################################
## FILTER                                          ##
#####################################################
def Big4_up_1;
def Big4_dn_1;
def TS_UP_1;
def TS_DN_1;
def SparkUP_1;
def SparkDN_1;
switch (Filter_OG_Signals) {
case EMAD_Filter:
    Big4_up_1 = if (MarketOpen and EMAD_Above_Zero and (direction2 == 1 and direction2[1] < 1)) within X_Signal_Bars bars then 1 else 0;
    Big4_dn_1 = if (MarketOpen and EMAD_Below_Zero and (direction2 == -1 and direction2[1] > -1)) within X_Signal_Bars bars then 1 else 0;
    TS_UP_1 = if (MarketOpen and EMAD_Above_Zero and (Upsignal and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    TS_DN_1 = if (MarketOpen and EMAD_Below_Zero and (Downsignal and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    SparkUP_1 = if (MarketOpen and EMAD_Above_Zero and (SparkUP1 and Hide_SparkUP)) within X_Signal_Bars bars then 1 else 0;
    SparkDN_1 = if (MarketOpen and EMAD_Above_Zero and (SparkDN1 and Hide_SparkDN)) within X_Signal_Bars bars then 1 else 0;
case Phase_Filter:
    Big4_up_1 = if (MarketOpen and Bullphase and (direction2 == 1 and direction2[1] < 1)) within X_Signal_Bars bars then 1 else 0;
    Big4_dn_1 = if (MarketOpen and Bearphase and (direction2 == -1 and direction2[1] > -1)) within X_Signal_Bars bars then 1 else 0;
    TS_UP_1 = if ((MarketOpen and Upsignal and Bullphase and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    TS_DN_1 = if ((MarketOpen and Downsignal and Bearphase and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    SparkUP_1 = if (MarketOpen and Bullphase and (SparkUP1 and Hide_SparkUP)) within X_Signal_Bars bars then 1 else 0;
    SparkDN_1 = if (MarketOpen and Bearphase and (SparkDN1 and Hide_SparkDN)) within X_Signal_Bars bars then 1 else 0;
case No_Filter:
    Big4_up_1 = if (MarketOpen and (direction2 == 1 and direction2[1] < 1)) within X_Signal_Bars bars then 1 else 0;
    Big4_dn_1 = if (MarketOpen and (direction2 == -1 and direction2[1] > -1)) within X_Signal_Bars bars then 1 else 0;
    TS_UP_1 = if ((MarketOpen and Upsignal and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    TS_DN_1 = if ((MarketOpen and Downsignal and !direction_Equals_zero)) within X_Signal_Bars bars then 1 else 0;
    SparkUP_1 = if (MarketOpen and (SparkUP1 and Hide_SparkUP)) within X_Signal_Bars bars then 1 else 0;
    SparkDN_1 = if (MarketOpen and (SparkDN1 and Hide_SparkDN)) within X_Signal_Bars bars then 1 else 0;}
#####################################################
## DIRECTION                                       ##
#####################################################
def Big4_up_bn = if Big4_up_1 then bn else Big4_up_bn[1];
def Big4_dn_bn = if Big4_dn_1 then bn else Big4_dn_bn[1];
def TS_Up_bn = if TS_UP_1 then bn else TS_Up_bn[1];
def TS_Dn_bn = if TS_DN_1 then bn else TS_Dn_bn[1];
def TS_Bars_Back = if TS_Last == 1 then bn - TS_Up_bn else if TS_Last == 0 then bn - TS_Dn_bn else Double.NaN;
def SparkUp_bn = if SparkUP_1 then bn else SparkUp_bn[1];
def SparkDn_bn = if SparkDN_1 then bn else SparkDn_bn[1];
def last_up_bn = if  Big4_up_1 or TS_UP_1 or SparkUP_1 then bn else last_up_bn[1];
def last_dn_bn = if  Big4_dn_1 or TS_DN_1 or SparkDN_1 then bn else last_dn_bn[1];
def Last_Arrow_Up = if last_up_bn > last_dn_bn then 1 else 0;
def Last_Arrow_Down = if last_dn_bn > last_up_bn then 1 else 0;
#####################################################
##                                                 ##
#####################################################
def First_HLLH_3 = if First_HL_2 then Halow else if First_LH_2 then hahigh else First_HLLH_3[1];
def Second_HLLH_3 = if Second_HL_2 then Halow else if Second_LH_2 then hahigh else Second_HLLH_3[1];
def CVD_Cloud_Green = (hl2 > ehlers) and (bandcolor > 0);
def CVD_Cloud_Red = (hl2 < ehlers) and (bandcolor < 0);
def CVD_No_Cloud = !CVD_Cloud_Green and !CVD_Cloud_Red;
def CVD_Green = !CVD_Cloud_Green and CVD_Cloud_Green[1];
def CVD_Green_Bn = if CVD_Green then bn else CVD_Green_Bn[1];
def CVD_Red = !CVD_Cloud_Red and CVD_Cloud_Red[1];
def CVD_Red_bn = if CVD_Red then bn else CVD_Red_bn[1];
def CVD_Last =  (CVD_Green_Bn - CVD_Red_Bn);
def CVD_Last_Green = CVD_Last > 0;
def CVD_Last_Red = CVD_Last < 0;
def countergreen = if CVD_Green and CVD_Last_Green and CVD_No_Cloud then countergreen[1] + 1 else if !CVD_Last_Green then 0 else countergreen[1];
def counterred = if CVD_red and CVD_Last_Red == 1 and CVD_No_Cloud then counterred[1] + 1 else if CVD_Last_Green then 0 else counterred[1];
def countergreen2 = if CVD_Last_Red then 0 else if CVD_Green then (countergreen) else countergreen2[1];
def counterred2 = if CVD_Last_Green then 0 else if CVD_Red then (counterred) else counterred2[1];
def Red_Cloud_Count = CVD_Last_Red and (counterred2 > Clouds_before);
def Green_Cloud_Count = CVD_Last_Green and (countergreen2 > Clouds_before);
def Ehlers_Avg_Length_2 = 120;
def Ehlers_Avg_2 = Average(Ehlers, Ehlers_Avg_Length_2);
#####################################################
##                                                 ##
#####################################################
def EMAD_Controller_1_Down = EMAD_Above_Zero and EMAD_EMA_Down and !EMAD_Controller;
def EMAD_Controller_1_Up = EMAD_Below_Zero and EMAD_EMA_Up and EMAD_Controller;
def EMAD_Controller_1_Down2 = EMAD_Below_Zero and EMAD_EMA_Down and !EMAD_Controller;
def EMAD_Controller_1_Up2 = EMAD_Above_Zero and EMAD_EMA_Up and EMAD_Controller;
#####################################################
##  EMAD CANDLE COLOR DEF                          ##
#####################################################
def CyanCandle = ((warnphase[1] or warnphase[2] or warnphase[3]) and bottomBand_PushDown) or Zone_Green_Wrapping;
def WhiteCandle = ((recphase[1] or recphase[2] or recphase[3]) and TopBand_PushUp) or Zone_Red_Wrapping;
def violetcandle =  EMAD_Controller_1_Up and !TopBand_StepUP and ((bandcolor > 0) within 5 bars);
def magentacandle = EMAD_Controller_1_Down and !bottomBand_StepUP and ((bandcolor < 0) within 5 bars);
def violetcandle2 =  EMAD_Controller_1_Up2 and !TopBand_StepUP and !TopBand_PushUp and ((bandcolor > 0) within 5 bars);
def magentacandle2 = EMAD_Controller_1_Down2 and !bottomBand_StepUP and !bottomBand_PushDown and ((bandcolor < 0) within 5 bars);
def volumecandle_Bull = Bull_Volume_Inc_Avg;
def volumecandle_Bear = Bear_Volume_Inc_Avg;
#####################################################
##                                                 ##
#####################################################
def CyanCandle2 = (!CyanCandle and CyanCandle[1]) Within X_Signal_Bars bars;
def Cyan_bn = if CyanCandle2 then bn else Cyan_bn[1];
def WhiteCandle2 = (!WhiteCandle and WhiteCandle[1]) Within X_Signal_Bars bars;
def white_bn = if whitecandle2 then bn else white_bn[1];
def last_candle_1 = white_bn > Cyan_bn;
def CyanCandle3 = (!CyanCandle2 and CyanCandle2[1]);
def WhiteCandle3 = (!WhiteCandle2 and WhiteCandle2[1]);
def GreenCandle2 = ((hl2 > ehlers) and EMAD_Above_Zero) or topband_PushUp;
def DarkGreenCandle2 = EMAD_EMA_up and bullphase;
def LightGreenCandle2 = EMAD_EMA_down and bullphase;
def RedCandle2 = ((hl2 < ehlers) and EMAD_below_Zero and EMAD_EMA_Down) or bottomband_Pushdown;
def DarkRedCandle2 = (EMAD_EMA_down and bearphase);
def LightRedCandle2 = (EMAD_EMA_up and bearphase) and !In_Key_OS;
def orangecandle2 = topband_compression or bottomband_Compression or Zone_Overlap;
def BlueCandle = (Alert4 or Regular_Sell_Line or Extreme_Sell_Line) and (CyanCandle2 and volumecandle_Bull) Within X_Signal_Bars_2 bars;;
def RedCondition1 = OBOS_Inside_Red and EMAD_EMA_Down and keyobpaint;
def GreenCondition1 =  OBOS_Inside_Green and EMAD_EMA_up and keyospaint;
def hizz1 = hl2 > hiz;
def hizz2 = hl2 < hiz;
def hizz3 = hl2 > hiz2;
def hizz4 = hl2 < hiz2;
def hizz11 = hizz1 and !hizz3;
def hizz111 = hizz1 and hizz3;
def hizz12 = hizz2 and !hizz4;
def hizz122 = hizz2 and hizz4;
def hizz13 = hizz3 and !hizz1;
def hizz14 = hizz4 and !hizz2;
def HIZehlers1 = (Ehlers + plothighz)/2;
def HizEHlers = average(HIZehlers1, hiz_Length);
def flatehlers = HIZEhlers1 == HIZEhlers1[1];
def Alert4_Overlap = Alert4 and orangecandle2;
def Regular_Buy_3X_HL_line = 1;
def CVDLINE = if CVD_Last_Green then halow else if CVD_Last_Red then Hahigh else CVDLINE[1];
def CVDLINEavg = average(cvdline, CVD_Length_avg);
def phaseLINE = if recphase then BH2ext else if warnphase then BL1ext else phaseLINE[1];
def BGbuy = if j crosses above BuyAlertLimit then 1 else 0;
def BGsell = if j crosses below SellAlertLimit then 1 else 0;


def true_count_1 = if condition1_Yellow_Candle then 1 else 0;
def true_count_2 = if condition2_RSI then 1 else 0;
def true_count_3 = if condition3_MFI then 1 else 0;
def true_count_4 = if condition4_Forcast then 1 else 0;
def true_count_5 = if condition5_CIP then 1 else 0;
def true_count_6 = if condition6_EMA_1 then 1 else 0;
def true_count_7 = if condition7_EMA_2 then 1 else 0;
def true_count_8 = if condition8_DMI then 1 else 0;
def true_count_9 = if condition9_Trend then 1 else 0;
def true_count_10 = if condition10_PFE then 1 else 0;
def true_count_11 = if condition11_BB then 1 else 0;
def true_count_12 = if condition12_BB then 1 else 0;
def true_count_13 = if condition13_KH then 1 else 0;
def true_count_14 = if condition14_PO then 1 else 0;
def true_count_15 = if conditionk1UP then 1 else 0;
def true_count_16 = if conditionk2UP then 1 else 0;
def true_count_17 = if conditionob1_RSI then 1 else 0;
def true_count_18 = if conditionob2_MFI then 1 else 0;
def true_count_19 = if conditionob3_Forcast then 1 else 0;
def true_count_20 = if conditionob4_Forcast then 1 else 0;
def true_count_21 = if conditionob5_PFE then 1 else 0;
def true_count_22 = if conditionob6_BB then 1 else 0;
def true_count_23 = if conditionob7_PO then 1 else 0;
def true_count_24 = if UP_OS then 1 else 0;
def true_count_25 = if UP_CL then 1 else 0;
def true_count_26 = if Bullphase then 1 else 0;
def true_count_27 = if direction == 1 then 1 else 0;
def true_count_28 = if EMAD_EMA_UP then 1 else 0;
def true_count_29 = if EMAD_ABOVE_ZERO then 1 else 0;
def true_count_30 = if Green_Cloud_Count then 1 else 0;
def true_count_31 = if Zone_Red_Wrapping then 1 else 0;
def true_count_32 = if Greencandle2 then 1 else 0;
def true_count_33 = if MF_UP then 1 else 0;
def true_count_34 = if upsignal then 1 else 0;
def true_count_35 = if buyerRegular or buyerExtreme then 1 else 0;
def true_count_36 = if HL2 > Ehlers_Avg then 1 else 0;
def true_count_37 = if HL2 > Ehlers_Avg_2 then 1 else 0;
def true_count_38 = if cond1_UP_AK then 1 else 0;
def true_count_39 = if cond2_UP_ZSCORE then 1 else 0;
def true_count_40 = if cond4_UP_AM then 1 else 0;
def true_count_41 = if cond5_UP_TMO then 1 else 0;
def true_count_42 = if BGcolor == 1 then 1 else 0;
def true_count_43 = if BGcolor_Last == 0 then 1 else 0;
def true_count_44 = if topband_Pushup then 1 else 0;

def false_count_1 = if condition1d_Yellow_Candle then 1 else 0;
def false_count_2 = if condition2d_RSI then 1 else 0;
def false_count_3 = if condition3d_MFI then 1 else 0;
def false_count_4 = if condition4d_Forcast then 1 else 0;
def false_count_5 = if condition5d_CIP then 1 else 0;
def false_count_6 = if condition6d_EMA_1 then 1 else 0;
def false_count_7 = if condition7d_EMA_2 then 1 else 0;
def false_count_8 = if condition8d_DMI then 1 else 0;
def false_count_9 = if condition9d_Trend then 1 else 0;
def false_count_10 = if condition10d_PFE then 1 else 0;
def false_count_11 = if condition11d_BB then 1 else 0;
def false_count_12 = if condition12d_BB then 1 else 0;
def false_count_13 = if condition13d_KH then 1 else 0;
def false_count_14 = if condition14d_PO then 1 else 0;
def false_count_15 = if conditionk3DN then 1 else 0;
def false_count_16 = if conditionk4DN then 1 else 0;
def false_count_17 = if conditionos1_RSI then 1 else 0;
def false_count_18 = if conditionOS2_MFI then 1 else 0;
def false_count_19 = if conditionos3_Forcast then 1 else 0;
def false_count_20 = if conditionos4_Forcast then 1 else 0;
def false_count_21 = if conditionos5_PFE then 1 else 0;
def false_count_22 = if conditionos6_BB then 1 else 0;
def false_count_23 = if conditionos7_PO then 1 else 0;
def false_count_24 = if DOWN_OB then 1 else 0;
def false_count_25 = if DOWN_CL then 1 else 0;
def false_count_26 = if Bearphase then 1 else 0;
def false_count_27 = if direction == -1 then 1 else 0;
def false_count_28 = if EMAD_EMA_DOWN then 1 else 0;
def false_count_29 = if EMAD_BELOW_ZERO then 1 else 0;
def false_count_30 = if Red_Cloud_Count then 1 else 0;
def false_count_31 = if Zone_Green_Wrapping then 1 else 0;
def false_count_32 = if Redcandle2 then 1 else 0;
def false_count_33 = if MF_DN then 1 else 0;
def false_count_34 = if Downsignal then 1 else 0;
def false_count_35 = if SellerRegular or SellerExtreme then 1 else 0;
def false_count_36 = if HL2 < Ehlers_Avg then 1 else 0;
def false_count_37 = if HL2 < Ehlers_Avg_2 then 1 else 0;
def false_count_38 = if cond1_DN_AK then 1 else 0;
def false_count_39 = if cond2_DN_ZSCORE then 1 else 0;
def false_count_40 = if cond4_DN_AM then 1 else 0;
def false_count_41 = if cond5_DN_TMO then 1 else 0;
def false_count_42 = if BGcolor == -1 then 1 else 0;
def false_count_43 = if BGcolor_Last == 1 then 1 else 0;
def false_count_44 = if bottomband_PushDown then 1 else 0;

def true_count_sum = true_count_1 + true_count_2 + true_count_3 + true_count_4 + true_count_5 +
                     true_count_6 + true_count_7 + true_count_8 + true_count_9 + true_count_10 +
                     true_count_11 + true_count_12 + true_count_13 + true_count_14 + true_count_15 +
                     true_count_16 + true_count_17 + true_count_18 + true_count_19 + true_count_20 +
                     true_count_21 + true_count_22 + true_count_23 + true_count_24 + true_count_25 +
                     true_count_26 + true_count_27 + true_count_28 + true_count_29 + true_count_30 +
                     true_count_31 + true_count_32 + true_count_33 + true_count_34 + true_count_35 +
                     true_count_36 + true_count_37 + true_count_38 + true_count_39 + true_count_40 +
                     true_count_41 + true_count_42 + true_count_43 + true_count_44;

def false_count_sum = false_count_1 + false_count_2 + false_count_3 + false_count_4 + false_count_5 +
                      false_count_6 + false_count_7 + false_count_8 + false_count_9 + false_count_10 +
                      false_count_11 + false_count_12 + false_count_13 + false_count_14 + false_count_15 +
                      false_count_16 + false_count_17 + false_count_18 + false_count_19 + false_count_20 +
                      false_count_21 + false_count_22 + false_count_23 + false_count_24 + false_count_25 +
                      false_count_26 + false_count_27 + false_count_28 + false_count_29 + false_count_30 +
                      false_count_31 + false_count_32 + false_count_33 + false_count_34 + false_count_35 +
                      false_count_36 + false_count_37 + false_count_38 + false_count_39 + false_count_40 +
                      false_count_41 + false_count_42 + false_count_43 + false_count_44;

def pos_neg_bar = true_count_sum - false_count_sum;
# Calculate average
def num_conditions = 44;
def average_pos_neg_bar = pos_neg_bar / num_conditions;
def average_pos_bar = true_count_sum / num_conditions;
def average_neg_bar = false_count_sum / num_conditions;
def averaged_average_pos = average(true_count_sum, Average_Length);
def averaged_average_neg = average(false_count_sum, Average_Length);
def avg_pos = (averaged_average_pos > averaged_average_neg);
def avg_neg = (averaged_average_pos < averaged_average_neg);
def avg_pos_inc = true_count_sum > true_count_sum[1];
def avg_neg_inc = false_count_sum < false_count_sum[1];

def averaged_average = average(average_pos_neg_bar, Average_Length);
def limit = IsNaN(close) and IsNaN(close[-1] ) && HighestAll(BarNumber());

plot average_line = if !limit then 0 else double.nan;
average_line.assignvaluecolor(if Zone_Overlap then Color.orange else if avg_pos then Color.GREEN  else if avg_neg then Color.Red else color.dark_gray);
average_line.SetLineWeight(2);

plot histogram = pos_neg_bar;
histogram.AssignValueColor(if histogram >= 0 then Color.GREEN else Color.RED);
histogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);

plot high_line = if !limit then High_Limit else double.nan;
high_line.assignvaluecolor(color.dark_gray);
high_line.SetLineWeight(1);

plot low_line = if !limit then Low_Limit else double.nan;
low_line.assignvaluecolor(color.dark_gray);
low_line.SetLineWeight(1);

plot high_line2 = if !limit then 43 else double.nan;
high_line.assignvaluecolor(color.dark_gray);
high_line2.SetLineWeight(2);

plot low_line2 = if !limit then -43 else double.nan;
low_line.assignvaluecolor(color.dark_gray);
low_line2.SetLineWeight(2);

Plot OB = if histogram >= high_line then pos_neg_bar else double.nan;
Plot OS = if histogram <= low_line then pos_neg_bar else double.nan;
#####################################################
##                                                 ##
#####################################################
OB.SetPaintingStrategy(PaintingStrategy.POINTS);
OB.SetLineWeight(3);
OB.assignvaluecolor(color.red);
OS.SetPaintingStrategy(PaintingStrategy.POINTS);
OS.SetLineWeight(3);
OS.assignvaluecolor(color.green);


#####################################################
## ZONE CLOUDS                                     ##
#####################################################
AddCloud(if !HideCloud then low_line else Double.NaN, low_line2, createcolor(60,60,60), createcolor(60,60,60));
AddCloud(if !HideCloud then high_line else Double.NaN, high_line2, createcolor(60,60,60), createcolor(60,60,60));

#FalseHistogram.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
#FalseHistogram.SetDefaultColor(Color.RED);

Addlabel(yes, " Consensus Level Histogram ", Color.orange);

Please what is the code to add white borders around these candles? Thanks

#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));
 
Confirmation Trend Chart 2024

(nothing re-paints / Good for all timeframes)

Chart Style: http://tos.mx/UkusWSy (updated 3/8/2024) (2:20pm)

********* Forgot to mention the settings for orange candles that indicate "Zone Compression" are currently set for use with /ES so if you use it on others you may need to adjust the setting*********

Disclaimer!

  • There is some unnecessary code that I will remove in time.
  • The white and cyan candles in the screenshots below have been changed to Red and Green.
  • All Arrows are effected by the "Use Clouds Before Filter" status (which I have updated the default settings to show only the "Combined Signals" (violet arrows) when 1 CVD cloud(s) precede the signal ((which is not the same settings pictured below)).
  • I will update the screenshots and whatnot soon.
********* Added another condition (2:20pm)*********

S8BjuBZ.png


White Candles Changed to Red / Cyan Candles changed to Green + Observation(s)

dB9RpXb.png


FDfgJQo.png


IPR7fOR.png


Candle Color Code

zzAkrS0.png


Vertical Clouds Between Zones (etc.)

V3xbzrX.png


Lower High Higher Low Candles

ZGW90fV.png


ELhmk6R.png


OB OS Zones Overlap

AhqtjLq.png


Pullbacks / Exhaustion (not triple exhaustion)

JhkCiIC.png


Hi thank you for this update with the painting.

I'm having issues with getting the Spark, Big4, And Bubbles to work as it did on the Big Mad versions. I just get a bunch of random bubbles and the Sparks/Big/Alerts don't seem to show or aligned with other previous versions.

Any assistance would great be appreciated. Right now I'm overlaying this Emad_V10 and Big Mad version over each other even though they have the same functionality.
 
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
290 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