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

Status
Not open for further replies.
Here is the rough draft to mess with... Explanation in screenshots (better one coming soon)... Removed alot of stuff I never mess with from settings also.

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

See white labels for settings adjustment:
xZ3DoHx.png


a3AalzE.png


Eo7RdCX.png


3W909yX.png


hI0wSIx.png


dHwnDEs.png


msw68DY.png


5r5ekk1.png
 
Last edited:
First... Hell will freeze over before we get an indicator with perfect confirmation... unless your code knows the future.
Yes the past is all the data we will ever have (time, sales); the past never repeats but it always rhymes.
Past patterns can be very kind to us so long as we keep nice tight stops and leave some gentle spaces for erratic behaviors to settle out . . . 😌
I am currently working on a thing... Testing at the moment with more improvements to come... or I will end up scrapping the idea all together who knows.
I wouldn't scrap the idea altogether. My advice is to be very hard on the code once you have completed the soft pattern visual testing on a variety of instruments and you know what visually looks best to you.
Remember the statistical benefits do not directly stack when you combine strategies and terms (Std Deviations, Series, Bid Ask imbalances, etcetera, etcetera.... )
For instance if you are entering a certain type of market and you find a strategy that offers you a 65% P/L in that type of market and you try to combine it with another strategy that offers a 73% P/L which is slower but you plan to use it for confirmation - the benefits might NOT stack ....
There are many ways it could fail - it might delay you from entering the trade on time and cause you to deeply shortcut your profits... It is necessary to take the correct amount of profits as you must comfortably cover the inevitable losses as market conditions change and you must pause your trades. Taking Profits inside the correct range in a trend is not always a matter of greed, and entering trades to late might cause you to behave greedily when you hope to hit the farther of your targets to reach your profit needs.

The other way combining these indicators could fail is by becoming CONVOLUTED, that is combining multiple indicators with similar mathematical equations could overly hold your model to one behavior which will not always fit the market.
 
@HODL-Lay-HE-hoo!
Of course you want beneficial convolution and not a curve fitting like failures some over-collinear situations collapse into. . .
Of course I imagine that is why you use non-directional indicators like the Squeeze. The Squeeze shows a non-trending time where the trend is less developed than an channel. The Squeeze was historically used to go long in stocks once the Debt market had already been pumped and tech darlings had not yet gotten their turn... Recently the 10 year debt has been somewhat resolved again so who knows maybe trading from the squeeze will come into favor again.
Unfortunately when there is not a reason a trend will begin soon the Squeeze will not do very much.
You need something to scale and zero out your trending and consolidating periods or else you will always be rotating strategies.

What do you think about a longer range market profile to zero out your trading simulations???
 

Attachments

  • TrendAdvisor+Diamond.png
    TrendAdvisor+Diamond.png
    161.9 KB · Views: 243
@HODL-Lay-HE-hoo! you have done a great deal of analysis on many different types of indicators, and you write very well about many different types of tools that you are using together.

It looks as if you have planned around the limitations of "over correlation" or the statistical costs of using to many indicators together

Squeezes alone could become stressful. There are other ways you may wish to filter out accumulation periods where trends are less likely to develop, as these false starts inside consolidations wear out not only your account but also your mental enjoyment of trading.
The "Squeeze" is when the curving lines of standard deviation style terms is confined inside of a stable channel or ATR style term. When we were buying calls for companies like TESLA we showed these Squeeze terms as clouds in ugly colors like offscale yellow-lime as we wanted to see those colors disappear from the chart so we could wait for a retracement down and hopefully let the market fill many of our lowball options offers.

For other types of markets besides the TESLA pump and Oil Inflation, you can use larger and longer terms like Hurst / Fractal Energy and Volume terms as well. You can also look at sector rotation to see what securities are due to end their periods of stagnation.
 
Last edited:
Yes the past is all the data we will ever have (time, sales); the past never repeats but it always rhymes.
Past patterns can be very kind to us so long as we keep nice tight stops and leave some gentle spaces for erratic behaviors to settle out . . . 😌

I wouldn't scrap the idea altogether. My advice is to be very hard on the code once you have completed the soft pattern visual testing on a variety of instruments and you know what visually looks best to you.
Remember the statistical benefits do not directly stack when you combine strategies and terms (Std Deviations, Series, Bid Ask imbalances, etcetera, etcetera.... )
For instance if you are entering a certain type of market and you find a strategy that offers you a 65% P/L in that type of market and you try to combine it with another strategy that offers a 73% P/L which is slower but you plan to use it for confirmation - the benefits might NOT stack ....
There are many ways it could fail - it might delay you from entering the trade on time and cause you to deeply shortcut your profits... It is necessary to take the correct amount of profits as you must comfortably cover the inevitable losses as market conditions change and you must pause your trades. Taking Profits inside the correct range in a trend is not always a matter of greed, and entering trades to late might cause you to behave greedily when you hope to hit the farther of your targets to reach your profit needs.

The other way combining these indicators could fail is by becoming CONVOLUTED, that is combining multiple indicators with similar mathematical equations could overly hold your model to one behavior which will not always fit the market.
Hmmm that’s a good point.
 
@HODL-Lay-HE-hoo!
Of course you want beneficial convolution and not a curve fitting like failures some over-collinear situations collapse into. . .
Of course I imagine that is why you use non-directional indicators like the Squeeze. The Squeeze shows a non-trending time where the trend is less developed than an channel. The Squeeze was historically used to go long in stocks once the Debt market had already been pumped and tech darlings had not yet gotten their turn... Recently the 10 year debt has been somewhat resolved again so who knows maybe trading from the squeeze will come into favor again.
Unfortunately when there is not a reason a trend will begin soon the Squeeze will not do very much.
You need something to scale and zero out your trending and consolidating periods or else you will always be rotating strategies.

What do you think about a longer range market profile to zero out your trading simulations???
That’s an interesting thought I will definitely look into that… by zeroing out are you referring to
Are you still using this strategy?

If you don't mind, can you share your document? I love your checklist :)
Hey man... I only use the entry exit methods (for the most part) as shown on page one. The screenshot you posted is how another person uses the setup.
 
I assume by "zero" you are referring to showing indications that match the direction of the longer range market profile? Correct?
Zeroing the shorter distance indicators around a long term trend is what the picture shows; but if you lumped that you would always be changing based off of the market that had just happened.

Suppose you have been trading very well in a bear market recovery and now you have lot's of BuyTheDip (Synthetic VIX based) indicators on hand... But then we go into a rangebound market and you no longer wish to accumulate large amounts of shares and hold until your active market orders fill on breakout targets that you set several Fibonacci Levels higher than your Cost Averaging Price...

Suppose now that we are in a range bound and rotating market you wish to sell Volatility with spreads...

Just attaching longer term indicators to the body of work you have completed would not be the best use of your time. But making certain that all the tools you use are balanced and not redundant is your best practices.
 
Code:
#Trend Advisor Market Phases;

#Credit to the Chuck Dukas for creating the system and for then author of the VolumeTrendLabels whose study was use to create this indicator. Ensure you set the correct aggregation period to then chart, this helps calculate the correct volume and price action.

def agg = getAggregationPeriod();
input vPeriod = AggregationPeriod.HOUR; #hint vPeriod: Enter the chart time you use here. Required to properly caluclate volume and price strength.

def O = open(period = vPeriod);
def H = high(period = vPeriod);
def C = close(period = vPeriod);
def L = low(period = vPeriod);
def V = volume(period = vPeriod);

def SV = V * (H - C) / (H - L);
def BV = V * (C - L) / (H - L);

# below determines if volume supports the move, adds conviction

AddLabel(yes, "Buyer Vol Strong ", if high > high[1] and low > low[1] and BV*1.05 > SV then Color.GREEN else color.black);

AddLabel(yes, "Seller Vol Strong", if high < high[1] and low < low[1] and SV*1.05 > BV then Color.MAGENTA else color.black);

# below determines if price supports the move

AddLabel(yes, "Price Strong ", if high > high[1] and high [1] > high[2] and low > low[1] and low[1] > low[2] then Color.GREEN else color.black);

AddLabel(yes, "Price Weak", if high < high[1] and high[1] < high[2] and low < low[1] and low[1] < low[2] then Color.MAGENTA else color.black);

declare upper;
input price = close;
input displace = 0;

input avglength = 10; #hint avgLength: Then exponential average length you want to use for your pullback entries.

def fastavg = 50;
def slowavg = 200;


plot fastsma = Average( price, fastavg);
fastsma.SetDefaultColor(Color.Green);

plot slowsma = Average(price, slowavg);
slowsma.SetDefaultColor(Color.Red);

# Bullish criteria define below

# Define criteria for Bullish Phase : close > 50 SMA, close > 200 SMA, 50 SMA > 200 SMA

def bullphase = fastsma > slowsma && price > fastsma && price > slowsma;

# Define criteria for Accumulation Phase : close > 50 SMA, close > 200 SMA, 50 SMA < 200 SMA

def accphase = fastsma < slowsma && price > fastsma && price > slowsma;

# Define criteria for Recovery Phase : close > 50 SMA, close < 200 SMA, 50 SMA < 200 SMA

def recphase = fastsma < slowsma && price < slowsma && price > fastsma;



# Bearish Criteria define below

# Define criteria for Bearish Phase : close < 50 SMA, close < 200 SMA, 50 SMA < 200 SMA

def bearphase = fastsma < slowsma && price < fastsma && price < slowsma;

# Define criteria for Distribution Phase : close < 50 SMA, close < 200 SMA, 50 SMA > 200 SMA

def distphase = fastsma > slowsma && price < fastsma && price < slowsma;

# Define criteria for Warning Phase : close < 50 SMA, close > 200 SMA, 50 SMA > 200 SMA

def warnphase = fastsma > slowsma && price > slowsma && price < fastsma;


# Below conditions are for a possible entry when price touches the fastema

#def pbavg = MovingAverage(Average, price, avglength);

def pbavg = ExpAverage(data = price[-displace], length = avglength);

input bullpullback = yes;  #hint bullpullback: Do you want to display the pullback arrows for bullish fast ema entries.
input bearpullback = yes; #hint bearpullback: Do you want to display the pullback arrows for bearish fast ema entries.

def bullishpb = low < pbavg && open > pbavg;
def bearishpb = high > pbavg && open < pbavg;

def bullpb = bullphase is true && bullishpb is true;
def bearpb = bearphase is true && bearishpb is true;

# Plot Signals
plot bullpb1 = if bullpullback then bullpb else 0;
bullpb1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
bullpb1.SetDefaultColor(Color.CYAN);
bullpb1.SetLineWeight(1);

plot bearpb1 = if bearpullback then bearpb else 0;
bearpb1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
bearpb1.SetDefaultColor(Color.red);
bearpb1.SetLineWeight(1);



#plot buphase = bullphase is true;
#plot acphase = accphase is true;
#plot rephase = recphase is true;

#plot bephase = bearphase is true;
#plot dphase = distphase is true;
#plot wphase = warnphase is true;


# Below adds labels to the chart to identify what phase the underlying is in


AddLabel(bullphase, " Bull Phase" , if bullphase is true then Color.GREEN else Color.BLACK);

AddLabel(accphase, " Accumation Phase ", if accphase is true then Color.lIGHT_GREEN else Color.BLACK);

AddLabel(recphase, " Recovery Phase ", if recphase is true then Color.lIGHT_ORANGE else Color.BLACK);

AddLabel(warnphase, " Warning Phase ", if warnphase is true then Color.orANGE else Color.BLACK);

AddLabel(distphase, " Distribution Phase ", if distphase is true then Color.light_red else Color.BLACK);

AddLabel(bearphase, " Bear Phase ", if bearphase is true then Color.red else Color.BLACK);


assignPriceColor(if bullphase then Color.GREEN else if bearphase then Color.RED else Color.orange);
Ahhhh ok I see. I have the Market phases thinkscript on this forum based on the image you posted... so this suggestion would be to have the code use specific types of indicators based on the current market phase... correct?
 
Ahhhh ok I see. I have the Market phases thinkscript on this forum based on the image you posted... so this suggestion would be to have the code use specific types of indicators based on the current market phase... correct?
Yes, That might be something you wish to try. I don't think it could hurt to use observations of long term indicators such as your Market Phase to define which indicators your code switches on and off.
I want to leave you with a good testing environment where your code doesn't become overnumbered.
I don't want to burden you with spam. 😇

Right now I am following up on a request for Relative Volume before I go to bed.
 
mod note:
ONLY the non-repainting. non-MTF portion of the studies found in this thread can be converted to Strategies. The mtf portions repaint out all the losses and unrealistically only report the gains.

Code:
#                                 /^\
#                                /   \
#                               /_____\
#                                 |||
#                                 |||
###########put all of your coding and indicators above this line ######
#where you see buysignal and sellsignal is where you signify your indicator conditions
#######################################################################

# MARK unsuppress AddOrder when you have the Buyorder or Sell order you want!


#AddOrder(condition = BuySignal, type = OrderType.BUY_TO_OPEN, price = open[-1], name = "OL");
#AddOrder(condition = SellSignal, type = OrderType.SELL_TO_CLOSE, price = open[-1], name = "TS");



#################################
######  BAR CHEAT  ##############

#2days 5min = 155 bars

#5days 15min = 130 bars

#10days 30min = 130 bars

#30days 1hour = 210 bars

#90days 4hours = 180 bars

#1Year DAY = 252 bars

#5Years Week = 260 bars



#def BAHstart = 100 * close[210];
#def BAHret = (close - close[210] / close);
#def BAHprofit = if BAHret <0 then   else (1 + BAHret)*


########## SEE BELOW FOR FPL ###########



############################
# FPL Extended
# Extended Floating P&L study.
# Author: Eddielee394
# Version: 1.2
# inspired by FPL Dashboard script developed by Mobius
#
############################

#Hint: An extended floating P&L study to be used alongside TOS strategies for measuring hypothetical strategy performance.\nThis is a work in progress.  And may contain some bugs or other programming issues.

############################
# Instructions
# - Due to limitations with the thinkscript public api, this specific script must be added to a "strategy" study.
#   Generally best practice is to append this script to the end of your custom strategy (ensuring it runs AFTER the
#   `AddOrder()` function is called from the strategy).  A better method would be to use as a lower study but unless
#    a workaround is implemented to handle the `Entry()` function in a lower study, it can only be applied to upper strategies.
#
# - the script uses the `HidePrice()` function which will hide the actual price candles within the upper study,
#   only displaying the FPL histogram.
#
############################


############################
#    Metrics               #
#  - Active Trade return % #
#  - Entry Count           #
#  - Winning Entry Count   #
#  - Win rate              #
#  - Avg return            #
#  - avg win               #
#  - avg loss              #
#  - peak to valley dd     #
#  - largest equity dd     #
#  - P&L low               #
#  - P&L high              #
#  - Highest return        #
#  - Lowest return         #
############################

############################
#     Todo:                #
# - Sharpe Ratio           #
# - Sortino Ratio          #
# - Calmar Ratio           #
# - Avg trade              #
#   duration               #
# -Buy/hold comparison     #
############################


#Globals
def nan = Double.NaN;
def bn = if !IsNaN(close) and !IsNaN(close[1]) and !IsNaN(close[-1]) then BarNumber() else bn[1];

#Inputs
input fplBegin = 0000;
#hint fplBegin: start time: the time in which then dailyHighLow profit should consider the day start.  Recommended value is 0000.

input fplTargetWinLoss = .50;
#hint fplTargetWinLoss: sets the target winlossRatio (in percent) which determines display colors of the W/L label.

input fplTargetWinRate = 1;
#hint fplTargetWinRate: sets the target winRate (float) which determines display colors of the WinRate label;

input fplHidePrice = no;
#hint fplHidePrice: hide's the underlying price graph. \nDefault is no.

input fplHideFPL = yes;
#hint fplHideFPL: hide's the underlying P&L graph.\nDefault is yes.

input fplShowEntryBubbles = no;
#hint fplShowEntryBubbles: display bubbles on the FPL showing the entry and exit P&L values

input fplEnableDebugging = no;
#hint fplEnableDebugging: displays various debugging labels and chart bubbles. \nIt's recommended to hide the price chart & set the fpl hide fpl setting to yes, when enabling.

#temp input var references
def begin = fplBegin;
def targetWinLoss = fplTargetWinLoss;
def targetWinRate = fplTargetWinRate;
def hidePrice = fplHidePrice;
def hideFPL = fplHideFPL;
def showEntryBubbles = fplShowEntryBubbles;
def enableDebugging = fplEnableDebugging;

#hide chart candles
HidePricePlot(hidePrice);

#Plot default Floating P&L
plot FPL = FPL();
FPL.SetPaintingStrategy(PaintingStrategy.SQUARED_HISTOGRAM);
FPL.DefineColor("Positive and Up", Color.GREEN);
FPL.DefineColor("Positive and Down", Color.DARK_GREEN);
FPL.DefineColor("Negative and Down", Color.RED);
FPL.DefineColor("Negative and Up", Color.DARK_RED);
FPL.AssignValueColor(if FPL >= 0
                            then if FPL > FPL[1]
                            then FPL.Color("Positive and Up")
                            else FPL.Color("Positive and Down")
                            else if FPL < FPL[1]
                            then FPL.Color("Negative and Down")
                            else FPL.Color("Negative and Up"));
