Trend Master
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sadmansamee

//@version=5
// Created By Sadman Samee
//


indicator(title='Trend Master V1.3')


// Instructions:-
// Works on all TimeFrame but gives more accuracey 4H, 1D.
// Buy when green big dot appears at the bottom.
// Sell when red big dot appears at the bottom.
// Red/green dot at the top line appears when three trend meter is aligned and this is a good confirmation.
// Any red/green dot below horizontal bars are trend signal. Buy/Sell Signals from Trend Indicator like Chandelier Exit, WaveTrend, QQE, Parabolic SAR
// Big red/green got at the bottom appears whenever there's a good confirmation from trend meter and a buy/sell signal comes from  any trend signals.


// Alert:- 
// 01 Buy Signal = Strong Buy Signal
// 02 Sell Signal = Strong Sell Signal
// 03 Buy Signal = Strong Buy Signal
// 04 Sell Signal = Strong Sell Signal


// Thanks to https://www.tradingview.com/u/everget and https://www.tradingview.com/u/Lij_MC for their work. 
// and other authors 
// Trend Meter: https://www.tradingview.com/script/Ciurp4Qn-Trend-Meter/ 
// Alphatrend: https://www.tradingview.com/script/o50NYLAZ-AlphaTrend/
// Chandelier Exit: www.tradingview.com/script/AqXxNS7j-Chandelier-Exit/]Chandelier Exit[/url],
// WaveTrend
// QQE Signals: www.tradingview.com/script/7R6ZxyZu-QQE-signals/]QQE Signals[/url],
// Parabolic Sar: www.tradingview.com/script/MddD4giy-Parabolic-SAR/]Parabolic Sar[/url]
// Technical Ratings: https://www.tradingview.com/v/Jdw7wW2g/
// Donchian Trend Ribbon: https://www.tradingview.com/script/PxLqmP8o-Donchian-Trend-Ribbon/
// Neural Network: https://www.tradingview.com/v/HCfdtUut/



ShowTrendBar = true

var string TM = 'Trend Meters'

BuySellPolicy = input.string(title='Select Buy/Sell policy',group = 'Generel',defval='Slow Buy and Fast Sell(Bear/SideWays)', options=['Fast Buy and Fast Sell(Bull/Bear)', 'Fast Buy and Slow Sell(Bull)','Slow Buy and Fast Sell(Bear/SideWays)', 'Slow Buy and Slow Sell'])