FPL.SetHiding(hideFPL);

plot ZeroLine = if IsNaN(close)
                then nan
                else 0;
ZeroLine.SetDefaultColor(Color.GRAY);
ZeroLine.SetHiding(hideFPL);

#Global Scripts
script calculateDrawdown {
    input plLow = 1;
    input plHigh = 1;

    def _drawdown = if plHigh == 0
                   then 0 #handles the divide by zero error
                   else (plLow - plHigh) / plHigh;
    plot calculateDrawdown = _drawdown;
}

script incrementValue {
    input condition = yes;
    input increment =  1;
    input startingValue = 0;

    def _value = CompoundValue(1,
                 if condition
                 then _value[1] + increment
                 else _value[1], startingValue);

    plot incrementValue = _value;
}
;

script getDurationInMins {
    input gdimBarCount = 1;

    #get the aggregation period (MS per bar)
    def aggPeriod = GetAggregationPeriod();

    #multiply length of bars by aggPeriod to determine total milliseconds then convert to minutes
    def _getDurationInMins = Floor((gdimBarCount * aggPeriod) / 60000);
    plot getDurationInMins = _getDurationInMins;
}

script formatDuration {
    input fdBarCount = 1;
    def _fdDuration = getDurationInMins(fdBarCount);
    def _formatDuration = if _fdDuration >= 60 and _fdDuration < 1440 #hours but not days
                         then 1
                         else if _fdDuration >= 1440 #days
                         then 2
                         else 0;

    plot formatDuration = _formatDuration;
}

script calculateDuration {
    input cdBarCount = 1;
    def _cdDurationFormat = formatDuration(cdBarCount);
    def _cdDuration = getDurationInMins(cdBarCount);
 
    #if minutes > hour convert to hour, else if minutes > day, then convert to days
    def _calculateDuration = if _cdDurationFormat == 1
                             then _cdDuration / 60 #convert to hours if greater than 60min but less than a day (1440)
                             else if  _cdDurationFormat == 2
                             then Ceil(_cdDuration / 1440) #convert to days if greater than 1440mins
                             else _cdDuration; #fallback to minutes

    plot calculateDuration = _calculateDuration;
}






# Entry Calculations.  Note: Only parses on a Strategy Chart
def entry = EntryPrice();

def entryPrice = if !IsNaN(entry)
                 then entry
                 else entryPrice[1];

def hasEntry = !IsNaN(entry);

def isNewEntry = entryPrice != entryPrice[1];

#is active trade
def Active = if SecondsTillTime(begin) == 0 and
                SecondsFromTime(begin) == 0
             then 1
             else 0;

def highFPL = HighestAll(FPL);
def lowFPL = LowestAll(FPL);

def fplreturn = (FPL - FPL[1]) / FPL[1];
def cumsum = Sum(fplreturn);

def highBarNumber = CompoundValue(1, if FPL == highFPL
                                     then bn
                                     else highBarNumber[1], 0);

def lowBarNumber = CompoundValue(1, if FPL == lowFPL
                                    then bn
                                    else lowBarNumber[1], 0);


#Win/Loss ratios
def entryBarsTemp = if hasEntry
                    then bn
                    else nan;

def entryBarNum = if hasEntry and isNewEntry
                  then bn
                  else entryBarNum[1];

def isEntryBar = entryBarNum != entryBarNum[1];

def entryBarPL = if isEntryBar
                 then FPL
                 else entryBarPL[1];

def exitBarsTemp = if !hasEntry
                   and bn > entryBarsTemp[1]
                   then bn
                   else nan;

def exitBarNum = if !hasEntry and !IsNaN(exitBarsTemp[1])
                 then bn
                 else exitBarNum[1];

def isExitBar = exitBarNum != exitBarNum[1];

def exitBarPL = if isExitBar
                then FPL
                else exitBarPL[1];

def entryReturn = if isExitBar then exitBarPL - exitBarPL[1] else entryReturn[1];
def isWin = if isExitBar and entryReturn >= 0 then 1 else 0;
def isLoss = if isExitBar and entryReturn < 0 then 1 else 0;
def entryReturnWin = if isWin then entryReturn else entryReturnWin[1];
def entryReturnLoss = if isLoss then entryReturn else entryReturnLoss[1];
def entryFPLWins = if isWin then entryReturn else 0;
def entryFPLLosses = if isLoss then entryReturn else 0;
def entryFPLAll = if isLoss or isWin then entryReturn else 0;


#Counts
def entryCount = incrementValue(entryFPLAll);
def winCount = incrementValue(isWin);
def lossCount = incrementValue(isLoss);

def highestReturn = if entryReturnWin[1] > highestReturn[1]
                    then entryReturnWin[1]
                    else highestReturn[1];

def lowestReturn = if entryReturnLoss[1] < lowestReturn[1]
                   then entryReturnLoss[1]
                   else lowestReturn[1];


def winRate = winCount / lossCount;
def winLossRatio = winCount / entryCount;
def avgReturn = TotalSum(entryFPLAll) / entryCount;
def avgWin = TotalSum(entryFPLWins) / winCount;
def avgLoss = TotalSum(entryFPLLosses) / lossCount;

#Drawdown
def lowestLowBarNumber = HighestAll(if FPL == lowFPL then bn else 0);
def highestHighBarNumber = HighestAll(if FPL == highFPL and FPL != FPL[1] then bn else 0);
def hasPrevLow = lowestLowBarNumber < highestHighBarNumber;

def isPeak = FPL > Highest(FPL[1], 12) and FPL > Highest(FPL[-12], 12);
def isTrough = FPL < Lowest(FPL[1], 12) and FPL < Lowest(FPL[-12], 12);
def _peak = if isPeak then FPL else nan;
def _trough = if isTrough then FPL else nan;
def peak = if !IsNaN(_peak) then FPL else peak[1];
def trough = if !IsNaN(_trough) then FPL else trough[1];
def peakBN = if isPeak then bn else peakBN[1];
def troughBN = if isTrough then bn else troughBN[1];

def ptvDrawdown = if !hasPrevLow then calculateDrawdown(lowFPL, highFPL) else ptvDrawdown[1];
def equityDrawdown = if isTrough and trough < peak then trough - peak else equityDrawdown[1];
def equityDrawdownPercent = if isTrough and trough < peak then calculateDrawdown(trough, peak) else equityDrawdownPercent[1];
def largestEquityDrawdown = LowestAll(equityDrawdown);
def largestEquityDrawdownPercent = LowestAll(equityDrawdownPercent);

def drawdown = if hasPrevLow
               then largestEquityDrawdownPercent
               else ptvDrawdown;

# Drawdown Durations
def equityDrawdownLength = if bn >= peakBN and bn <= troughBN
                           then troughBN - peakBN
                           else equityDrawdownLength[1];

def ptvDrawdownLength = if bn >= highestHighBarNumber and bn <= lowestLowBarNumber
                        then lowestLowBarNumber - highestHighBarNumber
                        else ptvDrawdownLength[1];

def equityDrawdownDuration = calculateDuration(HighestAll(equityDrawdownLength));
def equityDrawdownDurationFormat = formatDuration(HighestAll(equityDrawdownLength));
def ptvDrawdownDuration = calculateDuration(ptvDrawdownLength);

def ptvDrawdownDurationFormat = formatDuration(ptvDrawdownLength);

#Daily profit
def Midnight = if Active then FPL else Midnight[1];
def DaysProfit = FPL - Midnight;

#Plots

AddChartBubble(!hideFPL and showEntryBubbles and isEntryBar, FPL, "Entry: " + entryBarPL + " | " + bn, Color.WHITE);
AddChartBubble(!hideFPL and showEntryBubbles and isExitBar, FPL, "Exit: " + exitBarPL,
               color = if isWin
                       then Color.LIGHT_GREEN
                       else if isLoss
                       then Color.DARK_RED
                       else Color.GRAY,
               up = no
              );

#Labels

AddLabel(yes,
         text = "LastEntry: " + AsPrice(entryPrice)
         );

AddLabel(hasEntry,
         text = "Current Trade % Return:  " + AsPercent(cumsum),
         color = if cumsum > 0
         then Color.GREEN
         else Color.RED
        );

AddLabel(yes,
         text = "Total Trades: " + entryCount,
         color = Color.WHITE
         );

AddLabel(yes,
         text = "WinCount: " + winCount +
                " | LossCount: " + lossCount +
                " | WinRate: " + winRate,
         color = if winRate >= targetWinRate
                 then Color.GREEN
                 else Color.RED
         );

AddLabel(yes,
         text = "W/L: " + AsPercent(winLossRatio),
         color = if winLossRatio > targetWinLoss
                 then Color.GREEN
                 else Color.RED
         );

#AddLabel(yes,
#        text = "HighestReturn: " +  AsDollars(highestReturn),
#        color = if highestReturn > 0
#                then Color.GREEN
#                else Color.RED
#        );

#AddLabel(yes,
#        text = "LowestReturn: " +  AsDollars(lowestReturn),
#        color = if lowestReturn > 0
#                then Color.GREEN
#                else Color.RED
#        );

AddLabel(yes,
         text = "AvgReturn: " + AsDollars(avgReturn) +
                " | AvgWin: " + AsDollars(avgWin) +
                " | AvgLoss: " + AsDollars(avgLoss),
         color = if avgReturn >= 0
                 then Color.LIGHT_GREEN
                 else Color.RED
         );

AddLabel(yes,
        text = "PeakToValley DD: " +  AsPercent(drawdown) +
               " | Duration: " + ptvDrawdownDuration +
                if ptvDrawdownDurationFormat == 1
                then " hours"
                else if ptvDrawdownDurationFormat == 2
                then " days"
                else " mins" ,
        color = if drawdown > 0
                then Color.GREEN
                else Color.RED
        );


AddLabel(largestEquityDrawdown < 0,
        text = "Largest Equity DD: " +  AsDollars(largestEquityDrawdown) +
               " | Duration: " + equityDrawdownDuration +
                if equityDrawdownDurationFormat == 1
                then " hours"
                else if equityDrawdownDurationFormat == 2
                then " days"
                else " mins",
        color = if largestEquityDrawdown > 0
                then Color.GREEN
                else Color.RED
        );

AddLabel(yes,
         text = "P&L High" +
                (if enableDebugging
                then " at bar " + highBarNumber
                else "") +
                ":  " + AsDollars(highFPL),
        color = Color.GREEN
       );

AddLabel(yes,
         text = "P&L Low" +
                (if enableDebugging
                then " at bar " + lowBarNumber
                else "") +
                ":  " + AsDollars(lowFPL),
        color = Color.RED
       );

AddLabel(yes,
         text = "Days Profit: $" + DaysProfit,
         color = if DaysProfit > 0
                 then Color.GREEN
                 else Color.RED
        );

####

input PeriodofRETURN= 252;
def BAHret = (close - close[PeriodofRETURN]) / (close[PeriodofRETURN]);
####

AddLabel(yes,
         text = "Total Profit: " + AsDollars(FPL),
         color = if FPL > 0
                 then Color.GREEN
                 else Color.RED
        );

AddLabel(yes,
         text = "B&H Profit: " + AsDollars(BAHret * (close[252]*100)),
         color = if BAHret * (close[252]*100)> 0
                 then Color.GREEN
                 else Color.RED
        );

def StratROI = FPL / (close[PeriodofRETURN] * 100);

AddLabel(yes,
         text = "Strat RoI%: " + AsPercent(FPL / (close[PeriodofRETURN] * 100)),
         color = if FPL / (close[PeriodofRETURN] * 100) > 0
                 then Color.GREEN
                 else Color.RED
        );


AddLabel(yes,
         text = "B&H RoI%: " + AsPercent(BAHret),
         color = if BAHret > 0
                 then Color.GREEN
                else Color.RED
       );


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






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

#debugging

#peaks & troughs
AddChartBubble(enableDebugging and isPeak, FPL,
               text = "FPL: " + FPL
                      + " | Peak: " + peak
                      + " | Trough: " + trough[-1]
                      + " | Drawdown: " + AsPercent(calculateDrawdown(trough, peak))
                      + " | PeakBN: " + peakBN
                      + " | BarNumber: " + bn,
               color = Color.LIME
              );

AddChartBubble(enableDebugging and isTrough, FPL,
               text = "FPL: " + FPL
                      + " | Peak: " + peak
                      + " | Trough: " + trough
                      + " | Drawdown: " + AsPercent(calculateDrawdown(trough, peak))
                      + " | TroughBN: " + troughBN
                      + " | BarNumber: " + bn,
              color = Color.LIGHT_RED,
              up = no
             );

AddVerticalLine(enableDebugging and isEntryBar,
                text = "EntryBarNum: " + entryBarNum
                       + " | ExitBarNum: " + exitBarNum[-1]
                       + " | BarNumber: " + bn,
                color = Color.WHITE
);

AddVerticalLine(enableDebugging and isExitBar,
                text =  "EntryBarNum: " + entryBarNum[1]
                        + " | ExitbarNum: " + exitBarNum
                        + " | BarNumber: " + bn
                        + " | EntryReturn: " + entryReturn,
                color = if isWin
                        then Color.LIGHT_GREEN
                        else if isLoss
                        then Color.LIGHT_RED
                        else Color.LIGHT_GREEN
);

Ahhhh ok I see. I have the Market phases thinkscript on this forum based on the image you posted... so this suggestion would be to have the code use specific types of indicators based on the current market phase... correct?

I didn't see if you had this but this was the response by Mobius and his students when the ToS did not adopt a built in optimizer.

There are many option in this BACKTEST script I left all the options but I can gut the parts that won't be relevant to your design.

In the next year I hope to do some Volume Studies together as a community. I look forward to those days.
V/r
 
Last edited by a moderator:
@HODL-Lay-HE-hoo! Is there a way to backtest these signals/arrows for accuracy? I'd be happy to volunteer for extensive testing across all timeframes.
No, it is not possible to create accurate backtesting results, given that the MTF indicator repaints.
It is not possible to capture the inter-bar false signals that occurred waiting for the higher time candle to close.
 
@HODL-Lay-HE-hoo! Is there a way to backtest these signals/arrows for accuracy? I'd be happy to volunteer for extensive testing across all timeframes.
I plan to add that functionality at some point… as for testing across all timeframes if you mean making it MTF that’s a no go… currently I am exploring implementing something similar to one of @MatthewA suggestions above which will incorporate backtesting. The whole family finally getting over being sick for the last week so I’ll be back on it soon.
 
Hello... Have not changed much yet. Mainly cleaning up the code. Still need to create a version that uses specific signals during specific market conditions / phases but figured I would post the update. I did add some conditions to the arrow plots. There are a few more redundancies to be removed among other things but to whom it may concern:

Chart Style: https://tos.mx/wn3A43r


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

input use_EMAD_filter = yes;
input Arrow_Up_filter = 10;
input Arrow_Down_filter = 10; #hint number of conditions met must be greater than
input Show_filter_Cloud = no;
input Cloud_filter = 0; #hint number of conditions met must be greater than
input controlpercent = 50; 
input show_TS_lastlabel = yes; #hint shows which TS_V9 signal is most recent
input show_filter_TS = yes; 
input show_TS_V9_Lines = no; #Show horizontal long and short entry exit lines
input Use_Arrow_Inputs = yes;
input Use_Alert4_UP_C = yes;
input Use_Alert4_DN_C = NO;
input Use_signal_UP_C = yes; #hint Big4 signal up signal as part of "Allup" signal count
input Use_signal_DN_C = yes; #hint Big4 signal down as part of "Alldown" signal count
input Use_signal_2_UP_C = yes; #hint Big4 signal up signal as part of "Allup" signal count
input Use_signal_2_DN_C = yes; #hint Big4 signal down as part of "Alldown" signal count
input Use_Spark_UP_C = yes;
input Use_Spark_DN_C = yes;
input Use_Spark_DN2_C = yes;
input Use_Spark_UP2_C = no;
input Use_TS_UP_C = yes; #hint TS_V9 up signal as part of "Allup" signal count
input Use_TS_DN_C = yes; #hint TS_V9 down signal as part of "Alldown" signal count
input Use_TripleEx_UP_C = yes; #hint triple exhaustion 
input Use_TripleEx_DN_C = yes; #hint triple exhaustion 
input ShowEMAcloud = no; #hint default C3_Max cloud Average 8 and 9
input showall = no; #hint show all signals individually 
input length_HV = 20; #Horserider Volume Average
input showLabels  = yes;  #hint C3_Max
input tradeDaytimeOnly = no; #hint tradeDaytimeOnly: (IntraDay Only) Only perform trades during hours stated
input OpenTime = 0930; #hint OpenTime: Opening time of market
input CloseTime = 1600; #hint CloseTime: Closing time of market
input VolumeTime = 1030; #hint OpenTime: Opening time of market
input Strategy_Confirmation_Factor = 4; #hint Big4
input TargetMultiple = 0.5; #hint TS_V9
input control = 13; #hint percent distance from current price to key level (0 is at level)
input showbubbles = no; #hint TS_V9
input type = { default SMP, EXP }; #hint TS_V9
input trailType = {default modified, unmodified}; #hint TS_V9
input averagetype = AverageType.SIMPLE;
input MACD_AverageType = {SMA, default EMA};
input DMI_averageType = AverageType.WILDERS;
input AvgType = AverageType.HULL;
input firstTrade = {default long, short}; #hint TS_V9
input ehlers_length = 13;

def hotpct = 150; #hint Horserider High Volume indication
def elhers3length = 9;
def Triple_Ex_Lookback = 15;
def Triple_Ex_Control = 2;
def lookbackcontrol = 1;
def lookbackcontrol2 = 1;
def arrowfilter = 12;
def keyleveltolerance = 1;
def showverticallineday = yes;
def show_ts_signals = no;   
def length9 = 35;
def length8 = 10;
def length10 = 20;
def length_3x = 1000;
def LongTrades = yes; #hint LongTrades: perform long tradesvb  balanceOfMarketPower AbandonedBaby b           bbbbbbbbg
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
def ATRPeriod = 11;
def ATRFactor = 2.2;
def ATRPeriod2 = 5;
def ATRFactor2 = 1.5;
def AtrMult = 1.0;
def HideBoxLines = no;
def HideCloud = no;
def HideLabels = no; 
def Strategy_FilterWithTMO = no;
def Strategy_FilterWithTMO_arrows = yes;
def Strategy_HoldTrend = no;
def Strategy_ColoredCandlesOn = yes;
def coloredCandlesOn = yes;
def ColorPrice = yes;
def color_blst = no;
def color_3x = yes;
def color_3xt = yes;
def color_OBOS = no;
def BarsUsedForRange = 2; 
def BarsRequiredToRemainInRange = 2;
def trig = 20;# for Blast-off candle color
def HideTargets = no;   
def HideBalance = no; 
#USER INPUTS
## Upper and Lower EMAD Lines
def fastLength_EMAD = 10;
def slowLength_EMAD = 35;
def smoothLength_EMAD = 12;
def smoothLength2_EMAD = 14;
def priceType_EMAD = close;
def emadLineWeight_EMAD = 2;
def showEMACloud_EMAD = yes;
def showBubbles_EMAD = yes;
def averageType_EMAD = AverageType.WILDERS;
## Upper and Lower Band Lines
def bandLength_EMAD = 100;
def bandLength2_EMAD = 200;
#DEFINITIONS / CALCULATIONS
## UPPER EMAD LINE
def fastExpAvg_EMAD = ExpAverage(priceType_EMAD, fastLength_EMAD);
def slowExpAvg_EMAD = ExpAverage(priceType_EMAD, slowLength_EMAD);
def EMAD_EMAD = (priceType_EMAD - fastExpAvg_EMAD);
def EMAD2_EMAD = (priceType_EMAD - slowExpAvg_EMAD);
def EMADAvg_EMAD = (EMAD_EMAD + EMAD2_EMAD) / 2;
def upperEMADLine_EMAD = ExpAverage(EMADAvg_EMAD, smoothLength_EMAD);
## LOWER EMAD LINE
def emadOpen_EMAD = (upperEMADLine_EMAD + upperEMADLine_EMAD[1]) / 2;
def emadHigh_EMAD = Max(upperEMADLine_EMAD, upperEMADLine_EMAD[1]);
def emadLow_EMAD = Min(upperEMADLine_EMAD, upperEMADLine_EMAD[1]);
def emadClose_EMAD = upperEMADLine_EMAD;
def bottom_EMAD = Min(emadClose_EMAD[1], emadLow_EMAD);
def tr_EMAD = TrueRange(emadHigh_EMAD, emadClose_EMAD, emadLow_EMAD);
def ptr_EMAD = tr_EMAD / (bottom_EMAD + tr_EMAD / 2);
def APTR_EMAD = MovingAverage(averageType_EMAD, ptr_EMAD, smoothLength2_EMAD);
def upperBand_EMAD = emadClose_EMAD[1] + (APTR_EMAD * emadOpen_EMAD);
def lowerBand_EMAD = emadClose_EMAD[1] - (APTR_EMAD * emadOpen_EMAD);
def lowerEMADLine_EMAD = (upperBand_EMAD + lowerBand_EMAD) / 2;
## TOP AND BOTTOM BANDS
def zeroLineData_EMAD = if IsNaN(close) then Double.NaN else 0;
def EMADSUp_EMAD = upperEMADLine_EMAD > zeroLineData_EMAD;
def EMADSDown_EMAD = upperEMADLine_EMAD < zeroLineData_EMAD;
def EMADdown_EMAD = (lowerEMADLine_EMAD > upperEMADLine_EMAD);
def EMADup_EMAD = (upperEMADLine_EMAD >= lowerEMADLine_EMAD);
def topBand_EMAD = Highest(lowerEMADLine_EMAD, bandLength_EMAD);
def bottomBand_EMAD = Lowest(lowerEMADLine_EMAD, bandLength_EMAD);
## BAND DIRECTION (USED ONLY FOR COLORING - NOT USED FOR PLOTS)
def topBandStepDown_EMAD = if topBand_EMAD < topBand_EMAD[1] then 1 else 0;
def topBandStepUp_EMAD = if topBand_EMAD > topBand_EMAD[1] then 1 else 0;
def bottomBandStepDown_EMAD = if bottomBand_EMAD < bottomBand_EMAD[1] then 1 else 0;
def bottomBandStepUp_EMAD = if bottomBand_EMAD > bottomBand_EMAD[1] then 1 else 0;
def bothBandsDown_EMAD = bottomBandStepDown_EMAD and topBandStepDown_EMAD;
def bothBandsUp_EMAD = bottomBandStepUp_EMAD and topBandStepUp_EMAD;
def bullBias_EMAD = (bottomBand_EMAD > zeroLineData_EMAD);
def bearBias_EMAD = (topBand_EMAD < zeroLineData_EMAD);
## BUBBLE CALCULATIONS (USED ONLY FOR BUBBLES)
def midBand_EMAD = (upperBand_EMAD + lowerBand_EMAD) / 2;
def crossesUp_EMAD = if (midBand_EMAD[1] > upperEMADLine_EMAD[1]) and (midBand_EMAD < upperEMADLine_EMAD) then 1 else 0;
def crossesDown_EMAD = if (upperEMADLine_EMAD[1] > midBand_EMAD[1]) and (upperEMADLine_EMAD < midBand_EMAD) then 1 else 0;
def valueUp_EMAD = if crossesUp_EMAD then midBand_EMAD else 0;
def valueDown_EMAD = if crossesDown_EMAD then midBand_EMAD else 0;
def crossesUpline_EMAD = if (valueUp_EMAD - bottomBand_EMAD) == 0 then 1 else 0;
def crossesDownline_EMAD = if (valueDown_EMAD - topBand_EMAD) == 0 then 1 else 0;
def crossesUpline_filter_EMAD = if crossesUpline_EMAD and (crossesUpline_EMAD[1] or crossesUpline_EMAD[2] or crossesUpline_EMAD[3] or crossesUpline_EMAD[4]) then 0 else 1;
def crossesDownline_filter_EMAD = if crossesDownline_EMAD and (crossesDownline_EMAD[1] or crossesDownline_EMAD[2] or crossesDownline_EMAD[3] or crossesDownline_EMAD[4]) then 0 else 1;
#PLOTS
def zeroLine_EMAD = zeroLineData_EMAD;
def upperEMADLinePlot_EMAD = upperEMADLine_EMAD;
def lowerEMADLinePlot_EMAD = lowerEMADLine_EMAD;
def masterEMADLinePlot_EMAD = (upperEMADLinePlot_EMAD + lowerEMADLinePlot_EMAD) / 2;
def topBandPlot_EMAD = topBand_EMAD;
def bottomBandPlot_EMAD = bottomBand_EMAD;
def topunderzero = topBandPlot_EMAD < zeroLine_EMAD;
def bottomunderzero = bottomBandPlot_EMAD > zeroLine_EMAD;
def emaunderzero = upperEMADLinePlot_EMAD < zeroLine_EMAD;
def emaabovezero = upperEMADLinePlot_EMAD > zeroLine_EMAD;
def EMADaboveZero = emaabovezero or emaabovezero[1];
def EMADbelowZero = emaunderzero or emaunderzero[1];
def toppushline =  masterEMADLinePlot_EMAD >= topbandPlot_EMAD;
def bottompushline = masterEMADLinePlot_EMAD <= bottomBandPlot_EMAD;
#####################################################
#TS Strategy_V9 Created by Christopher84 08/10/2021
#####################################################
Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);
def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);
def state = {default init, long, short};
def trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;
    }
}
def price = close;
def TrailingStop = trail;
def LongEnter = (price crosses above TrailingStop);
def LongExit = (price crosses below TrailingStop);
def upsignal =  (price crosses above TrailingStop);
def downsignal = (price crosses below TrailingStop);
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 PLBuySignal3 = if  MarketOpen and (upsignal) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLSellSignal3 =  if MarketOpen and (downsignal) then 1 else 0; # insert condition to create short position in place of the 0>0
def PLBuyStop  = if !useStops then 0 else if  (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0<0
def PLSellStop = if !useStops then 0 else if (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0>0
def PLMktStop = if MarketOpen[-1] == 0 then 1 else 0; # If tradeDaytimeOnly is set, then stop at end of day
def PLBuySignal = if  MarketOpen and (upsignal) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLSellSignal =  if MarketOpen and (downsignal) then 1 else 0; # insert condition to create short position in place 0>0
def CurrentPosition;  # holds whether flat = 0 long = 1 short = -1
if (BarNumber() == 1) or IsNaN(CurrentPosition[1]) {
    CurrentPosition = 0;
} else {
    if CurrentPosition[1] == 0 {            # FLAT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == 1 {      # LONG
        if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else if ((PLBuyStop and useStops) or PLMktStop or (PLSellSignal and ShortTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == -1 {     # SHORT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if ((PLSellStop and useStops) or PLMktStop or (PLBuySignal and LongTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else {
        CurrentPosition = CurrentPosition[1];
    }
}
def isLong  = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat  = if CurrentPosition == 0 then 1 else 0;
#Addorder(OrderType.BUY_AUTO, condition = LongEnter, price = open[-1], 1, tickcolor = GetColor(1), arrowcolor = Color.LIME);
#AddOrder(OrderType.SELL_AUTO, condition = LongExit, price = open[-1], 1, tickcolor = GetColor(2), arrowcolor = Color.LIME);
def BuySig = if (((isShort[1] and LongTrades) or (isFlat[1] and LongTrades)) and PLBuySignal) then 1 else 0;
def SellSig = if (((isLong[1] and ShortTrades) or (isFlat[1] and ShortTrades)) and PLSellSignal) then 1 else 0;
def bn = barnumber();
def TS_UP1bn = if upsignal[1] then BN else TS_UP1bn[1];    
def TS_DN1bn = if downsignal[1] then BN else TS_DN1bn[1];
def cond13_TS_Buy = Buysig;
def cond13_TS_Sell = Sellsig;
def TS_Last = if TS_UP1bn > TS_DN1bn then 1 else 0;
###############################################
##OB_OS_Levels_v5 by Christopher84 12/10/2021
###############################################
#def TrailingStop = trail;
def H = Highest(TrailingStop, 12);
def L = Lowest(TrailingStop, 12);
def BulgeLengthPrice = 100;
def SqueezeLengthPrice = 100;
def BandwidthC3 = (H - L);
#def IntermResistance2 = Highest(BandwidthC3, BulgeLengthPrice);
def IntermSupport2 = Lowest(BandwidthC3, SqueezeLengthPrice);
def sqzTrigger = BandwidthC3 <= IntermSupport2;
def sqzLevel = if !sqzTrigger[1] and sqzTrigger then hl2
               else if !sqzTrigger then Double.NaN
               else sqzLevel[1];
###############################################
##Yellow Candle_height (OB_OS)
###############################################
def displace = 0;
def factorK2 = 3.25;
def lengthK2 = 20;
def price1 = open;
def trueRangeAverageType = AverageType.SIMPLE;
def ATR_length = 15;
def SMA_lengthS = 6;
def HiLo2 = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef2 = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef2 = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def loss2 = ATRFactor2 * MovingAverage(averageType, trueRange, ATRPeriod2);
def multiplier_factor = 1.25;
def valS = Average(price, SMA_lengthS);
def average_true_range = Average(TrueRange(high, close, low), length = ATR_length);
def Upper_BandS = valS[-displace] + multiplier_factor * average_true_range[-displace];
def Middle_BandS = valS[-displace];
def Lower_BandS = valS[-displace] - multiplier_factor * average_true_range[-displace];
def shiftK2 = factorK2 * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK2);
def averageK2 = MovingAverage(averageType, price, lengthK2);
def AvgK2 = averageK2[-displace];
def Upper_BandK2 = averageK2[-displace] + shiftK2[-displace];
def Lower_BandK2 = averageK2[-displace] - shiftK2[-displace];
def condition_BandRevDn = (Upper_BandS > Upper_BandK2);
def condition_BandRevUp = (Lower_BandS < Lower_BandK2);
def fastLength = 12;
def slowLength = 26;
def MACDLength = 9;
def fastEMA = ExpAverage(price, fastLength);
def slowEMA = ExpAverage(price, slowLength);
def Value;
def Avg;
switch (MACD_AverageType) {
case SMA:
    Value = Average(price, fastLength) - Average(price, slowLength);
    Avg = Average(Value, MACDLength);
case EMA:
    Value = fastEMA - slowEMA;
    Avg = ExpAverage(Value, MACDLength);
}
def Diff = Value - Avg;
def MACDLevel = 0.0;
def Level = MACDLevel;
def condition1_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;
########
#MFI
########
def MFI_Length = 14;
def MFIover_Sold = 20;
def MFIover_Bought = 80;
def movingAvgLength = 1;
def MoneyFlowIndex = Average(MoneyFlow(high, close, low, volume, MFI_Length), movingAvgLength);
def MFIOverBought = MFIover_Bought;
def MFIOverSold = MFIover_Sold;
def condition3_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 PercentB
###############################
def BBPB_length = 20;#Typically 20
def Num_Dev_Dn = -2.0;
def Num_Dev_up = 2.0;
def BBPB_OB = 100;
def BBPB_OS = 0;
def upperBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, averagetype).UpperBand;
def lowerBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, averagetype).LowerBand;
def PercentB = (price - lowerBand) / (upperBand - lowerBand) * 100;
def HalfLine = 50;
def UnitLine = 100;
def condition11_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;
############
# Ehlers
############
def ehlers_price = (high + low) / 2;
def ehlers_coeff = ehlers_length * ehlers_price * ehlers_price - 2 * ehlers_price * Sum(ehlers_price, ehlers_length)[1] + Sum(ehlers_price * ehlers_price, ehlers_length)[1];
def Ehlers = Sum(ehlers_coeff * ehlers_price, ehlers_length) / Sum(ehlers_coeff, ehlers_length);
def Ehlers3 = average(Ehlers, elhers3length);
def cond3_UP_Ehlers = if close > Ehlers3 then 1 else 0;
def cond3_DN_Ehlers = if close <= Ehlers3 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;
################################
# --- TRIPLE EXHAUSTION --- 
################################
def agperiod1 = GetAggregationPeriod();
def over_bought_3x = 80;
def over_sold_3x = 20;
def KPeriod_3x = 10;
def DPeriod_3x = 10;
def priceH1 = high(period = agperiod1);
def priceL1 = low(period = agperiod1);
def priceC1 = close(period = agperiod1);
def priceO1 = close(period = agperiod1);
def priceH_3x = high;
def priceL_3x = low;
def priceC_3x = close;     
def SlowK_3x = reference StochasticFull(over_bought_3x, over_sold_3x, KPeriod_3x, DPeriod_3x, priceH_3x, priceL_3x, priceC_3x, 3, averagetype).FullK;
def MACD_3x = reference MACD()."Value";
def priceMean_3x = Average(MACD_3x, length_3x);
def MACD_stdev_3x =  (MACD_3x - priceMean_3x) / StDev(MACD_3x, length_3x);
def dPlus_3x = reference DMI()."DI+";
def dMinus_3x = reference DMI()."DI-";
def sellerRegular = SlowK_3x < 20 and MACD_stdev_3x < -1 and dPlus_3x < 15;
def sellerExtreme = SlowK_3x < 20 and MACD_stdev_3x < -2 and dPlus_3x < 15;
def buyerRegular = SlowK_3x > 80 and MACD_stdev_3x > 1 and dMinus_3x < 15;
def buyerExtreme = SlowK_3x > 80 and MACD_stdev_3x > 2 and dMinus_3x < 15;   
def ExtremeBuy = if sellerExtreme[1] and !sellerExtreme then 1 else 0;        
def ExtremeSell = if buyerExtreme[1] and !buyerExtreme then 1 else 0;        
def RegularSell = if buyerRegular[1] and !buyerRegular then 1 else 0;        
def RegularBuy= if sellerRegular[1] and !sellerRegular then 1 else 0;   
def cond6_UP_Triple_Exh = if sellerRegular or sellerExtreme then 1 else 0;
def cond6_DN_Triple_Exh = if buyerRegular or buyerExtreme then -1 else 0;
###########################
# --- ALERT 4 --- #
###########################
def pd = 22;
def bbl = 20;
def lb = 50;
def ph = 0.85;
def pl = 1.01;
# Downtrend Criterias
def ltLB = 40;
def mtLB = 14;
def str = 3;
def AtrMult_Blst = 1.0;
def nATR_Blst = 4;
def AvgType_Blst = AverageType.HULL;
def ATR = MovingAverage(AvgType, TrueRange(high, close, low), nATR_Blst);
def UP_B = HL2 + (AtrMult * ATR);
def DN = HL2 + (-AtrMult * ATR);
def ST = if close < ST[1] then UP_B else DN;
def SuperTrend = ST;
def val1 = AbsValue(close - open);
def range = high - low;
def blastOffVal = (val1 / range) * 100;
def trigger = trig;
def alert1 = blastOffVal < trig;
def col = blastOffVal < trig;
def blast_candle = blastOffVal < trig;
# Downtrend Criterias
def wvf = ((highest(close, pd) - low) / (highest(close, pd))) * 100;
def sDev = lb * stdev(wvf, bbl);
def midLine1 = SimpleMovingAvg(wvf, bbl);
def lowerBand1 = midLine1 - sDev;
def upperBand1 = midLinE1 + sDev;
def rangeHigh = (highest(wvf, lb)) * ph;
#  Filtered Bar Criteria
def upRange = low > low[1] and close > high[1];
def upRange_Aggr = close > close[1] and close > open[1];
def filtered = ((wvf[1] >= upperBand1[1] or wvf[1] >= rangeHigh[1]) and (wvf<upperBand1 and wvf<rangeHigh));
def filtered_Aggr = (wvf[1] >= upperBand1[1] or wvf[1] >= rangeHigh[1]);
# Alerts Criteria 1
def alert4 = upRange_Aggr and close > close[str] and (close < close[ltLB] or close < close[mtLB]) and filtered_Aggr;
def lengthVolAvgPlot = 21;
def VolAvg = Average(volume, lengthVolAvgPlot);
def MA = if type == type.SMP then SimpleMovingAvg(volume, length_HV) else MovAvgExponential(volume, length_HV);
def HighV = if (100 * ((volume / ma) - 1) >= hotPct) then 1 else 0;
def VolAbvAverage = if volume >= VolAvg then 1 else 0;
def Cond_Alert4_UP = if Alert4 within 2 bars then 1 else 0;
#####################
# Market Phases
#####################
def O = open;
def H2 = high;
def C = close;
def L2 = low;
def V = volume;
def SV = V * (H - C) / (H - L);
def BV = V * (C - L) / (H - L);
def fastavg = 50;
def slowavg = 200;
def fastsma = Average( close, fastavg);
def slowsma = Average(close, slowavg);
def buystrong = if high > high[1] and low > low[1] and BV*1.05 > SV then 1 else 0;
def cond7_UP_Buystrong = if buystrong then 1 else 0;
def sellstrong = if high < high[1] and low < low[1] and SV*1.05 > BV then 1 else 0;
def cond7_DN_sellstrong = if sellstrong then -1 else 0;
def pricestrong = if high > high[1] and high [1] > high[2] and low > low[1] and low[1] > low[2] then 1 else 0;
def cond8_UP_pricestrong = if pricestrong then 1 else 0;
def priceweak = if high < high[1] and high[1] < high[2] and low < low[1] and low[1] < low[2] then 1 else 0;
def cond8_DN_priceweak = if priceweak then -1 else 0;
def bullphase = fastsma > slowsma && price > fastsma && price > slowsma;
def cond9_UP_bullphase = if bullphase then 1 else 0;
def bearphase = fastsma < slowsma && price < fastsma && price < slowsma;
def cond9_DN_bearphase = if bearphase then -1 else 0;
def accphase = fastsma < slowsma && price > fastsma && price > slowsma;
def cond10_UP_accphase = if accphase then 1 else 0;
def distphase = fastsma > slowsma && price < fastsma && price < slowsma;
def cond10_DN_distphase = if distphase then -1 else 0;
def recphase = fastsma < slowsma && price < slowsma && price > fastsma;
def cond11_UP_recphase = if recphase then 1 else 0;
def warnphase = fastsma > slowsma && price > slowsma && price < fastsma;
###################################
##Big4 Strategy
###################################
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 >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_UP_TMO) then 1
else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_DN_TMO) then -1
    else if !Strategy_HoldTrend and direction[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
        else if !Strategy_HoldTrend and direction[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0
            else direction[1];
def direction2 = if cond_UP >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_UP_TMO) then 1
    else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_DN_TMO) then -1
        else if !Strategy_HoldTrend and direction2[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
            else if !Strategy_HoldTrend and direction2[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0 else direction2[1];
def direction_Equals_zero = direction == 0;
###################################
#Trend Confirmation Calculator
###################################
def Confirmation_Factor = 7;
def Agreement_LevelOB = 12;
def Agreement_LevelOS = 2;
def factorK = 2.0;
def lengthK = 20;
def shift = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK);
def averageK = MovingAverage(averageType, price, lengthK);
def AvgK = averageK[-displace];
def Upper_BandK = averageK[-displace] + shift[-displace];
def Lower_BandK = averageK[-displace] - shift[-displace];
def conditionK1UP = price >= Upper_BandK;
def conditionK2UP = (Upper_BandK[1] < Upper_BandK) and (Lower_BandK[1] < Lower_BandK);
def conditionK3DN = (Upper_BandK[1] > Upper_BandK) and (Lower_BandK[1] > Lower_BandK);
def conditionK4DN = price < Lower_BandK;
#######################################################
## 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 = Consensus_Level >= Consensus_UP;
def DOWN = Consensus_Level < Consensus_DOWN;
def priceColor = if UP then 1
                 else if DOWN then -1
                 else priceColor[1];
def Consensus_Level_OB = 14;
def Consensus_Level_OS = -12;
#Super_OB/OS Signal
def OB_Level = conditionOB1_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;
input Super_OB = 4;
input Super_OS = -4;
def DOWN_OB = (Agreement_Level > Agreement_LevelOB) and (Consensus_Line > Super_OB) and (Consensus_Level > Consensus_Level_OB);
def UP_OS = (Agreement_Level < Agreement_LevelOS) and (Consensus_Line < Super_OS) and (Consensus_Level < Consensus_Level_OS);
def OS_Buy = UP_OS;
def OB_Sell = DOWN_OB;
def neutral = Consensus_Line < Super_OB and Consensus_Line > Super_OS;

def YHOB = if coloredCandlesOn and ((price1 > Upper_BandS) and (condition_BandRevDn)) then high else Double.NaN;
def YHOS = if coloredCandlesOn and ((price1 < Lower_BandS) and (condition_BandRevUp)) then high else Double.NaN;
def YLOB = if coloredCandlesOn and ((price1 > Upper_BandS) and (condition_BandRevDn)) then low else Double.NaN;
def YLOS = if coloredCandlesOn and ((price1 < Lower_BandS) and (condition_BandRevUp)) then low else Double.NaN;
#extend midline of yellow candle
plot YCOB = if !IsNaN(YHOB) then hl2 else Double.NaN;
YCOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOB.SetDefaultColor(Color.GREEN);
def YHextOB = if IsNaN(YCOB) then YHextOB[1] else YCOB;
plot YHextlineOB = YHextOB;
YHextlineOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOB.SetDefaultColor(Color.ORANGE);
YHextlineOB.SetLineWeight(2);
plot YCOS = if !IsNaN(YHOS) then hl2 else Double.NaN;
YCOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOS.SetDefaultColor(Color.GREEN);
def YHextOS = if IsNaN(YCOS) then YHextOS[1] else YCOS;
plot YHextlineOS = YHextOS;
YHextlineOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOS.SetDefaultColor(Color.LIGHT_GREEN);
YHextlineOS.SetLineWeight(2);
def YC = coloredCandlesOn and priceColor == 1 and price1 > Upper_BandS and condition_BandRevDn;
def HH = Highest(high[1], BarsUsedForRange);
def LL = Lowest(low[1], BarsUsedForRange);
def maxH = Highest(HH, BarsRequiredToRemainInRange);
def maxL = Lowest(LL, BarsRequiredToRemainInRange);
def HHn = if maxH == maxH[1] or maxL == maxL then maxH else HHn[1];
def LLn = if maxH == maxH[1] or maxL == maxL then maxL else LLn[1];
def Bh = if high <= HHn and HHn == HHn[1] then HHn else Double.NaN;
def Bl = if low >= LLn and LLn == LLn[1] then LLn else Double.NaN;
def CountH = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountH[1] + 1;
def CountL = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountL[1] + 1;
def ExpH = if BarNumber() == 1 then Double.NaN else
           if CountH[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then HHn[-BarsRequiredToRemainInRange] else
           if high <= ExpH[1] then ExpH[1] else Double.NaN;
def ExpL = if BarNumber() == 1 then Double.NaN else
           if CountL[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then LLn[-BarsRequiredToRemainInRange] else
           if low >= ExpL[1] then ExpL[1] else Double.NaN;
def BoxHigh = if ((DOWN_OB) or (Upper_BandS crosses above Upper_BandK2) or (condition_BandRevDn) and (high > high[1]) and ((price > Upper_BandK2) or (price > Upper_BandS))) then Highest(ExpH) else Double.NaN;
def BoxLow = if (DOWN_OB) or ((Upper_BandS crosses above Upper_BandK2)) then Lowest(low) else Double.NaN;
def BoxHigh2 = if ((UP_OS) or ((Lower_BandS crosses below Lower_BandK2))) then Highest(ExpH) else Double.NaN;
def BH2 = if !IsNaN(BoxHigh2) then high else Double.NaN;
def BH2ext = if IsNaN(BH2) then BH2ext[1] else BH2;
def BH2extline = BH2ext;
def H_BH2extline2 = Lowest(BH2extline, 1);
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;
## HORIZONTAL RED AND GREEN ZONE LINES
def BL1extline2 = BL1ext;
def BL2 = if !IsNaN(BoxLow2) then low else Double.NaN;
def BL2ext = if IsNaN(BL2) then BL2ext[1] else BL2;
def BL2extline2 = BL2ext;
def KeylevelOB = if ((BH1ext >= YHextlineOB) and (BL1ext <= YHextlineOB))then 1 else 0;
def KeylevelOS = if ((BH2ext >= YHextlineOS) and (BL2ext <= YHextlineOS))then 1 else 0;
## RED AND GREEN ZONE WHEN STEPPING DOWN
plot H_BH2extline = Lowest(BH2extline, 1);
H_BH2extline.SetDefaultColor(Color.dark_GREEN);
plot BL1extline = BL1ext;
BL1extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL1extline.SetDefaultColor(Color.dark_RED);
BL1extline.SetLineWeight(1);
plot BL2extline = BL2ext;
BL2extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL2extline.SetDefaultColor(Color.dark_GREEN);
BL2extline.SetLineWeight(1);
plot H_BH1extline = Highest(BH1extline, 1);
H_BH1extline.SetDefaultColor(Color.dark_RED);
plot L_BL1extline = Highest(BL1extline, 1);
L_BL1extline.SetDefaultColor(Color.dark_RED);
plot L_BL2extline = Lowest(BL2extline, 1);
L_BL2extline.SetDefaultColor(Color.dark_GREEN);
############################################################
AddCloud(if !HideCloud then BH1extline else Double.NaN, BL1extline, Color.DARK_RED, Color.GRAY);
AddCloud(if !HideCloud then BH2extline else Double.NaN, BL2extline, Color.DARK_GREEN, Color.GRAY);
############################################################
##C3_MF_Line_v2 Created by Christopher84 03/06/2022   
############################################################
script WMA_Smooth {
    input price_WMA = hl2;
    plot smooth = (4 * price_WMA
+ 3 * price_WMA[1]
+ 2 * price_WMA[2]
+ price_WMA[3]) / 10;
}
script Phase_Accumulation {
# This is Ehler's Phase Accumulation code. It has a full cycle delay.
# However, it computes the correction factor to a very high degree.
    input price_WMA = hl2;
    rec Smooth;
    rec Detrender;
    rec Period;
    rec Q1;
    rec I1;
    rec I1p;
    rec Q1p;
    rec Phase1;
    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase1;
    rec InstPeriod1;
    rec InstPeriod;
    def CorrectionFactor;

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

# Smooth and detrend my smoothed signal:

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

# Compute Quadrature and Phase of Detrended signal:

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

# Smooth out Quadrature and Phase:

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

# Determine Phase

        if I1 != 0
        then {

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

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

# Convert phase to degrees

        Phase = Phase1 * 180 / Double.Pi;

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

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

# Limit our delta phases between 7 and 60

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

# Determine Instantaneous period:

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

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

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

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


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

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

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

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

    rec SmoothPeriod;
    rec vmama;
    rec vfama;

    def CorrectionFactor = Phase_Accumulation(price_WMA).CorrectionFactor;

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

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

# Smooth and detrend my smoothed signal:

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

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

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

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

# This is the complex conjugate

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

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

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

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

# Compute the phase

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

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

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

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

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

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

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

    plot MAMA = vmama;
    plot FAMA = vfama;
}
def price2 = hl2;
def FastLimit = 0.5;
def SlowLimit = 0.05;
def MAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).MAMA;
def FAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).FAMA;
def Crossing = Crosses((MAMA < FAMA), yes);
def Crossing1 = Crosses((MAMA > FAMA), yes);
def C3_Line_1 = if ((priceColor == 1) and (price1 > Upper_BandS) and (condition_BandRevDn)) then 1 else 0;
def C3_Line_2 = if ((priceColor == -1) and (price1 < Lower_BandS) and (condition_BandRevUp)) then 1 else 0;
def C3_Green =  ((priceColor == 1));
def C3_red =  ((priceColor == 1));
AddLabel(yes, Concat("MAMA", Concat("",
if MAMA > FAMA then "" else "")),
if MAMA > FAMA then Color.LIGHT_GREEN else Color.red);
def MF_UP = FAMA < MAMA;
def MF_DN = FAMA > MAMA;
def Cond12_MF_UP = MF_DN[1] and !MF_DN;
def Cond12_MF_DN = MF_UP[1] and !MF_UP;
def priceColor10_MF = if MF_UP then 1
                 else if MF_DN then -1
                 else priceColor10_MF[1];
###################################
##Consensus Level & Squeeze Label
###################################
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);
###################################
#SPARK#
###################################
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 UpCalc = (priceColor == 1) + (priceColor == 1) + (priceColor8 == 1) + (priceColor10_MF == 1);
def StrongUpCalc = (priceColor == 1) + (priceColor == 1)  + (priceColor10_MF == 1);
def CandleColor = if (priceColor == 1) and (priceColor12 == 1) and (Spark >= 2) then 1 else 
                 if (priceColor == -1) and (Spark < 1) then -1 else 0;
def 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 timeframe = if agperiod1 <= aggregationperiod.DAY then aggregationperiod.DAY else agperiod1;
def Vol = volume(period = timeframe);
def at_High = high(period = timeframe);
def at_Open = open(period = timeframe);
def at_Close = close(period = timeframe);
def at_Low = low(period = timeframe);
def 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 buying = V*(C-L2)/(H2-L2);
def selling = V*(H2-C)/(H2-L2);
def SellVolPercent = Round((Selling / V) * 100, 0);
def buyVolPercent = Round((Buying / V) * 100, 0);
def SellVol = selling;
def TV =  volume;
def BuyVol = buying;
def percentdiff = (SellVolPercent - buyVolPercent);
def percentdiffAbs = absValue(percentdiff);
def cond14_horsebull = (buying > selling) and (percentdiffabs >= ControlPercent);
def cond14_horsebear = (selling > buying) and (percentdiffabs >= ControlPercent);        
def avg1 = ExpAverage(close(period = agperiod1), length8);
def height = avg1 - avg1[length8];
def UP1 = avg1[1] < avg1;
def DOWN1 = avg1[1] > avg1;
def avg2 = ExpAverage(close(period = agperiod1), length8);
#Label color                                                      
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;
###################################################################
def priceColor1 = if ((avg1[1]<avg1) and (avg2[1]<avg2)) then 1 else if((avg1[1]>avg1) and (avg2[1]>avg2)) then -1 else priceColor[1];
def keyobpaint = (hl2 < BH1ext) and (hl2 > BL1ext);
def keyospaint = (hl2 < BH2ext) and (hl2 > BL2ext);
def Alert4_UP_Condition = Use_Alert4_UP_C and alert4 within 3 bars;
def Alert4_DN_Condition = Use_Alert4_DN_C and alert4 within 3 bars;;
def signal_UP_Condition = Use_signal_UP_C and  (direction == 1 and direction[1] < 1) within 3 bars;;
def signal_DN_Condition = Use_signal_DN_C and (direction == -1 and direction[1] > -1) within 3 bars;;
def signal_2_UP_Condition = Use_signal_2_UP_C and (direction2 == 1 and direction2[1] < 1) within 3 bars;;
def signal_2_DN_Condition = Use_signal_2_DN_C and (direction2 == -1 and direction2[1] > -1) within 3 bars;;
def Spark_UP_Condition = Use_Spark_UP_C and (SparkUP1) within 3 bars;;
def Spark_DN_Condition = Use_Spark_DN_C and (SparkDN1) within 3 bars;;
def Spark_UP2_Condition = Use_Spark_UP2_C and (SparkUP1) and hide_SparkUP within 3 bars;;
def Spark_DN2_Condition = Use_Spark_DN2_C and (SparkDN1) and hide_SparkDN within 3 bars;; 
def TS_UP_Condition = Use_TS_UP_C and upsignal within 3 bars;
def TS_DN_Condition = Use_TS_DN_C and downsignal within 3 bars;;
def TripleExhaustion_UP_Condition = Use_TripleEx_UP_C and RegularBuy or Extremebuy within 3 bars;;
def TripleExhaustion_DN_Condition = Use_TripleEx_DN_C and RegularSell or ExtremeSell within 3 bars;;
def Key_OS_Condition = KeylevelOS and keyospaint;
def Key_OB_Condition = KeylevelOB and keyobpaint;
###################################
##
###################################
###################################
## Candle Color
###################################
AssignPriceColor(if Strategy_ColoredCandlesOn then
     if ALERT4 THEN COLOR.green
else if Color_3x and buyerRegular then Color.green
else if Color_3xt and buyerExtreme then Color.green 
else if Color_3x and buyerRegular[1] then Color.red
else if Color_3xt and buyerExtreme[1] then Color.red 
else if direction == 1 then Color.light_green
else if Color_3x and sellerRegular then Color.dark_red
else if Color_3xt and sellerExtreme then Color.Dark_red
else if Color_3x and sellerRegular[1] then Color.green
else if Color_3xt and sellerExtreme[1] then Color.green
else if direction == -1 then color.red
else if direction == 0 then Color.gray
else Color.GRAY 
else Color.CURRENT);
####################################################################################################
## Conditions 
####################################################################################################
def CloudConditionGreen = EMADaboveZero +
            keyobpaint +
            topBandStepUp_EMAD +
            toppushline +
            BottomBandStepup_EMAD +
            cond14_horsebull +
            bullphase +
            crossesUpline_EMAD +
            MF_UP;
###################################
## 
###################################
def CloudConditionRed = EMADbelowZero +
            keyospaint +
            topBandStepDown_EMAD +
            bottompushline +
            BottomBandStepdown_EMAD +
            cond14_horsebear +
            bearphase +
            crossesDownline_EMAD +
            MF_DN;
###################################
## 
###################################
def ALLup = Alert4_UP_Condition +
            signal_UP_Condition +
            signal_2_UP_Condition +
            Spark_UP_Condition +
            Spark_UP2_Condition +
#            cond6_UP_Triple_Exh +
            TripleExhaustion_UP_Condition +
#            cond7_UP_Buystrong +
#            cond8_UP_pricestrong +
#            cond9_UP_bullphase +
#            cond10_UP_accphase +
#            cond11_UP_recphase +
#            Cond12_MF_UP +
            cond13_TS_Buy +
#            cond1_UP_AK + 
#            cond2_UP_ZSCORE + 
#            cond3_UP_Ehlers + 
#            cond4_UP_AM +
#            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 +
#            conditionOS1_RSI + 
#            conditionOS2_MFI + 
#            conditionOS3_Forcast + 
#            conditionOS4_Forcast + 
#            conditionOS5_PFE + 
#            conditionOS6_BB + 
#            conditionOS7_PO +
#            topBandStepUp_EMAD +
#            toppushline +
#            BottomBandStepup_EMAD +
#            crossesUpline_EMAD +
            cond14_horsebull +
            Key_OS_Condition;
###################################
## 
###################################
def ALLdown = Alert4_DN_Condition +
              signal_DN_Condition +
              signal_2_DN_Condition +
              Spark_DN_Condition +
              Spark_DN2_Condition +
#              cond6_DN_Triple_Exh +
              TripleExhaustion_DN_Condition +
#              cond7_DN_sellstrong +
#              cond8_DN_priceweak +
#              cond9_DN_bearphase +
#              cond10_DN_distphase +
#              Cond12_MF_DN +
              cond13_TS_Sell +
#              cond1_DN_AK + 
#              cond2_DN_ZSCORE + 
#              cond3_DN_Ehlers + 
#              cond4_DN_AM +
#              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 +
#              conditionOB1_RSI + 
#              conditionOB2_MFI + 
#              conditionOB3_Forcast + 
#              conditionOB4_Forcast + 
#              conditionOB5_PFE + 
#              conditionOB6_BB + 
#              conditionOB7_PO +
#C             topBandStepDown_EMAD +
#              bottompushline +
#              BottomBandStepdown_EMAD +
#              crossesDownline_EMAD +
              cond14_horsebear +
              Key_OB_Condition;
###################################
## 
###################################
plot Ehlers_1 = Ehlers3;
Ehlers_1.SetStyle(Curve.SHORT_DASH);
Ehlers_1.SetLineWeight(1);
Ehlers_1.AssignValueColor(if CloudConditionred == CloudConditionGreen then color.gray
                     else if CloudConditionGreen > Cloud_filter then color.green 
                     else if CloudConditionred > Cloud_filter then color.red
                     else color.gray);
###################################
##
###################################
plot Squeeze_Alert = sqzLevel;
Squeeze_Alert.SetPaintingStrategy(PaintingStrategy.POINTS);
Squeeze_Alert.SetLineWeight(3);
Squeeze_Alert.AssignValueColor(if(direction2 == 1) then color.yellow 
                          else if direction2 == -1 then color.yellow 
                          else if direction2 == 0 then color.white 
                          else color.yellow);
###################################
##
###################################
def UpArrow_A = if Use_Arrow_Inputs and Allup > Arrow_Up_filter then 1 else 0;
def UpArrow_Unfiltered = if use_EMAD_filter == no and UpArrow_A then 1 else 0;
def UpArrow_Filtered = if use_EMAD_filter == yes and EMADaboveZero and UpArrow_A then 1 else 0;
def UpArrow_A_Bn = if UpArrow_A[1] then bn else UpArrow_A_Bn[1];
def DownArrow_A = if Use_Arrow_Inputs and Alldown > Arrow_Down_filter then 1 else 0;
def DownArrow_Unfiltered = if use_EMAD_filter == no and DownArrow_A then 1 else 0;
def DownArrow_Filtered = if use_EMAD_filter == yes and EMADbelowZero and DownArrow_A then 1 else 0;
def DownArrow_A_Bn = if DownArrow_A[1] then bn else DownArrow_A_Bn[1];
def Last_Arrow_Up = if UpArrow_A_Bn > DownArrow_A_Bn then 1 else 0; 
def Last_Arrow_Down = if DownArrow_A_Bn > UpArrow_A_Bn then 1 else 0; 
def EMAD_Filter_Up = if use_EMAD_filter and EMADaboveZero then 1 else 0;
def EMAD_Filter_Down = if use_EMAD_filter and EMADbelowZero then 1 else 0;
###################################
##
###################################
plot UpArrow = if (UpArrow_Unfiltered or UpArrow_filtered) and !Last_Arrow_Up then low else double.nan;
UpArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
UpArrow.AssignValueColor(color.green);
UpArrow.SetLineWeight(1);
plot DownArrow = if (DownArrow_Unfiltered or DownArrow_filtered) and !Last_Arrow_Down then high else double.nan;
DownArrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_Down);
DownArrow.AssignValueColor(color.red);
DownArrow.SetLineWeight(1);
###################################
##Labels
###################################
def Buy = UP_OS;
def Sell = DOWN_OB;
def conditionLTB = (conditionK2UP and (Consensus_Level < 0));
def conditionLTS = (conditionK3DN and (Consensus_Level > 0));
def conditionBO = ((Upper_BandS[1] < Upper_BandS)) 
              and ((Lower_BandS[1] < Lower_BandS)) 
              and ((Upper_BandK[1] < Upper_BandK)) 
              and ((Lower_BandK[1] < Lower_BandK));