BuyColor =  input.color(#1fb622, 'Positive Color', group = 'Generel')
SellColor =  input.color(color.red, 'Negative Color', group = 'Generel')
WeakColor =  input.color(color.yellow, 'Weak Color', group = 'Generel')
NeutralColor =  input.color(color.gray, 'Neutral Color', group = 'Generel')
DisabledColor =  input.color(#f0f0f0, 'Disabled Color', group = 'Generel')

MSBarCE = 'Trend Filter'  // input(title= "1 - Chandelier Exit",    defval = "Trend Filter",                             options = ["N/A", "Trend Filter", "Filter X", "Filter X + Trend Filter"])

MSBar1 = 'Trend Filter'  // input(title= "2 - Wave Trend Signals",    defval = "Trend Filter",                             options = ["N/A", "Trend Filter", "Filter X", "Filter X + Trend Filter"])


MSBar2 = 'Trend Filter'  // input(title= "2 - Wave Trend Signals",    defval = "Filter X",                                 options = ["N/A", "Trend Filter", "Filter X", "Filter X + Trend Filter"])

TrendBar1 = input.string(title='2 - Trend Meter 1', group = TM, defval='MACD Crossover - Fast - 8, 21, 5', options=['MACD Crossover - 12, 26, 9', 'MACD Crossover - Fast - 8, 21, 5', 'Mom Dad Cross (Top Dog Trading)', 'RSI Signal Line Cross - RSI 13, Sig 21', 'RSI 13: > or < 50', 'RSI 5: > or < 50', 'Trend Candles', 'N/A'])  // "MA Crossover", "DAD Direction (Top Dog Trading)",

TrendBar2 = input.string(title='3 - Trend Meter 2', group = TM,defval='RSI 13: > or < 50', options=['MACD Crossover - 12, 26, 9', 'MACD Crossover - Fast - 8, 21, 5', 'Mom Dad Cross (Top Dog Trading)', 'RSI Signal Line Cross - RSI 13, Sig 21', 'RSI 13: > or < 50', 'RSI 5: > or < 50', 'Trend Candles', 'N/A'])  // "MA Crossover", "DAD Direction (Top Dog Trading)",

TrendBar3 = input.string(title='4 - Trend Meter 3', group = TM,defval='RSI 5: > or < 50', options=['MACD Crossover - 12, 26, 9', 'MACD Crossover - Fast - 8, 21, 5', 'Mom Dad Cross (Top Dog Trading)', 'RSI Signal Line Cross - RSI 13, Sig 21', 'RSI 13: > or < 50', 'RSI 5: > or < 50', 'Trend Candles', 'N/A'])  // "MA Crossover", "DAD Direction (Top Dog Trading)",

TrendBar4 = input.string(title='5 - Trend Bar 1', group = TM,defval='MA Crossover', options=['MA Crossover', 'MA Direction - Fast MA - TB1', 'MA Direction - Slow MA - TB1', 'N/A'])  //  "MACD Crossover - 12, 26 9", "MACD Crossover - Fast - 8, 21, 5", "DAD Direction (Top Dog Trading)",

TrendBar5 = input.string(title='6 - Trend Bar 2', group = TM,defval='MA Crossover', options=['MA Crossover', 'MA Direction - Fast MA - TB2', 'MA Direction - Slow MA - TB2', 'N/A'])  //  "MACD Crossover - 12, 26 9", "MACD Crossover - Fast - 8, 21, 5", "DAD Direction (Top Dog Trading)",


////////////////Signals - Wave Trend/////////////////////////////////////////////////////////////////////////////////////////////////


// Wave Trend - RSI

RSIMC = ta.rsi(close, 14)

// Wave Trend

ap = hlc3  
n1 = 9  
n2 = 12  
esa = ta.ema(ap, n1)
de = ta.ema(math.abs(ap - esa), n1)
ci = (ap - esa) / (0.015 * de)
tci = ta.ema(ci, n2)
wt1 = tci
wt2 = ta.sma(wt1, 3)

// Wave Trend - Overbought & Oversold lines

obLevel2 = 60  
obLevel = 50  
osLevel = -50  
osLevel2 = -60  

// Wave Trend - Conditions

WTCross = ta.cross(wt1, wt2)
WTCrossUp = wt2 - wt1 <= 0
WTCrossDown = wt2 - wt1 >= 0
WTOverSold = wt2 <= osLevel2
WTOverBought = wt2 >= obLevel2



// MA Inputs

MA1_Type = input.string(title='Trend Bar 1 - Fast MA - Type', group = TM,defval='EMA', options=['EMA', 'SMA'])
MA1_Length = input.int(5, title='Trend Bar 1 - Fast MA - Length', group = TM,minval=1)

MA2_Type = input.string(title='Trend Bar 1 - Slow MA - Type', group = TM,defval='EMA', options=['EMA', 'SMA'])
MA2_Length = input.int(11, title='Trend Bar 1 - Slow MA - Length', minval=1)


MA3_Type = input.string(title='Trend Bar 2 - Fast MA - Type', group = TM,defval='EMA', options=['EMA', 'SMA'])
MA3_Length = input.int(13, title='Trend Bar 2 - Fast MA - Length', minval=1)

MA4_Type = input.string(title='Trend Bar 2 - Slow MA - Type', group = TM,defval='SMA', options=['EMA', 'SMA'])
MA4_Length = input.int(36, title='Trend Bar 2 - Slow MA - Length', minval=1)


// MA Calculations

MA1 = if MA1_Type == 'SMA'
    ta.sma(close, MA1_Length)
else
    ta.ema(close, MA1_Length)


MA2 = if MA2_Type == 'SMA'
    ta.sma(close, MA2_Length)
else
    ta.ema(close, MA2_Length)


MA3 = if MA3_Type == 'SMA'
    ta.sma(close, MA3_Length)
else
    ta.ema(close, MA3_Length)


MA4 = if MA4_Type == 'SMA'
    ta.sma(close, MA4_Length)
else
    ta.ema(close, MA4_Length)


// MA Crossover Condition

MACrossover1 = MA1 > MA2 ? 1 : 0

MACrossover2 = MA3 > MA4 ? 1 : 0

// MA Direction Condition

MA1Direction = MA1 > MA1[1] ? 1 : 0

MA2Direction = MA2 > MA2[1] ? 1 : 0

MA3Direction = MA3 > MA3[1] ? 1 : 0

MA4Direction = MA4 > MA4[1] ? 1 : 0

// MA Direction Change Condition

MA1PositiveDirectionChange = MA1Direction and not MA1Direction[1] ? 1 : 0

MA2PositiveDirectionChange = MA2Direction and not MA2Direction[1] ? 1 : 0

MA3PositiveDirectionChange = MA3Direction and not MA3Direction[1] ? 1 : 0

MA4PositiveDirectionChange = MA4Direction and not MA4Direction[1] ? 1 : 0


MA1NegativeDirectionChange = not MA1Direction and MA1Direction[1] ? 1 : 0

MA2NegativeDirectionChange = not MA2Direction and MA2Direction[1] ? 1 : 0

MA3NegativeDirectionChange = not MA3Direction and MA3Direction[1] ? 1 : 0

MA4NegativeDirectionChange = not MA4Direction and MA4Direction[1] ? 1 : 0


// MACD and MOM & DAD - Top Dog Trading

// Standard MACD Calculations

MACDfastMA = 12
MACDslowMA = 26
MACDsignalSmooth = 9


MACDLine = ta.ema(close, MACDfastMA) - ta.ema(close, MACDslowMA)

SignalLine = ta.ema(MACDLine, MACDsignalSmooth)

MACDHistogram = MACDLine - SignalLine


// MACD- Background Color Change Condition

MACDHistogramCross = MACDHistogram > 0 ? 1 : 0

MACDLineOverZero = MACDLine > 0 ? 1 : 0

MACDLineOverZeroandHistogramCross = MACDHistogramCross and MACDLineOverZero ? 1 : 0

MACDLineUnderZeroandHistogramCross = not MACDHistogramCross and not MACDLineOverZero ? 1 : 0


// Fast MACD Calculations

FastMACDfastMA = 8
FastMACDslowMA = 21
FastMACDsignalSmooth = 5


FastMACDLine = ta.ema(close, FastMACDfastMA) - ta.ema(close, FastMACDslowMA)

FastSignalLine = ta.ema(FastMACDLine, FastMACDsignalSmooth)

FastMACDHistogram = FastMACDLine - FastSignalLine

// Fast MACD- Background Color Change Condition

FastMACDHistogramCross = FastMACDHistogram > 0 ? 1 : 0

FastMACDLineOverZero = FastMACDLine > 0 ? 1 : 0

FastMACDLineOverZeroandHistogramCross = FastMACDHistogramCross and FastMACDLineOverZero ? 1 : 0

FastMACDLineUnderZeroandHistogramCross = not FastMACDHistogramCross and not FastMACDLineOverZero ? 1 : 0


// Top Dog Trading - Mom Dad Calculations

TopDog_Fast_MA = 5
TopDog_Slow_MA = 20
TopDog_Sig = 30


TopDogMom = ta.ema(close, TopDog_Fast_MA) - ta.ema(close, TopDog_Slow_MA)

TopDogDad = ta.ema(TopDogMom, TopDog_Sig)

// Top Dog Dad - Background Color Change Condition

TopDogDadDirection = TopDogDad > TopDogDad[1] ? 1 : 0

TopDogMomOverDad = TopDogMom > TopDogDad ? 1 : 0

TopDogMomOverZero = TopDogMom > 0 ? 1 : 0

TopDogDadDirectandMomOverZero = TopDogDadDirection and TopDogMomOverZero ? 1 : 0

TopDogDadDirectandMomUnderZero = not TopDogDadDirection and not TopDogMomOverZero ? 1 : 0



////// Trend Barmeter Calculations //////

// UCS_Trend / Trend Candles Trend Barmeter Calculations

//UCS_Trend by ucsgears copy Trend Candles
//Interpretation of TTM Trend bars. It is really close to the actual. 

haclose = ohlc4
haopen = 0.0
haopen := na(haopen[1]) ? (open + close) / 2 : (haopen[1] + haclose[1]) / 2

ccolor = haclose - haopen > 0 ? 1 : 0

inside6 = haopen <= math.max(haopen[6], haclose[6]) and haopen >= math.min(haopen[6], haclose[6]) and haclose <= math.max(haopen[6], haclose[6]) and haclose >= math.min(haopen[6], haclose[6]) ? 1 : 0

inside5 = haopen <= math.max(haopen[5], haclose[5]) and haopen >= math.min(haopen[5], haclose[5]) and haclose <= math.max(haopen[5], haclose[5]) and haclose >= math.min(haopen[5], haclose[5]) ? 1 : 0

inside4 = haopen <= math.max(haopen[4], haclose[4]) and haopen >= math.min(haopen[4], haclose[4]) and haclose <= math.max(haopen[4], haclose[4]) and haclose >= math.min(haopen[4], haclose[4]) ? 1 : 0

inside3 = haopen <= math.max(haopen[3], haclose[3]) and haopen >= math.min(haopen[3], haclose[3]) and haclose <= math.max(haopen[3], haclose[3]) and haclose >= math.min(haopen[3], haclose[3]) ? 1 : 0

inside2 = haopen <= math.max(haopen[2], haclose[2]) and haopen >= math.min(haopen[2], haclose[2]) and haclose <= math.max(haopen[2], haclose[2]) and haclose >= math.min(haopen[2], haclose[2]) ? 1 : 0

inside1 = haopen <= math.max(haopen[1], haclose[1]) and haopen >= math.min(haopen[1], haclose[1]) and haclose <= math.max(haopen[1], haclose[1]) and haclose >= math.min(haopen[1], haclose[1]) ? 1 : 0


colorvalue = inside6 ? ccolor[6] : inside5 ? ccolor[5] : inside4 ? ccolor[4] : inside3 ? ccolor[3] : inside2 ? ccolor[2] : inside1 ? ccolor[1] : ccolor

TrendBarTrend_Candle_Color = colorvalue ? BuyColor : SellColor

TrendBarTrend_Candle = colorvalue ? 1 : 0


// RSI 5 Trend Barmeter Calculations

RSI5 = ta.rsi(close, 5)

RSI5Above50 = RSI5 > 50 ? 1 : 0

RSI5Color = RSI5Above50 ? BuyColor : SellColor

TrendBarRSI5Color = RSI5Above50 ? BuyColor : SellColor


// RSI 5 Trend Barmeter Calculations

RSI13 = ta.rsi(close, 13)


// Linear Regression Calculation For RSI Signal Line

SignalLineLength1 = 21

x = bar_index
y = RSI13
x_ = ta.sma(x, SignalLineLength1)
y_ = ta.sma(y, SignalLineLength1)
mx = ta.stdev(x, SignalLineLength1)
my = ta.stdev(y, SignalLineLength1)
c = ta.correlation(x, y, SignalLineLength1)
slope = c * (my / mx)
inter = y_ - slope * x_
LinReg1 = x * slope + inter


RSISigDirection = LinReg1 > LinReg1[1] ? 1 : 0

RSISigCross = RSI13 > LinReg1 ? 1 : 0

RSI13Above50 = RSI13 > 50 ? 1 : 0


// Trend Barmeter Color Calculation

RSI13Color = RSI13Above50 ? BuyColor : SellColor

TrendBarRSI13Color = RSI13Above50 ? BuyColor : SellColor

TrendBarRSISigCrossColor = RSISigCross ? BuyColor : SellColor

TrendBarMACDColor = MACDHistogramCross ? BuyColor : SellColor

TrendBarFastMACDColor = FastMACDHistogramCross ? BuyColor : SellColor

TrendBarMACrossColor = MACrossover1 ? BuyColor : SellColor

TrendBarMomOverDadColor = TopDogMomOverDad ? BuyColor : SellColor

TrendBarDadDirectionColor = TopDogDadDirection ? BuyColor : SellColor


TrendBar1Result = TrendBar1 == 'MA Crossover' ? MACrossover1 : TrendBar1 == 'MACD Crossover - 12, 26, 9' ? MACDHistogramCross : TrendBar1 == 'MACD Crossover - Fast - 8, 21, 5' ? FastMACDHistogramCross : TrendBar1 == 'Mom Dad Cross (Top Dog Trading)' ? TopDogMomOverDad : TrendBar1 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar1 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? RSISigCross : TrendBar1 == 'RSI 5: > or < 50' ? RSI5Above50 : TrendBar1 == 'RSI 13: > or < 50' ? RSI13Above50 : TrendBar1 == 'Trend Candles' ? TrendBarTrend_Candle : na

TrendBar2Result = TrendBar2 == 'MA Crossover' ? MACrossover1 : TrendBar2 == 'MACD Crossover - 12, 26, 9' ? MACDHistogramCross : TrendBar2 == 'MACD Crossover - Fast - 8, 21, 5' ? FastMACDHistogramCross : TrendBar2 == 'Mom Dad Cross (Top Dog Trading)' ? TopDogMomOverDad : TrendBar2 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar2 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? RSISigCross : TrendBar2 == 'RSI 5: > or < 50' ? RSI5Above50 : TrendBar2 == 'RSI 13: > or < 50' ? RSI13Above50 : TrendBar2 == 'Trend Candles' ? TrendBarTrend_Candle : na

TrendBar3Result = TrendBar3 == 'MA Crossover' ? MACrossover1 : TrendBar3 == 'MACD Crossover - 12, 26, 9' ? MACDHistogramCross : TrendBar3 == 'MACD Crossover - Fast - 8, 21, 5' ? FastMACDHistogramCross : TrendBar3 == 'Mom Dad Cross (Top Dog Trading)' ? TopDogMomOverDad : TrendBar3 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar3 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? RSISigCross : TrendBar3 == 'RSI 5: > or < 50' ? RSI5Above50 : TrendBar3 == 'RSI 13: > or < 50' ? RSI13Above50 : TrendBar3 == 'Trend Candles' ? TrendBarTrend_Candle : na


TrendBars2Positive = TrendBar1Result and TrendBar2Result or TrendBar1Result and TrendBar3Result or TrendBar2Result and TrendBar3Result ? 1 : 0

TrendBars2Negative = not TrendBar1Result and not TrendBar2Result or not TrendBar1Result and not TrendBar3Result or not TrendBar2Result and not TrendBar3Result ? 1 : 0


TrendBars3Positive = TrendBar1Result and TrendBar2Result and TrendBar3Result ? 1 : 0

TrendBars3Negative = not TrendBar1Result and not TrendBar2Result and not TrendBar3Result ? 1 : 0


// Signal Filters

FilterXUp = FastMACDHistogramCross and ta.ema(close, 15) > ta.ema(close, 15)[1]

FilterXDown = not FastMACDHistogramCross and ta.ema(close, 15) < ta.ema(close, 15)[1]


TrendFilterPlus = ta.ema(close, 15) > ta.ema(close, 20) and ta.ema(close, 20) > ta.ema(close, 30) and ta.ema(close, 30) > ta.ema(close, 40) and ta.ema(close, 40) > ta.ema(close, 50) ? 1 : 0

TrendFilterMinus = ta.ema(close, 15) < ta.ema(close, 20) and ta.ema(close, 20) < ta.ema(close, 30) and ta.ema(close, 30) < ta.ema(close, 40) and ta.ema(close, 40) < ta.ema(close, 50) ? 1 : 0



///////////////////////////////////////////////////////////////////////////////////////////////////////////////

BackgroundColorChangePositive = TrendBars3Positive and not TrendBars3Positive[1]
BackgroundColorChangeNegative = TrendBars3Negative and not TrendBars3Negative[1]


// Trend Barmeter Color Assignments

TrendBar1Color = TrendBar1 == 'N/A' ? na : TrendBar1 == 'MACD Crossover - 12, 26, 9' ? TrendBarMACDColor : TrendBar1 == 'MACD Crossover - Fast - 8, 21, 5' ? TrendBarFastMACDColor : TrendBar1 == 'Mom Dad Cross (Top Dog Trading)' ? TrendBarMomOverDadColor : TrendBar1 == 'DAD Direction (Top Dog Trading)' ? TrendBarDadDirectionColor : TrendBar1 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? TrendBarRSISigCrossColor : TrendBar1 == 'RSI 5: > or < 50' ? TrendBarRSI5Color : TrendBar1 == 'RSI 13: > or < 50' ? TrendBarRSI13Color : TrendBar1 == 'Trend Candles' ? TrendBarTrend_Candle_Color : TrendBar1 == 'MA Crossover' ? TrendBarMACrossColor : na

TrendBar2Color = TrendBar2 == 'N/A' ? na : TrendBar2 == 'MACD Crossover - 12, 26, 9' ? TrendBarMACDColor : TrendBar2 == 'MACD Crossover - Fast - 8, 21, 5' ? TrendBarFastMACDColor : TrendBar2 == 'Mom Dad Cross (Top Dog Trading)' ? TrendBarMomOverDadColor : TrendBar2 == 'DAD Direction (Top Dog Trading)' ? TrendBarDadDirectionColor : TrendBar2 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? TrendBarRSISigCrossColor : TrendBar2 == 'RSI 5: > or < 50' ? TrendBarRSI5Color : TrendBar2 == 'RSI 13: > or < 50' ? TrendBarRSI13Color : TrendBar2 == 'Trend Candles' ? TrendBarTrend_Candle_Color : TrendBar2 == 'MA Crossover' ? TrendBarMACrossColor : na

TrendBar3Color = TrendBar3 == 'N/A' ? na : TrendBar3 == 'MACD Crossover - 12, 26, 9' ? TrendBarMACDColor : TrendBar3 == 'MACD Crossover - Fast - 8, 21, 5' ? TrendBarFastMACDColor : TrendBar3 == 'Mom Dad Cross (Top Dog Trading)' ? TrendBarMomOverDadColor : TrendBar3 == 'DAD Direction (Top Dog Trading)' ? TrendBarDadDirectionColor : TrendBar3 == 'RSI Signal Line Cross - RSI 13, Sig 21' ? TrendBarRSISigCrossColor : TrendBar3 == 'RSI 5: > or < 50' ? TrendBarRSI5Color : TrendBar3 == 'RSI 13: > or < 50' ? TrendBarRSI13Color : TrendBar3 == 'Trend Candles' ? TrendBarTrend_Candle_Color : TrendBar3 == 'MA Crossover' ? TrendBarMACrossColor : na


CrossoverType2 = TrendBar4 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar4 == 'MACD Crossover' ? MACDHistogramCross : TrendBar4 == 'MA Direction - Fast MA - TB1' ? MA1Direction : TrendBar4 == 'MA Direction - Slow MA - TB1' ? MA2Direction : MACrossover1

color_1 = color.new(BuyColor, 15)
color_2 = color.new(SellColor, 20)
TrendBar4Color1 = TrendBar4 == 'N/A' ? na : CrossoverType2 ? color_1 : color_2

CrossoverType3 = TrendBar5 == 'DAD Direction (Top Dog Trading)' ? TopDogDadDirection : TrendBar5 == 'MACD Crossover' ? MACDHistogramCross : TrendBar5 == 'MA Direction - Fast MA - TB2' ? MA3Direction : TrendBar5 == 'MA Direction - Slow MA - TB2' ? MA4Direction : MACrossover2

color_3 = color.new(BuyColor, 15)
color_4 = color.new(SellColor, 20)
TrendBar5Color1 = TrendBar5 == 'N/A' ? na : CrossoverType3 ? color_3 : color_4


alertcondition(BackgroundColorChangePositive, title='3 TMs Turn Green', message='All 3 Trend Meters Turn  Green - Trend Meter')
alertcondition(BackgroundColorChangeNegative, title='3 TMs Turn Red', message='All 3 Trend Meters Turn  Red - Trend Meter')
alertcondition(BackgroundColorChangePositive or BackgroundColorChangeNegative, title='3 TMs Change Color', message='All 3 Trend Meters Change Color - Trend Meter')


RapidColorChangePositive = TrendBars3Positive and (TrendBars3Negative[1] or TrendBars3Negative[2])
RapidColorChangeNegative = TrendBars3Negative and (TrendBars3Positive[1] or TrendBars3Positive[2])

alertcondition(RapidColorChangePositive, title='3 TMs Rapid Change Red to Green', message='3 Trend Meters Rapid Change Red to Green - Trend Meter')
alertcondition(RapidColorChangeNegative, title='3 TMs Rapid Change Green to Red', message='3 Trend Meters Rapid Change Green to Red - Trend Meter')
alertcondition(RapidColorChangePositive or RapidColorChangeNegative, title='3 TMs Rapid Color Change', message='3 Trend Meters Rapid Color Change - Trend Meter')


MaxValueMACrossUp = ta.crossover(ta.ema(close, 5), ta.ema(close, 11))
MaxValueMACrossDown = ta.crossunder(ta.ema(close, 5), ta.ema(close, 11))


TB1MACrossUp = ta.crossover(MA1, MA2)
TB1MACrossDown = ta.crossunder(MA1, MA2)


alertcondition(TB1MACrossUp, title='TB1 Fast MA X Above Slow MA', message='Trend Bar 1 - Fast MA X Above Slow MA - Trend Meter')
alertcondition(TB1MACrossDown, title='TB1 Fast MA X Below Slow MA', message='Trend Bar 1 - Fast MA X Below Slow MA - Trend Meter')
alertcondition(TB1MACrossUp or TB1MACrossDown, title='TB1 MAs X', message='Color Change - Trend Bar 1 - MAs Crossing - Trend Meter')


TB2MACrossUp = ta.crossover(MA3, MA4)
TB2MACrossDown = ta.crossunder(MA3, MA4)


alertcondition(TB2MACrossUp, title='TB2 Fast MA X Above Slow MA', message='Trend Bar 2 - Fast MA X Above Slow MA - Trend Meter')
alertcondition(TB2MACrossDown, title='TB2 Fast MA X Below Slow MA', message='Trend Bar 2 - Fast MA X Below Slow MA - Trend Meter')
alertcondition(TB2MACrossUp or TB2MACrossDown, title='TB2 MAs X', message='Color Change - Trend Bar 2 - MAs Crossing - Trend Meter')


TB1Green = MA1 > MA2
TB1Red = MA1 < MA2

TB2Green = MA3 > MA4
TB2Red = MA3 < MA4


alertcondition(BackgroundColorChangePositive and TB1Green, title='3 TMs Turn Green with TB 1', message='All 3 Trend Meters Turn  Green with TB 1 - Trend Meter')
alertcondition(BackgroundColorChangeNegative and TB1Red, title='3 TMs Turn Red with TB 1', message='All 3 Trend Meters Turn  Red with TB 1 - Trend Meter')
alertcondition(BackgroundColorChangePositive and TB1Green or BackgroundColorChangeNegative and TB1Red, title='3 TMs Change Color with TB 1', message='All 3 Trend Meters Change Color with TB 1 - Trend Meter')


alertcondition(BackgroundColorChangePositive and TB2Green, title='3 TMs Turn Green with TB 2', message='All 3 Trend Meters Turn  Green with TB 2 - Trend Meter')
alertcondition(BackgroundColorChangeNegative and TB2Red, title='3 TMs Turn Red with TB 2', message='All 3 Trend Meters Turn  Red with TB 2 - Trend Meter')
alertcondition(BackgroundColorChangePositive and TB2Green or BackgroundColorChangeNegative and TB2Red, title='3 TMs Change Color with TB 2', message='All 3 Trend Meters Change Color with TB 2 - Trend Meter')


alertcondition(BackgroundColorChangePositive and TB1Green and TB2Green, title='3 TMs Turn Green with TBs 1+2', message='All 3 Trend Meters Turn  Green with Trend Bar 1+2 - Trend Meter')
alertcondition(BackgroundColorChangeNegative and TB1Red and TB2Red, title='3 TMs Turn Red with TBs 1+2', message='All 3 Trend Meters Turn  Red with Trend Bar 1+2 - Trend Meter')
alertcondition(BackgroundColorChangePositive and TB1Green and TB2Green or BackgroundColorChangeNegative and TB1Red and TB2Red, title='3 TMs Change Color with TBs1+2', message='All 3 Trend Meters Change Color with Trend Bar 1+2 - Trend Meter')


//Trend Meter END

////////////////Chaikin Money Flow STARTS /////////////////////////////////////////////////////////////////////////////////////////////////

cmfLength = input(title='CMF length', defval=20,group = 'Chaikin Moneyflow')

ad = close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume
mf = math.sum(ad, cmfLength) / math.sum(volume, cmfLength)

cmfPositive = mf >= 0.05
cmfNeutral = mf < 0.05 and mf > -0.05 
cmfNegative = mf <= -0.05

MSBarCMFColor = cmfPositive ? color.new(BuyColor, 15) : cmfNeutral ? color.new(NeutralColor, 20) : color.new(SellColor, 20)


////////////////Chaikin Money Flow Exit End /////////////////////////////////////////////////////////////////////////////////////////////////

////////////////Signals - KDJ STARTS /////////////////////////////////////////////////////////////////////////////////////////////////

ilong = input(9, title="KDJ period",group = 'KDJ')
isig = input(3, title="KDJ signal",group = 'KDJ')

bcwsma(s, l, m) =>
    _bcwsma = float(na)
    _s = s
    _l = l
    _m = m
    _bcwsma := (_m * _s + (_l - _m) * nz(_bcwsma[1])) / _l
    _bcwsma
//c = close
h = ta.highest(high, ilong)
l = ta.lowest(low, ilong)
RSV = 100 * ((close - l) / (h - l))
pK = bcwsma(RSV, isig, 1)
pD = bcwsma(pK, isig, 1)
pJ = 3 * pK - 2 * pD
KDJ = math.avg(pD, pJ, pK)
 

MSBarKDJPositiveTrendSignal = pJ>pD

MSBarKDJNegativeTrendSignal = pJ<pD

MSBarKDJColor = MSBarKDJPositiveTrendSignal ? color.new(BuyColor, 15) : MSBarKDJNegativeTrendSignal ? color.new(SellColor, 20) : na


////////////////Signals - KDJ ENDS /////////////////////////////////////////////////////////////////////////////////////////////////


////////////////Signals - Chandelier Exit STARTS /////////////////////////////////////////////////////////////////////////////////////////////////


atrLength = input(title='ATR Period', defval=1,group = 'Chandelier Exit')
ceMult = input.float(title='ATR Multiplier', step=0.1, defval=1.85,group = 'Chandelier Exit')
ceUseClose = input(title='Use Close Price for Extremums ?', defval=false,group = 'Chandelier Exit')

atr = ceMult * ta.atr(atrLength)

ceLongStop = (ceUseClose ? ta.highest(close, atrLength) : ta.highest(atrLength)) - atr
ceLongStopPrev = nz(ceLongStop[1], ceLongStop)
ceLongStop := close[1] > ceLongStopPrev ? math.max(ceLongStop, ceLongStopPrev) : ceLongStop

ceShortStop = (ceUseClose ? ta.lowest(close, atrLength) : ta.lowest(atrLength)) + atr
ceShortStopPrev = nz(ceShortStop[1], ceShortStop)
ceShortStop := close[1] < ceShortStopPrev ? math.min(ceShortStop, ceShortStopPrev) : ceShortStop

var int ceDir = 1
ceDir := close > ceShortStopPrev ? 1 : close < ceLongStopPrev ? -1 : ceDir
ceBuySignal = ceDir == 1 and ceDir[1] == -1
ceSellSignal = ceDir == -1 and ceDir[1] == 1
ceChangeCond = ceDir != ceDir[1]


//Without filtering
MSBarCEPositiveTrendSignal = ceBuySignal 
MSBarCENegativeTrendSignal = ceSellSignal


MSBarCEColor = MSBarCEPositiveTrendSignal ? BuyColor : MSBarCENegativeTrendSignal ? SellColor : color.new(DisabledColor,90) 



////////////////Signals - Chandelier Exit Ends/////////////////////////////////////////////////////////////////////////////////////////////////


////////////////Signals - WaveTrend STARTS /////////////////////////////////////////////////////////////////////////////////////////////////


MSBar1PositiveWaveTrendSignal = MSBar1 == 'Filter X' ? FilterXUp and WTCross and WTCrossUp : MSBar1 == 'Trend Filter' ? TrendFilterPlus and WTCross and WTCrossUp : MSBar1 == 'Filter X + Trend Filter' ? FilterXUp and TrendFilterPlus and WTCross and WTCrossUp : WTCross and WTCrossUp

MSBar1NegativeWaveTrendSignal = MSBar1 == 'Filter X' ? FilterXDown and WTCross and WTCrossDown : MSBar1 == 'Trend Filter' ? TrendFilterMinus and WTCross and WTCrossDown : MSBar1 == 'Filter X + Trend Filter' ? FilterXDown and TrendFilterMinus and WTCross and WTCrossDown : WTCross and WTCrossDown

MSBar2PositiveWaveTrendSignal = MSBar2 == 'Filter X' ? FilterXUp and WTCross and WTCrossUp : MSBar2 == 'Trend Filter' ? TrendFilterPlus and WTCross and WTCrossUp : MSBar2 == 'Filter X + Trend Filter' ? FilterXUp and TrendFilterPlus and WTCross and WTCrossUp : WTCross and WTCrossUp

MSBar2NegativeWaveTrendSignal = MSBar2 == 'Filter X' ? FilterXDown and WTCross and WTCrossDown : MSBar2 == 'Trend Filter' ? TrendFilterMinus and WTCross and WTCrossDown : MSBar2 == 'Filter X + Trend Filter' ? FilterXDown and TrendFilterMinus and WTCross and WTCrossDown : WTCross and WTCrossDown

MSBar1Color = MSBar1PositiveWaveTrendSignal ? BuyColor : MSBar1NegativeWaveTrendSignal ? SellColor : color.new(DisabledColor,90)

MSBar2Color = BackgroundColorChangePositive ? BuyColor : BackgroundColorChangeNegative ? SellColor : color.new(DisabledColor,90)



////////////////Signals - WaveTrend ENDS /////////////////////////////////////////////////////////////////////////////////////////////////

////////////////Signals - QQE STARTS /////////////////////////////////////////////////////////////////////////////////////////////////


RSI_Period = input(14, title='RSI Length',group = 'QQE')
SF = input(5, title='RSI Smoothing',group = 'QQE')
QQE = input(4.238, title='Fast QQE Factor',group = 'QQE')
ThreshHold = input(10, title='Thresh-hold',group = 'QQE')

qqrSrc = close
Wilders_Period = RSI_Period * 2 - 1

Rsi = ta.rsi(qqrSrc, RSI_Period)
RsiMa = ta.ema(Rsi, SF)
AtrRsi = math.abs(RsiMa[1] - RsiMa)
MaAtrRsi = ta.ema(AtrRsi, Wilders_Period)
dar = ta.ema(MaAtrRsi, Wilders_Period) * QQE

qqeLongband = 0.0
qqeShortband = 0.0
qqeTrend = 0

DeltaFastAtrRsi = dar
RSIndex = RsiMa
qqeNewshortband = RSIndex + DeltaFastAtrRsi
qqeNewlongband = RSIndex - DeltaFastAtrRsi
qqeLongband := RSIndex[1] > qqeLongband[1] and RSIndex > qqeLongband[1] ? math.max(qqeLongband[1], qqeNewlongband) : qqeNewlongband
qqeShortband := RSIndex[1] < qqeShortband[1] and RSIndex < qqeShortband[1] ? math.min(qqeShortband[1], qqeNewshortband) : qqeNewshortband
cross_1 = ta.cross(qqeLongband[1], RSIndex)
qqeTrend := ta.cross(RSIndex, qqeShortband[1]) ? 1 : cross_1 ? -1 : nz(qqeTrend[1], 1)
FastAtrRsiTL = qqeTrend == 1 ? qqeLongband : qqeShortband

// Find all the QQE Crosses

QQExlong = 0
QQExlong := nz(QQExlong[1])
QQExshort = 0
QQExshort := nz(QQExshort[1])
QQExlong := FastAtrRsiTL < RSIndex ? QQExlong + 1 : 0
QQExshort := FastAtrRsiTL > RSIndex ? QQExshort + 1 : 0

//Conditions

qqeLong = QQExlong == 1 ? FastAtrRsiTL[1] - 50 : na
qqeShort = QQExshort == 1 ? FastAtrRsiTL[1] - 50 : na


MSBarQQEPositiveTrendSignal = qqeLong

MSBarQQENegativeTrendSignal = qqeShort


MSBarQQEColor = MSBarQQEPositiveTrendSignal ? BuyColor : MSBarQQENegativeTrendSignal ? SellColor : color.new(DisabledColor,90)


////////////////Signals - QQE ENDS /////////////////////////////////////////////////////////////////////////////////////////////////


////////////////Signals - PSAR STARTS /////////////////////////////////////////////////////////////////////////////////////////////////


psStart = input.float(title='Start', step=0.001, defval=0.02,group = 'Parabolic SAR')
psIncrement = input.float(title='Increment', step=0.001, defval=0.02,group = 'Parabolic SAR')
psMaximum = input.float(title='Maximum', step=0.01, defval=0.2,group = 'Parabolic SAR')
psWidth = input.int(title='Point Width', minval=1, defval=2,group = 'Parabolic SAR')

psar = ta.sar(psStart, psIncrement, psMaximum)
psDir = psar < close ? 1 : -1


psBuySignal = psDir == 1 and psDir[1] == -1

psSellSignal = psDir == -1 and psDir[1] == 1

MSBarPSPositiveTrendSignal = psBuySignal

MSBarPSNegativeTrendSignal = psSellSignal

MSBarPSColor = MSBarPSPositiveTrendSignal ? BuyColor : MSBarPSNegativeTrendSignal ? SellColor : color.new(DisabledColor,90)


changeCond = psDir != psDir[1]

////////////////Signals - PSAR ENDS /////////////////////////////////////////////////////////////////////////////////////////////////


//////////////// Technical Ratings ENDS /////////////////////////////////////////////////////////////////////////////////////////////////


// ———————————————————— Constants, global arrays and inputs {
var string TR = 'Technical Ratings'

// ————— Input `options` selections.
var string RT1 = 'MAs and Oscillators'
var string RT2 = 'MAs'
var string RT3 = 'Oscillators'

var string ON = 'On'
var string OFF = 'Off'

var string TD0 = 'None'
var string TD1 = 'Longs'
var string TD2 = 'Shorts'
var string TD3 = 'Longs and Shorts'

var string PS1 = 'Columns'
var string PS2 = 'Histogram'
var string PS3 = 'Area'
var string PS4 = 'Line'

// Levels determining "Strong Buy/Sell" and "Buy/Sell" ratings.
var float LEVEL_STRONG = 0.5
var float LEVEL_WEAK = 0.1

// Color constants.
var color C_AQUA = #0080FFff
var color C_BLACK = #000000ff
var color C_BLUE = #013BCAff
var color C_CORAL = #FF8080ff
var color C_GOLD = #CCCC00ff
var color C_GRAY = #808080ff
var color C_GREEN = #008000ff
var color C_LIME = #00FF00ff
var color C_MAROON = #800000ff
var color C_ORANGE = #FF8000ff
var color C_PINK = #FF0080ff
var color C_RED = #FF0000ff
var color C_VIOLET = #AA00FFff
var color C_YELLOW = #FFFF00ff
var color C_WHITE = #FFFFFFff

var color C_NEUTRAL = #434650

// ————— Global arrays
// Array holding values for the 3 ratings in this order: All, MAs, Osc.
var float[] ratings = array.new_float(3)
// Array holding the text used as a legend in the displayed results.
var string[] TEXTS = array.from('All', 'MAs', 'Osc')
// Array holding the index into `ratings` and `texts` arrays determined by which rating user chooses to display.
var int[] indices = array.new_int(3)

// ————— Inputs
string i_tf = ''//input.timeframe('', 'Higher timeframe for technical rating', group=TR, tooltip='When using a higher timeframe, values do not repaint, which means that only values from COMPLETED timeframes are displayed. This provides late, more reliable values, and also ensures the indicator behaves in realtime the same way it does on historical bars.')
bool i_repaint = false//input.string(OFF, 'Repainting', options=[ON, OFF], group=TR, tooltip='This only controls the repainting of the displayed signal when NOT using a higher timeframe. Alerts never repaint, regardless of this setting. This means you can display repainting calculations but still have non-repainting markers and alerts.') == ON
string i_calcs = input.string(RT1, 'Rating uses', group=TR, options=[RT2, RT3, RT1])
float i_weightMAs = input.int(50, 'Weight of MAs (%)', minval=0, maxval=100, step=10, group=TR, tooltip='Determines the respective weight of MAs and Oscillators when both are used to calculate the overall rating. Equal weight for MAs and Oscillators is 50%. If you use 60% for MAs, then Oscillators weigh in at 40% of the overall rating.') / 100
string i_plotStyle = PS1 //input.string(PS1, 'Plot style', inline='10', options=[PS1, PS2, PS3, PS4])
int i_plotWidth = 1 //input.int(1, '', inline='10', minval=1, maxval=50, tooltip='Width for styles other than \'Columns\'.')

color i_c_01 = BuyColor //input.color(C_LIME, 'Bull  ', inline='11', tooltip='Pick only one. These are preset colors, but you can modify anyone of them.')
bool i_01 = true //input.bool(true, '', inline='11')
color i_c_02 = C_GOLD //input.color(C_GOLD, '', inline='11')
bool i_02 = false //input.bool(false, '', inline='11')
color i_c_03 = C_WHITE //input.color(C_WHITE, '', inline='11')
bool i_03 = false //input.bool(false, '', inline='11')
color i_c_04 = SellColor //input.color(C_PINK, 'Bear   ', inline='12', tooltip='Pick only one. These are preset colors, but you can modify anyone of them.')
bool i_04 = true//input.bool(true, '', inline='12')
color i_c_05 = C_VIOLET//input.color(C_VIOLET, '', inline='12')
bool i_05 = false//input.bool(false, '', inline='12')
color i_c_06 = C_BLUE//input.color(C_BLUE, '', inline='12')
bool i_06 = false //input.bool(false, '', inline='12')
color i_c_neutral = color.new(NeutralColor, 20) //input.color(C_NEUTRAL, 'Neutral', inline='13')

//var string GP1 = 'Alert Markers (non-repainting)'
string i_markerDir = TD3 //input.string(TD0, 'Direction', options=[TD0, TD1, TD2, TD3], group=GP1, tooltip='Markers only become active when you select a direction here. Your marker setup defines the conditions that will trigger an alert configured on the indicator.')
bool i_markerAlt = ON == ON and i_markerDir == TD3 //input.string(ON, 'Alternate Longs & Shorts', options=[ON, OFF], group=GP1, tooltip='If both Longs and Shorts are displayed, shows only the first marker in a given direction. This prevents triggering successive markers in the same direction. Has no effect when only long or only short markers are displayed.') == ON and i_markerDir == TD3
float i_levelUp = LEVEL_STRONG //input.float(LEVEL_STRONG, 'Longs Level', minval=0, maxval=1, step=0.05, group=GP1, tooltip='The level that must be breached upward to trigger a long.\n\'Buy\' state corresponds to 0.1\n\'Strong Buy\' state corresponds to 0.5\n\nUse zero if you do not want triggers on this condition.')
float i_levelDn = -LEVEL_STRONG //input.float(-LEVEL_STRONG, 'Shorts Level', minval=-1, maxval=0, step=0.05, group=GP1, tooltip='The level that must be breached downward to trigger a short.\n\'Sell\' state corresponds to -0.1\n\'Strong Sell\' state corresponds to -0.5\n\nUse zero if you do not want triggers on this condition.')
float i_gradLevel = 0 //input.int(0, 'Cumulative adv./decl.', minval=0, maxval=5, step=1, group=GP1, tooltip='The number of cumulative advances or declines in the signal (capped to 5). The maximum of 5 corresponds to the brightest color for the signal.\n\nUse zero if you do not want triggers on this condition.')

// Determine base bull/bear colors as per user selection.
var color i_c_bull = i_01 ? i_c_01 : i_02 ? i_c_02 : i_03 ? i_c_03 : i_c_01
var color i_c_bear = i_04 ? i_c_04 : i_05 ? i_c_05 : i_06 ? i_c_06 : i_c_04

var bool doLongs = i_markerDir == TD1 or i_markerDir == TD3
var bool doShorts = i_markerDir == TD2 or i_markerDir == TD3

int plotStyle = i_plotStyle == PS1 ? 5 : i_plotStyle == PS2 ? 1 : i_plotStyle == PS3 ? 4 : 0
// }



// ———————————————————— Functions {
// RATINGS CALCULATION METHOD:
// Individual ratings are one of four values:
//  • +1 for bull bias.
//  •  0 for neutral.
//  • -1 for bear bias.
//  • na when no value can be determined yet.
// The average of all non-na values within each of the MAs and Oscillators groups determines the group's rating.
// The overall rating is the average of the two group ratings.

// ————— Helper functions.
f_rising(_src) =>
    ta.rising(_src, 1)
f_falling(_src) =>
    ta.falling(_src, 1)
f_trendUp() =>
    close > ta.ema(close, 50)
f_trendDn() =>
    close < ta.ema(close, 50)
f_notNa(_src) =>
    not na(_src) and not na(_src[1])

// ————— Function returning `_color` with `_transp` transparency.
f_colorNew(_color, _transp) =>
    _r = color.r(_color)
    _g = color.g(_color)
    _b = color.b(_color)
    color _return = color.rgb(_r, _g, _b, _transp)
    _return

// ————— General MA rating (+1/0/-1) calculated using position of `_src` price with regards to `_ma`.
f_ratingMa(_ma, _src) =>
    math.sign(_src - _ma)

// ————— Converts bull/bear conditions into a +1/0/-1 value corresponding to a bull/neutral/bear bias.
f_ratingBullBear(_bullCond, _bearCond) =>
    na(_bullCond) or na(_bearCond) ? na : _bullCond ? 1 : _bearCond ? -1 : 0

// ————— Ichimoku rating.
f_donchian(_p) =>
    math.avg(ta.lowest(_p), ta.highest(_p))
f_ratingIchimoku() =>
    float _conversion = f_donchian(9)
    float _base = f_donchian(26)
    float _lead1 = math.avg(_conversion, _base)
    float _lead2 = f_donchian(52)
    float _return = f_ratingBullBear(_lead1 > _lead2 and close > _lead1 and close < _base and close[1] < _conversion and close > _conversion, _lead2 > _lead1 and close < _lead2 and close > _base and close[1] > _conversion and close < _conversion)
    if not(na(_lead1) or na(_lead2) or na(close) or na(close[1]) or na(_base) or na(_conversion))
        _return
    else
        float(na)

// ————— RSI rating.
f_ratingRsi() =>
    float _rsi = ta.rsi(close, 14)
    float _return = f_ratingBullBear(_rsi < 30 and f_falling(_rsi), _rsi > 70 and f_rising(_rsi))
    _return := f_notNa(_rsi) ? _return : na
    _return

// ————— Stochastic rating.
f_ratingStoch() =>
    float _k = ta.sma(ta.stoch(close, high, low, 14), 3)
    float _d = ta.sma(_k, 3)
    float _return = f_ratingBullBear(_k < 20 and _d < 20 and _k > _d and _k[1] < _d[1], _k > 80 and _d > 80 and _k < _d and _k[1] > _d[1])
    _return := f_notNa(_k) and f_notNa(_d) ? _return : na
    _return

// ————— CCI rating.
f_ratingCci() =>
    float _cci = ta.cci(close, 20)
    float _return = f_ratingBullBear(_cci < -100 and f_rising(_cci), _cci > 100 and f_falling(_cci))
    _return := f_notNa(_cci) ? _return : na
    _return

// ————— ADX rating.
f_ratingAdx() =>
    [_diPlus, _diMinus, _adx] = ta.dmi(14, 14)
    float _return = f_ratingBullBear(_adx > 20 and _diPlus[1] < _diMinus[1] and _diPlus > _diMinus, _adx > 20 and _diPlus[1] > _diMinus[1] and _diPlus < _diMinus)
    _return := f_notNa(_diPlus) and f_notNa(_diMinus) and not na(_adx) ? _return : na
    _return

// ————— Awesome Oscillator rating.
f_ratingAo() =>
    float _ao = ta.sma(hl2, 5) - ta.sma(hl2, 34)
    bool _aoXUp = ta.crossover(_ao, 0)
    bool _aoXDn = ta.crossunder(_ao, 0)
    float _return = f_ratingBullBear(_aoXUp or _ao > 0 and _ao[1] > 0 and f_rising(_ao), _aoXDn or _ao < 0 and _ao[1] < 0 and f_falling(_ao))
    _return := f_notNa(_ao) ? _return : na
    _return

// ————— Momentum rating.
f_ratingMom() =>
    float _mom = close - close[10]
    float _return = f_ratingBullBear(f_rising(_mom), f_falling(_mom))
    _return := f_notNa(_mom) ? _return : na
    _return

// ————— MACD rating.
f_ratingMacd() =>
    [_macd, _signal, _] = ta.macd(close, 12, 26, 9)
    float _return = f_ratingBullBear(_macd > _signal, _macd < _signal)
    _return := not na(_macd) and not na(_signal) ? _return : na
    _return

// ————— Stoch RSI rating.
f_ratingStochRsi() =>
    float _rsi = ta.rsi(close, 14)
    float _k = ta.sma(ta.stoch(_rsi, _rsi, _rsi, 14), 3)
    float _d = ta.sma(_k, 3)
    float _return = f_ratingBullBear(f_trendDn() and _k < 20 and _d < 20 and _k > _d and _k[1] < _d[1], f_trendUp() and _k > 80 and _d > 80 and _k < _d and _k[1] > _d[1])
    _return := f_notNa(_k) and f_notNa(_d) and not na(f_trendDn()) and not na(f_trendUp()) ? _return : na
    _return

// ————— Williams %R rating.
f_ratingWpr() =>
    float _wpr = ta.wpr(14)
    float _return = f_ratingBullBear(_wpr < -80 and f_rising(_wpr), _wpr > -20 and f_falling(_wpr))
    _return := f_notNa(_wpr) ? _return : na
    _return

// ————— Bull Bear Power rating.
f_ratingBbp() =>
    float _powerBull = high - ta.ema(close, 13)
    float _powerBear = low - ta.ema(close, 13)
    float _return = f_ratingBullBear(f_trendUp() and _powerBear < 0 and f_rising(_powerBear), f_trendDn() and _powerBull > 0 and f_falling(_powerBull))
    _return := f_notNa(_powerBull) and f_notNa(_powerBear) and not na(f_trendDn()) and not na(f_trendUp()) ? _return : na
    _return

// ————— Ultimate Oscillator rating.
f_ratingUo() =>
    var int _pFast = 7
    var int _pMid = 14
    var int _pLong = 28
    float _tl = close[1] < low ? close[1] : low
    float _uo = na
    float _v1 = math.sum(ta.tr, _pFast)
    float _v2 = math.sum(ta.tr, _pMid)
    float _v3 = math.sum(ta.tr, _pLong)
    float _v4 = math.sum(close - _tl, _pFast)
    float _v5 = math.sum(close - _tl, _pMid)
    float _v6 = math.sum(close - _tl, _pLong)
    if _v1 != 0 and _v2 != 0 and _v3 != 0
        float _p0 = _pLong / _pFast
        float _p1 = _pLong / _pMid
        float _v7 = _v4 / _v1 * _p0
        float _v8 = _v5 / _v2 * _p1
        float _v9 = _v6 / _v3
        _uo := 100 * (_v7 + _v8 + _v9) / (_p0 + _p1 + 1)
        _uo
    float _return = f_ratingBullBear(_uo > 70, _uo < 30)
    _return := not na(_uo) ? _return : na
    _return

// ————— Function that calculates the ratings for the three groups: All, MAs, Oscillators.
f_ratings(_offset) =>
    // int _offset: offset of values returned. Required to control repainting. Can be 0 or 1.
    // Dependencies: `f_ratingMa()`, `f_ratingIchimoku()`, and one function for each of the oscillators.

    // Array holding the calculated ratings for MAs group, then for Oscillators.
    var float[] _ratings = array.new_float(0)

    // Calculate MAs rating.
    array.clear(_ratings)
    array.push(_ratings, f_ratingMa(ta.sma(close, 10), close))
    array.push(_ratings, f_ratingMa(ta.sma(close, 20), close))
    array.push(_ratings, f_ratingMa(ta.sma(close, 30), close))
    array.push(_ratings, f_ratingMa(ta.sma(close, 50), close))
    array.push(_ratings, f_ratingMa(ta.sma(close, 100), close))
    array.push(_ratings, f_ratingMa(ta.sma(close, 200), close))
    array.push(_ratings, f_ratingMa(ta.ema(close, 10), close))
    array.push(_ratings, f_ratingMa(ta.ema(close, 20), close))
    array.push(_ratings, f_ratingMa(ta.ema(close, 30), close))
    array.push(_ratings, f_ratingMa(ta.ema(close, 50), close))
    array.push(_ratings, f_ratingMa(ta.ema(close, 100), close))
    array.push(_ratings, f_ratingMa(ta.ema(close, 200), close))
    array.push(_ratings, f_ratingMa(ta.hma(close, 9), close))
    array.push(_ratings, f_ratingMa(ta.vwma(close, 20), close))
    array.push(_ratings, f_ratingIchimoku())
    float _ratingMas = array.avg(_ratings)

    // Calculate Oscillators rating.
    array.clear(_ratings)
    array.push(_ratings, f_ratingRsi())
    array.push(_ratings, f_ratingStoch())
    array.push(_ratings, f_ratingCci())
    array.push(_ratings, f_ratingAdx())
    array.push(_ratings, f_ratingAo())
    array.push(_ratings, f_ratingMom())
    array.push(_ratings, f_ratingMacd())
    array.push(_ratings, f_ratingStochRsi())
    array.push(_ratings, f_ratingWpr())
    array.push(_ratings, f_ratingBbp())
    array.push(_ratings, f_ratingUo())
    float _ratingOsc = array.avg(_ratings)

    // Calculate weighed average of the two groups: MAs and Oscillators.
    float _ratingTot = nz(_ratingMas * i_weightMAs) + nz(_ratingOsc * (1. - i_weightMAs))
    [_ratingTot[_offset], _ratingMas[_offset], _ratingOsc[_offset]]

// ————— Function returning the index to be used in arrays `ratings` and `texts` to get values and legends in the correct order when printing results.
f_idx(_pos) =>
    // int _pos: line number (0-2) for which we need the index into our `ratings` and `texts` arrays.
    // Dependency: `indices` array containing the vertical order of appearance of the current ratings.
    int _return = array.get(indices, _pos)
    _return

// ————— Function that orders the `indices` array such that its elements represent the indices into arrays `ratings` and `texts`,
//       which `f_idx()` will then use to fetch the proper values and legends for each of the three lines in the results.
//       The order used is derived from the "Rating uses" user selection. User's choice always appears on line 1, with the remaining ones on lines 2 and 3.
f_orderSignals(_userSelection) =>
    // string _userSelection: user choice of which rating group to display.
    // Dependencies: `indices` array, `RTx` constants.
    if _userSelection == RT2
        array.set(indices, 0, 1)
        array.set(indices, 1, 2)
        array.set(indices, 2, 0)
    else if _userSelection == RT3
        array.set(indices, 0, 2)
        array.set(indices, 1, 1)
        array.set(indices, 2, 0)
    else
        array.set(indices, 0, 0)
        array.set(indices, 1, 1)
        array.set(indices, 2, 2)

// ————— Function counting the number of consecutive ups and downs for `_src`.
f_countRising(_src) =>
    // float _src: value of ratings to color.
    var int _cnt = 0
    float _chg = ta.change(math.abs(_src))
    if _src == 0
        _cnt := 0
        _cnt
    else if _chg > 0
        _cnt := math.min(5, _cnt + 1)
        _cnt
    else if _chg < 0
        _cnt := math.max(1, _cnt - 1)
        _cnt
    int _return = _src > 0 ? _cnt : -_cnt
    _return

f_c_signal(_gradient) =>
    // int _gradient: gradient level (+5 to -5) from which to derive a color.
    color _color = _gradient > 0 ? i_c_bull : _gradient < 0 ? i_c_bear : i_c_neutral
    float _transp = 100 - math.abs(_gradient) * 20
    _transp := _transp == 80 ? 75 : _transp
    color _return = _color == i_c_neutral ? _color : f_colorNew(_color, _transp)
    _return

// ————— Function returning the color used to display a state string in the results.
f_c_colorFromRating(_rating) =>
    // float _rating: rating from which to derive a color.
    color _return = if _rating > LEVEL_STRONG
        f_colorNew(i_c_bull, 00)
    else if _rating > LEVEL_WEAK
        f_colorNew(i_c_bull, 25)
    else if _rating < -LEVEL_STRONG
        f_colorNew(i_c_bear, 00)
    else if _rating < -LEVEL_WEAK
        f_colorNew(i_c_bear, 25)
    else
        i_c_neutral
    _return

// ————— Function returning a string corresponding to the state of a `_rating`.
f_textFromRating(_rating) =>
    // float _rating: rating from which to derive a string.
    string _return = if _rating > LEVEL_STRONG
        'Strong Buy'
    else if _rating > LEVEL_WEAK
        'Buy'
    else if _rating < -LEVEL_STRONG
        'Strong Sell'
    else if _rating < -LEVEL_WEAK
        'Sell'
    else
        'Neutral'
    _return

// ————— Function that prints one line at a time in rating results to the right of the last bar.
f_print(_txt, _lineNo, _txtColor) =>
    // string _txt     : text of the line.
    // int    _lineNo  : number of the line (0-2).
    // color  _txtColor: color of the text.
    var _lbl = label.new(bar_index, 0, '', xloc.bar_index, yloc.price, color(na), label.style_label_left, color.white, textalign=text.align_left)
    // Create dynamic prefix and suffix containing the appropriate qty of newlines before and after the line, to place it in the correct vertical position.
    string[] _returnsPrefix = array.new_string(math.max(0, _lineNo - 1), '\n')
    string[] _returnsSuffix = array.new_string(math.max(0, 4 - _lineNo), '\n')
    string _prefix = array.join(_returnsPrefix, '')
    string _suffix = array.join(_returnsSuffix, '')
    // Update label.
    if barstate.islast
        label.set_x(_lbl, bar_index)
        label.set_text(_lbl, _prefix + _txt + _suffix)
        label.set_textcolor(_lbl, _txtColor)

// ————— Function that triggers alert with `_txt` message when `_cond` is true.
// Note that while we call `alert()` with `alert.freq_all`, the moment when alerts will trigger is controlled in the triggering conditions.
f_alert(_txt) =>
    alert(_txt, alert.freq_once_per_bar)

// ————— Converts current chart timeframe into a float minutes value.
f_tfInMinutes() =>
    float _return = timeframe.multiplier * (timeframe.isseconds ? 1. / 60 : timeframe.isminutes ? 1. : timeframe.isdaily ? 60. * 24 : timeframe.isweekly ? 60. * 24 * 7 : timeframe.ismonthly ? 60. * 24 * 30.4375 : na)
    _return

// ————— Returns resolution of _res string timeframe in minutes.
f_tfInMinutesFrom(_tf) =>
    // _tf: string timeframe (in `timeframe.period` string format) to convert in float minutes.
    // Dependency: f_tfInMinutes()
    float _return = request.security(syminfo.tickerid, _tf, f_tfInMinutes())
    _return
// }



// ———————————————————— Calculations {

// ————— Set text of results legends and determine their order from user-selected group of ratings.
if barstate.isfirst
    f_orderSignals(i_calcs)

// ————— Calculate ratings.
// Determine if HTF is used.
var bool htfUsed = i_tf != ''
// If HTF is used, ensure chart TF < HTF.
bool chartTfIsTooHigh = htfUsed and f_tfInMinutes() >= f_tfInMinutesFrom(i_tf)
// Fetch ratings, adjusting series offset with HTF (which never repaints) and user-selected repaint settings (when no HTF is used). Two-stage offsetting is required because `f_ratings()` returns a tuple.
int idx1 = htfUsed and barstate.isrealtime ? 1 : 0
int idx2 = i_repaint and not htfUsed or htfUsed and barstate.isrealtime ? 0 : 1
[ratingTot_, ratingMas_, ratingOsc_] = request.security(syminfo.tickerid, i_tf, f_ratings(idx1))
float ratingTot = ratingTot_[idx2]
float ratingMas = ratingMas_[idx2]
float ratingOsc = ratingOsc_[idx2]

// ————— Place ratings in known order.
array.set(ratings, 0, ratingTot)
array.set(ratings, 1, ratingMas)
array.set(ratings, 2, ratingOsc)
// User-selected ratings group to display as the signal and whose state always appears on the first line of results.
float userRating = array.get(ratings, f_idx(0))
// }



// ———————————————————— Plots {

// ————— Build signal color.
bool condBuy = userRating > LEVEL_WEAK
bool condSell = userRating < -LEVEL_WEAK
bool condNeutral = not condBuy and not condSell
float valsBuy = condBuy ? userRating : 0
float valsSell = condSell ? userRating : 0
int risingBuys = f_countRising(valsBuy)
int fallingSells = f_countRising(valsSell)
int gradientLvl = condBuy ? risingBuys : condSell ? fallingSells : 0
color c_signal = f_c_signal(gradientLvl)



// ————— Print text corresponding to the rating on last bar, with user-selected group always on the first line.
//       Legends and rating states are printed separately so they align vertically.
// Indices into `ratings` and `texts` arrays corresponding to the order in which they need to be displayed, given user selection of which group to use as the main signal.
var int idxOfLine1 = f_idx(0)
var int idxOfLine2 = f_idx(1)
var int idxOfLine3 = f_idx(2)
// Display label to the right of last bar.
var string COLUMN_PADDING = ' '


if barstate.islast
    f_print(COLUMN_PADDING + array.get(TEXTS, idxOfLine1) + ': ' + f_textFromRating(array.get(ratings, idxOfLine1)), 1, f_c_colorFromRating(array.get(ratings, idxOfLine1)))
    f_print(COLUMN_PADDING + array.get(TEXTS, idxOfLine2) + ': ' + f_textFromRating(array.get(ratings, idxOfLine2)), 2, f_c_colorFromRating(array.get(ratings, idxOfLine2)))
    f_print(COLUMN_PADDING + array.get(TEXTS, idxOfLine3) + ': ' + f_textFromRating(array.get(ratings, idxOfLine3)), 3, f_c_colorFromRating(array.get(ratings, idxOfLine3)))



// ———————————————————— Alerts and markers. {

// ————— Alerts.
// The triggering conditions can only be met in such a way that they never repaint.
// If no HTF is used and no-repainting is required, we wait for the bar to close. Otherwise we can trigger at the bar's open because the signal is non-repainting signal.
int ensureNoRepaintIdx = not htfUsed and i_repaint ? 1 : 0
bool xUp = i_levelUp != 0 and ta.crossover(userRating, i_levelUp)
bool xDn = i_levelDn != 0 and ta.crossunder(userRating, i_levelDn)
bool gUp = i_gradLevel != 0 and gradientLvl == i_gradLevel and gradientLvl[1] < i_gradLevel
bool gDn = i_gradLevel != 0 and gradientLvl == -i_gradLevel and gradientLvl[1] > -i_gradLevel



//////////////// Technical Ratings ENDS /////////////////////////////////////////////////////////////////////////////////////////////////

//////////////// Volatility STARTS/////////////////////////////////////////////////////////////////////////////////////////////////
Volatility_Group = "Volatility"

//Volatility Calculation
volatilityCalculation = ta.tr(true) * 100 / math.abs(low)


//Resolution 1
volatilityPercentageRes1 = input.timeframe(defval='1D', title='Volatility Resolution 1', inline='Volatility 1 Inline', group=Volatility_Group)
volatilityPercentSec1 = request.security(syminfo.tickerid, volatilityPercentageRes1, volatilityCalculation)
volatilityConvertToLive1 = volatilityPercentSec1 - volatilityCalculation
volatilityDetector1 = volatilityCalculation + volatilityConvertToLive1
volatilityDetector1Condition = volatilityDetector1 

//Resolution 2
volatilityPercentageRes2 = input.timeframe(defval='1W', title='Volatility Resolution 2', inline='Volatility 2 Inline', group=Volatility_Group)
volatilityPercentSec2 = request.security(syminfo.tickerid, volatilityPercentageRes2, volatilityCalculation)
volatilityConvertToLive2 = volatilityPercentSec2 - volatilityCalculation
volatilityDetector2 = volatilityCalculation + volatilityConvertToLive2
volatilityDetector2Condition = volatilityDetector2

//Resolution 3
volatilityPercentageRes3 = input.timeframe(defval='1M', title='Volatility Resolution 3', inline='Volatility 3 Inline', group=Volatility_Group)
volatilityPercentSec3 = request.security(syminfo.tickerid, volatilityPercentageRes3, volatilityCalculation)
volatilityConvertToLive3 = volatilityPercentSec3 - volatilityCalculation
volatilityDetector3 = volatilityCalculation + volatilityConvertToLive3
volatilityDetector3Condition = volatilityDetector3

Volatility = "Volatility (" + str.tostring(volatilityPercentageRes1) + "): " + str.tostring(volatilityDetector1Condition, '#.##') + "%" + " (" + str.tostring(volatilityPercentageRes2) + "): " + str.tostring(volatilityDetector2Condition, '#.##') + "%" + " (" + str.tostring(volatilityPercentageRes3) + "): " + str.tostring(volatilityDetector3Condition, '#.##') + "%" 

if barstate.islast
    if chartTfIsTooHigh
        f_print(COLUMN_PADDING + 'Chart\'s timeframe must be smaller than ' + i_tf, 4, color.red)
    // Rating states.
    f_print(COLUMN_PADDING  + Volatility, 4, color.teal)

//////////////// Volatility ENDS/////////////////////////////////////////////////////////////////////////////////////////////////


//////////////// Donchin Channel Ribbon  /////////////////////////////////////////////////////////////////////////////////////////////////


dlen = input.int(defval=20, title='Donchian Channel Period', minval=10,group= "Donchian Trend Ribbon")

dchannel(len) =>
    float hh = ta.highest(len)
    float ll = ta.lowest(len)

    int trend = 0
    trend := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(trend[1])
    trend

dchannelalt(len, maintrend) =>
    float hh = ta.highest(len)
    float ll = ta.lowest(len)

    int trend = 0
    trend := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(trend[1])
    maintrend == 1 ? trend == 1 ? color.new(BuyColor, 15) : color.new(BuyColor, 15) : maintrend == -1 ? trend == -1 ? color.new(SellColor, 20) : color.new(SellColor, 20) : na

maintrend = dchannel(dlen)
dcColor = dchannelalt(dlen - 1, maintrend)


//////////////// Donchin Channel Ribbon  /////////////////////////////////////////////////////////////////////////////////////////////////


//////////////// Alpha Trend /////////////////////////////////////////////////////////////////////////////////////////////////

coeff = input.float(1, 'Multiplier', step=0.1,group = 'Alpha Trend')
AP = input(14, 'Common Period',group = 'Alpha Trend')
ATR = ta.sma(ta.tr, AP)
src = input(close)
novolumedata = input(title='Change calculation (no volume data)?', defval=false,group = 'Alpha Trend')
atUpT = low - ATR * coeff
atDownT = high + ATR * coeff
AlphaTrend = 0.0
AlphaTrend := (novolumedata ? ta.rsi(src, AP) >= 50 : ta.mfi(hlc3, AP) >= 50) ? atUpT < nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : atUpT : atDownT > nz(AlphaTrend[1]) ? nz(AlphaTrend[1]) : atDownT


ATStrongBuySell = false 
ATWeakBuySell = false 

BARAtColor = color.gray 


if AlphaTrend > AlphaTrend[2] 
    BARAtColor := color.new(BuyColor, 15)
    ATStrongBuySell := true
else 
    BARAtColor := color.new(SellColor, 20)
    ATStrongBuySell := false
    if AlphaTrend[1] > AlphaTrend[3] 
        BARAtColor :=  NeutralColor //color.new(color.gray, 15)
        ATWeakBuySell := true
    else 
        BARAtColor = color.yellow
        ATWeakBuySell := false



//////////////// Alpha Trend /////////////////////////////////////////////////////////////////////////////////////////////////

//////////////// Half Trend /////////////////////////////////////////////////////////////////////////////////////////////////

amplitude = input(title='Amplitude', defval=2)
channelDeviation = input(title='Channel Deviation', defval=2)
showArrows = input(title='Show Arrows', defval=true)
showChannels = input(title='Show Channels', defval=true)

var int halftrend = 0
var int nextTrend = 0
var float maxLowPrice = nz(low[1], low)
var float minHighPrice = nz(high[1], high)

var float htup = 0.0
var float htdown = 0.0
float atrHigh = 0.0
float atrLow = 0.0
float arrowUp = na
float arrowDown = na

atr2 = ta.atr(100) / 2
dev = channelDeviation * atr2

highPrice = high[math.abs(ta.highestbars(amplitude))]
lowPrice = low[math.abs(ta.lowestbars(amplitude))]
highma = ta.sma(high, amplitude)
lowma = ta.sma(low, amplitude)

if nextTrend == 1
    maxLowPrice := math.max(lowPrice, maxLowPrice)

    if highma < maxLowPrice and close < nz(low[1], low)
        halftrend := 1
        nextTrend := 0
        minHighPrice := highPrice
        minHighPrice
else
    minHighPrice := math.min(highPrice, minHighPrice)

    if lowma > minHighPrice and close > nz(high[1], high)
        halftrend := 0
        nextTrend := 1
        maxLowPrice := lowPrice
        maxLowPrice

if halftrend == 0
    if not na(halftrend[1]) and halftrend[1] != 0
        htup := na(htdown[1]) ? htdown : htdown[1]
        arrowUp := htup - atr2
        arrowUp
    else
        htup := na(htup[1]) ? maxLowPrice : math.max(maxLowPrice, htup[1])
        htup
    atrHigh := htup + dev
    atrLow := htup - dev
    atrLow
else
    if not na(halftrend[1]) and halftrend[1] != 1
        htdown := na(htup[1]) ? htup : htup[1]
        arrowDown := htdown + atr2
        arrowDown
    else
        htdown := na(htdown[1]) ? minHighPrice : math.min(minHighPrice, htdown[1])
        htdown
    atrHigh := htdown + dev
    atrLow := htdown - dev
    atrLow

ht = halftrend == 0 ? htup : htdown

htBuySignal = not na(arrowUp) and halftrend == 0 and halftrend[1] == 1
htSellSignal = not na(arrowDown) and halftrend == 1 and halftrend[1] == 0

//////////////// Half Trend /////////////////////////////////////////////////////////////////////////////////////////////////


//////////////// Neural Network /////////////////////////////////////////////////////////////////////////////////////////////////
NeuralNetwork = 'Neural Network'
price = close//plot(close, title='Close Line', color=color.new(color.blue, 0), display=display.none)

////////////////////////////////////////////////////////////////////////////////
//TREND INDICATORS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//Trend EMA
tttradetrend = 'Only place BUY or SELL orders with the direction of the Trend EMA.'
tradetrendoption = input.bool(false, title='Only Tade with Trend', tooltip=tttradetrend,group=NeuralNetwork)
len111 = input.int(defval=200, minval=0, maxval=2000, title='Trend EMA Length',group=NeuralNetwork)
src111 = close
out111 = ta.ema(src111, len111)
//ma111 = plot(out111, title='EMA 200', linewidth=2, color=color.new(color.blue, 0), offset=0)
mabuy = out111 > out111[1]
masell = out111 < out111[1]
//5 EMAs////////////////////////////////////////////////////////////////////////
len1 = 9
src1 = close
out1 = ta.ema(src1, len1)
ema1color = out1 > out1[1] ? #00bcd4 : #e91e63
//ema1 = plot(out1, title='EMA 9', linewidth=3, color=color.new(ema1color, 50), offset=0, display=display.none)
//fill(price, ema1, title='EMA 9 Fill', color=color.new(ema1color, 90), editable=true)
len2 = 21
src2 = close
out2 = ta.ema(src2, len2)
ema2color = out2 > out2[1] ? #00bcd4 : #e91e63
//ema2 = plot(out2, title='EMA 21', linewidth=3, color=color.new(ema2color, 50), offset=0, display=display.none)
//fill(price, ema2, title='EMA 21 Fill', color=color.new(ema2color, 90), editable=true)
len3 = 55
src3 = close
out3 = ta.ema(src3, len3)
ema3color = out3 > out3[1] ? #00bcd4 : #e91e63
//ema3 = plot(out3, title='EMA 55', linewidth=3, color=color.new(ema3color, 50), offset=0, display=display.none)
//fill(price, ema3, title='EMA 55 Fill', color=color.new(ema3color, 90), editable=true)
len4 = 100
src4 = close
out4 = ta.ema(src4, len4)
ema4color = out4 > out4[1] ? #00bcd4 : #e91e63
//ema4 = plot(out4, title='EMA 100', linewidth=3, color=color.new(ema4color, 50), offset=0, display=display.none)
//fill(price, ema4, title='EMA 100 Fill', color=color.new(ema4color, 90), editable=true)
len5 = 200
src5 = close
out5 = ta.ema(src5, len5)
ema5color = out5 > out5[1] ? #00bcd4 : #e91e63
//ema5 = plot(out5, title='EMA 200', linewidth=3, color=color.new(ema5color, 50), offset=0, display=display.none)
//fill(price, ema5, title='EMA 200 Fill', color=color.new(ema5color, 90), editable=true)

//Supertrend////////////////////////////////////////////////////////////////////
atrPeriod = 10
factor = 3
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
//bodyMiddle = plot((open + close) / 2, display=display.none, title='Body Middle Line')
uptrend = direction < 0 and direction[1] > 0[1] ? supertrend : na
downtrend = direction > 0 and direction[1] < 0[1] ? supertrend : na
//fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
//fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
//bullishsupertrend = supertrend < close and supertrend[1] > close
//plotshape(uptrend, style=shape.labelup, color=color.green, location=location.belowbar, size=size.large)

//HMA///////////////////////////////////////////////////////////////////////////
len6 = 100
src6 = close
hma = ta.wma(2 * ta.wma(src6, len6 / 2) - ta.wma(src6, len6), math.floor(math.sqrt(len6)))
//hmacolor = close > hma ? #00bcd4 : #e91e63
//plot(hma, title='HMA Line', color=color.new(hmacolor, 25), linewidth=5)

//Parabolic SAR/////////////////////////////////////////////////////////////////
start = 0.02
increment = 0.01
maximum = 0.2
psarN = ta.sar(start, increment, maximum)
//plot(psar, "ParabolicSAR", style=plot.style_circles, color=#ffffff)


//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//MOMENTUM INCIDATORS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//RSI Divergence////////////////////////////////////////////////////////////////
len11 = 14
src11 = close
lbR11 = 2
lbL11 = 6
rangeUpper11 = 60
rangeLower11 = 5
plotBull11 = true
plotHiddenBull11 = false
plotBear11 = true
plotHiddenBear11 = false
bearColor11 = color.red
bullColor11 = color.green
hiddenBullColor11 = color.new(color.green, 80)
hiddenBearColor11 = color.new(color.red, 80)
textColor11 = color.white
noneColor11 = color.new(color.white, 100)
osc11 = ta.rsi(src11, len11)

//plot(osc11, title="RSI", linewidth=2, color=#2962FF)
//hline(50, title="Middle Line", color=#787B86, linestyle=hline.style_dotted)
//obLevel11 = hline(70, title="Overbought", color=#787B86, linestyle=hline.style_dotted)
//osLevel11 = hline(30, title="Oversold", color=#787B86, linestyle=hline.style_dotted)
//fill(obLevel11, osLevel11, title="Background", color=color.rgb(33, 150, 243, 90))

plFound11 = na(ta.pivotlow(osc11, lbL11, lbR11)) ? false : true
phFound11 = na(ta.pivothigh(osc11, lbL11, lbR11)) ? false : true
_inRange11(cond) =>
    bars11 = ta.barssince(cond == true)
    rangeLower11 <= bars11 and bars11 <= rangeUpper11

//Regular Bullish Divergence

//Osc: Higher Low
oscHL11 = osc11[lbR11] > ta.valuewhen(plFound11, osc11[lbR11], 1) and _inRange11(plFound11[1])
//Price: Lower Low
priceLL11 = low[lbR11] < ta.valuewhen(plFound11, low[lbR11], 1)

bullCond11 = plotBull11 and priceLL11 and oscHL11 and plFound11
//plot(plFound11 ? osc11[lbR11] : na, offset=-lbR11, title="Regular Bullish", linewidth=2, color=(bullCond11 ? bullColor11 : noneColor11))
//plotshape(bullCond11 ? osc11[lbR11] : na, offset=-lbR11, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor11, textcolor=textColor11)

//Hidden Bullish Divergence

//Osc: Lower Low
oscLL11 = osc11[lbR11] < ta.valuewhen(plFound11, osc11[lbR11], 1) and _inRange11(plFound11[1])
//Price: Higher Low
priceHL11 = low[lbR11] > ta.valuewhen(plFound11, low[lbR11], 1)

hiddenBullCond11 = plotHiddenBull11 and priceHL11 and oscLL11 and plFound11
//plot(plFound11 ? osc11[lbR11] : na, offset=-lbR11, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond11 ? hiddenBullColor11 : noneColor11))
//plotshape(hiddenBullCond11 ? osc11[lbR11] : na, offset=-lbR11, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor11, textcolor=textColor11)

//Regular Bearish Divergence

//Osc: Lower High
oscLH11 = osc11[lbR11] < ta.valuewhen(phFound11, osc11[lbR11], 1) and _inRange11(phFound11[1])
//Price: Higher High
priceHH11 = high[lbR11] > ta.valuewhen(phFound11, high[lbR11], 1)

bearCond11 = plotBear11 and priceHH11 and oscLH11 and phFound11
//plot(phFound11 ? osc11[lbR11] : na, offset=-lbR11, title="Regular Bearish", linewidth=2, color=(bearCond11 ? bearColor11 : noneColor11))
//plotshape(bearCond11 ? osc11[lbR11] : na, offset=-lbR11, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor11, textcolor=textColor11)

//Hidden Bearish Divergence

//Osc: Higher High
oscHH11 = osc11[lbR11] > ta.valuewhen(phFound11, osc11[lbR11], 1) and _inRange11(phFound11[1])
// Price: Lower High
priceLH11 = high[lbR11] < ta.valuewhen(phFound11, high[lbR11], 1)

hiddenBearCond11 = plotHiddenBear11 and priceLH11 and oscHH11 and phFound11
//plot(phFound11 ? osc11[lbR11] : na, offset=-lbR11, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond11 ? hiddenBearColor11 : noneColor11))
//plotshape(hiddenBearCond11 ? osc11[lbR11] : na, offset=-lbR11, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor11, textcolor=textColor11)

//MACD Divergence///////////////////////////////////////////////////////////////
fast_length12 = 12
slow_length12 = 26
src12 = close
signal_length12 = 9
sma_source12 = 'EMA'
sma_signal12 = 'EMA'
//Plot colors
col_macd12 = #2962FF
col_signal12 = #FF6D00
col_grow_above12 = #26A69A
col_fall_above12 = #B2DFDB
col_grow_below12 = #FFCDD2
col_fall_below12 = #FF5252
//Calculating
fast_ma12 = sma_source12 == 'SMA' ? ta.sma(src12, fast_length12) : ta.ema(src12, fast_length12)
slow_ma12 = sma_source12 == 'SMA' ? ta.sma(src12, slow_length12) : ta.ema(src12, slow_length12)
macd = fast_ma12 - slow_ma12
signal = sma_signal12 == 'SMA' ? ta.sma(macd, signal_length12) : ta.ema(macd, signal_length12)
hist = macd - signal
//plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above12 : col_fall_above12) : (hist[1] < hist ? col_grow_below12 : col_fall_below12)))
//plot(macd, title="MACD", color=col_macd12)
//plot(signal, title="Signal", color=col_signal12)

donttouchzero12 = true

lbR12 = 2
lbL12 = 6
rangeUpper12 = 60
rangeLower12 = 5
plotBull12 = true
plotHiddenBull12 = false
plotBear12 = true
plotHiddenBear12 = false
bearColor12 = color.red
bullColor12 = color.green
hiddenBullColor12 = color.new(color.green, 80)
hiddenBearColor12 = color.new(color.red, 80)
textColor12 = color.white
noneColor12 = color.new(color.white, 100)
osc12 = macd

plFound12 = na(ta.pivotlow(osc12, lbL12, lbR12)) ? false : true
phFound12 = na(ta.pivothigh(osc12, lbL12, lbR12)) ? false : true
_inRange12(cond) =>
    bars12 = ta.barssince(cond == true)
    rangeLower12 <= bars12 and bars12 <= rangeUpper12

//Regular Bullish Divergence

//Osc: Higher Low
oscHL12 = osc12[lbR12] > ta.valuewhen(plFound12, osc12[lbR12], 1) and _inRange12(plFound12[1]) and osc12[lbR12] < 0
// Price: Lower Low
priceLL12 = low[lbR12] < ta.valuewhen(plFound12, low[lbR12], 1)
priceHHZero12 = ta.highest(osc12, lbL12 + lbR12 + 5)
//plot(priceHHZero,title="priceHHZero",color=color.green)
blowzero12 = donttouchzero12 ? priceHHZero12 < 0 : true

bullCond12 = plotBull12 and priceLL12 and oscHL12 and plFound12 and blowzero12
//plot(plFound12 ? osc12[lbR12] : na, offset=-lbR12, title="Regular Bullish", linewidth=2, color=(bullCond12 ? bullColor12 : noneColor12))
//plotshape(bullCond12 ? osc12[lbR12] : na, offset=-lbR12, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor12, textcolor=textColor12)

//Hidden Bullish Divergence

//Osc: Lower Low
oscLL12 = osc12[lbR12] < ta.valuewhen(plFound12, osc12[lbR12], 1) and _inRange12(plFound12[1])
//Price: Higher Low
priceHL12 = low[lbR12] > ta.valuewhen(plFound12, low[lbR12], 1)

hiddenBullCond12 = plotHiddenBull12 and priceHL12 and oscLL12 and plFound12
//plot(plFound12 ? osc12[lbR12] : na, offset=-lbR12, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond12 ? hiddenBullColor12 : noneColor12))
//plotshape(hiddenBullCond12 ? osc12[lbR12] : na, offset=-lbR12, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor12, textcolor=textColor12)

//Regular Bearish Divergence

//Osc: Lower High
oscLH12 = osc12[lbR12] < ta.valuewhen(phFound12, osc12[lbR12], 1) and _inRange12(phFound12[1]) and osc12[lbR12] > 0
priceLLZero12 = ta.lowest(osc12, lbL12 + lbR12 + 5)
//plot(priceLLZero,title="priceLLZero", color=color.red)
bearzero12 = donttouchzero12 ? priceLLZero12 > 0 : true
//Price: Higher High
priceHH12 = high[lbR12] > ta.valuewhen(phFound12, high[lbR12], 1)

bearCond12 = plotBear12 and priceHH12 and oscLH12 and phFound12 and bearzero12
//plot(phFound12 ? osc12[lbR12] : na, offset=-lbR12, title="Regular Bearish", linewidth=2, color=(bearCond12 ? bearColor12 : noneColor12))
//plotshape(bearCond12 ? osc12[lbR12] : na, offset=-lbR12, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor12, textcolor=textColor12)

//Hidden Bearish Divergence

//Osc: Higher High
oscHH12 = osc12[lbR12] > ta.valuewhen(phFound12, osc12[lbR12], 1) and _inRange12(phFound12[1])
//Price: Lower High
priceLH12 = high[lbR12] < ta.valuewhen(phFound12, high[lbR12], 1)

hiddenBearCond12 = plotHiddenBear12 and priceLH12 and oscHH12 and phFound12
//plot(phFound12 ? osc12[lbR12] : na, offset=-lbR12, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond12 ? hiddenBearColor12 : noneColor12))
//plotshape(hiddenBearCond12 ? osc12[lbR12] : na, offset=-lbR12, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor12, textcolor=textColor12)


//Wave Trend Divergence/////////////////////////////////////////////////////////
n1W = 9
n2W = 12
apW = hlc3
esaW = ta.ema(ap, n1W)
d1W = ta.ema(math.abs(apW - esaW), n1W)
ciW = (apW - esaW) / (0.015 * d1W)
tciW = ta.ema(ciW, n2W)
hlineW = 0
wt1W = tciW
wt2W = ta.sma(wt1W, 4)

//plot(hline, color=color.gray)
//plot(wt1, color=color.white)
//plot(wt2, color=color.blue)


//Divergence
lbR13 = 2
lbL13 = 6
rangeUpper13 = 60
rangeLower13 = 5
plotBull13 = true
plotHiddenBull13 = false
plotBear13 = true
plotHiddenBear13 = false

bearColor13 = color.red
bullColor13 = color.green
hiddenBullColor13 = color.green
hiddenBearColor13 = color.red
textColor13 = color.white
noneColor13 = color.new(color.white, 100)

k13 = wt1
d13 = wt2
osc13 = k13

plFound13 = na(ta.pivotlow(osc13, lbL13, lbR13)) ? false : true
phFound13 = na(ta.pivothigh(osc13, lbL13, lbR13)) ? false : true

_inRange13(cond) =>
    bars13 = ta.barssince(cond == true)
    rangeLower13 <= bars13 and bars13 <= rangeUpper13

//Regular Bullish

//Osc: Higher Low
oscHL13 = osc13[lbR13] > ta.valuewhen(plFound13, osc13[lbR13], 1) and _inRange13(plFound13[1])

//Price: Lower Low
priceLL13 = low[lbR13] < ta.valuewhen(plFound13, low[lbR13], 1)

bullCond13 = plotBull13 and priceLL13 and oscHL13 and plFound13
//plot(plFound13 ? osc13[lbR13] : na, offset=-lbR13, title="Regular Bullish", linewidth=2, color=(bullCond13 ? bullColor13 : noneColor13))
//plotshape(bullCond13 ? osc13[lbR13] : na, offset=-lbR13, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor13, textcolor=textColor13)

//Hidden Bullish

//Osc: Lower Low
oscLL13 = osc13[lbR13] < ta.valuewhen(plFound13, osc13[lbR13], 1) and _inRange13(plFound13[1])

//Price: Higher Low
priceHL13 = low[lbR13] > ta.valuewhen(plFound13, low[lbR13], 1)

hiddenBullCond13 = plotHiddenBull13 and priceHL13 and oscLL13 and plFound13
//plot(plFound13 ? osc13[lbR13] : na, offset=-lbR13, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond13 ? hiddenBullColor13 : noneColor13))
//plotshape(hiddenBullCond13 ? osc13[lbR13] : na, offset=-lbR13, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor13, textcolor=textColor13)

//Regular Bearish

//Osc: Lower High
oscLH13 = osc13[lbR13] < ta.valuewhen(phFound13, osc13[lbR13], 1) and _inRange13(phFound13[1])

//Price: Higher High
priceHH13 = high[lbR13] > ta.valuewhen(phFound13, high[lbR13], 1)

bearCond13 = plotBear13 and priceHH13 and oscLH13 and phFound13
//plot(phFound13 ? osc13[lbR13] : na, offset=-lbR13, title="Regular Bearish", linewidth=2, color=(bearCond13 ? bearColor13 : noneColor13))
//plotshape(bearCond13 ? osc13[lbR13] : na, offset=-lbR13, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor13, textcolor=textColor13)

//Hidden Bearish

//Osc: Higher High
oscHH13 = osc13[lbR13] > ta.valuewhen(phFound13, osc13[lbR13], 1) and _inRange13(phFound13[1])

//Price: Lower High
priceLH13 = high[lbR13] < ta.valuewhen(phFound13, high[lbR13], 1)

hiddenBearCond13 = plotHiddenBear13 and priceLH13 and oscHH13 and phFound13
//plot(phFound13 ? osc13[lbR13] : na, offset=-lbR13, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond13 ? hiddenBearColor13 : noneColor13))
//plotshape(hiddenBearCond13 ? osc13[lbR13] : na, offset=-lbR13, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor13, textcolor=textColor13)


//Stochastic Divergence/////////////////////////////////////////////////////////
periodK14 = 14
smoothK14 = 3
periodD14 = 3
k14 = ta.sma(ta.stoch(close, high, low, periodK14), smoothK14)
d14 = ta.sma(k14, periodD14)
//plot(k14, title="%K", color=#2962FF)
//plot(d14, title="%D", color=#FF6D00)
//h0 = hline(80, "Upper Band", color=#787B86)
//h1 = hline(20, "Lower Band", color=#787B86)
//fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background")

//Divergence
lbR14 = 2
lbL14 = 6
rangeUpper14 = 60
rangeLower14 = 5
plotBull14 = true
plotHiddenBull14 = false
plotBear14 = true
plotHiddenBear14 = false

bearColor14 = color.red
bullColor14 = color.green
hiddenBullColor14 = color.green
hiddenBearColor14 = color.red
textColor14 = color.white
noneColor14 = color.new(color.white, 100)

osc14 = k14

plFound14 = na(ta.pivotlow(osc14, lbL14, lbR14)) ? false : true
phFound14 = na(ta.pivothigh(osc14, lbL14, lbR14)) ? false : true

_inRange14(cond) =>
    bars14 = ta.barssince(cond == true)
    rangeLower14 <= bars14 and bars14 <= rangeUpper14

//Regular Bullish

//Osc: Higher Low
oscHL14 = osc14[lbR14] > ta.valuewhen(plFound14, osc14[lbR14], 1) and _inRange14(plFound14[1])

//Price: Lower Low
priceLL14 = low[lbR14] < ta.valuewhen(plFound14, low[lbR14], 1)

bullCond14 = plotBull14 and priceLL14 and oscHL14 and plFound14
//plot(plFound14 ? osc14[lbR14] : na, offset=-lbR14, title="Regular Bullish", linewidth=2, color=(bullCond14 ? bullColor14 : noneColor14))
//plotshape(bullCond14 ? osc14[lbR14] : na, offset=-lbR14, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor14, textcolor=textColor14)

//Hidden Bullish

//Osc: Lower Low
oscLL14 = osc14[lbR14] < ta.valuewhen(plFound14, osc14[lbR14], 1) and _inRange14(plFound14[1])

//Price: Higher Low
priceHL14 = low[lbR14] > ta.valuewhen(plFound14, low[lbR14], 1)

hiddenBullCond14 = plotHiddenBull14 and priceHL14 and oscLL14 and plFound14
//plot(plFound14 ? osc14[lbR14] : na, offset=-lbR14, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond14 ? hiddenBullColor14 : noneColor14))
//plotshape(hiddenBullCond14 ? osc14[lbR14] : na, offset=-lbR14, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor14, textcolor=textColor14)

//Regular Bearish

//Osc: Lower High
oscLH14 = osc14[lbR14] < ta.valuewhen(phFound14, osc14[lbR14], 1) and _inRange14(phFound14[1])

//Price: Higher High
priceHH14 = high[lbR14] > ta.valuewhen(phFound14, high[lbR14], 1)

bearCond14 = plotBear14 and priceHH14 and oscLH14 and phFound14
//plot(phFound14 ? osc14[lbR14] : na, offset=-lbR14, title="Regular Bearish", linewidth=2, color=(bearCond14 ? bearColor14 : noneColor14))
//plotshape(bearCond14 ? osc14[lbR14] : na, offset=-lbR14, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor14, textcolor=textColor14)

//Hidden Bearish

//Osc: Higher High
oscHH14 = osc14[lbR14] > ta.valuewhen(phFound14, osc14[lbR14], 1) and _inRange14(phFound14[1])

//Price: Lower High
priceLH14 = high[lbR14] < ta.valuewhen(phFound14, high[lbR14], 1)

hiddenBearCond14 = plotHiddenBear14 and priceLH14 and oscHH14 and phFound14
//plot(phFound14 ? osc14[lbR14] : na, offset=-lbR14, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond14 ? hiddenBearColor14 : noneColor14))
//plotshape(hiddenBearCond14 ? osc14[lbR14] : na, offset=-lbR14, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor14, textcolor=textColor14)


//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//VOLATILITY INDICATORS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//Bollinger Bands///////////////////////////////////////////////////////////////
length1 = 20
src7 = close
mult1 = 2.0
basis = ta.sma(src7, length1)
devW = mult1 * ta.stdev(src7, length1)
upper = basis + devW
lower = basis - devW
offset = 0
//plot(basis, "Basis", color=#FF6D00, offset = offset)
//p1 = plot(upper, "Upper", color=#2962FF, offset = 0)
//p2 = plot(lower, "Lower", color=#2962FF, offset = 0)
//fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))


//Average True Range /////////////////////////////////////////////////
length2 = 1
mult2 = 1.85
showLabels = true
useClose = false
highlightState = false

atrN = mult2 * ta.atr(length2)

longStop = (useClose ? ta.highest(close, length2) : ta.highest(length2)) - atrN
longStopPrev = nz(longStop[1], longStop)
longStop := close[1] > longStopPrev ? math.max(longStop, longStopPrev) : longStop

shortStop = (useClose ? ta.lowest(close, length2) : ta.lowest(length2)) + atrN
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := close[1] < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop

var int dirN = 1
dirN := close > shortStopPrev ? 1 : close < longStopPrev ? -1 : dirN

var color longColor = color.green
var color shortColor = color.red

buySignal = dirN == 1 and dirN[1] == -1
//plotshape(buySignal and showLabels ? longStop : na, title="Gold Buy", text="Buy", location=location.belowbar, style=shape.labelup, size=size.tiny, color=longColor, textcolor=color.new(color.white, 0))

sellSignal = dirN == -1 and dirN[1] == 1
//plotshape(sellSignal and showLabels ? shortStop : na, title="Gold Sell", text="Sell", location=location.abovebar, style=shape.labeldown, size=size.tiny, color=shortColor, textcolor=color.new(color.white, 0))


//Relative Volatility Index Divergence//////////////////////////////////////////
length15 = 12
src15 = close
len15 = 14
stddev15 = ta.stdev(src15, length15)
upper15 = ta.ema(ta.change(src15) <= 0 ? 0 : stddev15, len15)
lower15 = ta.ema(ta.change(src15) > 0 ? 0 : stddev15, len15)
rvi = upper15 / (upper15 + lower15) * 100
//h0 = hline(80, "Upper Band", color=#787B86)
//h1 = hline(20, "Lower Band", color=#787B86)
//fill(h0, h1, color=color.rgb(126, 87, 194, 90), title="Background")
//plot(rvi15, title="RVI", color=#7E57C2, offset = offset)

//Divergence
lbR15 = 2
lbL15 = 6
rangeUpper15 = 60
rangeLower15 = 5
plotBull15 = true
plotHiddenBull15 = false
plotBear15 = true
plotHiddenBear15 = false

bearColor15 = color.red
bullColor15 = color.green
hiddenBullColor15 = color.green
hiddenBearColor15 = color.red
textColor15 = color.white
noneColor15 = color.new(color.white, 100)

d15 = rvi
osc15 = d15

plFound15 = na(ta.pivotlow(osc15, lbL15, lbR15)) ? false : true
phFound15 = na(ta.pivothigh(osc15, lbL15, lbR15)) ? false : true

_inRange15(cond) =>
    bars15 = ta.barssince(cond == true)
    rangeLower15 <= bars15 and bars15 <= rangeUpper15

//Regular Bullish

//Osc: Higher Low
oscHL15 = osc15[lbR15] > ta.valuewhen(plFound15, osc15[lbR15], 1) and _inRange15(plFound15[1])

//Price: Lower Low
priceLL15 = low[lbR15] < ta.valuewhen(plFound15, low[lbR15], 1)

bullCond15 = plotBull15 and priceLL15 and oscHL15 and plFound15
//plot(plFound15 ? osc15[lbR15] : na, offset=-lbR15, title="Regular Bullish", linewidth=2, color=(bullCond15 ? bullColor15 : noneColor15))
//plotshape(bullCond15 ? osc15[lbR15] : na, offset=-lbR15, title="Regular Bullish Label", text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor15, textcolor=textColor15)

//Hidden Bullish

//Osc: Lower Low
oscLL15 = osc15[lbR15] < ta.valuewhen(plFound15, osc15[lbR15], 1) and _inRange15(plFound15[1])

//Price: Higher Low
priceHL15 = low[lbR15] > ta.valuewhen(plFound15, low[lbR15], 1)

hiddenBullCond15 = plotHiddenBull15 and priceHL15 and oscLL15 and plFound15
//plot(plFound15 ? osc15[lbR15] : na, offset=-lbR15, title="Hidden Bullish", linewidth=2, color=(hiddenBullCond15 ? hiddenBullColor15 : noneColor15))
//plotshape(hiddenBullCond15 ? osc15[lbR15] : na, offset=-lbR15, title="Hidden Bullish Label", text=" H Bull ", style=shape.labelup, location=location.absolute, color=bullColor15, textcolor=textColor15)

//Regular Bearish

//Osc: Lower High
oscLH15 = osc15[lbR15] < ta.valuewhen(phFound15, osc15[lbR15], 1) and _inRange15(phFound15[1])

//Price: Higher High
priceHH15 = high[lbR15] > ta.valuewhen(phFound15, high[lbR15], 1)

bearCond15 = plotBear15 and priceHH15 and oscLH15 and phFound15
//plot(phFound15 ? osc15[lbR15] : na, offset=-lbR15, title="Regular Bearish", linewidth=2, color=(bearCond15 ? bearColor15 : noneColor15))
//plotshape(bearCond15 ? osc15[lbR15] : na, offset=-lbR15, title="Regular Bearish Label", text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor15, textcolor=textColor15)

//Hidden Bearish

//Osc: Higher High
oscHH15 = osc15[lbR15] > ta.valuewhen(phFound15, osc15[lbR15], 1) and _inRange15(phFound15[1])

//Price: Lower High
priceLH15 = high[lbR15] < ta.valuewhen(phFound15, high[lbR15], 1)

hiddenBearCond15 = plotHiddenBear15 and priceLH15 and oscHH15 and phFound15
//plot(phFound15 ? osc15[lbR15] : na, offset=-lbR15, title="Hidden Bearish", linewidth=2, color=(hiddenBearCond15 ? hiddenBearColor15 : noneColor15))
//plotshape(hiddenBearCond15 ? osc15[lbR15] : na, offset=-lbR15, title="Hidden Bearish Label", text=" H Bear ", style=shape.labeldown, location=location.absolute, color=bearColor15, textcolor=textColor15)

//Support and Resistance////////////////////////////////////////////////////////
left16 = 200
right16 = 20
quick_right16 = 5
src16 = 'Close'

pivothigh_1 = ta.pivothigh(close, left16, right16)
pivothigh_2 = ta.pivothigh(high, left16, right16)
pivot_high16 = src16 == 'Close' ? pivothigh_1 : pivothigh_2
pivotlow_1 = ta.pivotlow(close, left16, right16)
pivotlow_2 = ta.pivotlow(low, left16, right16)
pivot_lows16 = src16 == 'Close' ? pivotlow_1 : pivotlow_2

pivothigh_3 = ta.pivothigh(close, left16, quick_right16)
pivothigh_4 = ta.pivothigh(high, left16, quick_right16)
quick_pivot_high16 = src16 == 'Close' ? pivothigh_3 : pivothigh_4
pivotlow_3 = ta.pivotlow(close, left16, quick_right16)
pivotlow_4 = ta.pivotlow(low, left16, quick_right16)
quick_pivot_lows16 = src16 == 'Close' ? pivotlow_3 : pivotlow_4

valuewhen_1 = ta.valuewhen(quick_pivot_high16, close[quick_right16], 0)
valuewhen_2 = ta.valuewhen(quick_pivot_high16, high[quick_right16], 0)
level1 = src16 == 'Close' ? valuewhen_1 : valuewhen_2
valuewhen_3 = ta.valuewhen(quick_pivot_lows16, close[quick_right16], 0)
valuewhen_4 = ta.valuewhen(quick_pivot_lows16, low[quick_right16], 0)
level2 = src16 == 'Close' ? valuewhen_3 : valuewhen_4
valuewhen_5 = ta.valuewhen(pivot_high16, close[right16], 0)
valuewhen_6 = ta.valuewhen(pivot_high16, high[right16], 0)
level3 = src16 == 'Close' ? valuewhen_5 : valuewhen_6
valuewhen_7 = ta.valuewhen(pivot_lows16, close[right16], 0)
valuewhen_8 = ta.valuewhen(pivot_lows16, low[right16], 0)
level4 = src16 == 'Close' ? valuewhen_7 : valuewhen_8
valuewhen_9 = ta.valuewhen(pivot_high16, close[right16], 1)
valuewhen_10 = ta.valuewhen(pivot_high16, high[right16], 1)
level5 = src16 == 'Close' ? valuewhen_9 : valuewhen_10
valuewhen_11 = ta.valuewhen(pivot_lows16, close[right16], 1)
valuewhen_12 = ta.valuewhen(pivot_lows16, low[right16], 1)
level6 = src16 == 'Close' ? valuewhen_11 : valuewhen_12
valuewhen_13 = ta.valuewhen(pivot_high16, close[right16], 2)
valuewhen_14 = ta.valuewhen(pivot_high16, high[right16], 2)
level7 = src16 == 'Close' ? valuewhen_13 : valuewhen_14
valuewhen_15 = ta.valuewhen(pivot_lows16, close[right16], 2)
valuewhen_16 = ta.valuewhen(pivot_lows16, low[right16], 2)
level8 = src16 == 'Close' ? valuewhen_15 : valuewhen_16

level1_col = close >= level1 ? color.green : color.red
level2_col = close >= level2 ? color.green : color.red
level3_col = close >= level3 ? color.green : color.red
level4_col = close >= level4 ? color.green : color.red
level5_col = close >= level5 ? color.green : color.red
level6_col = close >= level6 ? color.green : color.red
level7_col = close >= level7 ? color.green : color.red
level8_col = close >= level8 ? color.green : color.red

length17 = 9
src17 = close
hma17 = ta.wma(2 * ta.wma(src17, length17 / 2) - ta.wma(src17, length17), math.floor(math.sqrt(length17)))

buy1 = hma17 > level1 and hma17[1] < level1[1] and close > close[2]
buy2 = hma17 > level2 and hma17[1] < level2[1] and close > close[2]
buy3 = hma17 > level3 and hma17[1] < level3[1] and close > close[2]
buy4 = hma17 > level4 and hma17[1] < level4[1] and close > close[2]
buy5 = hma17 > level5 and hma17[1] < level5[1] and close > close[2]
buy6 = hma17 > level6 and hma17[1] < level6[1] and close > close[2]
buy7 = hma17 > level7 and hma17[1] < level7[1] and close > close[2]
buy8 = hma17 > level8 and hma17[1] < level8[1] and close > close[2]

sell1 = hma17 < level1 and hma17[1] > level1[1] and close < close[2]
sell2 = hma17 < level2 and hma17[1] > level2[1] and close < close[2]
sell3 = hma17 < level3 and hma17[1] > level3[1] and close < close[2]
sell4 = hma17 < level4 and hma17[1] > level4[1] and close < close[2]
sell5 = hma17 < level5 and hma17[1] > level5[1] and close < close[2]
sell6 = hma17 < level6 and hma17[1] > level6[1] and close < close[2]
sell7 = hma17 < level7 and hma17[1] > level7[1] and close < close[2]
sell8 = hma17 < level8 and hma17[1] > level8[1] and close < close[2]


//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//VOLUME INDICATORS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//OBV Divergence////////////////////////////////////////////////////////////////
len18 = 20
src18 = close
lbR18 = 2
lbL18 = 6
rangeUpper18 = 60
rangeLower18 = 5
plotBull18 = true
plotHiddenBull18 = false
plotBear18 = true
plotHiddenBear18 = false


bearColor18 = color.red
bullColor18 = color.green
hiddenBullColor18 = color.green
hiddenBearColor18 = color.new(color.red, 80)
textColor18 = color.white
noneColor18 = color.new(color.white, 100)

csrc = ta.change(src18)
obv1(src18) =>
    ta.cum(ta.change(src18) > 0 ? volume : csrc < 0 ? -volume : 0 * volume)
os = obv1(src18)
obv_osc = os - ta.ema(os, len18)
obc_color = obv_osc > 0 ? color.green : color.red
//plot(obv_osc, color=obc_color, style=plot.style_line,title="OBV-Points", linewidth=2)
//plot(obv_osc, color=color.silver, transp=70, title="OBV", style=plot.style_area)
//hline(0)

plFound18 = na(ta.pivotlow(obv_osc, lbL18, lbR18)) ? false : true
phFound18 = na(ta.pivothigh(obv_osc, lbL18, lbR18)) ? false : true

_inRange(cond) =>
    bars = ta.barssince(cond == true)
    rangeLower18 <= bars and bars <= rangeUpper18

// Regular Bullish

// Osc: Higher Low
oscHL18 = obv_osc[lbR18] > ta.valuewhen(plFound18, obv_osc[lbR18], 1) and _inRange(plFound18[1])

// Price: Lower Low
priceLL18 = low[lbR18] < ta.valuewhen(plFound18, low[lbR18], 1)
bullCond18 = plotBull18 and priceLL18 and oscHL18 and plFound18
//plot(plFound18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Regular Bullish",linewidth=2,color=(bullCond18 ? bullColor18 : noneColor18))
//plotshape(bullCond18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Regular Bullish Label",text=" Bull ",style=shape.labelup,location=location.absolute,color=bullColor18,textcolor=textColor18)

// Hidden Bullish

// Osc: Lower Low
oscLL18 = obv_osc[lbR18] < ta.valuewhen(plFound18, obv_osc[lbR18], 1) and _inRange(plFound18[1])

// Price: Higher Low
priceHL18 = low[lbR18] > ta.valuewhen(plFound18, low[lbR18], 1)
hiddenBullCond18 = plotHiddenBull18 and priceHL18 and oscLL18 and plFound18
//plot(plFound18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Hidden Bullish",linewidth=2,color=(hiddenBullCond18 ? hiddenBullColor18 : noneColor18))
//plotshape(hiddenBullCond18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Hidden Bullish Label",text=" H Bull ",style=shape.labelup,location=location.absolute,color=bullColor18,textcolor=textColor18)

// Regular Bearish

// Osc: Lower High
oscLH18 = obv_osc[lbR18] < ta.valuewhen(phFound18, obv_osc[lbR18], 1) and _inRange(phFound18[1])

// Price: Higher High
priceHH18 = high[lbR18] > ta.valuewhen(phFound18, high[lbR18], 1)
bearCond18 = plotBear18 and priceHH18 and oscLH18 and phFound18
//plot(phFound18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Regular Bearish",linewidth=2,color=(bearCond18 ? bearColor18 : noneColor18))
//plotshape(bearCond18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Regular Bearish Label",text=" Bear ",style=shape.labeldown,location=location.absolute,color=bearColor18,textcolor=textColor18)

// Hidden Bearish

// Osc: Higher High
oscHH18 = obv_osc[lbR18] > ta.valuewhen(phFound18, obv_osc[lbR18], 1) and _inRange(phFound18[1])

// Price: Lower High
priceLH18 = high[lbR18] < ta.valuewhen(phFound18, high[lbR18], 1)
hiddenBearCond18 = plotHiddenBear18 and priceLH18 and oscHH18 and phFound18
//plot(phFound18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Hidden Bearish",linewidth=2,color=(hiddenBearCond18 ? hiddenBearColor18 : noneColor18))
//plotshape(hiddenBearCond18 ? obv_osc[lbR18] : na,offset=-lbR18,title="Hidden Bearish Label",text=" H Bear ",style=shape.labeldown,location=location.absolute,color=bearColor18,textcolor=textColor18)


//Chaikin Money Flow////////////////////////////////////////////////////////////
length19 = 50
ad19 = close == high and close == low or high == low ? 0 : (2 * close - low - high) / (high - low) * volume
cmf = math.sum(ad19, length19) / math.sum(volume, length19)
//plot(cmf, color=#43A047, title="MF")
//hline(0, color=#787B86, title="Zero", linestyle=hline.style_dashed)

//VWAP//////////////////////////////////////////////////////////////////////////
computeVWAP(src20, isNewPeriod, stDevMultiplier) =>
    var float sumSrcVol = na
    var float sumVol = na
    var float sumSrcSrcVol = na

    sumSrcVol := isNewPeriod ? src20 * volume : src20 * volume + sumSrcVol[1]
    sumVol := isNewPeriod ? volume : volume + sumVol[1]
    // sumSrcSrcVol calculates the dividend of the equation that is later used to calculate the standard deviation
    sumSrcSrcVol := isNewPeriod ? volume * math.pow(src20, 2) : volume * math.pow(src20, 2) + sumSrcSrcVol[1]

    _vwap = sumSrcVol / sumVol
    variance = sumSrcSrcVol / sumVol - math.pow(_vwap, 2)
    variance := variance < 0 ? 0 : variance
    stDev = math.sqrt(variance)

    lowerBand20 = _vwap - stDev * stDevMultiplier
    upperBand20 = _vwap + stDev * stDevMultiplier

    [_vwap, lowerBand20, upperBand20]

hideonDWM = false
var anchor = 'Session'
src20 = hlc3
offset20 = 0

showBands = true
stdevMult = 1.0

timeChange(period) =>
    ta.change(time(period))

new_earnings = request.earnings(syminfo.tickerid, earnings.actual, barmerge.gaps_on, barmerge.lookahead_on)
new_dividends = request.dividends(syminfo.tickerid, dividends.gross, barmerge.gaps_on, barmerge.lookahead_on)
new_split = request.splits(syminfo.tickerid, splits.denominator, barmerge.gaps_on, barmerge.lookahead_on)

tcD = timeChange('D')
tcW = timeChange('W')
tcM = timeChange('M')
tc3M = timeChange('3M')
tc12M = timeChange('12M')

isNewPeriod = anchor == 'Earnings' ? new_earnings : anchor == 'Dividends' ? new_dividends : anchor == 'Splits' ? new_split : na(src20[1]) ? true : anchor == 'Session' ? tcD : anchor == 'Week' ? tcW : anchor == 'Month' ? tcM : anchor == 'Quarter' ? tc3M : anchor == 'Year' ? tc12M : anchor == 'Decade' ? tc12M and year % 10 == 0 : anchor == 'Century' ? tc12M and year % 100 == 0 : false

float vwapValue = na
float std = na
float upperBandValue = na
float lowerBandValue = na

if not(hideonDWM and timeframe.isdwm)
    [_vwap, bottom, top] = computeVWAP(src20, isNewPeriod, stdevMult)
    vwapValue := _vwap
    upperBandValue := showBands ? top : na
    lowerBandValue := showBands ? bottom : na
    lowerBandValue

//plot(vwapValue, title="VWAP", color=#2962FF, offset=offset)

//upperBand20 = plot(upperBandValue, title="Upper Band", color=color.green, offset=offset)
//lowerBand20 = plot(lowerBandValue, title="Lower Band", color=color.green, offset=offset)

//fill(upperBand20, lowerBand20, title="Bands Fill", color= showBands ? color.new(color.green, 95) : na)

//Candle Patterns///////////////////////////////////////////////////////////////

//Bullish Engulfing
C_DownTrend = true
C_UpTrend = true
var trendRule1 = 'SMA50'
var trendRule2 = 'SMA50, SMA200'
var trendRule = trendRule1

if trendRule == trendRule1
    priceAvg = ta.sma(close, 50)
    C_DownTrend := close < priceAvg
    C_UpTrend := close > priceAvg
    C_UpTrend

if trendRule == trendRule2
    sma200 = ta.sma(close, 200)
    sma50 = ta.sma(close, 50)
    C_DownTrend := close < sma50 and sma50 < sma200
    C_UpTrend := close > sma50 and sma50 > sma200
    C_UpTrend
C_Len = 14  // ema depth for bodyAvg
C_ShadowPercent = 5.0  // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0  // shows the number of times the shadow dominates the candlestick body

C_BodyHi = math.max(close, open)
C_BodyLo = math.min(close, open)
C_Body = C_BodyHi - C_BodyLo
C_BodyAvg = ta.ema(C_Body, C_Len)
C_SmallBody = C_Body < C_BodyAvg
C_LongBody = C_Body > C_BodyAvg
C_UpShadow = high - C_BodyHi
C_DnShadow = C_BodyLo - low
C_HasUpShadow = C_UpShadow > C_ShadowPercent / 100 * C_Body
C_HasDnShadow = C_DnShadow > C_ShadowPercent / 100 * C_Body
C_WhiteBody = open < close
C_BlackBody = open > close
C_Range = high - low
C_IsInsideBar = C_BodyHi[1] > C_BodyHi and C_BodyLo[1] < C_BodyLo
C_BodyMiddle = C_Body / 2 + C_BodyLo
C_ShadowEquals = C_UpShadow == C_DnShadow or math.abs(C_UpShadow - C_DnShadow) / C_DnShadow * 100 < C_ShadowEqualsPercent and math.abs(C_DnShadow - C_UpShadow) / C_UpShadow * 100 < C_ShadowEqualsPercent
C_IsDojiBody = C_Range > 0 and C_Body <= C_Range * C_DojiBodyPercent / 100
C_Doji = C_IsDojiBody and C_ShadowEquals

patternLabelPosLow = low - ta.atr(30) * 0.6
patternLabelPosHigh = high + ta.atr(30) * 0.6

label_color_bullish = color.blue
C_EngulfingBullishNumberOfCandles = 2
C_EngulfingBullish = C_DownTrend and C_WhiteBody and C_LongBody and C_BlackBody[1] and C_SmallBody[1] and close >= open[1] and open <= close[1] and (close > open[1] or open < close[1])
if C_EngulfingBullish
    var ttBullishEngulfing = 'Engulfing\nAt the end of a given downward trend, there will most likely be a reversal pattern. To distinguish the first day, this candlestick pattern uses a small body, followed by a day where the candle body fully overtakes the body from the day before, and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to completely overtake the range (high to low), rather only the open and the close.'
    ttBullishEngulfing
    //label.new(bar_index, patternLabelPosLow, text="BE", style=label.style_label_up, color = label_color_bullish, textcolor=color.white, tooltip = ttBullishEngulfing)
//bgcolor(highest(C_EngulfingBullish?1:0, C_EngulfingBullishNumberOfCandles)!=0 ? color.blue : na, offset=-(C_EngulfingBullishNumberOfCandles-1))

//Bearish Engulfing
label_color_bearish = color.red
C_EngulfingBearishNumberOfCandles = 2
C_EngulfingBearish = C_UpTrend and C_BlackBody and C_LongBody and C_WhiteBody[1] and C_SmallBody[1] and close <= open[1] and open >= close[1] and (close < open[1] or open > close[1])
if C_EngulfingBearish
    var ttBearishEngulfing = 'Engulfing\nAt the end of a given uptrend, a reversal pattern will most likely appear. During the first day, this candlestick pattern uses a small body. It is then followed by a day where the candle body fully overtakes the body from the day before it and closes in the trend’s opposite direction. Although similar to the outside reversal chart pattern, it is not essential for this pattern to fully overtake the range (high to low), rather only the open and the close.'
    ttBearishEngulfing
    //label.new(bar_index, patternLabelPosHigh, text="BE", style=label.style_label_down, color = label_color_bearish, textcolor=color.white, tooltip = ttBearishEngulfing)
//bgcolor(highest(C_EngulfingBearish?1:0, C_EngulfingBearishNumberOfCandles)!=0 ? color.red : na, offset=-(C_EngulfingBearishNumberOfCandles-1))


//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//SIGNAL SCORES▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//Alternate Signals Option
alternatesignals = input(title='Alternate Signals', defval=true)

//Position Options
longpositions = input(title='Long Positions', defval=false)
shortpositions = input(title='Short Positions', defval=false)

//Stop Loss Warning Option
stoplosspercent = input.float(title='Stop Loss Warning (%)', defval=-2.5, minval=-50, maxval=0, step=.1) / 100

//Score Requirements
stronglongscore = input.int(defval=10, minval=0, maxval=1000, title='Required Strong LONG Score')
strongshortscore = input.int(defval=10, minval=0, maxval=1000, title='Required Strong SHORT Score')
weaklongscore = input.int(defval=8, minval=0, maxval=1000, title='Required Weak LONG Score')
weakshortscore = input.int(defval=8, minval=0, maxval=1000, title='Required Weak SHORT Score')

//Trend Indicator Signals///////////////////////////////////////////////////////

//EMA Signals
emadirectionimportance = input.int(defval=2, minval=0, maxval=100, title='EMA Trend Direction Importance')
emadirectionup = out5 < close ? emadirectionimportance : 0
emadirectionupstatus = emadirectionup ? 'EMA Trend Direction Up' : na
emadirectiondown = out5 > close ? emadirectionimportance : 0
emadirectiondownstatus = emadirectiondown ? 'EMA Trend Direction Down' : na

emapushpullimportance = input.int(defval=1, minval=0, maxval=100, title='EMA Pressure Importance')
emapushup = out2 > out2[1] and out3 < out3[1] ? emapushpullimportance : 0
emapushupstatus = emapushup ? 'EMA Pushing Up' : na
emapulldown = out2 < out2[1] and out3 > out3[1] ? emapushpullimportance : 0
emapulldownstatus = emapulldown ? 'EMA Pulling Down' : na

//Super Trend Signals
supertrenddirimportance = input.int(defval=2, minval=0, maxval=100, title='SuperTrend Direction Importance')
supertrendup = direction < 0 ? supertrenddirimportance : 0
supertrendupstatus = supertrendup ? 'SuperTrend Direction Up' : na
supertrenddown = direction > 0 ? supertrenddirimportance : 0
supertrenddownstatus = supertrenddown ? 'SuperTrend Direction Down' : na

supertrendrevimportance = input.int(defval=4, minval=0, maxval=100, title='SuperTrend Reversal Importance')
supertrendrevup = direction < 0 and direction[1] > 0[1] ? supertrendrevimportance : 0
supertrendrevupstatus = supertrendrevup ? 'SuperTrend Reversed Up' : na
supertrendrevdown = direction > 0 and direction[1] < 0[1] ? supertrendrevimportance : 0
supertrendrevdownstatus = supertrendrevdown ? 'SuperTrend Reversed Down' : na

//Parabolic SAR Signals
psardirimportance = input.int(defval=0, minval=0, maxval=100, title='Parabolic SAR Direction Importance')
psardirup = psar < close ? psardirimportance : 0
psardirupstatus = psardirup ? 'PSAR Direction Up' : na
psardirdown = psar > close ? psardirimportance : 0
psardirdownstatus = psardirdown ? 'PSAR Direction Down' : na

psarrevimportance = input.int(defval=3, minval=0, maxval=100, title='Parabolic SAR Reversal Importance')
psarrevup = psar < close and psar[1] > close[1] ? psarrevimportance : 0
psarrevupstatus = psarrevup ? 'PSAR Reversed Up' : na
psarrevdown = psar > close and psar[1] < close ? psarrevimportance : 0
psarrevdownstatus = psarrevdown ? 'PSAR Reversed Down' : na

//HMA Signals
hmacloseposimportance = input.int(defval=1, minval=0, maxval=100, title='HMA Trend Direction Importance')
hmacloseposup = hma < close and hma[1] ? hmacloseposimportance : 0
hmacloseposupstatus = hmacloseposup ? 'Price Crossed Over HMA' : na
hmacloseposdown = hma > close ? hmacloseposimportance : 0
hmacloseposdownstatus = hmacloseposdown ? 'Price Crossed Under HMA' : na

hmapivotimportance = input.int(defval=4, minval=0, maxval=100, title='HMA Pivot Importance')
hmapivotup = hma > hma[1] and hma[1] < hma[2] ? hmapivotimportance : 0
hmapivotupstatus = hmapivotup ? 'HMA Pivot Up' : na
hmapivotdown = hma < hma[1] and hma[1] > hma[2] ? hmapivotimportance : 0
hmapivotdownstatus = hmapivotdown ? 'HMA Pivot Down' : na

//Momentum Indicator Signals////////////////////////////////////////////////////

//RSI Signals
rsidivimportance = input.int(defval=4, minval=0, maxval=100, title='RSI Divergence Importance')
rsidivup = bullCond11 or bullCond11[1] or bullCond11[2] ? rsidivimportance : 0
rsidivupstatus = rsidivup ? 'Bullish RSI Divergence' : na
rsidivdown = bearCond11 or bearCond11[1] or bearCond11[2] ? rsidivimportance : 0
rsidivdownstatus = rsidivdown ? 'Bearish RSI Divergence' : na

rsilevelimportance = input.int(defval=0, minval=0, maxval=100, title='RSI Level Importance')
rsioversold = osc11 < 30 ? rsilevelimportance : 0
rsioversoldstatus = rsioversold ? 'RSI Oversold' : na
rsioverbought = osc11 > 70 ? rsilevelimportance : 0
rsioverboughtstatus = rsioverbought ? 'RSI Overbought' : na

rsidirectionimportance = input.int(defval=1, minval=0, maxval=100, title='RSI Cross 50-Line Importance')
rsicrossup = osc11 > 50 and osc11[1] < 50 or osc11 > 50 and osc11[2] < 50 ? rsidirectionimportance : 0
rsicrossupstatus = rsicrossup ? 'RSI Crossed 50-Line Up' : na
rsicrossdown = osc11 < 50 and osc11[1] > 50 or osc11 < 50 and osc11[2] > 50 ? rsidirectionimportance : 0
rsicrossdownstatus = rsicrossdown ? 'RSI Crossed 50-Line Down' : na

//MACD Signals
macddivimportance = input.int(defval=2, minval=0, maxval=100, title='MACD Divergence Importance')
macddivup = bullCond12 or bullCond12[1] or bullCond12[2] ? macddivimportance : 0
macddivupstatus = macddivup ? 'Bullish MACD Divergence' : na
macddivdown = bearCond12 or bearCond12[1] or bearCond12[2] ? macddivimportance : 0
macddivdownstatus = macddivdown ? 'Bearish MACD Divergence' : na

histpivotimportance = input.int(defval=1, minval=0, maxval=100, title='MACD Histogram Pivot Importance')
histpivotup = hist > hist[1] and hist[1] < hist[2] and hist < 0 ? histpivotimportance : 0
histpivotupstatus = histpivotup ? 'MACD Histogram Pivot Up' : na
histpivotdown = hist < hist[1] and hist[1] > hist[2] and hist > 0 ? histpivotimportance : 0
histpivotdownstatus = histpivotdown ? 'MACD Histogram Pivot Down' : na

macdcrosssignalimportance = input.int(defval=1, minval=0, maxval=100, title='MACD Cross Signal Importance')
macdcrosssignalup = macd > signal and macd[1] < signal[1] and signal < 0 ? macdcrosssignalimportance : 0
macdcrosssignalupstatus = macdcrosssignalup ? 'MACD Crossed Signal Up' : na
macdcrosssignaldown = macd < signal and macd[1] > signal[1] and signal > 0 ? macdcrosssignalimportance : 0
macdcrosssignaldownstatus = macdcrosssignaldown ? 'MACD Crossed Signal Down' : na

//WaveTrend Signals
wtdivimportance = input.int(defval=1, minval=0, maxval=100, title='WaveTrend Divergence Importance')
wtdivup = bullCond13 or bullCond13[1] or bullCond13[2] ? wtdivimportance : 0
wtdivupstatus = wtdivup ? 'Bullish WaveTrend Divergence' : na
wtdivdown = bearCond13 or bearCond13[1] or bearCond13[2] ? wtdivimportance : 0
wtdivdownstatus = wtdivdown ? 'Bearish WaveTrend Divergence' : na

wtcrosssignalimportance = input.int(defval=4, minval=0, maxval=100, title='WaveTrend Cross Signal Importance')
wtcrosssignalup = wt1 > wt2 and wt1[1] < wt2[1] and wt2 < -10 ? wtcrosssignalimportance : 0
wtcrosssignalupstatus = wtcrosssignalup ? 'WaveTrend Crossed Signal Up' : na
wtcrosssignaldown = wt1 < wt2 and wt1[1] > wt2[1] and wt2 > 10 ? wtcrosssignalimportance : 0
wtcrosssignaldownstatus = wtcrosssignaldown ? 'WaveTrend Crossed Signal Down' : na

//Stochastic Signals
sdivimportance = input.int(defval=1, minval=0, maxval=100, title='Stochastic Divergence Importance')
sdivup = bullCond14 or bullCond14[1] or bullCond14[2] ? sdivimportance : 0
sdivupstatus = sdivup ? 'Bullish Stoch Divergence' : na
sdivdown = bearCond14 or bearCond14[1] or bearCond14[2] ? sdivimportance : 0
sdivdownstatus = sdivdown ? 'Bearish Stoch Divergence' : na

scrosssignalimportance = input.int(defval=1, minval=0, maxval=100, title='Stoch Cross Signal Importance')
scrosssignalup = k14 > d14 and k14[1] < d14[1] ? scrosssignalimportance : 0
scrosssignalupstatus = scrosssignalup ? 'Stoch Crossed Signal Up' : na
scrosssignaldown = k14 < d14 and k14[1] > d14[1] ? scrosssignalimportance : 0
scrosssignaldownstatus = scrosssignaldown ? 'Stoch Crossed Signal Down' : na


//Volatility Indicators/////////////////////////////////////////////////////////

//Bollinger Bands Signals
bbcontimportance = input.int(defval=2, minval=0, maxval=100, title='BollingerBands Contact Importance')
bbcontup = close < lower ? bbcontimportance : 0
bbcontupstatus = bbcontup ? 'Price Contacted Lower BB' : na
bbcontdown = open > upper ? bbcontimportance : 0
bbcontdownstatus = bbcontdown ? 'Price Contacted Upper BB' : na

//Average True Range Signals
atrrevimportance = input.int(defval=1, minval=0, maxval=100, title='ATR Reversal Importance')
atrrevup = buySignal ? atrrevimportance : 0
atrrevupstatus = atrrevup ? 'ATR Reversed Up' : na
atrrevdown = sellSignal ? atrrevimportance : 0
atrrevdownstatus = atrrevdown ? 'ATR Reversed Down' : na

//Relative Volatility Index Signals
rviposimportance = input.int(defval=3, minval=0, maxval=100, title='RVI Position Importance')
rviposup = rvi > 25 and rvi[1] < 40 ? rviposimportance : 0
rviposupstatus = rviposup ? 'RVI Volatility Increasing' : na
rviposdown = rvi < 75 and rvi[1] > 60 ? rviposimportance : 0
rviposdownstatus = rviposdown ? 'RVI Volatility Decreasing' : na

rvidivimportance = input.int(defval=4, minval=0, maxval=100, title='RVI Divergence Importance')
rvidivup = bullCond15 or bullCond15[1] or bullCond15[2] ? rvidivimportance : 0
rvidivupstatus = rvidivup ? 'Bullish RVI Divergence' : na
rvidivdown = bearCond15 or bearCond15[1] or bearCond15[2] ? rvidivimportance : 0
rvidivdownstatus = rvidivdown ? 'Bearish RVI Divergence' : na

//Support and Resistance Signals
srcrossimportance = input.int(defval=0, minval=0, maxval=100, title='Support/Resistance Cross Importance')
srcrossup = buy1 or buy2 or buy3 or buy4 or buy5 or buy6 or buy7 or buy8 ? srcrossimportance : 0
srcrossupstatus = srcrossup ? 'Crossed Key Level Up' : na
srcrossdown = sell1 or sell2 or sell3 or sell4 or sell5 or sell6 or sell7 or sell8 ? srcrossimportance : 0
srcrossdownstatus = srcrossdown ? 'Crossed Key Level Down' : na

//Volume Indicator Signals//////////////////////////////////////////////////////

//On Balance Volume Divergence Signals
obvdivimportance = input.int(defval=0, minval=0, maxval=100, title='OBV Divergence Importance')
obvdivup = bullCond18 or bullCond18[1] or bullCond18[2] ? obvdivimportance : 0
obvdivupstatus = obvdivup ? 'Bullish OBV Divergence' : na
obvdivdown = bearCond18 or bearCond18[1] or bearCond18[2] ? obvdivimportance : 0
obvdivdownstatus = obvdivdown ? 'Bearish OBV Divergence' : na

//Chaikin Money Flow Signals
cmfcrossimportance = input.int(defval=1, minval=0, maxval=100, title='CMF Cross 50-Line Importance')
cmfcrossup = cmf > 0 and cmf[1] < 0 ? cmfcrossimportance : 0
cmfcrossupstatus = cmfcrossup ? 'CMF Crossed 50-Line Up' : na
cmfcrossdown = cmf < 0 and cmf[1] > 0 ? cmfcrossimportance : 0
cmfcrossdownstatus = cmfcrossdown ? 'CMF Crossed 50-Line Down' : na

cmflevimportance = input.int(defval=0, minval=0, maxval=100, title='CMF Level Importance')
cmflevup = cmf > 0 ? cmflevimportance : 0
cmflevupstatus = cmflevup ? 'CMF Level Up' : na
cmflevdown = cmf < 0 ? cmflevimportance : 0
cmflevdownstatus = cmflevdown ? 'CMF Level Down' : na

//VWAP Signals
vwapcrossimportance = input.int(defval=0, minval=0, maxval=100, title='VWAP Cross HMA Importance')
vwapcrossup = hma < vwapValue and hma[1] > vwapValue[1] ? vwapcrossimportance : 0
vwapcrossupstatus = vwapcrossup ? 'VWAP Crossed Above HMA' : na
vwapcrossdown = hma > vwapValue and hma[1] < vwapValue[1] ? vwapcrossimportance : 0
vwapcrossdownstatus = vwapcrossdown ? 'VWAP Crossed Below HMA' : na

vwaptrendimportance = input.int(defval=0, minval=0, maxval=100, title='VWAP Trend Importance')
vwaptrendup = out2 > vwapValue ? vwaptrendimportance : 0
vwaptrendupstatus = vwaptrendup ? 'VWAP Up Trend' : na
vwaptrenddown = out2 < vwapValue ? vwaptrendimportance : 0
vwaptrenddownstatus = vwaptrenddown ? 'VWAP Down Trend' : na

//Candle Patterns Signals
engulfingcandleimportance = input.int(defval=1, minval=0, maxval=100, title='Engulfing Candle Importance')
bulleng = C_EngulfingBullish ? engulfingcandleimportance : 0
bullengstatus = bulleng ? 'Bullish Engulfing Candle' : na
beareng = C_EngulfingBearish ? engulfingcandleimportance : 0
bearengstatus = beareng ? 'Bearish Engulfing Candle' : na


//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//COLLECT SIGNALS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//Classify Entries
stronglongentrysignal = emadirectionup + emapushup + supertrendup + supertrendrevup + psardirup + psarrevup + hmacloseposup + hmapivotup + rsidivup + rsioversold + rsicrossup + macddivup + histpivotup + macdcrosssignalup + wtdivup + wtcrosssignalup + sdivup + scrosssignalup + bbcontup + atrrevup + rviposup + rvidivup + srcrossup + obvdivup + cmfcrossup + cmflevup + vwapcrossup + vwaptrendup + bulleng >= stronglongscore
strongshortentrysignal = emadirectiondown + emapulldown + supertrenddown + supertrendrevdown + psardirdown + psarrevdown + hmacloseposdown + hmapivotdown + rsidivdown + rsioverbought + rsicrossdown + macddivdown + histpivotdown + macdcrosssignaldown + wtdivdown + wtcrosssignaldown + sdivdown + scrosssignaldown + bbcontdown + atrrevdown + rviposdown + rvidivdown + srcrossdown + obvdivdown + cmfcrossdown + cmflevdown + vwapcrossdown + vwaptrenddown + beareng >= strongshortscore
weaklongentrysignal = emadirectionup + emapushup + supertrendup + supertrendrevup + psardirup + psarrevup + hmacloseposup + hmapivotup + rsidivup + rsioversold + rsicrossup + macddivup + histpivotup + macdcrosssignalup + wtdivup + wtcrosssignalup + sdivup + scrosssignalup + bbcontup + atrrevup + rviposup + rvidivup + srcrossup + obvdivup + cmfcrossup + cmflevup + vwapcrossup + vwaptrendup + bulleng >= weaklongscore
weakshortentrysignal = emadirectiondown + emapulldown + supertrenddown + supertrendrevdown + psardirdown + psarrevdown + hmacloseposdown + hmapivotdown + rsidivdown + rsioverbought + rsicrossdown + macddivdown + histpivotdown + macdcrosssignaldown + wtdivdown + wtcrosssignaldown + sdivdown + scrosssignaldown + bbcontdown + atrrevdown + rviposdown + rvidivdown + srcrossdown + obvdivdown + cmfcrossdown + cmflevdown + vwapcrossdown + vwaptrenddown + beareng >= weakshortscore

//Alternate Entry Signals
var pos = 0
if stronglongentrysignal and pos <= 0
    pos := 1
    pos
if strongshortentrysignal and pos >= 0
    pos := -1
    pos
longentry = pos == 1 and (pos != 1)[1]
shortentry = pos == -1 and (pos != -1)[1]
alternatelong = alternatesignals ? longentry : stronglongentrysignal
alternateshort = alternatesignals ? shortentry : strongshortentrysignal

NUBuySignal = tradetrendoption ? alternatelong and mabuy and longpositions : alternatelong and longpositions
NUSellSignal = tradetrendoption ? alternateshort and masell and shortpositions : alternateshort and shortpositions

MSBarNUColor = NUBuySignal ? BuyColor : NUSellSignal ? SellColor : color.new(DisabledColor,90)

//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//PLOT SIGNALS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//CHANGED
//plotshape(tradetrendoption ? alternatelong and mabuy : alternatelong, title='Strong Long Label', style=shape.labelup, location=location.belowbar, color=color.new(#00bcd4, 0), text='𝐋𝐎𝐍𝐆', textcolor=color.new(color.white, 0), size=size.small)
//plotshape(tradetrendoption ? alternateshort and masell : alternateshort, title='Strong Short Label', style=shape.labeldown, location=location.abovebar, color=color.new(#e91e63, 0), text='𝐒𝐇𝐎𝐑𝐓', textcolor=color.new(color.white, 0), size=size.small)
//plotshape(weaklongentrysignal, title='Weak Long Triangle', style=shape.triangleup, location=location.belowbar, color=color.new(#00bcd4, 50), size=size.tiny)
//plotshape(weakshortentrysignal, title='Weak Short Triangle', style=shape.triangledown, location=location.abovebar, color=color.new(#e91e63, 50), size=size.tiny)


//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//PLOT STATUS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//var table statuswindow = table.new(position.top_right, 100, 100, border_width=2)

//Trend Status//////////////////////////////////////////////////////////////////


//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//STOP LOSS WARNINGS▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//Stop Loss Criteria
//longstoploss = strategy.position_avg_price * (1 + stoplosspercent)
//shortstoploss = strategy.position_avg_price * (1 - stoplosspercent)
//printstoplong = longstoploss > close and longstoploss[1] < close[1] and strategy.position_size > 0
//printstopshort = shortstoploss < close and shortstoploss[1] > close[1] and strategy.position_size < 0

//Stop Loss Lines
//plot(strategy.position_size > 0 ? longstoploss : na, style=plot.style_line, color=color.new(color.yellow, 50), linewidth=1, title='Stop Long Line', display=display.none)
//plot(strategy.position_size < 0 ? shortstoploss : na, style=plot.style_line, color=color.new(color.yellow, 50), linewidth=1, title='Stop Short Line', display=display.none)

//Stop Loss Labels
//plotshape(printstoplong, title='Stop Long Label', style=shape.labelup, location=location.belowbar, color=color.new(color.yellow, 0), text='𝐒𝐓𝐎𝐏', textcolor=color.new(color.black, 0), size=size.tiny)
//plotshape(printstopshort, title='Stop Short Label', style=shape.labeldown, location=location.abovebar, color=color.new(color.yellow, 0), text='𝐒𝐓𝐎𝐏', textcolor=color.new(color.black, 0), size=size.tiny)


//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////
//STRATEGY TESTER▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼

//Long
// if tradetrendoption ? alternatelong and mabuy and longpositions : alternatelong and longpositions
//     strategy.entry('longposition', strategy.long, comment='Long Entry')
// if (shortentry or printstoplong) and longpositions
//     strategy.close('longposition', comment='Long Exit')

// //Short
// if tradetrendoption ? alternateshort and masell and shortpositions : alternateshort and shortpositions
//     strategy.entry('shortposition', strategy.short, comment=' Short Entry')
// if (longentry or printstopshort) and shortpositions
//     strategy.close('shortposition', comment='Short Exit')

//Alerts
// ttbuystring = 'Input your custom alert message here. In the Alert settings, choose "Neural Network" and "Alert() functionc calls only"\nIf you\'re using a 3Commas Bot, make sure to format your message correctly with forward slashes in front of each quotation, you can find videos about how to do this on YouTube. Or ask 3Commas support about how to format the message for PineScript.'
// ttsellstring = 'Input your custom alert message here. In the Alert settings, choose "Neural Network" and "Alert() functionc calls only"\nIf you\'re using a 3Commas Bot, make sure to format your message correctly with forward slashes in front of each quotation, you can find videos about how to do this on YouTube. Or ask 3Commas support about how to format the message for PineScript.'
// ttstopstring = 'Input your custom alert message here. In the Alert settings, choose "Neural Network" and "Alert() functionc calls only"\nIf you\'re using a 3Commas Bot, make sure to format your message correctly with forward slashes in front of each quotation, you can find videos about how to do this on YouTube. Or ask 3Commas support about how to format the message for PineScript.'
// usebuyalert = input.bool(defval=true, title='Use BUY Alert', group='Alert Messages')
// buystring = input.string(title='Buy Alert Message', defval='BUY', confirm=false, group='Alert Messages', tooltip=ttbuystring)
// usesellalert = input.bool(defval=true, title='Use SELL Alert', group='Alert Messages')
// sellstring = input.string(title='Sell Alert Message', defval='SELL', confirm=false, group='Alert Messages', tooltip=ttsellstring)
// usestopalert = input.bool(defval=true, title='Use STOP Alert', group='Alert Messages')
// stopstring = input.string(title='Stop Alert Message', defval='STOP', confirm=false, group='Alert Messages', tooltip=ttstopstring)

// if longentry and longpositions and usebuyalert
//     alert(buystring, alert.freq_once_per_bar)
// if shortentry and shortpositions and usesellalert
//     alert(sellstring, alert.freq_once_per_bar)
// if printstoplong or printstopshort and usestopalert
//     alert(stopstring, alert.freq_once_per_bar)

//END▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
////////////////////////////////////////////////////////////////////////////////



//////////////// Buy/Sell STARTS /////////////////////////////////////////////////////////////////////////////////////////////////


buySellAnyPositive = MSBar1PositiveWaveTrendSignal or BackgroundColorChangePositive or MaxValueMACrossUp or MSBarCEPositiveTrendSignal or MSBarPSPositiveTrendSignal or MSBarQQEPositiveTrendSignal  or htBuySignal or NUBuySignal
buySellAnyNegative = MSBar1NegativeWaveTrendSignal or BackgroundColorChangeNegative or MaxValueMACrossDown or MSBarCENegativeTrendSignal or MSBarPSNegativeTrendSignal or MSBarQQENegativeTrendSignal  or htSellSignal or NUSellSignal
buySellAnyPositiveNegative = MSBar1PositiveWaveTrendSignal or MSBar1NegativeWaveTrendSignal or BackgroundColorChangePositive or BackgroundColorChangeNegative or MaxValueMACrossUp or MaxValueMACrossDown or MSBarCEPositiveTrendSignal or MSBarPSPositiveTrendSignal or MSBarQQEPositiveTrendSignal or MSBarCENegativeTrendSignal or MSBarPSNegativeTrendSignal or MSBarQQENegativeTrendSignal or NUSellSignal or NUBuySignal

bool buySellStrongPositive = na 
bool buySellStrongNegative = na

// FOR BULL: 2 then 1
// FOR BEAR or Side Ways: 3 then 1

//BULL: 2 BEAR: 2
if BuySellPolicy == 'Fast Buy and Fast Sell(Bull/Bear)' 
    //if BuyTRating
        //Fast Buy
    buySellStrongPositive := (TrendBars3Positive and not condSell) and (NUBuySignal or MSBar1PositiveWaveTrendSignal or MSBarCEPositiveTrendSignal or MSBarPSPositiveTrendSignal or MSBarQQEPositiveTrendSignal or htBuySignal) and ((xUp or gUp) or MSBarKDJPositiveTrendSignal or cmfPositive) 

    //if SellTRating
        //Fast Sell
    buySellStrongNegative := (TrendBars3Negative or MSBarKDJNegativeTrendSignal or not condBuy) and (NUSellSignal or MSBar1NegativeWaveTrendSignal or MSBarCENegativeTrendSignal or MSBarPSNegativeTrendSignal or MSBarQQENegativeTrendSignal or htSellSignal or (xDn or gDn) or (condSell and not TrendBars3Positive)) 

//BULL: 1
if BuySellPolicy == 'Fast Buy and Slow Sell(Bull)' 
    //if BuyTRating
        //Fast Buy
    buySellStrongPositive := (TrendBars3Positive and not condSell) and (NUBuySignal or MSBar1PositiveWaveTrendSignal or MSBarCEPositiveTrendSignal or MSBarPSPositiveTrendSignal or MSBarQQEPositiveTrendSignal or htBuySignal) and ((xUp or gUp) or MSBarKDJPositiveTrendSignal or cmfPositive) 

    //if SellTRating
        //Slow Sell
    buySellStrongNegative := (TrendBars3Negative and not condBuy) and (NUSellSignal or MSBar1NegativeWaveTrendSignal or MSBarCENegativeTrendSignal or MSBarPSNegativeTrendSignal or MSBarQQENegativeTrendSignal or htSellSignal or (xDn or gDn) or (condSell and not TrendBars3Positive)) 
 
 
//BEAR: 1
if BuySellPolicy == 'Slow Buy and Fast Sell(Bear/SideWays)' 
    //if BuyTRating
        //Slow Buy
    buySellStrongPositive := (TrendBars3Positive or condBuy) and (NUBuySignal or MSBar1PositiveWaveTrendSignal or MSBarCEPositiveTrendSignal or MSBarPSPositiveTrendSignal or MSBarQQEPositiveTrendSignal  or htBuySignal) //and ((xUp or gUp) or MSBarKDJPositiveTrendSignal or cmfPositive) 

    //if SellTRating
        //Fast Sell
    buySellStrongNegative := (TrendBars3Negative or MSBarKDJNegativeTrendSignal or not condBuy) and (NUSellSignal or MSBar1NegativeWaveTrendSignal or MSBarCENegativeTrendSignal or MSBarPSNegativeTrendSignal or MSBarQQENegativeTrendSignal or htSellSignal or (xDn or gDn) or (condSell and not TrendBars3Positive)) 

//BULL: 2 BEAR: 3
if BuySellPolicy == 'Slow Buy and Slow Sell' 
    //if BuyTRating
        //Slow Buy
    buySellStrongPositive := (TrendBars3Positive or condBuy) and (NUBuySignal or MSBar1PositiveWaveTrendSignal or MSBarCEPositiveTrendSignal or MSBarPSPositiveTrendSignal or MSBarQQEPositiveTrendSignal  or htBuySignal) //and ((xUp or gUp) or MSBarKDJPositiveTrendSignal or cmfPositive) 

    //if SellTRating
        //Slow Sell
    buySellStrongNegative := (TrendBars3Negative and not condBuy) and (NUSellSignal or MSBar1NegativeWaveTrendSignal or MSBarCENegativeTrendSignal or MSBarPSNegativeTrendSignal or MSBarQQENegativeTrendSignal or htSellSignal or (xDn or gDn) or (condSell and not TrendBars3Positive)) 

BarBuySellColor = color.gray


var bool lastDirectionUp = na
// Trigger alerts on user-selected conditions.
bool triggerLong = (buySellStrongPositive and (na(lastDirectionUp) or not lastDirectionUp))[ensureNoRepaintIdx]
bool triggerShort = (buySellStrongNegative and (na(lastDirectionUp) or lastDirectionUp))[ensureNoRepaintIdx]


if triggerLong
    lastDirectionUp := true
    BarBuySellColor := BuyColor
else if triggerShort
    lastDirectionUp := false
    BarBuySellColor := SellColor


alertcondition(triggerLong, title='01 Buy Signal', message='Buy')
alertcondition(triggerShort, title='02 Sell Signal', message='Sell')

alertcondition(buySellAnyPositive, title='03 Positive Signals', message='Buy')
alertcondition(buySellAnyNegative, title='04 Negative Signals', message='Sell')
alertcondition(buySellAnyPositiveNegative, title='05 Positive/Negative Signal', message='Buy/Sell')



//////////////// Buy/Sell Ends /////////////////////////////////////////////////////////////////////////////////////////////////


//////////////// PLOTTING STARTS /////////////////////////////////////////////////////////////////////////////////////////////////

plot(ShowTrendBar ? 50 : na, title='Signals 1 - All 3 Trend Meters Now Align', style=plot.style_circles, color=MSBar2Color, linewidth=2, transp=1)


// Trend Barmeter Plots

plot(ShowTrendBar ? 43 : na, title='2 - Trend Meter', style=plot.style_circles, color=TrendBar1Color, linewidth=2, transp=1)

plot(ShowTrendBar ? 37.5 : na, title='3 - Trend Meter', style=plot.style_circles, color=TrendBar2Color, linewidth=2, transp=1)

plot(ShowTrendBar ? 31 : na, title='4 - Trend Meter', style=plot.style_circles, color=TrendBar3Color, linewidth=2, transp=1)

plot(ShowTrendBar and not(TrendBar5 == 'N/A') ? 24.5 : na, title='5 - Trend Bar 1 - Thin Line', style=plot.style_line, color=TrendBar4Color1, linewidth=4, transp=1)

plot(ShowTrendBar and not(TrendBar4 == 'N/A') ? 18.5 : na, title='6 - Trend Bar 2 - Thin Line', style=plot.style_line, color=TrendBar5Color1, linewidth=4, transp=1)

plot(ShowTrendBar ? 13 : na, title='8 - Trend Bar 3 - AlphaTrend', style=plot.style_line, color=BARAtColor, linewidth=4, transp=1)

plot(ShowTrendBar ? 8 : na, title='7 - Trend Bar 3 - Donchin Channel', style=plot.style_line, color=dcColor, linewidth=4, transp=1)

plot(0, title='7 - Trend Bar 3 - Technical Ratings', style=plot.style_line, color=c_signal, linewidth=7, transp=1)


// Momentum Setup Plots 

plot(ShowTrendBar ? -8  : na, title='Signals 9 - Chandelier Exit', style=plot.style_circles, color=MSBarCEColor, linewidth=2, transp=1)


plot(ShowTrendBar ? -16 : na, title='Signals 10 - Wave Trend Signals', style=plot.style_circles, color=MSBar1Color, linewidth=2, transp=1)


plot(ShowTrendBar  ? -22 : na, title='Signals 11 - QQE', style=plot.style_circles, color=MSBarQQEColor, linewidth=2, transp=1)


plot(ShowTrendBar ? -29 : na, title='Signals 12 - Nural Network', style=plot.style_circles, color=MSBarNUColor, linewidth=2, transp=1)


plot((triggerLong or triggerShort) ? -36 : na, title='Signals 13 - Buy Sell', style=plot.style_circles, color=BarBuySellColor, linewidth=3, transp=1)


//////////////// PLOTTING ENDS /////////////////////////////////////////////////////////////////////////////////////////////////

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