def conditionBD = ((Upper_BandS[1] > Upper_BandS)) 
              and ((Lower_BandS[1] > Lower_BandS)) 
              and ((Upper_BandK[1] > Upper_BandK)) 
              and ((Lower_BandK[1] > Lower_BandK));   
AddLabel(yes, if conditionLTB then "LOOK TO BUY" 
         else if conditionLTS then "LOOK TO SELL" 
         else if conditionK2UP then "TREND: BULL" 
         else if conditionK3DN then "TREND: BEAR" else "TREND: CONSOLIDATION", 
              if conditionLTB then Color.YELLOW
         else if conditionLTS then Color.YELLOW
         else if conditionK2UP then Color.LIGHT_GREEN 
         else if conditionK3DN then Color.RED else Color.GRAY);
AddLabel(yes, if conditionBD then "BREAKDOWN" 
         else if conditionBO then "BREAKOUT" else "NO BREAK", 
              if conditionBD then Color.RED 
         else if conditionBO then Color.GREEN else Color.GRAY);
AddLabel(showLabels, if (Spark == 3) then "SPARK: " + Round(Spark, 1) 
         else if (Spark == 0) then  "SPARK: " + Round(Spark, 1) else "SPARK: " + Round(Spark, 1), 
              if (Spark == 3) then Color.orange 
         else if (Spark == 2) then Color.light_GREEN 
         else if (Spark == 0) then Color.RED else Color.GRAY);
AddLabel(showlabels, if  Condition1UP==1 and Condition2UP == 1 and (Condition3UP == 1 or Condition4UP == 1) then "**CALLS ONLY!**" 
else if Condition1UP == 1 and Condition2UP == 1 then "VERY BULLISH"   
else if direction == 1 then "BULLISH"                
else if Condition1DN == 1 and Condition2DN == 1 and (Condition3DN == 1 or Condition4DN == 1) then "**PUTS ONLY!**" 
else if Condition1DN == 1 and Condition2DN == 1 then "VERY BEARISH" 
else if direction == -1 then "BEARISH"              
else if ((avg[1] > avg) and (avg > avg2) and (Buy_percent > 50)) then "BULLISH RETRACEMENT" 
else if ((avg[1] < avg) and (avg < avg2) and (Buy_percent < 50)) then "BEARISH RETRACEMENT" else "CHOP", 
     if Condition1UP == 1 and Condition2UP == 1 and (Condition3UP == 1 or Condition4UP == 1) then Color.cyan
else if Condition1DN == 1 and Condition2DN == 1 and (Condition3DN == 1 or Condition4DN == 1) then Color.Magenta
else if Condition1UP == 1 and Condition2UP == 1 then Color.light_GREEN 
else if direction == 1 then Color.light_green                          
else if Condition1DN == 1 and Condition2DN == 1 then Color.RED 
else if direction == -1 then Color.red           
else Color.orange);
AddLabel(yes, if MomentumUP then "Consensus Increasing = " + Round(Consensus_Level, 1) else if MomentumUP or MomentumDOWN and conditionOB_CL then "Consensus OVERBOUGHT = " + Round(Consensus_Level, 1) else if MomentumDOWN then  "Consensus Decreasing = " + Round(Consensus_Level, 1) else if MomentumUP or MomentumDOWN and conditionOS_CL then "Consensus OVERSOLD = " + Round(Consensus_Level, 1) else "Consensus = " + Round(Consensus_Level, 1), if conditionOB_CL then Color.light_green else if conditionOS_CL then Color.red else Color.GRAY);
AddLabel(squeeze_Alert, "SQUEEZE ALERT", if Squeeze_Alert then Color.YELLOW else Color.GRAY);
def ag = getaggregationPeriod();
def agcondition = if ag >= aggregationPeriod.DAY then 0 else 1;
AddVerticalLine(showverticallineday and agcondition and( GetDay() <> GetDay()[1]), "", Color.dark_gray, Curve.SHORT_DASH);
def Keylevel2OB = (round(absvalue(close - yhextlineOB),1));
def Keylevel2OS = (round(absvalue(close - yhextlineOS),1));
def lengthHLOSOB = 1000;
def HighestKeyOB = highest(yhextlineOB, LengthHLOSOB);
def LowestKeyOS = lowest(yhextlineOS, LengthHLOSOB);
def gethighestKeyOB = if KeylevelOB then HighestKeyOB else double.nan;
def getLowestKeyOS = if KeylevelOB then LowestKeyOS else double.nan;
def Keylevel2cond = if KeylevelOS and (Keylevel2OS < Keylevel2OB) and (Keylevel2OS < control) then 1 
else if KeylevelOB and (Keylevel2OB < Keylevel2OS) and (Keylevel2OB < control) then -1 else 0; 
AddLabel(KeylevelOS and keyospaint," Near Key Support Level: $" + round(yhextlineOS,0), color.light_green);
AddLabel(KeylevelOB and keyobpaint," Near Key Resistance Level: $" + round(yhextlineOB,0), color.orange);
AddLabel(show_TS_lastlabel, 
     if TS_Last == 1 then " TS Last Signal: BUY "  
else if TS_Last == 0 and ((alert4 or regularBuy or extremebuy) within 5 bars) then " TS Last Signal: SELL "  
else if TS_Last == 0 then " TS Last Signal: SELL "
else "",
     if TS_Last == 1 then color.light_gray
else if TS_Last == 0 and((alert4 or regularBuy or extremebuy) within 5 bars) then color.orange
else if TS_Last == 0 then color.light_gray
else color.white);
addlabel(yes, if use_EMAD_filter then " EMAD Filter: ON " else  if !use_EMAD_filter then " EMAD Filter: OFF " else "", if EMADaboveZero then color.green else if EMADbelowZero then color.red else color.gray);
####################################################################################################
## C3 EMA Cloud
####################################################################################################
AddCloud(if ShowEMAcloud and (AvgExp9 > AvgExp8) then AvgExp9 else Double.NaN, AvgExp8, Createcolor(0,0,0), Color.CURRENT);
AddCloud(if ShowEMAcloud and (AvgExp8 > AvgExp9) then AvgExp8 else Double.NaN, AvgExp9, Createcolor(0,60,0), Color.CURRENT);
###################################
## EMAD Condition Cloud
###################################
AddCloud(if Show_filter_Cloud and (CloudConditionGreen > Cloud_filter) then ehlers3 else Double.NaN, ehlers, color.green, color.dark_green);
AddCloud(if Show_filter_Cloud and (CloudConditionRed > Cloud_filter) then ehlers else Double.NaN, ehlers3, color.red, color.dark_red);
#####################################################################################################################################################################################
 
Last edited:
Hello... Have not changed much yet. Mainly cleaning up the code. Still need to create a version that uses specific signals during specific market conditions / phases but figured I would post the update. I did add some conditions to the arrow plots. There are a few more redundancies to be removed among other things but to whom it may concern:


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

input use_EMAD_filter = yes;
input Arrow_filter = 2; #hint number of conditions met must be greater than
input Show_filter_Cloud = no;
input Cloud_filter = 0; #hint number of conditions met must be greater than
input controlpercent = 50;
input show_TS_lastlabel = yes; #hint shows which TS_V9 signal is most recent
input show_filter_TS = yes;
input show_TS_V9_Lines = no; #Show horizontal long and short entry exit lines
input Use_Arrow_Inputs = yes;
input Use_Alert4_UP_C = yes;
input Use_Alert4_DN_C = yes;
input Use_signal_UP_C = yes; #hint Big4 signal up signal as part of "Allup" signal count
input Use_signal_DN_C = yes; #hint Big4 signal down as part of "Alldown" signal count
input Use_signal_2_UP_C = yes; #hint Big4 signal up signal as part of "Allup" signal count
input Use_signal_2_DN_C = yes; #hint Big4 signal down as part of "Alldown" signal count
input Use_Spark_UP_C = yes;
input Use_Spark_DN_C = yes;
input Use_Spark_DN2_C = yes;
input Use_Spark_UP2_C = no;
input Use_TS_UP_C = yes; #hint TS_V9 up signal as part of "Allup" signal count
input Use_TS_DN_C = yes; #hint TS_V9 down signal as part of "Alldown" signal count
input Use_TripleEx_UP_C = yes; #hint triple exhaustion
input Use_TripleEx_DN_C = yes; #hint triple exhaustion
input ShowEMAcloud = no; #hint default C3_Max cloud Average 8 and 9
input showall = no; #hint show all signals individually
input length_HV = 20; #Horserider Volume Average
input showLabels  = yes;  #hint C3_Max
input tradeDaytimeOnly = no; #hint tradeDaytimeOnly: (IntraDay Only) Only perform trades during hours stated
input OpenTime = 0930; #hint OpenTime: Opening time of market
input CloseTime = 1600; #hint CloseTime: Closing time of market
input VolumeTime = 1030; #hint OpenTime: Opening time of market
input Strategy_Confirmation_Factor = 4; #hint Big4
input TargetMultiple = 0.5; #hint TS_V9
input control = 13; #hint percent distance from current price to key level (0 is at level)
input showbubbles = no; #hint TS_V9
input type = { default SMP, EXP }; #hint TS_V9
input trailType = {default modified, unmodified}; #hint TS_V9
input averagetype = AverageType.SIMPLE;
input MACD_AverageType = {SMA, default EMA};
input DMI_averageType = AverageType.WILDERS;
input AvgType = AverageType.HULL;
input firstTrade = {default long, short}; #hint TS_V9
input ehlers_length = 13;

def hotpct = 150; #hint Horserider High Volume indication
def elhers3length = 9;
def Triple_Ex_Lookback = 15;
def Triple_Ex_Control = 2;
def lookbackcontrol = 1;
def lookbackcontrol2 = 1;
def arrowfilter = 12;
def keyleveltolerance = 1;
def showverticallineday = yes;
def show_ts_signals = no;
def length9 = 35;
def length8 = 10;
def length10 = 20;
def length_3x = 1000;
def LongTrades = yes; #hint LongTrades: perform long tradesvb  balanceOfMarketPower AbandonedBaby b           bbbbbbbbg
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
def ATRPeriod = 11;
def ATRFactor = 2.2;
def ATRPeriod2 = 5;
def ATRFactor2 = 1.5;
def AtrMult = 1.0;
def HideBoxLines = no;
def HideCloud = no;
def HideLabels = no;
def Strategy_FilterWithTMO = no;
def Strategy_FilterWithTMO_arrows = yes;
def Strategy_HoldTrend = no;
def Strategy_ColoredCandlesOn = yes;
def coloredCandlesOn = yes;
def ColorPrice = yes;
def color_blst = no;
def color_3x = yes;
def color_3xt = yes;
def color_OBOS = no;
def BarsUsedForRange = 2;
def BarsRequiredToRemainInRange = 2;
def trig = 20;# for Blast-off candle color
def HideTargets = no;
def HideBalance = no;
#USER INPUTS
## Upper and Lower EMAD Lines
def fastLength_EMAD = 10;
def slowLength_EMAD = 35;
def smoothLength_EMAD = 12;
def smoothLength2_EMAD = 14;
def priceType_EMAD = close;
def emadLineWeight_EMAD = 2;
def showEMACloud_EMAD = yes;
def showBubbles_EMAD = yes;
def averageType_EMAD = AverageType.WILDERS;
## Upper and Lower Band Lines
def bandLength_EMAD = 100;
def bandLength2_EMAD = 200;
#DEFINITIONS / CALCULATIONS
## UPPER EMAD LINE
def fastExpAvg_EMAD = ExpAverage(priceType_EMAD, fastLength_EMAD);
def slowExpAvg_EMAD = ExpAverage(priceType_EMAD, slowLength_EMAD);
def EMAD_EMAD = (priceType_EMAD - fastExpAvg_EMAD);
def EMAD2_EMAD = (priceType_EMAD - slowExpAvg_EMAD);
def EMADAvg_EMAD = (EMAD_EMAD + EMAD2_EMAD) / 2;
def upperEMADLine_EMAD = ExpAverage(EMADAvg_EMAD, smoothLength_EMAD);
## LOWER EMAD LINE
def emadOpen_EMAD = (upperEMADLine_EMAD + upperEMADLine_EMAD[1]) / 2;
def emadHigh_EMAD = Max(upperEMADLine_EMAD, upperEMADLine_EMAD[1]);
def emadLow_EMAD = Min(upperEMADLine_EMAD, upperEMADLine_EMAD[1]);
def emadClose_EMAD = upperEMADLine_EMAD;
def bottom_EMAD = Min(emadClose_EMAD[1], emadLow_EMAD);
def tr_EMAD = TrueRange(emadHigh_EMAD, emadClose_EMAD, emadLow_EMAD);
def ptr_EMAD = tr_EMAD / (bottom_EMAD + tr_EMAD / 2);
def APTR_EMAD = MovingAverage(averageType_EMAD, ptr_EMAD, smoothLength2_EMAD);
def upperBand_EMAD = emadClose_EMAD[1] + (APTR_EMAD * emadOpen_EMAD);
def lowerBand_EMAD = emadClose_EMAD[1] - (APTR_EMAD * emadOpen_EMAD);
def lowerEMADLine_EMAD = (upperBand_EMAD + lowerBand_EMAD) / 2;
## TOP AND BOTTOM BANDS
def zeroLineData_EMAD = if IsNaN(close) then Double.NaN else 0;
def EMADSUp_EMAD = upperEMADLine_EMAD > zeroLineData_EMAD;
def EMADSDown_EMAD = upperEMADLine_EMAD < zeroLineData_EMAD;
def EMADdown_EMAD = (lowerEMADLine_EMAD > upperEMADLine_EMAD);
def EMADup_EMAD = (upperEMADLine_EMAD >= lowerEMADLine_EMAD);
def topBand_EMAD = Highest(lowerEMADLine_EMAD, bandLength_EMAD);
def bottomBand_EMAD = Lowest(lowerEMADLine_EMAD, bandLength_EMAD);
## BAND DIRECTION (USED ONLY FOR COLORING - NOT USED FOR PLOTS)
def topBandStepDown_EMAD = if topBand_EMAD < topBand_EMAD[1] then 1 else 0;
def topBandStepUp_EMAD = if topBand_EMAD > topBand_EMAD[1] then 1 else 0;
def bottomBandStepDown_EMAD = if bottomBand_EMAD < bottomBand_EMAD[1] then 1 else 0;
def bottomBandStepUp_EMAD = if bottomBand_EMAD > bottomBand_EMAD[1] then 1 else 0;
def bothBandsDown_EMAD = bottomBandStepDown_EMAD and topBandStepDown_EMAD;
def bothBandsUp_EMAD = bottomBandStepUp_EMAD and topBandStepUp_EMAD;
def bullBias_EMAD = (bottomBand_EMAD > zeroLineData_EMAD);
def bearBias_EMAD = (topBand_EMAD < zeroLineData_EMAD);
## BUBBLE CALCULATIONS (USED ONLY FOR BUBBLES)
def midBand_EMAD = (upperBand_EMAD + lowerBand_EMAD) / 2;
def crossesUp_EMAD = if (midBand_EMAD[1] > upperEMADLine_EMAD[1]) and (midBand_EMAD < upperEMADLine_EMAD) then 1 else 0;
def crossesDown_EMAD = if (upperEMADLine_EMAD[1] > midBand_EMAD[1]) and (upperEMADLine_EMAD < midBand_EMAD) then 1 else 0;
def valueUp_EMAD = if crossesUp_EMAD then midBand_EMAD else 0;
def valueDown_EMAD = if crossesDown_EMAD then midBand_EMAD else 0;
def crossesUpline_EMAD = if (valueUp_EMAD - bottomBand_EMAD) == 0 then 1 else 0;
def crossesDownline_EMAD = if (valueDown_EMAD - topBand_EMAD) == 0 then 1 else 0;
def crossesUpline_filter_EMAD = if crossesUpline_EMAD and (crossesUpline_EMAD[1] or crossesUpline_EMAD[2] or crossesUpline_EMAD[3] or crossesUpline_EMAD[4]) then 0 else 1;
def crossesDownline_filter_EMAD = if crossesDownline_EMAD and (crossesDownline_EMAD[1] or crossesDownline_EMAD[2] or crossesDownline_EMAD[3] or crossesDownline_EMAD[4]) then 0 else 1;
#PLOTS
def zeroLine_EMAD = zeroLineData_EMAD;
def upperEMADLinePlot_EMAD = upperEMADLine_EMAD;
def lowerEMADLinePlot_EMAD = lowerEMADLine_EMAD;
def masterEMADLinePlot_EMAD = (upperEMADLinePlot_EMAD + lowerEMADLinePlot_EMAD) / 2;
def topBandPlot_EMAD = topBand_EMAD;
def bottomBandPlot_EMAD = bottomBand_EMAD;
def topunderzero = topBandPlot_EMAD < zeroLine_EMAD;
def bottomunderzero = bottomBandPlot_EMAD > zeroLine_EMAD;
def emaunderzero = upperEMADLinePlot_EMAD < zeroLine_EMAD;
def emaabovezero = upperEMADLinePlot_EMAD > zeroLine_EMAD;
def EMADaboveZero = emaabovezero or emaabovezero[1];
def EMADbelowZero = emaunderzero or emaunderzero[1];
def toppushline =  masterEMADLinePlot_EMAD >= topbandPlot_EMAD;
def bottompushline = masterEMADLinePlot_EMAD <= bottomBandPlot_EMAD;
#####################################################
#TS Strategy_V9 Created by Christopher84 08/10/2021
#####################################################
Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);
def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);
def state = {default init, long, short};
def trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;
    }
}
def price = close;
def TrailingStop = trail;
def LongEnter = (price crosses above TrailingStop);
def LongExit = (price crosses below TrailingStop);
def upsignal =  (price crosses above TrailingStop);
def downsignal = (price crosses below TrailingStop);
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 PLBuySignal3 = if  MarketOpen and (upsignal) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLSellSignal3 =  if MarketOpen and (downsignal) then 1 else 0; # insert condition to create short position in place of the 0>0
def PLBuyStop  = if !useStops then 0 else if  (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0<0
def PLSellStop = if !useStops then 0 else if (0 > 0) then 1 else 0  ; # insert condition to stop in place of the 0>0
def PLMktStop = if MarketOpen[-1] == 0 then 1 else 0; # If tradeDaytimeOnly is set, then stop at end of day
def PLBuySignal = if  MarketOpen and (upsignal) then 1 else 0 ; # insert condition to create long position in place of the 0>0
def PLSellSignal =  if MarketOpen and (downsignal) then 1 else 0; # insert condition to create short position in place 0>0
def CurrentPosition;  # holds whether flat = 0 long = 1 short = -1
if (BarNumber() == 1) or IsNaN(CurrentPosition[1]) {
    CurrentPosition = 0;
} else {
    if CurrentPosition[1] == 0 {            # FLAT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == 1 {      # LONG
        if (PLSellSignal and ShortTrades) {
            CurrentPosition = -1;
        } else if ((PLBuyStop and useStops) or PLMktStop or (PLSellSignal and ShortTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else if CurrentPosition[1] == -1 {     # SHORT
        if (PLBuySignal and LongTrades) {
            CurrentPosition = 1;
        } else if ((PLSellStop and useStops) or PLMktStop or (PLBuySignal and LongTrades == 0)) {
            CurrentPosition = 0;
        } else {
            CurrentPosition = CurrentPosition[1];
        }
    } else {
        CurrentPosition = CurrentPosition[1];
    }
}
def isLong  = if CurrentPosition == 1 then 1 else 0;
def isShort = if CurrentPosition == -1 then 1 else 0;
def isFlat  = if CurrentPosition == 0 then 1 else 0;
#Addorder(OrderType.BUY_AUTO, condition = LongEnter, price = open[-1], 1, tickcolor = GetColor(1), arrowcolor = Color.LIME);
#AddOrder(OrderType.SELL_AUTO, condition = LongExit, price = open[-1], 1, tickcolor = GetColor(2), arrowcolor = Color.LIME);
def BuySig = if (((isShort[1] and LongTrades) or (isFlat[1] and LongTrades)) and PLBuySignal) then 1 else 0;
def SellSig = if (((isLong[1] and ShortTrades) or (isFlat[1] and ShortTrades)) and PLSellSignal) then 1 else 0;
def bn = barnumber();
def TS_UP1bn = if upsignal[1] then BN else TS_UP1bn[1];
def TS_DN1bn = if downsignal[1] then BN else TS_DN1bn[1];
def cond13_TS_Buy = Buysig;
def cond13_TS_Sell = Sellsig;
def TS_Last = if TS_UP1bn > TS_DN1bn then 1 else 0;
###############################################
##OB_OS_Levels_v5 by Christopher84 12/10/2021
###############################################
#def TrailingStop = trail;
def H = Highest(TrailingStop, 12);
def L = Lowest(TrailingStop, 12);
def BulgeLengthPrice = 100;
def SqueezeLengthPrice = 100;
def BandwidthC3 = (H - L);
#def IntermResistance2 = Highest(BandwidthC3, BulgeLengthPrice);
def IntermSupport2 = Lowest(BandwidthC3, SqueezeLengthPrice);
def sqzTrigger = BandwidthC3 <= IntermSupport2;
def sqzLevel = if !sqzTrigger[1] and sqzTrigger then hl2
               else if !sqzTrigger then Double.NaN
               else sqzLevel[1];
###############################################
##Yellow Candle_height (OB_OS)
###############################################
def displace = 0;
def factorK2 = 3.25;
def lengthK2 = 20;
def price1 = open;
def trueRangeAverageType = AverageType.SIMPLE;
def ATR_length = 15;
def SMA_lengthS = 6;
def HiLo2 = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef2 = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef2 = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);
def loss2 = ATRFactor2 * MovingAverage(averageType, trueRange, ATRPeriod2);
def multiplier_factor = 1.25;
def valS = Average(price, SMA_lengthS);
def average_true_range = Average(TrueRange(high, close, low), length = ATR_length);
def Upper_BandS = valS[-displace] + multiplier_factor * average_true_range[-displace];
def Middle_BandS = valS[-displace];
def Lower_BandS = valS[-displace] - multiplier_factor * average_true_range[-displace];
def shiftK2 = factorK2 * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK2);
def averageK2 = MovingAverage(averageType, price, lengthK2);
def AvgK2 = averageK2[-displace];
def Upper_BandK2 = averageK2[-displace] + shiftK2[-displace];
def Lower_BandK2 = averageK2[-displace] - shiftK2[-displace];
def condition_BandRevDn = (Upper_BandS > Upper_BandK2);
def condition_BandRevUp = (Lower_BandS < Lower_BandK2);
def fastLength = 12;
def slowLength = 26;
def MACDLength = 9;
def fastEMA = ExpAverage(price, fastLength);
def slowEMA = ExpAverage(price, slowLength);
def Value;
def Avg;
switch (MACD_AverageType) {
case SMA:
    Value = Average(price, fastLength) - Average(price, slowLength);
    Avg = Average(Value, MACDLength);
case EMA:
    Value = fastEMA - slowEMA;
    Avg = ExpAverage(Value, MACDLength);
}
def Diff = Value - Avg;
def MACDLevel = 0.0;
def Level = MACDLevel;
def condition1_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;
########
#MFI
########
def MFI_Length = 14;
def MFIover_Sold = 20;
def MFIover_Bought = 80;
def movingAvgLength = 1;
def MoneyFlowIndex = Average(MoneyFlow(high, close, low, volume, MFI_Length), movingAvgLength);
def MFIOverBought = MFIover_Bought;
def MFIOverSold = MFIover_Sold;
def condition3_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 PercentB
###############################
def BBPB_length = 20;#Typically 20
def Num_Dev_Dn = -2.0;
def Num_Dev_up = 2.0;
def BBPB_OB = 100;
def BBPB_OS = 0;
def upperBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, averagetype).UpperBand;
def lowerBand = BollingerBands(price, displace, BBPB_length, Num_Dev_Dn, Num_Dev_up, averagetype).LowerBand;
def PercentB = (price - lowerBand) / (upperBand - lowerBand) * 100;
def HalfLine = 50;
def UnitLine = 100;
def condition11_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;
############
# Ehlers
############
def ehlers_price = (high + low) / 2;
def ehlers_coeff = ehlers_length * ehlers_price * ehlers_price - 2 * ehlers_price * Sum(ehlers_price, ehlers_length)[1] + Sum(ehlers_price * ehlers_price, ehlers_length)[1];
def Ehlers = Sum(ehlers_coeff * ehlers_price, ehlers_length) / Sum(ehlers_coeff, ehlers_length);
def Ehlers3 = average(Ehlers, elhers3length);
def cond3_UP_Ehlers = if close > Ehlers3 then 1 else 0;
def cond3_DN_Ehlers = if close <= Ehlers3 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;
################################
# --- TRIPLE EXHAUSTION ---
################################
def agperiod1 = GetAggregationPeriod();
def over_bought_3x = 80;
def over_sold_3x = 20;
def KPeriod_3x = 10;
def DPeriod_3x = 10;
def priceH1 = high(period = agperiod1);
def priceL1 = low(period = agperiod1);
def priceC1 = close(period = agperiod1);
def priceO1 = close(period = agperiod1);
def priceH_3x = high;
def priceL_3x = low;
def priceC_3x = close;  
def SlowK_3x = reference StochasticFull(over_bought_3x, over_sold_3x, KPeriod_3x, DPeriod_3x, priceH_3x, priceL_3x, priceC_3x, 3, averagetype).FullK;
def MACD_3x = reference MACD()."Value";
def priceMean_3x = Average(MACD_3x, length_3x);
def MACD_stdev_3x =  (MACD_3x - priceMean_3x) / StDev(MACD_3x, length_3x);
def dPlus_3x = reference DMI()."DI+";
def dMinus_3x = reference DMI()."DI-";
def sellerRegular = SlowK_3x < 20 and MACD_stdev_3x < -1 and dPlus_3x < 15;
def sellerExtreme = SlowK_3x < 20 and MACD_stdev_3x < -2 and dPlus_3x < 15;
def buyerRegular = SlowK_3x > 80 and MACD_stdev_3x > 1 and dMinus_3x < 15;
def buyerExtreme = SlowK_3x > 80 and MACD_stdev_3x > 2 and dMinus_3x < 15;
def ExtremeBuy = if sellerExtreme[1] and !sellerExtreme then 1 else 0;    
def ExtremeSell = if buyerExtreme[1] and !buyerExtreme then 1 else 0;    
def RegularSell = if buyerRegular[1] and !buyerRegular then 1 else 0;    
def RegularBuy= if sellerRegular[1] and !sellerRegular then 1 else 0;
def cond6_UP_Triple_Exh = if sellerRegular or sellerExtreme then 1 else 0;
def cond6_DN_Triple_Exh = if buyerRegular or buyerExtreme then -1 else 0;
###########################
# --- ALERT 4 --- #
###########################
def pd = 22;
def bbl = 20;
def lb = 50;
def ph = 0.85;
def pl = 1.01;
# Downtrend Criterias
def ltLB = 40;
def mtLB = 14;
def str = 3;
def AtrMult_Blst = 1.0;
def nATR_Blst = 4;
def AvgType_Blst = AverageType.HULL;
def ATR = MovingAverage(AvgType, TrueRange(high, close, low), nATR_Blst);
def UP_B = HL2 + (AtrMult * ATR);
def DN = HL2 + (-AtrMult * ATR);
def ST = if close < ST[1] then UP_B else DN;
def SuperTrend = ST;
def val1 = AbsValue(close - open);
def range = high - low;
def blastOffVal = (val1 / range) * 100;
def trigger = trig;
def alert1 = blastOffVal < trig;
def col = blastOffVal < trig;
def blast_candle = blastOffVal < trig;
# Downtrend Criterias
def wvf = ((highest(close, pd) - low) / (highest(close, pd))) * 100;
def sDev = lb * stdev(wvf, bbl);
def midLine1 = SimpleMovingAvg(wvf, bbl);
def lowerBand1 = midLine1 - sDev;
def upperBand1 = midLinE1 + sDev;
def rangeHigh = (highest(wvf, lb)) * ph;
#  Filtered Bar Criteria
def upRange = low > low[1] and close > high[1];
def upRange_Aggr = close > close[1] and close > open[1];
def filtered = ((wvf[1] >= upperBand1[1] or wvf[1] >= rangeHigh[1]) and (wvf<upperBand1 and wvf<rangeHigh));
def filtered_Aggr = (wvf[1] >= upperBand1[1] or wvf[1] >= rangeHigh[1]);
# Alerts Criteria 1
def alert4 = upRange_Aggr and close > close[str] and (close < close[ltLB] or close < close[mtLB]) and filtered_Aggr;
def lengthVolAvgPlot = 21;
def VolAvg = Average(volume, lengthVolAvgPlot);
def MA = if type == type.SMP then SimpleMovingAvg(volume, length_HV) else MovAvgExponential(volume, length_HV);
def HighV = if (100 * ((volume / ma) - 1) >= hotPct) then 1 else 0;
def VolAbvAverage = if volume >= VolAvg then 1 else 0;
def Cond_Alert4_UP = if Alert4 within 2 bars then 1 else 0;
#####################
# Market Phases
#####################
def O = open;
def H2 = high;
def C = close;
def L2 = low;
def V = volume;
def SV = V * (H - C) / (H - L);
def BV = V * (C - L) / (H - L);
def fastavg = 50;
def slowavg = 200;
def fastsma = Average( close, fastavg);
def slowsma = Average(close, slowavg);
def buystrong = if high > high[1] and low > low[1] and BV*1.05 > SV then 1 else 0;
def cond7_UP_Buystrong = if buystrong then 1 else 0;
def sellstrong = if high < high[1] and low < low[1] and SV*1.05 > BV then 1 else 0;
def cond7_DN_sellstrong = if sellstrong then -1 else 0;
def pricestrong = if high > high[1] and high [1] > high[2] and low > low[1] and low[1] > low[2] then 1 else 0;
def cond8_UP_pricestrong = if pricestrong then 1 else 0;
def priceweak = if high < high[1] and high[1] < high[2] and low < low[1] and low[1] < low[2] then 1 else 0;
def cond8_DN_priceweak = if priceweak then -1 else 0;
def bullphase = fastsma > slowsma && price > fastsma && price > slowsma;
def cond9_UP_bullphase = if bullphase then 1 else 0;
def bearphase = fastsma < slowsma && price < fastsma && price < slowsma;
def cond9_DN_bearphase = if bearphase then -1 else 0;
def accphase = fastsma < slowsma && price > fastsma && price > slowsma;
def cond10_UP_accphase = if accphase then 1 else 0;
def distphase = fastsma > slowsma && price < fastsma && price < slowsma;
def cond10_DN_distphase = if distphase then -1 else 0;
def recphase = fastsma < slowsma && price < slowsma && price > fastsma;
def cond11_UP_recphase = if recphase then 1 else 0;
def warnphase = fastsma > slowsma && price > slowsma && price < fastsma;
###################################
##Big4 Strategy
###################################
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 >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_UP_TMO) then 1
else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO or cond5_DN_TMO) then -1
    else if !Strategy_HoldTrend and direction[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
        else if !Strategy_HoldTrend and direction[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0
            else direction[1];
def direction2 = if cond_UP >= Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_UP_TMO) then 1
    else if cond_DN <= -Strategy_Confirmation_Factor and (!Strategy_FilterWithTMO_arrows or cond5_DN_TMO) then -1
        else if !Strategy_HoldTrend and direction2[1] == 1 and cond_UP < Strategy_Confirmation_Factor and cond_DN > -Strategy_Confirmation_Factor then 0
            else if !Strategy_HoldTrend and direction2[1] == -1 and cond_DN > -Strategy_Confirmation_Factor and cond_UP < Strategy_Confirmation_Factor then 0 else direction2[1];
def direction_Equals_zero = direction == 0;
###################################
#Trend Confirmation Calculator
###################################
def Confirmation_Factor = 7;
def Agreement_LevelOB = 12;
def Agreement_LevelOS = 2;
def factorK = 2.0;
def lengthK = 20;
def shift = factorK * MovingAverage(trueRangeAverageType, TrueRange(high, close, low), lengthK);
def averageK = MovingAverage(averageType, price, lengthK);
def AvgK = averageK[-displace];
def Upper_BandK = averageK[-displace] + shift[-displace];
def Lower_BandK = averageK[-displace] - shift[-displace];
def conditionK1UP = price >= Upper_BandK;
def conditionK2UP = (Upper_BandK[1] < Upper_BandK) and (Lower_BandK[1] < Lower_BandK);
def conditionK3DN = (Upper_BandK[1] > Upper_BandK) and (Lower_BandK[1] > Lower_BandK);
def conditionK4DN = price < Lower_BandK;
#######################################################
## 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 = Consensus_Level >= Consensus_UP;
def DOWN = Consensus_Level < Consensus_DOWN;
def priceColor = if UP then 1
                 else if DOWN then -1
                 else priceColor[1];
def Consensus_Level_OB = 14;
def Consensus_Level_OS = -12;
#Super_OB/OS Signal
def OB_Level = conditionOB1_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;
input Super_OB = 4;
input Super_OS = -4;
def DOWN_OB = (Agreement_Level > Agreement_LevelOB) and (Consensus_Line > Super_OB) and (Consensus_Level > Consensus_Level_OB);
def UP_OS = (Agreement_Level < Agreement_LevelOS) and (Consensus_Line < Super_OS) and (Consensus_Level < Consensus_Level_OS);
def OS_Buy = UP_OS;
def OB_Sell = DOWN_OB;
def neutral = Consensus_Line < Super_OB and Consensus_Line > Super_OS;

def YHOB = if coloredCandlesOn and ((price1 > Upper_BandS) and (condition_BandRevDn)) then high else Double.NaN;
def YHOS = if coloredCandlesOn and ((price1 < Lower_BandS) and (condition_BandRevUp)) then high else Double.NaN;
def YLOB = if coloredCandlesOn and ((price1 > Upper_BandS) and (condition_BandRevDn)) then low else Double.NaN;
def YLOS = if coloredCandlesOn and ((price1 < Lower_BandS) and (condition_BandRevUp)) then low else Double.NaN;
#extend midline of yellow candle
plot YCOB = if !IsNaN(YHOB) then hl2 else Double.NaN;
YCOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOB.SetDefaultColor(Color.GREEN);
def YHextOB = if IsNaN(YCOB) then YHextOB[1] else YCOB;
plot YHextlineOB = YHextOB;
YHextlineOB.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOB.SetDefaultColor(Color.ORANGE);
YHextlineOB.SetLineWeight(2);
plot YCOS = if !IsNaN(YHOS) then hl2 else Double.NaN;
YCOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YCOS.SetDefaultColor(Color.GREEN);
def YHextOS = if IsNaN(YCOS) then YHextOS[1] else YCOS;
plot YHextlineOS = YHextOS;
YHextlineOS.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
YHextlineOS.SetDefaultColor(Color.LIGHT_GREEN);
YHextlineOS.SetLineWeight(2);
def YC = coloredCandlesOn and priceColor == 1 and price1 > Upper_BandS and condition_BandRevDn;
def HH = Highest(high[1], BarsUsedForRange);
def LL = Lowest(low[1], BarsUsedForRange);
def maxH = Highest(HH, BarsRequiredToRemainInRange);
def maxL = Lowest(LL, BarsRequiredToRemainInRange);
def HHn = if maxH == maxH[1] or maxL == maxL then maxH else HHn[1];
def LLn = if maxH == maxH[1] or maxL == maxL then maxL else LLn[1];
def Bh = if high <= HHn and HHn == HHn[1] then HHn else Double.NaN;
def Bl = if low >= LLn and LLn == LLn[1] then LLn else Double.NaN;
def CountH = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountH[1] + 1;
def CountL = if IsNaN(Bh) or IsNaN(Bl) then 2 else CountL[1] + 1;
def ExpH = if BarNumber() == 1 then Double.NaN else
           if CountH[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then HHn[-BarsRequiredToRemainInRange] else
           if high <= ExpH[1] then ExpH[1] else Double.NaN;
def ExpL = if BarNumber() == 1 then Double.NaN else
           if CountL[-BarsRequiredToRemainInRange] >= BarsRequiredToRemainInRange then LLn[-BarsRequiredToRemainInRange] else
           if low >= ExpL[1] then ExpL[1] else Double.NaN;
def BoxHigh = if ((DOWN_OB) or (Upper_BandS crosses above Upper_BandK2) or (condition_BandRevDn) and (high > high[1]) and ((price > Upper_BandK2) or (price > Upper_BandS))) then Highest(ExpH) else Double.NaN;
def BoxLow = if (DOWN_OB) or ((Upper_BandS crosses above Upper_BandK2)) then Lowest(low) else Double.NaN;
def BoxHigh2 = if ((UP_OS) or ((Lower_BandS crosses below Lower_BandK2))) then Highest(ExpH) else Double.NaN;
def BH2 = if !IsNaN(BoxHigh2) then high else Double.NaN;
def BH2ext = if IsNaN(BH2) then BH2ext[1] else BH2;
def BH2extline = BH2ext;
def H_BH2extline2 = Lowest(BH2extline, 1);
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;
## HORIZONTAL RED AND GREEN ZONE LINES
def BL1extline2 = BL1ext;
def BL2 = if !IsNaN(BoxLow2) then low else Double.NaN;
def BL2ext = if IsNaN(BL2) then BL2ext[1] else BL2;
def BL2extline2 = BL2ext;
def KeylevelOB = if ((BH1ext >= YHextlineOB) and (BL1ext <= YHextlineOB))then 1 else 0;
def KeylevelOS = if ((BH2ext >= YHextlineOS) and (BL2ext <= YHextlineOS))then 1 else 0;
## RED AND GREEN ZONE WHEN STEPPING DOWN
plot H_BH2extline = Lowest(BH2extline, 1);
H_BH2extline.SetDefaultColor(Color.dark_GREEN);
plot BL1extline = BL1ext;
BL1extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL1extline.SetDefaultColor(Color.dark_RED);
BL1extline.SetLineWeight(1);
plot BL2extline = BL2ext;
BL2extline.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
BL2extline.SetDefaultColor(Color.dark_GREEN);
BL2extline.SetLineWeight(1);
plot H_BH1extline = Highest(BH1extline, 1);
H_BH1extline.SetDefaultColor(Color.dark_RED);
plot L_BL1extline = Highest(BL1extline, 1);
L_BL1extline.SetDefaultColor(Color.dark_RED);
plot L_BL2extline = Lowest(BL2extline, 1);
L_BL2extline.SetDefaultColor(Color.dark_GREEN);
############################################################
AddCloud(if !HideCloud then BH1extline else Double.NaN, BL1extline, Color.DARK_RED, Color.GRAY);
AddCloud(if !HideCloud then BH2extline else Double.NaN, BL2extline, Color.DARK_GREEN, Color.GRAY);
############################################################
##C3_MF_Line_v2 Created by Christopher84 03/06/2022
############################################################
script WMA_Smooth {
    input price_WMA = hl2;
    plot smooth = (4 * price_WMA
+ 3 * price_WMA[1]
+ 2 * price_WMA[2]
+ price_WMA[3]) / 10;
}
script Phase_Accumulation {
# This is Ehler's Phase Accumulation code. It has a full cycle delay.
# However, it computes the correction factor to a very high degree.
    input price_WMA = hl2;
    rec Smooth;
    rec Detrender;
    rec Period;
    rec Q1;
    rec I1;
    rec I1p;
    rec Q1p;
    rec Phase1;
    rec Phase;
    rec DeltaPhase;
    rec DeltaPhase1;
    rec InstPeriod1;
    rec InstPeriod;
    def CorrectionFactor;

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

# Smooth and detrend my smoothed signal:

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

# Compute Quadrature and Phase of Detrended signal:

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

# Smooth out Quadrature and Phase:

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

# Determine Phase

        if I1 != 0
        then {

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

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

# Convert phase to degrees

        Phase = Phase1 * 180 / Double.Pi;

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

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

# Limit our delta phases between 7 and 60

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

# Determine Instantaneous period:

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

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

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

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


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

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

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

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

    rec SmoothPeriod;
    rec vmama;
    rec vfama;

    def CorrectionFactor = Phase_Accumulation(price_WMA).CorrectionFactor;

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

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

# Smooth and detrend my smoothed signal:

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

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

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

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

# This is the complex conjugate

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

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

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

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

# Compute the phase

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

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

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

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

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

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

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

    plot MAMA = vmama;
    plot FAMA = vfama;
}
def price2 = hl2;
def FastLimit = 0.5;
def SlowLimit = 0.05;
def MAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).MAMA;
def FAMA = Ehler_MAMA(price2, FastLimit, SlowLimit).FAMA;
def Crossing = Crosses((MAMA < FAMA), yes);
def Crossing1 = Crosses((MAMA > FAMA), yes);
def C3_Line_1 = if ((priceColor == 1) and (price1 > Upper_BandS) and (condition_BandRevDn)) then 1 else 0;
def C3_Line_2 = if ((priceColor == -1) and (price1 < Lower_BandS) and (condition_BandRevUp)) then 1 else 0;
def C3_Green =  ((priceColor == 1));
def C3_red =  ((priceColor == 1));
AddLabel(yes, Concat("MAMA", Concat("",
if MAMA > FAMA then "" else "")),
if MAMA > FAMA then Color.LIGHT_GREEN else Color.red);
def MF_UP = FAMA < MAMA;
def MF_DN = FAMA > MAMA;
def Cond12_MF_UP = MF_DN[1] and !MF_DN;
def Cond12_MF_DN = MF_UP[1] and !MF_UP;
def priceColor10_MF = if MF_UP then 1
                 else if MF_DN then -1
                 else priceColor10_MF[1];
###################################
##Consensus Level & Squeeze Label
###################################
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);
###################################
#SPARK#
###################################
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 UpCalc = (priceColor == 1) + (priceColor == 1) + (priceColor8 == 1) + (priceColor10_MF == 1);
def StrongUpCalc = (priceColor == 1) + (priceColor == 1)  + (priceColor10_MF == 1);
def CandleColor = if (priceColor == 1) and (priceColor12 == 1) and (Spark >= 2) then 1 else
                 if (priceColor == -1) and (Spark < 1) then -1 else 0;
def 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 timeframe = if agperiod1 <= aggregationperiod.DAY then aggregationperiod.DAY else agperiod1;
def Vol = volume(period = timeframe);
def at_High = high(period = timeframe);
def at_Open = open(period = timeframe);
def at_Close = close(period = timeframe);
def at_Low = low(period = timeframe);
def 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 buying = V*(C-L2)/(H2-L2);
def selling = V*(H2-C)/(H2-L2);
def SellVolPercent = Round((Selling / V) * 100, 0);
def buyVolPercent = Round((Buying / V) * 100, 0);
def SellVol = selling;
def TV =  volume;
def BuyVol = buying;
def percentdiff = (SellVolPercent - buyVolPercent);
def percentdiffAbs = absValue(percentdiff);
def horsebull = (buying > selling) and (percentdiffabs >= ControlPercent);
def horsebear = (selling > buying) and (percentdiffabs >= ControlPercent);    
def avg1 = ExpAverage(close(period = agperiod1), length8);
def height = avg1 - avg1[length8];
def UP1 = avg1[1] < avg1;
def DOWN1 = avg1[1] > avg1;
def avg2 = ExpAverage(close(period = agperiod1), length8);
#Label color                                                  
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;
###################################################################
def priceColor1 = if ((avg1[1]<avg1) and (avg2[1]<avg2)) then 1 else if((avg1[1]>avg1) and (avg2[1]>avg2)) then -1 else priceColor[1];
def keyobpaint = (hl2 < BH1ext) and (hl2 > BL1ext);
def keyospaint = (hl2 < BH2ext) and (hl2 > BL2ext);
def Alert4_UP_Condition = Use_Alert4_UP_C and alert4;
def Alert4_DN_Condition = Use_Alert4_DN_C and alert4;
def signal_UP_Condition = Use_signal_UP_C and  (direction == 1 and direction[1] < 1);
def signal_DN_Condition = Use_signal_DN_C and (direction == -1 and direction[1] > -1);
def signal_2_UP_Condition = Use_signal_2_UP_C and (direction2 == 1 and direction2[1] < 1);
def signal_2_DN_Condition = Use_signal_2_DN_C and (direction2 == -1 and direction2[1] > -1);
def Spark_UP_Condition = Use_Spark_UP_C and (SparkUP1);
def Spark_DN_Condition = Use_Spark_DN_C and (SparkDN1);
def Spark_UP2_Condition = Use_Spark_UP2_C and (SparkUP1) and hide_SparkUP;
def Spark_DN2_Condition = Use_Spark_DN2_C and (SparkDN1) and hide_SparkDN;
def TS_UP_Condition = Use_TS_UP_C and upsignal;
def TS_DN_Condition = Use_TS_DN_C and downsignal;
def TripleExhaustion_UP_Condition = Use_TripleEx_UP_C and RegularBuy or Extremebuy;
def TripleExhaustion_DN_Condition = Use_TripleEx_DN_C and RegularSell or ExtremeSell;
###################################
##
###################################
###################################
## Candle Color
###################################
AssignPriceColor(if Strategy_ColoredCandlesOn then
     if ALERT4 THEN COLOR.green
else if Color_3x and buyerRegular then Color.green
else if Color_3xt and buyerExtreme then Color.green
else if Color_3x and buyerRegular[1] then Color.red
else if Color_3xt and buyerExtreme[1] then Color.red
else if direction == 1 then Color.light_green
else if Color_3x and sellerRegular then Color.dark_red
else if Color_3xt and sellerExtreme then Color.Dark_red
else if Color_3x and sellerRegular[1] then Color.green
else if Color_3xt and sellerExtreme[1] then Color.green
else if direction == -1 then color.red
else if direction == 0 then Color.gray
else Color.GRAY
else Color.CURRENT);
####################################################################################################
## Conditions
####################################################################################################
def CloudConditionGreen = EMADaboveZero +
            keyobpaint +
            topBandStepUp_EMAD +
            toppushline +
            BottomBandStepup_EMAD +
            horsebull +
            bullphase +
            crossesUpline_EMAD +
            MF_UP;
###################################
##
###################################
def CloudConditionRed = EMADbelowZero +
            keyospaint +
            topBandStepDown_EMAD +
            bottompushline +
            BottomBandStepdown_EMAD +
            horsebear +
            bearphase +
            crossesDownline_EMAD +
            MF_DN;
###################################
##
###################################
def ALLup = if use_EMAD_filter and EMADaboveZero then Alert4_UP_Condition +
            signal_UP_Condition +
            signal_2_UP_Condition +
            Spark_UP_Condition +
            Spark_UP2_Condition +
            cond6_UP_Triple_Exh +
            cond7_UP_Buystrong +
            cond8_UP_pricestrong +
            cond9_UP_bullphase +
            cond10_UP_accphase +
            cond11_UP_recphase +
            Cond12_MF_UP +
            cond13_TS_Buy +
            Key_OS_Condition
            else if use_EMAD_filter == no then  Alert4_UP_Condition +
            signal_UP_Condition +
            signal_2_UP_Condition +
            Spark_UP_Condition +
            Spark_UP2_Condition +
            cond6_UP_Triple_Exh +
            cond7_UP_Buystrong +
            cond8_UP_pricestrong +
            cond9_UP_bullphase +
            cond10_UP_accphase +
            cond11_UP_recphase +
            Cond12_MF_UP +
            cond13_TS_Buy +
            Key_OS_Condition
            else double.nan;
###################################
##
###################################
def ALLdown = if use_EMAD_filter and EMADbelowZero then Alert4_DN_Condition +
              signal_DN_Condition +
              signal_2_DN_Condition +
              Spark_DN_Condition +
              Spark_DN2_Condition +
              cond6_DN_Triple_Exh +
              cond7_DN_sellstrong +
              cond8_DN_priceweak +
              cond9_DN_bearphase +
              cond10_DN_distphase +
              cond11_UP_recphase +
              Cond12_MF_DN +
              cond13_TS_Sell +
              Key_OB_Condition
              else if use_EMAD_filter == no then  Alert4_DN_Condition +
              signal_DN_Condition +
              signal_2_DN_Condition +
              Spark_DN_Condition +
              Spark_DN2_Condition +
              cond6_DN_Triple_Exh +
              cond7_DN_sellstrong +
              cond8_DN_priceweak +
              cond9_DN_bearphase +
              cond10_DN_distphase +
              cond11_UP_recphase +
              Cond12_MF_DN +
              cond13_TS_Sell +
              Key_OB_Condition
              else double.nan;
###################################
##
###################################
plot Ehlers_1 = Ehlers3;
Ehlers_1.SetStyle(Curve.SHORT_DASH);
Ehlers_1.SetLineWeight(1);
Ehlers_1.AssignValueColor(if CloudConditionred == CloudConditionGreen then color.gray
                     else if CloudConditionGreen > Cloud_filter then color.green
                     else if CloudConditionred > Cloud_filter then color.red
                     else color.gray);
###################################
##
###################################
plot Squeeze_Alert = sqzLevel;
Squeeze_Alert.SetPaintingStrategy(PaintingStrategy.POINTS);
Squeeze_Alert.SetLineWeight(3);
Squeeze_Alert.AssignValueColor(if(direction2 == 1) then color.yellow
                          else if direction2 == -1 then color.yellow
                          else if direction2 == 0 then color.white
                          else color.yellow);
###################################
##
###################################
plot UpArrow_1 = if Use_Arrow_Inputs and Allup > Arrow_filter then low else double.nan;
UpArrow_1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
UpArrow_1.AssignValueColor(color.green);
UpArrow_1.SetLineWeight(1);
plot DownArrow_1 = if Use_Arrow_Inputs and Alldown > Arrow_filter then high else double.nan;
DownArrow_1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_Down);
DownArrow_1.AssignValueColor(color.red);
DownArrow_1.SetLineWeight(1);
###################################
##Labels
###################################
def Buy = UP_OS;
def Sell = DOWN_OB;
def conditionLTB = (conditionK2UP and (Consensus_Level < 0));
def conditionLTS = (conditionK3DN and (Consensus_Level > 0));
def conditionBO = ((Upper_BandS[1] < Upper_BandS))
              and ((Lower_BandS[1] < Lower_BandS))
              and ((Upper_BandK[1] < Upper_BandK))
              and ((Lower_BandK[1] < Lower_BandK));
def conditionBD = ((Upper_BandS[1] > Upper_BandS))
              and ((Lower_BandS[1] > Lower_BandS))
              and ((Upper_BandK[1] > Upper_BandK))
              and ((Lower_BandK[1] > Lower_BandK));
AddLabel(yes, if conditionLTB then "LOOK TO BUY"
         else if conditionLTS then "LOOK TO SELL"
         else if conditionK2UP then "TREND: BULL"
         else if conditionK3DN then "TREND: BEAR" else "TREND: CONSOLIDATION",
              if conditionLTB then Color.YELLOW
         else if conditionLTS then Color.YELLOW
         else if conditionK2UP then Color.LIGHT_GREEN
         else if conditionK3DN then Color.RED else Color.GRAY);
AddLabel(yes, if conditionBD then "BREAKDOWN"
         else if conditionBO then "BREAKOUT" else "NO BREAK",
              if conditionBD then Color.RED
         else if conditionBO then Color.GREEN else Color.GRAY);
AddLabel(showLabels, if (Spark == 3) then "SPARK: " + Round(Spark, 1)
         else if (Spark == 0) then  "SPARK: " + Round(Spark, 1) else "SPARK: " + Round(Spark, 1),
              if (Spark == 3) then Color.orange
         else if (Spark == 2) then Color.light_GREEN
         else if (Spark == 0) then Color.RED else Color.GRAY);
AddLabel(showlabels, if  Condition1UP==1 and Condition2UP == 1 and (Condition3UP == 1 or Condition4UP == 1) then "**CALLS ONLY!**"
else if Condition1UP == 1 and Condition2UP == 1 then "VERY BULLISH"
else if direction == 1 then "BULLISH"            
else if Condition1DN == 1 and Condition2DN == 1 and (Condition3DN == 1 or Condition4DN == 1) then "**PUTS ONLY!**"
else if Condition1DN == 1 and Condition2DN == 1 then "VERY BEARISH"
else if direction == -1 then "BEARISH"          
else if ((avg[1] > avg) and (avg > avg2) and (Buy_percent > 50)) then "BULLISH RETRACEMENT"
else if ((avg[1] < avg) and (avg < avg2) and (Buy_percent < 50)) then "BEARISH RETRACEMENT" else "CHOP",
     if Condition1UP == 1 and Condition2UP == 1 and (Condition3UP == 1 or Condition4UP == 1) then Color.cyan
else if Condition1DN == 1 and Condition2DN == 1 and (Condition3DN == 1 or Condition4DN == 1) then Color.Magenta
else if Condition1UP == 1 and Condition2UP == 1 then Color.light_GREEN
else if direction == 1 then Color.light_green                      
else if Condition1DN == 1 and Condition2DN == 1 then Color.RED
else if direction == -1 then Color.red        
else Color.orange);
AddLabel(yes, if MomentumUP then "Consensus Increasing = " + Round(Consensus_Level, 1) else if MomentumUP or MomentumDOWN and conditionOB_CL then "Consensus OVERBOUGHT = " + Round(Consensus_Level, 1) else if MomentumDOWN then  "Consensus Decreasing = " + Round(Consensus_Level, 1) else if MomentumUP or MomentumDOWN and conditionOS_CL then "Consensus OVERSOLD = " + Round(Consensus_Level, 1) else "Consensus = " + Round(Consensus_Level, 1), if conditionOB_CL then Color.light_green else if conditionOS_CL then Color.red else Color.GRAY);
AddLabel(squeeze_Alert, "SQUEEZE ALERT", if Squeeze_Alert then Color.YELLOW else Color.GRAY);
def ag = getaggregationPeriod();
def agcondition = if ag >= aggregationPeriod.DAY then 0 else 1;
AddVerticalLine(showverticallineday and agcondition and( GetDay() <> GetDay()[1]), "", Color.dark_gray, Curve.SHORT_DASH);
def Keylevel2OB = (round(absvalue(close - yhextlineOB),1));
def Keylevel2OS = (round(absvalue(close - yhextlineOS),1));
def lengthHLOSOB = 1000;
def HighestKeyOB = highest(yhextlineOB, LengthHLOSOB);
def LowestKeyOS = lowest(yhextlineOS, LengthHLOSOB);
def gethighestKeyOB = if KeylevelOB then HighestKeyOB else double.nan;
def getLowestKeyOS = if KeylevelOB then LowestKeyOS else double.nan;
def Keylevel2cond = if KeylevelOS and (Keylevel2OS < Keylevel2OB) and (Keylevel2OS < control) then 1
else if KeylevelOB and (Keylevel2OB < Keylevel2OS) and (Keylevel2OB < control) then -1 else 0;
AddLabel(KeylevelOS and keyospaint," Near Key Support Level: $" + round(yhextlineOS,0), color.light_green);
AddLabel(KeylevelOB and keyobpaint," Near Key Resistance Level: $" + round(yhextlineOB,0), color.orange);
AddLabel(show_TS_lastlabel,
     if TS_Last == 1 then " TS Last Signal: BUY "
else if TS_Last == 0 and ((alert4 or regularBuy or extremebuy) within 5 bars) then " TS Last Signal: SELL "
else if TS_Last == 0 then " TS Last Signal: SELL "
else "",
     if TS_Last == 1 then color.light_gray
else if TS_Last == 0 and((alert4 or regularBuy or extremebuy) within 5 bars) then color.orange
else if TS_Last == 0 then color.light_gray
else color.white);
#AddLabel(buystrong, "Buyer Vol Strong ", if buystrong then Color.GREEN else color.black);
#AddLabel(sellstrong, "Seller Vol Strong", if sellstrong then Color.MAGENTA else color.black);
#AddLabel(pricestrong, "Price Strong ", if pricestrong then Color.GREEN else color.black);
#AddLabel(priceweak, "Price Weak", if priceweak then Color.MAGENTA else color.black);
#AddLabel(bullphase, " Bull Phase" , if bullphase is true then Color.GREEN else Color.BLACk);
#AddLabel(accphase, " Accumation Phase ", if accphase is true then Color.lIGHT_GREEN else Color.BLACK);
#AddLabel(recphase, " Recovery Phase ", if recphase is true then Color.lIGHT_ORANGE else Color.BLACK);
#AddLabel(warnphase, " Warning Phase ", if warnphase is true then Color.orANGE else Color.BLACK);
#AddLabel(distphase, " Distribution Phase ", if distphase is true then Color.light_red else Color.BLACK);
#AddLabel(bearphase, " Bear Phase ", if bearphase is true then Color.red else Color.BLACK);
addlabel(yes, " Arrow Filter: " + Arrow_filter, color.white);
#addlabel(yes, " Cloud Filter: " + cloud_filter + " | " + "Up: " + cloudconditionGreen + " | " +  "Down: " + cloudconditionred, color.white);
addlabel(yes, if use_EMAD_filter then " EMAD Filter: ON " else  if !use_EMAD_filter then " EMAD Filter: OFF " else "", if EMADaboveZero then color.green else if EMADbelowZero then color.red else color.gray);
####################################################################################################
## C3 EMA Cloud
####################################################################################################
AddCloud(if ShowEMAcloud and (AvgExp9 > AvgExp8) then AvgExp9 else Double.NaN, AvgExp8, Createcolor(0,0,0), Color.CURRENT);
AddCloud(if ShowEMAcloud and (AvgExp8 > AvgExp9) then AvgExp8 else Double.NaN, AvgExp9, Createcolor(0,60,0), Color.CURRENT);
###################################
## EMAD Condition Cloud
###################################
AddCloud(if Show_filter_Cloud and (CloudConditionGreen > Cloud_filter) then ehlers3 else Double.NaN, ehlers, color.green, color.dark_green);
AddCloud(if Show_filter_Cloud and (CloudConditionRed > Cloud_filter) then ehlers else Double.NaN, ehlers3, color.red, color.dark_red);
#####################################################################################################################################################################################
@HODL-Lay-HE-hoo! Copied this as a study and get the following errors.
Expected double
No such variable: Key_OS_Condition at 1337:13
No such variable: Key_OS_Condition at 1351:13
No such variable: Key_OB_Condition at 1369:15
No such variable: Key_OB_Condition at 1383:15
No such variable: Key_OS_Condition at 1337:13
No such variable: Key_OS_Condition at 1351:13
No such variable: Key_OB_Condition at 1369:15
No such variable: Key_OB_Condition at 1383:15
 
Using this chart style https://tos.mx/wn3A43r but the one you are referring to is essentially the same but this one is more a work in progress and does not plot arrows the same as the link on page one.

Thanks! I notice you don't use the V4 version of EMAD with the labels? Furthermore, I notice the EMAD lower study in the style has white arrows. Do the white arrows correspond to the entry points of higher lows and lower highs?
 
Last edited:
Status
Not open for further replies.

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

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
215 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