Kve - All

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 35

//@version=5

// Table Options
Showema = input.bool(false, 'SHOW EMA ON/OFF ', inline = 'overlayLine1',
group = 'K2024')
ShowSmartNLN = input.bool(false, 'Trend Cloud ON/OFF ', inline =
'overlayLine1', group = 'K2024')
ShowSmartema = input.bool(false, 'Trend EMA ON/OFF ', inline =
'overlayLine1', group = 'K2024')

enableSR = input.bool(false, 'Support/Resistance ', inline = 'overlayLine2',


group = 'K2024')
reversalZone = input.bool(true, "Reversal Zones ", inline =
'overlayLine2', group = 'K2024')
ShowSR = input(true, "Supply and Demand", inline = 'overlayLine2', group = 'K2024')

Zigzag = input.bool(false, ' Zigzag ', inline = 'overlayLine3', group =


'K2024')
ShowBS = input.bool(false, "Show Signals ON/OFF ", inline =
'overlayLine3', group = 'K2024')

ShowSmartTrail = input.bool(true, 'Smart Trail ON/OFF ', inline =


'overlayLine4', group = 'K2024')
showSessions = input(false, "Sessions", inline = 'overlayLine4', group = 'K2024')
CPR = input.bool(false, 'CPR ON/OFF ', inline = 'overlayLine4', group =
'K2024')

//*** START of COMMENT OUT [Alerts]


indicator(shorttitle='K-Trend with BB', title='K-Trend with BB', overlay=true)

// Use Alternate Anchor TF for MAs


anchor = input.int(4, minval=0, maxval=100, title='Relative TimeFrame Multiplier
for Second MA Ribbon (0=none, max=100)',group = " 👉 EMA TREND")
//

// - INPUTS START
// Fast MA - type, source, length
showAvgs = input(true, title='Show Moving Average Lines')
type1 = input.string(defval='EMA', title='Fast MA Type: ', options=['SMA', 'EMA',
'WMA', 'VWMA', 'SMMA', 'DEMA', 'TEMA', 'HullMA', 'ZEMA', 'TMA', 'SSMA'])
len1 = input.int(defval=16, title='Fast - Length', minval=1)
gamma1 = 0.33
// Medium Fast MA - type, source, length
type2 = input.string(defval='EMA', title='Medium MA Type: ', options=['SMA', 'EMA',
'WMA', 'VWMA', 'SMMA', 'DEMA', 'TEMA', 'HullMA', 'ZEMA', 'TMA', 'SSMA'])
len2 = input.int(defval=21, title='Medium - Length', minval=1)
gamma2 = 0.55
// Slow MA - type, source, length
type3 = input.string(defval='EMA', title='Slow MA Type: ', options=['SMA', 'EMA',
'WMA', 'VWMA', 'SMMA', 'DEMA', 'TEMA', 'HullMA', 'ZEMA', 'TMA', 'SSMA'])
len3 = input.int(defval=26, title='Slow Length', minval=1)
gamma3 = 0.77
//
// QQE rsi Length, Smoothing, fast ATR factor, source
RSILen = input(14, title='RSI Length')
SF = input(8, title='RSI Smoothing Factor')
QQEfactor = input(5.0, title='Fast QQE Factor')
threshhold = input(10, title='RSI Threshhold')
//
sQQEx = input(false, title='Show QQE Signal crosses')
sQQEz = input(false, title='Show QQE Zero crosses')
sQQEc = input(false, title='Show QQE Thresh Hold Channel Exits')
//
tradeSignal = input.string('XC', title='Select which QQE signal to Buy/Sell',
options=['XC', 'XQ', 'XZ'])
closeSignal = input.string('XQ', title='Select which QQE signal to Close Order',
options=['XC', 'XQ', 'XZ'])
//
xfilter = input(false, title='Filter XQ Buy/Sell Orders by Threshold')
filter = input(false, title='Use Moving Average Filter')
dfilter = input(false, title='Use Trend Directional Filter')
ufirst = input(false, title='Only Alert First Buy/Sell in a new Trend')
RSIsrc = input(close, title='Source')

src = RSIsrc // MA source


srcclose = RSIsrc

///////////////////////////////////////////////
//* Backtesting Period Selector | Component *//
///////////////////////////////////////////////

//* https://www.tradingview.com/script/eCC1cvxQ-Backtesting-Period-Selector-
Component *//
//* https://www.tradingview.com/u/pbergden/ *//
//* Modifications made by JustUncleL*//

// - INPUTS END
colorRED = input.color(color.new(#ff5252, 0))
colorAQUA = input.color(color.new(#00bcd4,0))
colorLIME = input.color(color.new(#4caf50, 0))
colorRED1 = input.color(color.new(#ff5252, 90))
colorAQUA1 = input.color(color.new(#00bcd4,90))
colorLIME1 = input.color(color.new(#4caf50,90))
//gold = #FFD700
//AQUA = #00FFFFFF
//BLUE = #0000FFFF
//RED = #FF0000FF
//LIME = #00FF00FF
//GRAY = #808080FF

// - FUNCTIONS

// - variant(type, src, len, gamma)


// Returns MA input selection variant, default to SMA if blank or typo.

// SuperSmoother filter
// © 2013 John F. Ehlers
variant_supersmoother(src, len) =>
a1 = math.exp(-1.414 * 3.14159 / len)
b1 = 2 * a1 * math.cos(1.414 * 3.14159 / len)
c2 = b1
c3 = -a1 * a1
c1 = 1 - c2 - c3
v9 = 0.0
v9 := c1 * (src + nz(src[1])) / 2 + c2 * nz(v9[1]) + c3 * nz(v9[2])
v9

variant_smoothed(src, len) =>


v5 = 0.0
sma_1 = ta.sma(src, len)
v5 := na(v5[1]) ? sma_1 : (v5[1] * (len - 1) + src) / len
v5

variant_zerolagema(src, len) =>


ema1 = ta.ema(src, len)
ema2 = ta.ema(ema1, len)
v10 = ema1 + ema1 - ema2
v10

variant_doubleema(src, len) =>


v2 = ta.ema(src, len)
v6 = 2 * v2 - ta.ema(v2, len)
v6

variant_tripleema(src, len) =>


v2 = ta.ema(src, len)
v7 = 3 * (v2 - ta.ema(v2, len)) + ta.ema(ta.ema(v2, len), len) // Triple
Exponential
v7

//calc Laguerre
variant_lag(p, g) =>
L0 = 0.0
L1 = 0.0
L2 = 0.0
L3 = 0.0
L0 := (1 - g) * p + g * nz(L0[1])
L1 := -g * L0 + nz(L0[1]) + g * nz(L1[1])
L2 := -g * L1 + nz(L1[1]) + g * nz(L2[1])
L3 := -g * L2 + nz(L2[1]) + g * nz(L3[1])
f = (L0 + 2 * L1 + 2 * L2 + L3) / 6
f

// return variant, defaults to SMA


variant(type, src, len, g) =>
ema_1 = ta.ema(src, len)
wma_1 = ta.wma(src, len)
vwma_1 = ta.vwma(src, len)
variant_smoothed__1 = variant_smoothed(src, len)
variant_doubleema__1 = variant_doubleema(src, len)
variant_tripleema__1 = variant_tripleema(src, len)
variant_lag__1 = variant_lag(src, g)
wma_2 = ta.wma(src, len / 2)
wma_3 = ta.wma(src, len)
wma_4 = ta.wma(2 * wma_2 - wma_3, math.round(math.sqrt(len)))
variant_supersmoother__1 = variant_supersmoother(src, len)
variant_zerolagema__1 = variant_zerolagema(src, len)
sma_1 = ta.sma(src, len)
sma_2 = ta.sma(sma_1, len)
sma_3 = ta.sma(src, len)
type == 'EMA' ? ema_1 : type == 'WMA' ? wma_1 : type == 'VWMA' ? vwma_1 : type
== 'SMMA' ? variant_smoothed__1 : type == 'DEMA' ? variant_doubleema__1 : type ==
'TEMA' ? variant_tripleema__1 : type == 'LAGMA' ? variant_lag__1 : type == 'HullMA'
? wma_4 : type == 'SSMA' ? variant_supersmoother__1 : type == 'ZEMA' ?
variant_zerolagema__1 : type == 'TMA' ? sma_2 : sma_3

// - /variant

// If have anchor specified, calculate the base multiplier, base on time in mins
//mult = isintraday ? anchor==0 or interval<=0 or interval>=anchor or anchor>1440?
1 : round(anchor/interval) : 1
//mult := not isintraday? 1 : mult // Only available Daily or less

// Anchor is a relative multiplier based on current TF.


mult = anchor > 0 ? anchor : 1

// - FUNCTIONS END

// - Fast ATR QQE


//
Wilders_Period = RSILen * 2 - 1
//
Rsi = ta.rsi(RSIsrc, RSILen)
RSIndex = ta.ema(Rsi, SF)
AtrRsi = math.abs(RSIndex[1] - RSIndex)
MaAtrRsi = ta.ema(AtrRsi, Wilders_Period)
DeltaFastAtrRsi = ta.ema(MaAtrRsi, Wilders_Period) * QQEfactor
//
newshortband = RSIndex + DeltaFastAtrRsi
newlongband = RSIndex - DeltaFastAtrRsi
longband = 0.0
shortband = 0.0
trend = 0
longband := RSIndex[1] > longband[1] and RSIndex > longband[1] ?
math.max(longband[1], newlongband) : newlongband
shortband := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ?
math.min(shortband[1], newshortband) : newshortband
cross_1 = ta.cross(longband[1], RSIndex)
trend := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1)
FastAtrRsiTL = trend == 1 ? longband : shortband

// - SERIES VARIABLES
// MA's
ma_fast = variant(type1, srcclose, len1, gamma1)
ma_medium = variant(type2, srcclose, len2, gamma2)
ma_slow = variant(type3, srcclose, len3, gamma3)
// MA's
ma_fast_alt = variant(type1, srcclose, len1 * mult, gamma1)
ma_medium_alt = variant(type2, srcclose, len2 * mult, gamma2)
ma_slow_alt = variant(type3, srcclose, len3 * mult, gamma3)

// Get Direction From Medium Moving Average


falling_1 = ta.falling(ma_medium, 3)
direction = ta.rising(ma_medium, 3) ? 1 : falling_1 ? -1 : 0
falling_2 = ta.falling(ma_medium_alt, 3)
altDirection = ta.rising(ma_medium_alt, 3) ? 1 : falling_2 ? -1 : 0
//
// 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
// Zero cross
QQEzlong = 0
QQEzlong := nz(QQEzlong[1])
QQEzshort = 0
QQEzshort := nz(QQEzshort[1])
QQEzlong := RSIndex >= 50 ? QQEzlong + 1 : 0
QQEzshort := RSIndex < 50 ? QQEzshort + 1 : 0
//
// Thresh Hold channel Crosses give the BUY/SELL alerts.
QQEclong = 0
QQEclong := nz(QQEclong[1])
QQEcshort = 0
QQEcshort := nz(QQEcshort[1])
QQEclong := RSIndex > 50 + threshhold ? QQEclong + 1 : 0
QQEcshort := RSIndex < 50 - threshhold ? QQEcshort + 1 : 0

//
// Check Filtering.
QQEflong = mult == 1 ? (not filter or srcclose > ma_medium and ma_medium > ma_slow
and ma_fast > ma_medium) and (not dfilter or direction > 0) : (not filter or
ma_medium > ma_medium_alt and srcclose > ma_fast and ma_fast > ma_medium) and (not
dfilter or direction > 0 and altDirection > 0 and srcclose > ma_medium)
QQEfshort = mult == 1 ? (not filter or srcclose < ma_medium and ma_medium < ma_slow
and ma_fast < ma_medium) and (not dfilter or direction < 0) : (not filter or
ma_medium < ma_medium_alt and srcclose < ma_fast and ma_fast < ma_medium) and (not
dfilter or direction < 0 and altDirection < 0 and srcclose < ma_medium)

QQExfilter = not xfilter or RSIndex > 50 + threshhold or RSIndex < 50 - threshhold


//
// Get final BUY / SELL alert determination
buy_ = 0
buy_ := nz(buy_[1])
sell_ = 0
sell_ := nz(sell_[1])

// Make sure Buy/Sell are non-repaint and occur after close signal.
buy_ := tradeSignal == 'XC' ? QQEclong[1] == 1 and QQEflong[1] ? buy_ + 1 : 0 :
tradeSignal == 'XQ' ? QQExlong[1] == 1 and QQEflong[1] and QQExfilter[1] ? buy_ + 1
: 0 : tradeSignal == 'XZ' ? QQEzlong[1] == 1 and QQEflong[1] ? buy_ + 1 : 0 : 0
sell_ := tradeSignal == 'XC' ? QQEcshort[1] == 1 and QQEfshort[1] ? sell_ + 1 : 0 :
tradeSignal == 'XQ' ? QQExshort[1] == 1 and QQEfshort[1] and QQExfilter[1] ? sell_
+ 1 : 0 : tradeSignal == 'XZ' ? QQEzshort[1] == 1 and QQEfshort[1] ? sell_ + 1 :
0 : 0
//
// Find the first Buy/Sell in trend swing.
Buy = 0
Buy := nz(Buy[1])
Sell = 0
Sell := nz(Sell[1])
Buy := sell_ > 0 ? 0 : buy_ == 1 or Buy > 0 ? Buy + 1 : Buy
Sell := buy_ > 0 ? 0 : sell_ == 1 or Sell > 0 ? Sell + 1 : Sell

// Select First or all buy/sell alerts.


buy = ufirst ? Buy : buy_
sell = ufirst ? Sell : sell_
closeLong = 0
closeLong := nz(closeLong[1])
closeShort = 0
closeShort := nz(closeShort[1])
closeLong := closeSignal == 'XC' ? QQEcshort == 1 ? closeLong + 1 : 0 : closeSignal
== 'XQ' ? tradeSignal == 'XQ' ? QQExshort == 1 ? closeLong + 1 : 0 : QQExshort == 1
or QQEzshort or QQEcshort ? closeLong + 1 : 0 : closeSignal == 'XZ' ? QQEzshort ==
1 ? closeLong + 1 : 0 : 0
closeShort := closeSignal == 'XC' ? QQEclong == 1 ? closeShort + 1 : 0 :
closeSignal == 'XQ' ? tradeSignal == 'XQ' ? QQExlong == 1 ? closeShort + 1 : 0 :
QQExlong == 1 or QQEzlong or QQEclong == 1 ? closeShort + 1 : 0 : closeSignal ==
'XZ' ? QQEzlong == 1 ? closeShort + 1 : 0 : 0

tradestate = 0
tradestate := nz(tradestate[1])
tradestate := tradestate == 0 ? buy == 1 ? 1 : sell == 1 ? 2 : 0 : tradestate == 1
and closeLong == 1 or tradestate == 2 and closeShort == 1 ? 0 : tradestate

isLong = ta.change(tradestate) and tradestate == 1


isShort = ta.change(tradestate) and tradestate == 2
isCloseLong = ta.change(tradestate) and tradestate == 0 and nz(tradestate[1]) == 1
isCloseShort = ta.change(tradestate) and tradestate == 0 and nz(tradestate[1]) == 2

// - SERIES VARIABLES END

// - PLOTTING
// Ma's
tcolor = ShowSmartema?( direction < 0 ? colorRED : colorLIME ):na
tcolor1 = ShowSmartema?( direction < 0 ? colorRED1 : colorLIME1 ):na
ma1 = plot(showAvgs ? ma_fast : na, title='MA Fast', color=tcolor, linewidth=1,
transp=50)
ma2 = plot(showAvgs ? ma_medium : na, title='MA Medium Fast', color=tcolor,
linewidth=2, transp=50)
ma3 = plot(showAvgs ? ma_slow : na, title='MA Slow', color=tcolor, linewidth=1,
transp=50)
fill(ma1, ma3, color=tcolor1, transp=10)
// Ma's
altTcolor = ShowSmartema?(altDirection < 0 ? colorRED : colorAQUA):na
altTcolor1 = ShowSmartema?(altDirection < 0 ? colorRED1 : colorAQUA1):na
ma4 = plot(showAvgs and mult > 1 ? ma_fast_alt : na, title='MA Fast',
color=altTcolor, linewidth=1, transp=50)
ma5 = plot(showAvgs and mult > 1 ? ma_medium_alt : na, title='MA Medium Fast',
color=altTcolor, linewidth=2, transp=50)
ma6 = plot(showAvgs and mult > 1 ? ma_slow_alt : na, title='MA Slow',
color=altTcolor, linewidth=1, transp=50)
fill(ma4, ma6, altTcolor1, transp=10)

//EOF

///////////////////////////////////////////////////////////////////////////////////
//////////////
//indicator("LNL Trend System", shorttitle = "LNL Trend System", overlay=true)

// Inputs

string TrendMode = input.string("Tight", "Trend Mode", options = ["Tight",


"Normal", "Loose", "FOMC", "Net"], group = "👉 Trend Cloud", tooltip = "There are
several trend modes available. The mods are lined up based on the aggressiveness of
the ATR. Tight & Normal modes are the going to flip way much often whereas the
Loose or FOMC will provide much higher wiggle room. The good rule of thumb to use
is to just stick with first two modes when trading less volatile sessions or
ranges, and use the other two on fast moving expanding environments. The Net mode
provides the combination of all modes in one giant net. Some might prefer this mode
since it suits well to the scale in scale out methods. ")
string HTFMode = input.string("Auto", "HTF Mode", options = ["Auto", "Manual"],
group = "👉 Trend Cloud", tooltip = "Changes the higher time frame mode. The HTF
mode set to auto will automatically change the HTF Trend System time frame for you.
The auto mode is choosing the most suitable time frames based on the pre-defined
time frame pairs that are the most suitable ones. If you prefer your own time frame
choose the manual mode.")
TimeFrameM = input.timeframe('60', "HTF Aggregation", options =
['1','2','3','5','10','15','20','30','45','60','120','180','240','D','2D','3D','4D'
,'W','2W','3W','M','2M','3M'], group = "👉 Trend Cloud", tooltip = "Set the manual
time frame for the HTF Trend System.")

ShowTrendBars = input(defval=false, title="Show Trend Bars", group = "Trend Bars",


tooltip = "Trend Bars are based on the DMI and ADX indicators. Whenever the DMI is
bearish and ADX is above 20 the candles paint themselfs red. And vice versa for the
green candles and bullish DMI. Whenever the ADX falls below the 20, candles are
netural which means there is no real trend in place.")
TrendBarBullish = input(#27c22e, title="Bullish", group = "Trend Bars")
TrendBarBearish = input(#ff0000, title="Bearish", group = "Trend Bars")
TrendBarNeutral = input(#434651, title="Neutral", group = "Trend Bars")
ShowTrend = input(defval=false, title="Show Trend Line", group = "Trend Line",
tooltip = "Trend Line is the first part of the L&L Trend System. The trend line is
nothing simplier than the 13 exponential moving average. The color of the Trend
Line depends on the position of multiple exponential averages and whether they are
stacked on top of each other or not.")
TrendBullish = input(#27c22e, title="Bullish", group = "Trend Line")
TrendBearish = input(#ff0000, title="Bearish", group = "Trend Line")
TrendNeutral = input(#434651, title="Neutral", group = "Trend Line")
ShowStop = input(defval=false, title="Show Stop Line", group = "Stop Line", tooltip
= "Stop Line is the main and most important part of the system. It is based on a
special ATR calculation that takes into consideration the past ATRs and prices of
the 13 EMA. Stop Line provides zones that no moving average can. To make it simple
it is something like a moving average that uses the ATR not the average price of
the previous bars.")
StopBullish = input(#27c22e, title="Bullish", group = "Stop Line")
StopBearish = input(#ff0000, title="Bearish", group = "Stop Line")
ShowTrend2 = input(defval=false, title="Show HTF Trend Line", group = "Higher Time
Frame Trend Line", tooltip = "Higher Time Frame Trend Line.")
TrendBullish2 = input(#27c22e, title="Bullish", group = "Higher Time Frame Trend
Line")
TrendBearish2 = input(#ff0000, title="Bearish", group = "Higher Time Frame Trend
Line")
TrendNeutral2 = input(#434651, title="Neutral", group = "Higher Time Frame Trend
Line")
ShowStop2 = input(defval=false, title="Show HTF Stop Line", group = "Higher Time
Frame Stop Line", tooltip = "Higher Time Frame Stop Line")
StopBullish2 = input(#27c22e, title="Bullish", group = "Higher Time Frame Stop
Line")
StopBearish2 = input(#ff0000, title="Bearish", group = "Higher Time Frame Stop
Line")
ShowCloud = input(defval=true, title="Show Cloud", group = "Trend Cloud", tooltip =
"Cloud will paint the area behind the Trend Line and Stop Line with custom color.")
CloudBullish = input(color.rgb(39,194,46,65), title="Bullish", group = "Trend
Cloud")
CloudBearish = input(color.rgb(255,0,0,65), title="Bearish", group = "Trend Cloud")
ShowHTFCloud = input(defval=true, title="Show HTF Cloud", group = "Higher Time
Frame Trend Cloud", tooltip = "Higher Time Frame Cloud.")
CloudBullish2 = input(color.rgb(39,194,46,65), title="Bullish", group = "Higher
Time Frame Trend Cloud")
CloudBearish2 = input(color.rgb(255,0,0,65), title="Bearish", group = "Higher Time
Frame Trend Cloud")

// Trend Bars (DMI Colored Candles)

BullishDMI = (high - high[1]) > (low[1] - low) and (high - high[1]) > 0 ? (high -
high[1]) : 0
BearishDMI = (low[1] - low) > (high - high[1]) and (low[1] - low) > 0 ? (low[1] -
low) : 0
DMIUp = 100 * ta.rma(BullishDMI,14) / ta.rma(ta.tr(true),14)
DMIDown = 100 * ta.rma(BearishDMI,14) / ta.rma(ta.tr(true),14)
ADXx = (DMIUp + DMIDown) > 0 ? 100 * math.abs(DMIUp - DMIDown) / (DMIUp +
DMIDown) : na
ADX = ta.rma(ADXx,14)
ColorBars = ShowTrendBars and (DMIUp > DMIDown and ADX > 20) ? TrendBarBullish :
ShowTrendBars and (DMIUp < DMIDown and ADX > 20) ? TrendBarBearish :
ShowTrendBars ? TrendBarNeutral : na
barcolor(color = ColorBars, editable = false)

// Trend System (First Time Frame)

ema8 = ta.vwma(close, 8)
ema13 = ta.vwma(close, 13)
ema21 = ta.vwma(close, 21)
ema34 = ta.vwma(close, 34)
emaup = ema8 > ema13 and ema13 > ema21 and ema21 > ema34
emadn = ema8 < ema13 and ema13 < ema21 and ema21 < ema34

Trend = ta.ema(close, 13)


TrendColor = ShowTrend and emadn and close <= Trend ? TrendBearish : ShowTrend and
emaup and close >= Trend ? TrendBullish : ShowTrend ? TrendNeutral : na
//plot(Trend,title = "Trend", color = TrendColor, linewidth = 2, editable = false)

ATRLength = if TrendMode == "Tight"


60
else if TrendMode == "Normal"
80
else if TrendMode == "Loose"
100
else if TrendMode == "FOMC"
120
else if TrendMode == "Net"
140

ATR = (ATRLength/100) * ta.ema(ta.tr(true),8)


Up = close > (Trend + ATR)
Down = close < (Trend - ATR)
var T = 0.0
T := Up ? 1 : Down ? -1 : T[1]

StopLineColor = ShowStop and T == 1 ? StopBullish : ShowStop ? StopBearish : na


//plotchar(T == 1 ? (Trend-ATR) : T == -1 ? (Trend+ATR) : T[1], title =
"StopLine",char = "-", location = location.absolute, size = size.tiny, color =
StopLineColor, editable = false)

ATRA = (ATRLength - 20) /100 * ta.ema(ta.tr(true),8)


Up11 = close > (Trend + ATRA)
Down11 = close < (Trend - ATRA)
var T11 = 0.0
T11 := Up11 ? 1 : Down11 ? -1 : T11[1]

StopLineColor1 = ShowStop and T11 == 1 ? StopBullish : ShowStop ? StopBearish : na


//plotchar(T11 == 1 ? (Trend-ATRA) : T11 == -1 ? (Trend+ATRA) : T11[1], title =
"StopLine2",char = "-", location = location.absolute, size = size.tiny, color =
StopLineColor1, editable = false)

ATRNET = TrendMode == "Net" ? (ATRLength - 40) /100 * ta.ema(ta.tr(true),8) : na


UpNET = close > (Trend + ATRNET)
DownNET = close < (Trend - ATRNET)
var TNET = 0.0
TNET := UpNET ? 1 : DownNET ? -1 : TNET[1]

StopLineColorNET = ShowStop and TNET == 1 ? StopBullish : ShowStop ? StopBearish :


na
//plotchar(TNET == 1 ? (Trend-ATRNET) : TNET == -1 ? (Trend+ATRNET) : TNET[1],
title = "StopLineNET",char = "-", location = location.absolute, size = size.tiny,
color = StopLineColorNET, editable = false)

ATRNET1 = TrendMode == "Net" ? (ATRLength - 60) /100 * ta.ema(ta.tr(true),8) : na


UpNET1 = close > (Trend + ATRNET1)
DownNET1 = close < (Trend - ATRNET1)
var TNET1 = 0.0
TNET1 := UpNET1 ? 1 : DownNET1 ? -1 : TNET1[1]

StopLineColorNET1 = ShowStop and TNET1 == 1 ? StopBullish : ShowStop ?


StopBearish : na
//plotchar(TNET1 == 1 ? (Trend-ATRNET1) : TNET1 == -1 ? (Trend+ATRNET1) :
TNET1[1], title = "StopLineNET1",char = "-", location = location.absolute, size =
size.tiny, color = StopLineColorNET1, editable = false)

ATRNET2 = TrendMode == "Net" ? (ATRLength - 80) /100 * ta.ema(ta.tr(true),8) : na


UpNET2 = close > (Trend + ATRNET2)
DownNET2 = close < (Trend - ATRNET2)
var TNET2 = 0.0
TNET2 := UpNET2 ? 1 : DownNET2 ? -1 : TNET2[1]

StopLineColorNET2 = ShowStop and TNET2 == 1 ? StopBullish : ShowStop ?


StopBearish : na
//plotchar(TNET2 == 1 ? (Trend-ATRNET2) : TNET2 == -1 ? (Trend+ATRNET2) :
TNET2[1], title = "StopLineNET2",char = "-", location = location.absolute, size =
size.tiny, color = StopLineColorNET2, editable = false)

// Higher Time Frame Aggregations

TimeFrameA =
timeframe.period == '1' ? '5' :
timeframe.period == '2' ? '5' :
timeframe.period == '3' ? '5' :
timeframe.period == '4' ? '5' :
timeframe.period == '5' ? '30' :
timeframe.period == '10' ? '30' :
timeframe.period == '15' ? '30' :
timeframe.period == '30' ? '240' :
timeframe.period == '60' ? '240' :
timeframe.period == '120' ? '240' :
timeframe.period == '180' ? 'D' :
timeframe.period == '240' ? 'D' :
timeframe.period == 'D' ? 'W' :
timeframe.period == 'W' ? 'M' :
timeframe.period == 'M' ? '3M' : timeframe.period

TimeFrame = if HTFMode == "Auto"


TimeFrameA

else if HTFMode == "Manual"


TimeFrameM

// Trend System (Second Time Frame)

ema82 = request.security(syminfo.tickerid, TimeFrame, ta.vwma(close, 8))


ema132 = request.security(syminfo.tickerid, TimeFrame, ta.vwma(close, 13))
ema212 = request.security(syminfo.tickerid, TimeFrame, ta.vwma(close, 21))
ema342 = request.security(syminfo.tickerid, TimeFrame, ta.vwma(close, 34))
emaup2 = ema82 > ema132 and ema132 > ema212 and ema212 > ema342
emadn2 = ema82 < ema132 and ema132 < ema212 and ema212 < ema342

Trend2 = request.security(syminfo.tickerid, TimeFrame, ta.ema(close, 13))


TrendColor2 = ShowTrend2 and emadn2 and request.security(syminfo.tickerid,
TimeFrame, close) <= Trend2 ? TrendBearish2 : ShowTrend2 and emaup2 and
request.security(syminfo.tickerid, TimeFrame, close) >= Trend2 ? TrendBullish2 :
ShowTrend2 ? TrendNeutral2 : na
plot(Trend2, title = "Trend2", color = TrendColor2, linewidth = 2, editable =
false)

ATRLength2 = if TrendMode == "Tight"


60
else if TrendMode == "Normal"
80
else if TrendMode == "Loose"
100
else if TrendMode == "FOMC"
120
else if TrendMode == "Net"
140

ATR2 = (ATRLength2/100) * request.security(syminfo.tickerid, TimeFrame,


ta.ema(ta.tr(true),8))
Up2 = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 + ATR2)
Down2 = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 - ATR2)
var T2 = 0.0
T2 := Up2 ? 1 : Down2 ? -1 : T2[1]

StopLineColor2 = ShowStop2 and T2 == 1 ? StopBullish2 : ShowStop2 ? StopBearish2 :


na
//plotchar(T2 == 1 ? (Trend2-ATR2) : T2 == -1 ? (Trend2+ATR2) : T2[1], title =
"StopLine2",char = "-", location = location.absolute, size = size.tiny, color =
StopLineColor2, editable = false)

ATR2A = (ATRLength2 - 20) /100 * request.security(syminfo.tickerid, TimeFrame,


ta.ema(ta.tr(true),8))
Up2A = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 + ATR2A)
Down2A = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 - ATR2A)
var T2A = 0.0
T2A := Up2A ? 1 : Down2A[1] ? -1 : T2A[1]

StopLineColor2A = ShowStop2 and T2A == 1 ? StopBullish2 : ShowStop2 ?


StopBearish2 : na
//plotchar(T2A == 1 ? (Trend2-ATR2A) : T2A == -1 ? (Trend2+ATR2A) : T2A[1], title
= "StopLine2",char = "-", location = location.absolute, size = size.tiny, color =
StopLineColor2A, editable = false)

ATR2ANET = TrendMode == "Net" ? (ATRLength2 - 40) /100 *


request.security(syminfo.tickerid, TimeFrame, ta.ema(ta.tr(true),8)) : na
Up2ANET = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 +
ATR2ANET)
Down2ANET = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 -
ATR2ANET)
var T2ANET = 0.0
T2ANET := Up2ANET ? 1 : Down2ANET[1] ? -1 : T2ANET[1]

StopLineColor2ANET = ShowStop2 and T2ANET == 1 ? StopBullish2 : ShowStop2 ?


StopBearish2 : na
//plotchar(T2ANET == 1 ? (Trend2-ATR2ANET) : T2ANET == -1 ? (Trend2+ATR2ANET) :
T2ANET[1], title = "StopLine2",char = "-", location = location.absolute, size =
size.tiny, color = StopLineColor2ANET, editable = false)

ATR2ANET1 = TrendMode == "Net" ? (ATRLength2 - 60) /100 *


request.security(syminfo.tickerid, TimeFrame, ta.ema(ta.tr(true),8)) : na
Up2ANET1 = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 +
ATR2ANET1)
Down2ANET1 = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 -
ATR2ANET1)
var T2ANET1 = 0.0
T2ANET1 := Up2ANET1 ? 1 : Down2ANET1[1] ? -1 : T2ANET1[1]

StopLineColor2ANET1 = ShowStop2 and T2ANET1 == 1 ? StopBullish2 : ShowStop2 ?


StopBearish2 : na
//plotchar(T2ANET1 == 1 ? (Trend2-ATR2ANET1) : T2ANET1 == -1 ? (Trend2+ATR2ANET1)
: T2ANET1[1], title = "StopLine2",char = "-", location = location.absolute, size =
size.tiny, color = StopLineColor2ANET1, editable = false)

ATR2ANET2 = TrendMode == "Net" ? (ATRLength2 - 80) /100 *


request.security(syminfo.tickerid, TimeFrame, ta.ema(ta.tr(true),8)) : na
Up2ANET2 = request.security(syminfo.tickerid, TimeFrame, close) > (Trend2 +
ATR2ANET2)
Down2ANET2 = request.security(syminfo.tickerid, TimeFrame, close) < (Trend2 -
ATR2ANET2)
var T2ANET2 = 0.0
T2ANET2 := Up2ANET2 ? 1 : Down2ANET2[1] ? -1 : T2ANET2[1]

StopLineColor2ANET2 = ShowStop2 and T2ANET2 == 1 ? StopBullish2 : ShowStop2 ?


StopBearish2 : na
//plotchar(T2ANET2 == 1 ? (Trend2-ATR2ANET2) : T2ANET2 == -1 ? (Trend2+ATR2ANET2)
: T2ANET2[1], title = "StopLine2",char = "-", location = location.absolute, size =
size.tiny, color = StopLineColor2ANET2, editable = false)

// Trend Clouds

p1 = plot(ShowSmartNLN?Trend:na, title = "Trend Line", color = TrendColor,


linewidth = 2, display = display.none, editable = false)
p2 = plot(ShowSmartNLN?(T == 1 ? (Trend-ATR) : T == -1 ? (Trend+ATR) :
T[1]):na,title ="StopLine ", color = StopLineColor, linewidth = 2, display =
display.none, editable = false)
Cloud = ShowCloud and T == 1 ? CloudBullish : ShowCloud ? CloudBearish : na
fill(p1,p2,title="TrendCloud",color = Cloud, editable = false)

p3 = plot(ShowSmartNLN?Trend2:na, title = "Trend Line 2", color = TrendColor2,


linewidth = 2, display = display.none, editable = false)
p4 = plot(ShowSmartNLN?(T2 == 1 ? (Trend2-ATR2) : T2 == -1 ? (Trend2+ATR2) :
T2[1]):na,title ="StopLine 2", color = StopLineColor2, linewidth = 2, display =
display.none, editable = false)
Cloud2 = ShowHTFCloud and T2 == 1 ? CloudBullish2 : ShowHTFCloud ? CloudBearish2 :
na
fill(p3,p4,title="TrendCloud2",color = Cloud2, editable = false)
//////////////////////////////

////////////ShowSmartTrail//////////////

trailType = input.string('modified', 'Trailtype', options=['modified',


'unmodified'], group = "👉 SmartTrail Settings")
ATRPeriod = input(200, 'ATR Period', group = "👉 SmartTrail Settings")
ATRFactor = input.float(4.2, 'ATR Factor', group = "👉 SmartTrail Settings" ,minval
= 2, maxval = 10, step = 0.5)
//box_width = input.float(7, title = 'Supply/Demand Box Width', group = "👉 SUPPLY
AND DEMAND", minval = 1, maxval = 10, step = 0.5)
Smoothing = input(5, 'Smoothing', group = "👉 SmartTrail Settings")

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

norm_o = request.security(ticker.new(syminfo.prefix, syminfo.ticker),


timeframe.period, open)
norm_h = request.security(ticker.new(syminfo.prefix, syminfo.ticker),
timeframe.period, high)
norm_l = request.security(ticker.new(syminfo.prefix, syminfo.ticker),
timeframe.period, low)
norm_c = request.security(ticker.new(syminfo.prefix, syminfo.ticker),
timeframe.period, close)
//}

//////// FUNCTIONS //////////////


//{
// Wilders ma //
Wild_ma(_src, _malength) =>
_wild = 0.0
_wild := nz(_wild[1]) + (_src - nz(_wild[1])) / _malength
_wild

/////////// TRUE RANGE CALCULATIONS /////////////////


HiLo = math.min(norm_h - norm_l, 1.5 * nz(ta.sma(norm_h - norm_l, ATRPeriod)))

HRef = norm_l <= norm_h[1] ? norm_h - norm_c[1] : norm_h - norm_c[1] - 0.5 *


(norm_l - norm_h[1])

LRef = norm_h >= norm_l[1] ? norm_c[1] - norm_l : norm_c[1] - norm_l - 0.5 *


(norm_l[1] - norm_h)

trueRange = trailType == 'modified' ? math.max(HiLo, HRef, LRef) : math.max(norm_h


- norm_l, math.abs(norm_h - norm_c[1]), math.abs(norm_l - norm_c[1]))
//}

/////////// TRADE LOGIC ////////////////////////


//{
loss = ATRFactor * Wild_ma(trueRange, ATRPeriod)

Up68 = norm_c - loss


Dn68 = norm_c + loss

TrendUp = Up68
TrendDown = Dn68
Trendtrade = 1

TrendUp := norm_c[1] > TrendUp[1] ? math.max(Up68, TrendUp[1]) : Up68


TrendDown := norm_c[1] < TrendDown[1] ? math.min(Dn68, TrendDown[1]) : Dn68

Trendtrade := norm_c > TrendDown[1] ? 1 : norm_c < TrendUp[1] ? -1 :


nz(Trendtrade[1], 1)
trail = Trendtrade == 1 ? TrendUp : TrendDown

ex = 0.0
ex := ta.crossover(Trendtrade, 0) ? norm_h : ta.crossunder(Trendtrade, 0) ?
norm_l : Trendtrade == 1 ? math.max(ex[1], norm_h) : Trendtrade == -1 ?
math.min(ex[1], norm_l) : ex[1]
//}

// //////// PLOT TP and SL /////////////


//{
plot(ShowSmartTrail ?trail:na, 'S/R - SIGNAL', style=plot.style_line,
color=Trendtrade == 1 ? color.rgb(0, 13, 255) : Trendtrade == -1 ? color.rgb(255,
0, 0) : na,linewidth = 1,editable = false)

//}

////// FIBONACCI LEVELS ///////////


//{
state = Trendtrade == 1 ? 'long' : 'short'

fib1Level = 61.8
fib2Level = 78.6
fib3Level = 88.6
f1 = ex + (trail - ex) * fib1Level / 100
f2 = ex + (trail - ex) * fib2Level / 100
f3 = ex + (trail - ex) * fib3Level / 100
l100 = trail + 0

//Fib1 = plot(ShowSmartTrail ?f1:na, 'Ranger A', display = display.none,


color=color.new(#72760d, 0), display = display.none,editable = false)
Fib2 = plot(ShowSmartTrail ?f2:na, 'Ranger B', color=color.new(#72760d, 0))
Fib3 = plot(ShowSmartTrail ?f3:na, 'Ranger C',color=color.new(#72760d, 0))
//L100 = plot(l100, display = display.none, color=color.new(#f408a2, 0))

//fill(plot(ShowSmartTrail ? (ta.sma(trail, Smoothing)) : na, 'Trailingstop',


style=plot.style_line, color=Trend == 1 ? color.new(#2157f9, 0) : Trend == -1 ?
color.new(#ff1100, 0) : na),
//plot( ShowSmartTrail ? (ta.sma(f2, Smoothing)) : na, 'Fib 2',
style=plot.style_line, display=display.none),
//color=state == 'long' ? color.new(#2157f9, 80) : state == 'short' ?
color.new(#ff1100, 80) : na) //ALL_Bỏ_3_cái_dưới
//}
//fill(plot(ShowSmartTrail ? (ta.sma(trail, Smoothing)) : na,
style=plot.style_line,display = display.none, editable = false, color=Trend == 1 ?
color.new(#2157f9, 0) : Trend == -1 ? color.new(#ff1100, 0) : na),
///plot( ShowSmartTrail ? (ta.sma(f1, Smoothing)) : na, 'Fib 2',
style=plot.style_line, editable = false,display = display.none),
//color=state == 'long' ? color.new(#2157f9, 85) : state == 'short' ?
color.new(#ff1100, 90) : na,display = display.none)

//fill(plot(ShowSmartTrail ? (ta.sma(trail, Smoothing)) : na,


style=plot.style_line,display = display.none, editable = false, color=Trend == 1 ?
color.new(#2157f9, 0) : Trend == -1 ? color.new(#ff1100, 0) : na),
//plot( ShowSmartTrail ? (ta.sma(f2, Smoothing)) : na, 'Fib 2',
style=plot.style_line,editable = false,display = display.none),
//color=state == 'long' ? color.new(#2157f9, 75) : state == 'short' ?
color.new(#ff1100, 70) : na)

//fill(plot(ShowSmartTrail ? (ta.sma(trail, Smoothing)) : na,


style=plot.style_line, editable = false, color=Trend == 1 ? color.new(#2157f9, 0) :
Trend == -1 ? color.new(#ff1100, 0) : na),
//plot( ShowSmartTrail ? (ta.sma(f3, Smoothing)) : na, 'Fib 2',
style=plot.style_line, editable = false,display = display.none),
//color=state == 'long' ? color.new(#2157f9, 75) : state == 'short' ?
color.new(#ff1100, 70) : na)

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

///////////////////// SIGNAL RSI 75/25 ////////////////////

// Condiciones de vela alcista y bajista


bullishCandle = close > open[1] and close[1] < open[1]
bearishCandle = close < open[1] and close[1] > open[1]

// Integración de RSI

rsiLength = input.int(14, title="RSI Length", minval=1,group = " 👉 Signal")


rsiOverBought = input.int(75, title="RSI Overbought Level",group = " 👉 Signal")
rsiOverSold = input.int(25, title="RSI Oversold Level",group = " 👉 Signal")
rsiSource = input(close, title="RSI Source",group = " 👉 Signal")
// Obtener el valor de RSI
rsiValue = ta.rsi(rsiSource, rsiLength)
isRSIOB = rsiValue >= rsiOverBought
isRSIOS = rsiValue <= rsiOverSold

// Señal de trading
var bool buySignal = na
var bool sellSignal = na

buySignal := (isRSIOS or isRSIOS[1] or isRSIOS[2]) and bullishCandle ? true : na


sellSignal := (isRSIOB or isRSIOB[1] or isRSIOB[2]) and bearishCandle ? true : na

// Plot en el gráfico
plotshape( ShowBS ?buySignal:na, title="Buy Signal", location=location.belowbar,
color=color.green, style=shape.triangleup, size=size.small, text="Buy",
textcolor=color.rgb(255, 0, 0))
plotshape( ShowBS ?sellSignal:na, title="Sell Signal", location=location.abovebar,
color=color.red, style=shape.triangledown, size=size.small, text="Sell",
textcolor=color.rgb(255, 0, 0))

////////////////////////////
////////////////// REV ZONES BB ////////////////////

length = input.int(160, minval=1,title = "BAND",group = " Reversal Band")


maType = input.string("SMA", "Basis MA Type", options = ["SMA", "EMA", "SMMA
(RMA)", "WMA", "VWMA"],group = " Reversal Band")
srcb = input(close, title="Source",group = " Reversal Band")
multb = input.float(2.0, minval=0.001, maxval=50, title="StdDev",group = " Reversal
Band")
Smoothing1 = input(5, 'Smoothing')
ma(source, length, _type) =>
switch _type
"SMA" => ta.sma(source, length)
"EMA" => ta.ema(source, length)
"SMMA (RMA)" => ta.rma(source, length)
"WMA" => ta.wma(source, length)
"VWMA" => ta.vwma(source, length)

basis = ma(srcb, length, maType)


dev = multb * ta.stdev(srcb, length)
upper = basis + dev
lower = basis - dev
offset11 = input.int(0, "Offset", minval = -500, maxval = 500)
//plot(basis, "Basis", color=#FF6D00, offset = offset11,display = display.none,
editable = false)
A1 = plot(reversalZone?(ta.sma(upper, Smoothing1)):na, "Upper", color=#2962FF,
offset = offset11,display = display.none, editable = false)
B1 = plot(reversalZone?(ta.sma(lower, Smoothing1)):na, "Lower", color=#2962FF,
offset = offset11,display = display.none, editable = false)

mult1 = input.float(3.0, minval=0.001, maxval=50, title="StdDev")

basis1 = ma(srcb, length, maType)


dev1 = mult1 * ta.stdev(srcb, length)
upper1 = basis1 + dev1
lower1 = basis1 - dev1
offset12 = input.int(0, "Offset", minval = -500, maxval = 500)
//plot(basis1, "Basis", color=#FF6D00, offset = offset12,display = display.none,
editable = false)
A11 = plot(reversalZone?(ta.sma(upper1, Smoothing1)) : na, "Upper", color=#2962FF,
offset = offset12, editable = false)
B11 = plot(reversalZone?(ta.sma(lower1, Smoothing1)) : na, "Lower", color=#2962FF,
offset = offset12, editable = false)

fill(A1, A11, color = #a5a9ab86, transp = 60, editable = false)


fill(B1, B11, color = #a5a9ab86, transp = 60, editable = false)

////////////////// CPR //////////////////

pivottimeframe = input.string(title='Pivot Resolution Big Timeframe', defval='D',


options=['W', 'D', '240', '180', '120', '60'])

mdp = input(defval=1, title='Multiday CPR')


//dp = input(true, title="Show Daily CPR")
mp = input(true, title='Show Multiday CPR')

//mp in the prefix implies multiday pivot calculation


mpopen = request.security(syminfo.tickerid, pivottimeframe, open[mdp],
barmerge.gaps_off, barmerge.lookahead_on)
mphigh = request.security(syminfo.tickerid, pivottimeframe, ta.highest(high, mdp)
[1], barmerge.gaps_off, barmerge.lookahead_on)
mplow = request.security(syminfo.tickerid, pivottimeframe, ta.lowest(low, mdp)[1],
barmerge.gaps_off, barmerge.lookahead_on)
mpclose = request.security(syminfo.tickerid, pivottimeframe, close[1],
barmerge.gaps_off, barmerge.lookahead_on)

//Multiday CPR Calculation


mpivot = (mphigh + mplow + mpclose) / 3.0
mbc = (mphigh + mplow) / 2.0
mtc = mpivot - mbc + mpivot

plot(CPR?(mp and mpivot ? mpivot : na):na, title='P', color=color.new(color.purple,


0), style=plot.style_line)
c = plot(CPR?(mp and mbc ? mbc : na):na, title='BC', color=color.new(color.blue,
0), style=plot.style_line)
d = plot(CPR?(mp and mtc ? mtc : na):na, title='TC', color=color.new(color.blue,
0), style=plot.style_line)
fill(c, d, color=color.new(#318da7, 62))

//
===================================================================================
============================================

// EzAlgo SR

// Get user input


//colorSup = input.color(color.new(#66bb6a,80), 'Long Boxes')
//colorRes = input.color(color.new(#f7525f,80), 'Short Boxes')
colorSup = #04994b
colorRes = #b4060d
strengthSR = input.int(4, "Support&Resistance Strength", 1, group="👉
Support/Resistance")
lineStylea = input.string("Solid", "Line Style", ["Solid", "Dotted", "Dashed"])
lineWidtha = input.int(2, "S/R Line Width", 1)
useZones = input(true, "SR Zones")
useHLZones = input(true, "Zones On/Off")
zoneWidtha = input.int(2, "Zone Width %", 0, tooltip="it's calculated using % of
the distance between highest/lowest in last 300 bars")
expandSR = input(true, "Expand Support and Resistances")
// Functions
percWidth(len, perc) => (ta.highest(len) - ta.lowest(len)) * perc / 100
// Get components
rb = 10
prd = 284
ChannelW = 10
label_loc = 55
style = lineStylea == "Solid" ? line.style_solid : lineStylea == "Dotted" ?
line.style_dotted : line.style_dashed
ph = ta.pivothigh(rb, rb)
pl = ta.pivotlow (rb, rb)
sr_levels = array.new_float(21, na)
prdhighest = ta.highest(prd)
prdlowest = ta.lowest(prd)
cwidth = percWidth(prd, ChannelW)
zonePerc = percWidth(300, zoneWidtha)
aas = array.new_bool(41, true)
u1 = 0.0, u1 := nz(u1[1])
d1 = 0.0, d1 := nz(d1[1])
highestph = 0.0, highestph := highestph[1]
lowestpl = 0.0, lowestpl := lowestpl[1]
var sr_levs = array.new_float(21, na)
var sr_lines = array.new_line(21, na)
var sr_linesH = array.new_line(21, na)
var sr_linesL = array.new_line(21, na)
var sr_linesF = array.new_linefill(21, na)
var sr_labels = array.new_label(21, na)
if ph or pl
for x = 0 to array.size(sr_levels) - 1
array.set(sr_levels, x, na)
highestph := prdlowest
lowestpl := prdhighest
countpp = 0
for x = 0 to prd
if na(close[x])
break
if not na(ph[x]) or not na(pl[x])
highestph := math.max(highestph, nz(ph[x], prdlowest), nz(pl[x],
prdlowest))
lowestpl := math.min(lowestpl, nz(ph[x], prdhighest), nz(pl[x],
prdhighest))
countpp += 1
if countpp > 40
break
if array.get(aas, countpp)
upl = (ph[x] ? high[x + rb] : low[x + rb]) + cwidth
dnl = (ph[x] ? high[x + rb] : low[x + rb]) - cwidth
u1 := countpp == 1 ? upl : u1
d1 := countpp == 1 ? dnl : d1
tmp = array.new_bool(41, true)
cnt = 0
tpoint = 0
for xx = 0 to prd
if na(close[xx])
break
if not na(ph[xx]) or not na(pl[xx])
chg = false
cnt += 1
if cnt > 40
break
if array.get(aas, cnt)
if not na(ph[xx])
if high[xx + rb] <= upl and high[xx + rb] >= dnl
tpoint += 1
chg := true
if not na(pl[xx])
if low[xx + rb] <= upl and low[xx + rb] >= dnl
tpoint += 1
chg := true
if chg and cnt < 41
array.set(tmp, cnt, false)
if tpoint >= strengthSR
for g = 0 to 40 by 1
if not array.get(tmp, g)
array.set(aas, g, false)
if ph[x] and countpp < 21
array.set(sr_levels, countpp, high[x + rb])
if pl[x] and countpp < 21
array.set(sr_levels, countpp, low[x + rb])
// Plot
var line highest_ = na, line.delete(highest_)
var line lowest_ = na, line.delete(lowest_)
var line highest_fill1 = na, line.delete(highest_fill1)
var line highest_fill2 = na, line.delete(highest_fill2)
var line lowest_fill1 = na, line.delete(lowest_fill1)
var line lowest_fill2 = na, line.delete(lowest_fill2)
hi_col = close >= highestph ? colorSup : colorRes
lo_col = close >= lowestpl ? colorSup : colorRes
if enableSR
highest_ := line.new(bar_index - 311, highestph, bar_index, highestph,
xloc.bar_index, expandSR ? extend.both : extend.right, hi_col, style, lineWidtha)
lowest_ := line.new(bar_index - 311, lowestpl , bar_index, lowestpl ,
xloc.bar_index, expandSR ? extend.both : extend.right, lo_col, style, lineWidtha)
if useHLZones
highest_fill1 := line.new(bar_index - 311, highestph + zonePerc, bar_index,
highestph + zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
highest_fill2 := line.new(bar_index - 311, highestph - zonePerc, bar_index,
highestph - zonePerc, xloc.bar_index, expandSR ? extend.both : extend.right, na)
lowest_fill1 := line.new(bar_index - 311, lowestpl + zonePerc , bar_index,
lowestpl + zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
lowest_fill2 := line.new(bar_index - 311, lowestpl - zonePerc , bar_index,
lowestpl - zonePerc , xloc.bar_index, expandSR ? extend.both : extend.right, na)
linefill.new(highest_fill1, highest_fill2, color.new(hi_col, 80))
linefill.new(lowest_fill1 , lowest_fill2 , color.new(lo_col, 80))
if ph or pl
for x = 0 to array.size(sr_lines) - 1
array.set(sr_levs, x, array.get(sr_levels, x))
for x = 0 to array.size(sr_lines) - 1
line.delete(array.get(sr_lines, x))
line.delete(array.get(sr_linesH, x))
line.delete(array.get(sr_linesL, x))
linefill.delete(array.get(sr_linesF, x))
if array.get(sr_levs, x) and enableSR
line_col = close >= array.get(sr_levs, x) ? colorSup : colorRes
array.set(sr_lines, x, line.new(bar_index - 355, array.get(sr_levs, x),
bar_index, array.get(sr_levs, x), xloc.bar_index, expandSR ? extend.both :
extend.right, line_col, style, lineWidtha))
if useZones
array.set(sr_linesH, x, line.new(bar_index - 355, array.get(sr_levs, x)
+ zonePerc, bar_index, array.get(sr_levs, x) + zonePerc, xloc.bar_index, expandSR ?
extend.both : extend.right, na))
array.set(sr_linesL, x, line.new(bar_index - 355, array.get(sr_levs, x)
- zonePerc, bar_index, array.get(sr_levs, x) - zonePerc, xloc.bar_index, expandSR ?
extend.both : extend.right, na))
array.set(sr_linesF, x, linefill.new(array.get(sr_linesH, x),
array.get(sr_linesL, x), color.new(line_col, 80)))

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

//////////////////////////// SUPPLY AND DEMAND/////////////////////////////////

// INDICATOR SETTINGS
swing_length = input.int(10, title = 'Swing High/Low Length', group = "👉 SUPPLY AND
DEMAND", minval = 1, maxval = 50)
history_of_demand_to_keep = input.int(20, title = 'History To Keep',group = "👉
SUPPLY AND DEMAND" ,minval = 5, maxval = 50)
box_width = input.float(7, title = 'Supply/Demand Box Width', group = "👉 SUPPLY AND
DEMAND", minval = 1, maxval = 10, step = 0.5)

// INDICATOR VISUAL SETTINGS


show_zigzag = input.bool(false, title = 'Show Zig Zag', group = 'Visual Settings',
inline = '1')
show_price_action_labels = input.bool(false, title = 'Show Price Action Labels',
group = 'Visual Settings', inline = '2')

supply_color = input.color(color.new(#807878, 70), title = 'SELL ZONE', group =


'Visual Settings', inline = '3')
supply_outline_color = input.color(color.new(#ffffff, 100), title = 'Outline',
group = 'Visual Settings', inline = '3')

demand_color = input.color(color.new(#807878,70), title = 'BUY ZONE', group =


'Visual Settings', inline = '4')
demand_outline_color = input.color(color.new(#ffffff, 100), title = 'Outline',
group = 'Visual Settings', inline = '4')

bos_label_color = input.color(color.rgb(255, 255, 255, 100), title = 'BOS Label',


group = 'Visual Settings', inline = '5')
poi_label_color = input.color(color.rgb(0, 94, 255), title = 'POI Label', group =
'Visual Settings', inline = '7')

swing_type_color = input.color(color.black, title = 'Price Action Label', group =


'Visual Settings', inline = '8')
zigzag_color = input.color(color.new(#000000,0), title = 'Zig Zag', group = 'Visual
Settings', inline = '9')

//
//END SETTINGS
//

//
//FUNCTIONS
//

// FUNCTION TO ADD NEW AND REMOVE LAST IN ARRAY


f_array_add_pop(array, new_value_to_add) =>
array.unshift(array, new_value_to_add)
array.pop(array)

// FUNCTION SWING H & L LABELS


f_sh_sl_labels(array, swing_type) =>

var string label_text = na


if swing_type == 1
if array.get(array, 0) >= array.get(array, 1)
label_text := 'HH'
else
label_text := 'LH'
label.new(bar_index - swing_length, array.get(array,0), text = label_text,
style=label.style_label_down, textcolor = swing_type_color, color =
color.new(swing_type_color, 100), size = size.tiny)

else if swing_type == -1
if array.get(array, 0) >= array.get(array, 1)
label_text := 'HL'
else
label_text := 'LL'
label.new(bar_index - swing_length, array.get(array,0), text = label_text,
style=label.style_label_up, textcolor = swing_type_color, color =
color.new(swing_type_color, 100), size = size.tiny)

// FUNCTION MAKE SURE SUPPLY ISNT OVERLAPPING


f_check_overlapping(new_poi, box_array, atr7) =>

atr_threshold = atr7 * 2
okay_to_draw = true

for i = 0 to array.size(box_array) - 1
top = box.get_top(array.get(box_array, i))
bottom = box.get_bottom(array.get(box_array, i))
poi = (top + bottom) / 2

upper_boundary = poi + atr_threshold


lower_boundary = poi - atr_threshold

if new_poi >= lower_boundary and new_poi <= upper_boundary


okay_to_draw := false
break
else
okay_to_draw := true
okay_to_draw
// FUNCTION TO DRAW SUPPLY OR DEMAND ZONE
f_supply_demand(value_array, bn_array, box_array, label_array, box_type, atr7) =>

atr_buffer = atr7 * (box_width / 10)


box_left = array.get(bn_array, 0)
box_right = bar_index

var float box_top = 0.00


var float box_bottom = 0.00
var float poi = 0.00

if box_type == 1
box_top := array.get(value_array, 0)
box_bottom := box_top - atr_buffer
poi := (box_top + box_bottom) / 2
else if box_type == -1
box_bottom := array.get(value_array, 0)
box_top := box_bottom + atr_buffer
poi := (box_top + box_bottom) / 2

okay_to_draw = f_check_overlapping(poi, box_array, atr7)


// okay_to_draw = true

//delete oldest box, and then create a new box and add it to the array
if box_type == 1 and okay_to_draw
box.delete( array.get(box_array, array.size(box_array) - 1) )
f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right =
box_right, bottom = box_bottom, border_color = supply_outline_color,
bgcolor = ShowSR?supply_color:na, extend = extend.right, text = 'SELL
ZONE', text_halign = text.align_center, text_valign = text.align_center, text_color
= ShowSR?poi_label_color:na, text_size = size.small, xloc = xloc.bar_index))

box.delete( array.get(label_array, array.size(label_array) - 1) )


f_array_add_pop(label_array, box.new( left = box_left, top = poi, right =
box_right, bottom = poi, border_color = ShowSR?color.new(poi_label_color,90):na,
bgcolor = ShowSR?color.new(poi_label_color,90):na, extend =
extend.right, text_halign = text.align_left, text_valign = text.align_center,
text_color = ShowSR?poi_label_color:na, text_size = size.small, xloc =
xloc.bar_index))

else if box_type == -1 and okay_to_draw


box.delete( array.get(box_array, array.size(box_array) - 1) )
f_array_add_pop(box_array, box.new( left = box_left, top = box_top, right =
box_right, bottom = box_bottom, border_color = demand_outline_color,
bgcolor = ShowSR?demand_color:na, extend = extend.right, text = 'BUY
ZONE', text_halign = text.align_center, text_valign = text.align_center, text_color
= ShowSR?poi_label_color:na, text_size = size.small, xloc = xloc.bar_index))

box.delete( array.get(label_array, array.size(label_array) - 1) )


f_array_add_pop(label_array, box.new( left = box_left, top = poi, right =
box_right, bottom = poi, border_color = ShowSR?color.new(poi_label_color,90):na,
bgcolor = ShowSR?color.new(poi_label_color,90):na, extend =
extend.right, text_halign = text.align_left, text_valign = text.align_center,
text_color = ShowSR?poi_label_color:na, text_size = size.small, xloc =
xloc.bar_index))
// FUNCTION TO CHANGE SUPPLY/DEMAND TO A BOS IF BROKEN
f_sd_to_bos(box_array, bos_array, label_array, zone_type) =>

if zone_type == 1
for i = 0 to array.size(box_array) - 1
level_to_break = box.get_top(array.get(box_array,i))
// if ta.crossover(close, level_to_break)
if close >= level_to_break
copied_box = box.copy(array.get(box_array,i))
f_array_add_pop(bos_array, copied_box)
mid = (box.get_top(array.get(box_array,i)) +
box.get_bottom(array.get(box_array,i))) / 2
box.set_top(array.get(bos_array,0), mid)
box.set_bottom(array.get(bos_array,0), mid)
box.set_extend( array.get(bos_array,0), extend.none)
box.set_right( array.get(bos_array,0), bar_index)
box.set_text( array.get(bos_array,0), 'BOS' )
box.set_text_color( array.get(bos_array,0), bos_label_color)
box.set_text_size( array.get(bos_array,0), size.small)
box.set_text_halign( array.get(bos_array,0), text.align_center)
box.set_text_valign( array.get(bos_array,0), text.align_center)
box.delete(array.get(box_array, i))
box.delete(array.get(label_array, i))

if zone_type == -1
for i = 0 to array.size(box_array) - 1
level_to_break = box.get_bottom(array.get(box_array,i))
// if ta.crossunder(close, level_to_break)
if close <= level_to_break
copied_box = box.copy(array.get(box_array,i))
f_array_add_pop(bos_array, copied_box)
mid = (box.get_top(array.get(box_array,i)) +
box.get_bottom(array.get(box_array,i))) / 2
box.set_top(array.get(bos_array,0), mid)
box.set_bottom(array.get(bos_array,0), mid)
box.set_extend( array.get(bos_array,0), extend.none)
box.set_right( array.get(bos_array,0), bar_index)
box.set_text( array.get(bos_array,0), 'BOS' )
box.set_text_color( array.get(bos_array,0), bos_label_color)
box.set_text_size( array.get(bos_array,0), size.small)
box.set_text_halign( array.get(bos_array,0), text.align_center)
box.set_text_valign( array.get(bos_array,0), text.align_center)
box.delete(array.get(box_array, i))
box.delete(array.get(label_array, i))

// FUNCTION MANAGE CURRENT BOXES BY CHANGING ENDPOINT


f_extend_box_endpoint(box_array) =>

for i = 0 to array.size(box_array) - 1
box.set_right(array.get(box_array, i), bar_index + 100)

//
//END FUNCTIONS
//
//
//CALCULATIONS
//

// CALCULATE ATR
atr7 = ta.atr(50)

// CALCULATE SWING HIGHS & SWING LOWS


swing_high = ta.pivothigh(high, swing_length, swing_length)
swing_low = ta.pivotlow(low, swing_length, swing_length)

// ARRAYS FOR SWING H/L & BN


var swing_high_values = array.new_float(5,0.00)
var swing_low_values = array.new_float(5,0.00)

var swing_high_bns = array.new_int(5,0)


var swing_low_bns = array.new_int(5,0)

// ARRAYS FOR SUPPLY / DEMAND


var current_supply_box = array.new_box(history_of_demand_to_keep, na)
var current_demand_box = array.new_box(history_of_demand_to_keep, na)

// ARRAYS FOR SUPPLY / DEMAND POI LABELS


var current_supply_poi = array.new_box(history_of_demand_to_keep, na)
var current_demand_poi = array.new_box(history_of_demand_to_keep, na)

// ARRAYS FOR BOS


var supply_bos = array.new_box(5, na)
var demand_bos = array.new_box(5, na)
//
//END CALCULATIONS
//

// NEW SWING HIGH


if not na(swing_high)

//MANAGE SWING HIGH VALUES


f_array_add_pop(swing_high_values, swing_high)
f_array_add_pop(swing_high_bns, bar_index[swing_length])
if show_price_action_labels
f_sh_sl_labels(swing_high_values, 1)

f_supply_demand(swing_high_values, swing_high_bns, current_supply_box,


current_supply_poi, 1, atr7)

// NEW SWING LOW


else if not na(swing_low)

//MANAGE SWING LOW VALUES


f_array_add_pop(swing_low_values, swing_low)
f_array_add_pop(swing_low_bns, bar_index[swing_length])
if show_price_action_labels
f_sh_sl_labels(swing_low_values, -1)

f_supply_demand(swing_low_values, swing_low_bns, current_demand_box,


current_demand_poi, -1, atr7)
f_sd_to_bos(current_supply_box, supply_bos, current_supply_poi, 1)
f_sd_to_bos(current_demand_box, demand_bos, current_demand_poi, -1)

f_extend_box_endpoint(current_supply_box)
f_extend_box_endpoint(current_demand_box)

//ZIG ZAG
h = ta.highest(high, swing_length * 2 + 1)
l = ta.lowest(low, swing_length * 2 + 1)
f_isMin(len) =>
l == low[len]
f_isMax(len) =>
h == high[len]

var dirUp = false


var lastLow = high * 100
var lastHigh = 0.0
var timeLow = bar_index
var timeHigh = bar_index
var line li = na

f_drawLine() =>
_li_color = show_zigzag ? zigzag_color : color.new(#ffffff,100)
line.new(timeHigh - swing_length, lastHigh, timeLow - swing_length, lastLow,
xloc.bar_index, color=_li_color, width=2)

if dirUp
if f_isMin(swing_length) and low[swing_length] < lastLow
lastLow := low[swing_length]
timeLow := bar_index
line.delete(li)
li := f_drawLine()
li

if f_isMax(swing_length) and high[swing_length] > lastLow


lastHigh := high[swing_length]
timeHigh := bar_index
dirUp := false
li := f_drawLine()
li

if not dirUp
if f_isMax(swing_length) and high[swing_length] > lastHigh
lastHigh := high[swing_length]
timeHigh := bar_index
line.delete(li)
li := f_drawLine()
li
if f_isMin(swing_length) and low[swing_length] < lastHigh
lastLow := low[swing_length]
timeLow := bar_index
dirUp := true
li := f_drawLine()
if f_isMax(swing_length) and high[swing_length] > lastLow
lastHigh := high[swing_length]
timeHigh := bar_index
dirUp := false
li := f_drawLine()
li
// if barstate.islast
// label.new(x = bar_index + 10, y = close[1], text =
str.tostring( array.size(current_supply_poi) ))
// label.new(x = bar_index + 20, y = close[1], text =
str.tostring( box.get_bottom( array.get(current_supply_box, 0))))
// label.new(x = bar_index + 30, y = close[1], text =
str.tostring( box.get_bottom( array.get(current_supply_box, 1))))
// label.new(x = bar_index + 40, y = close[1], text =
str.tostring( box.get_bottom( array.get(current_supply_box, 2))))
// label.new(x = bar_index + 50, y = close[1], text =
str.tostring( box.get_bottom( array.get(current_supply_box, 3))))
// label.new(x = bar_index + 60, y = close[1], text =
str.tostring( box.get_bottom( array.get(current_supply_box, 4))))

// # ============================[SESSIONS]============================ #

//Session A
show_sesa = input(true, '', inline = 'sesa', group = 'Session A')
sesa_txt = input('New York', '', inline = 'sesa', group = 'Session A')
sesa_ses = input.session('1300-2200', '', inline = 'sesa', group = 'Session A')
sesa_css = input.color(#ff5e0049, '', inline = 'sesa', group = 'Session A')

sesa_range = input(true, 'Range', inline = 'sesa_overlays', group = 'Session A')


sesa_tl = input(false, 'Trendline', inline = 'sesa_overlays', group = 'Session A')
sesa_avg = input(false, 'Mean', inline = 'sesa_overlays', group = 'Session A')
sesa_vwap = input(false, 'VWAP', inline = 'sesa_overlays', group = 'Session A')
sesa_maxmin = input(false, 'Max/Min', inline = 'sesa_overlays', group = 'Session
A')

//Session B
show_sesb = input(true, '', inline = 'sesb', group = 'Session B')
sesb_txt = input('London', '', inline = 'sesb', group = 'Session B')
sesb_ses = input.session('0700-1600', '', inline = 'sesb', group = 'Session B')
sesb_css = input.color(#2156f349, '', inline = 'sesb', group = 'Session B')

sesb_range = input(true, 'Range', inline = 'sesb_overlays', group = 'Session B')


sesb_tl = input(false, 'Trendline', inline = 'sesb_overlays', group = 'Session B')
sesb_avg = input(false, 'Mean', inline = 'sesb_overlays', group = 'Session B')
sesb_vwap = input(false, 'VWAP', inline = 'sesb_overlays', group = 'Session B')
sesb_maxmin = input(false, 'Max/Min', inline = 'sesb_overlays', group = 'Session
B')

//Session C
show_sesc = input(true, '', inline = 'sesc', group = 'Session C')
sesc_txt = input('Tokyo', '', inline = 'sesc', group = 'Session C')
sesc_ses = input.session('0000-0900', '', inline = 'sesc', group = 'Session C')
sesc_css = input.color(#00000049, '', inline = 'sesc', group = 'Session C')

sesc_range = input(true, 'Range', inline = 'sesc_overlays', group = 'Session C')


sesc_tl = input(false, 'Trendline', inline = 'sesc_overlays', group = 'Session C')
sesc_avg = input(false, 'Mean', inline = 'sesc_overlays', group = 'Session C')
sesc_vwap = input(false, 'VWAP', inline = 'sesc_overlays', group = 'Session C')
sesc_maxmin = input(false, 'Max/Min', inline = 'sesc_overlays', group = 'Session
C')

//Timezones
tz_incr = input.int(0, 'UTC (+/-)', group = 'Timezone')
use_exchange = input(false, 'Use Exchange Timezone', group = 'Timezone')

//Ranges Options
bg_transp = input.float(90, 'Background Borders', group = 'Ranges Settings')
show_outline = input(true, 'Range Outline', group = 'Ranges Settings')
show_txt = input(true, 'Range Label', group = 'Ranges Settings')

//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n = bar_index

//Get session average


get_avg(session)=>
var len = 1
var float csma = na
var float sma = na

if session > session[1]


len := 1
csma := close

if session and session == session[1]


len += 1
csma += close
sma := csma / len

sma

//Get trendline coordinates


get_linreg(session)=>
var len = 1
var float cwma = na
var float csma = na
var float csma2 = na

var float y1 = na
var float y2 = na
var float stdev = na
var float r2 = na

if session > session[1]


len := 1
cwma := close
csma := close
csma2 := close * close

if session and session == session[1]


len += 1
csma += close
csma2 += close * close
cwma += close * len

sma = csma / len


wma = cwma / (len * (len + 1) / 2)

cov = (wma - sma) * (len+1)/2


stdev := math.sqrt(csma2 / len - sma * sma)
r2 := cov / (stdev * (math.sqrt(len*len - 1) / (2 * math.sqrt(3))))
y1 := 4 * sma - 3 * wma
y2 := 3 * wma - 2 * sma

[y1 , y2, stdev, r2]

//Session Vwap
get_vwap(session) =>
var float num = na
var float den = na

if session > session[1]


num := close * volume
den := volume

else if session and session == session[1]


num += close * volume
den += volume
else
num := na

[num, den]

//Set line
set_line(session, y1, y2, session_css)=>
var line tl = na

if session > session[1]


tl := line.new(n, close, n, close, color = session_css)

if session and session == session[1]


line.set_y1(tl, y1)
line.set_xy2(tl, n, y2)

//Set session range


get_range(session, session_name, session_css)=>
var t = 0
var max = high
var min = low
var box bx = na
var label lbl = na

if session > session[1]


t := time
max := high
min := low

bx := box.new(n, max, n, min


, bgcolor = color.new(session_css, bg_transp)
, border_color = show_outline ? session_css : na
, border_style = line.style_dotted)

if show_txt
lbl := label.new(t, max, session_name
, xloc = xloc.bar_time
, textcolor = session_css
, style = label.style_label_down
, color = color.new(color.white, 100)
, size = size.tiny)
if session and session == session[1]
max := math.max(high, max)
min := math.min(low, min)

box.set_top(bx, max)
box.set_rightbottom(bx, n, min)

if show_txt
label.set_xy(lbl, int(math.avg(t, time)), max)

[session ? na : max, session ? na : min]

//-----------------------------------------------------------------------------}
//Sessions
//-----------------------------------------------------------------------------{
tf = timeframe.period

var tz = use_exchange ? syminfo.timezone :


str.format('UTC{0}{1}', tz_incr >= 0 ? '+' : '-', math.abs(tz_incr))

is_sesa = math.sign(nz(time(tf, sesa_ses, tz)))


is_sesb = math.sign(nz(time(tf, sesb_ses, tz)))
is_sesc = math.sign(nz(time(tf, sesc_ses, tz)))

//-----------------------------------------------------------------------------}
//Overlays
//-----------------------------------------------------------------------------{
var float max_sesa = na
var float min_sesa = na
var float max_sesb = na
var float min_sesb = na
var float max_sesc = na
var float min_sesc = na
var float max_sesd = na
var float min_sesd = na

//Ranges
if showSessions? (show_sesa and sesa_range):na
[max, min] = get_range(is_sesa, sesa_txt, sesa_css)
max_sesa := max
min_sesa := min

if showSessions? (show_sesb and sesb_range):na


[max, min] = get_range(is_sesb, sesb_txt, sesb_css)
max_sesb := max
min_sesb := min

if showSessions?(show_sesc and sesc_range):na


[max, min] = get_range(is_sesc, sesc_txt, sesc_css)
max_sesc := max
min_sesc := min

//-----------------------------------------------------------------------------{
//Plot max/min
plot(showSessions and sesa_maxmin ? max_sesa : na, 'Session A Maximum', sesa_css,
1, plot.style_linebr,editable = false)
plot(showSessions and sesa_maxmin ? min_sesa : na, 'Session A Minimum', sesa_css,
1, plot.style_linebr,editable = false)

plot(showSessions and sesb_maxmin ? max_sesb : na, 'Session B Maximum', sesb_css,


1, plot.style_linebr,editable = false)
plot(showSessions and sesb_maxmin ? min_sesb : na, 'Session B Minimum', sesb_css,
1, plot.style_linebr,editable = false)

plot(showSessions and sesc_maxmin ? max_sesc : na, 'Session C Maximum', sesc_css,


1, plot.style_linebr,editable = false)
plot(showSessions and sesc_maxmin ? min_sesc : na, 'Session C Minimum', sesc_css,
1, plot.style_linebr,editable = false)

///////////////////////////////////////// ZIGZAG HIGH


LOW //////////////////////////

// 0. Inputs
// 1. Types
// 2. Switches
// 3. Variables and arrays
// 4. Custom Functions
// 5. Execution
// 6. Constructs

//#region ———————————————————— 0. Inputs


K0 = 'Zigzag values\nDefault : 14\nMin : 2\nMax : 50'
K1 = 'Short\nExamKle : L or LL\nLong\nExamKle : Low or Lower Low'
K2 = 'Constrast : Constrast color of chart background\nCustom : Input color\nNone :
Color follow Trend Color'
K3 = 'Small font size recommended for mobile app or multiKle layout'
K4 = 'Default\nStyle : Solid\nWidth : 4'
length1 = input.int( 21, 'Trend Speed', minval = 2, maxval = 50,
tooltip = K0,group = " ZIGZAG HIGH - LOW")
colorUp = input.color(color.rgb(187, 194, 190),'Trend Color', inline = '0')
colorDn = input.color( color.rgb(196, 187, 187), '', inline = '0')
showLabel = input.bool( true, 'Label', group = 'Show / hide',
inline = '1')
showLine = input.bool( true, 'Line', group = 'Show / hide',
inline = '1')
disKlayLabel = input.string( 'HHLL', 'Text', group = 'Label', inline =
'2', options = ['HHLL', 'HL'])
nameHL = input.string( 'Short', '', group = 'Label', inline =
'2', options = ['Short', 'Long'], tooltip = K1)
colorLabel = input.string( 'Trend', 'Color', group = 'Label', inline =
'3', options = ['Contrast', 'Custom', 'Trend'])
customLabel = input.color(color.blue, '', group = 'Label', inline = '3',
tooltip = K2)
sizeLabel = input.string( 'normal', 'Size', group = 'Label', inline =
'4', options = ['tiny', 'small', 'normal', 'large', 'huge'], tooltip = K3)
lineType = input.string( 'solid', 'DisKlay', group = 'Line', inline =
'5', options = ['dash', 'dot', 'solid', 'arrow right', 'arrow left'])
width = input.int( 1, '', group = 'Line', inline =
'5', minval = 1, maxval = 4, tooltip = K4)
colorLine = input.string( 'Trend', 'Color', group = 'Line', inline =
'6', options = ['Contrast', 'Custom', 'Trend'])
customLine = input.color(color.blue, '', group = 'Line', inline = '6',
tooltip = K2)
//#endregion

//#region ———————————————————— 1. Types


// @type Used for label
// @field Hi Float value of high
// @field Lo Float value of low
type HL
string Hi = na
string Lo = na

// @type Used for point especially for array


// @field x int value for bar_index
// @field y float value for price
// @field sty label style
// @field col color for text label
// @field str high or low string
type point
int x = na
float y = na
string sty = na
color col = na
string str = na

// @type Used for initial setup


// @field hi high value
// @field lo low value
// @field colorHi color for high value
// @field colorLo color for low value
// @field strHi string for high value
// @field strLo string for low value
type startUp
float hi = na
float lo = na
color colorHi = na
color colorLo = na
string strHi = na
string strLo = na
//#endregion

//#region ———————————————————— 2. Switches


[H, L] = switch nameHL
'Short' => [ 'H', 'L']
'Long' => ['HIGH', 'LOW']
[Hi, Lo] = switch nameHL
'Short' => [ 'H', 'L']
'Long' => ['HIGHER\n', 'LOWER\n']
switchLine = switch lineType
'dash' => line.style_dashed
'dot' => line.style_dotted
'solid' => line.style_solid
'arrow right' => line.style_arrow_right
'arrow left' => line.style_arrow_left
switchLabelColor = switch colorLabel
'Contrast' => chart.fg_color
'Custom' => customLabel
switchLineColor = switch colorLine
'Contrast' => chart.fg_color
'Custom' => customLine
//#endregion

//#region ———————————————————— 3. Variables and arrays


float Kh = na, Kh := ta.highestbars(high, length1 ) == 0 ? high : na
float Kl = na, Kl := ta.lowestbars( low, length1 ) == 0 ? low : na
var dir = 0, dir := Kh and na(Kl) ? 1 : Kl and na(Kh) ? -1 : dir
var zigzag = array.new<point>(0)
oldzigzag = zigzag.copy()
dirchanged = ta.change(dir)
hiLo = HL.new(Hi, Lo)
varSetup = startUp.new(Kh, Kl, colorUp, colorDn, H, L)
//#endregion

//#region ———————————————————— 4. Custom Functions


// @function variable for point
// @param setup type containing ternary conditional operator
// @returns newPoint to be used later in initialize
method dirVariables(startUp setup = na) =>
var point newPoint = na
x = bar_index
y = dir == 1 ? setup.hi : setup.lo
sty = dir == 1 ? label.style_label_down : label.style_label_up
col = dir == 1 ? setup.colorHi : setup.colorLo
str = dir == 1 ? setup.strHi : setup.strLo
newPoint := point.new(x, y, sty, col, str)
newPoint

// @function initialize zigzag array


// @param setup type containing ternary conditional operator
// @param maxSize maximum array size
// @returns zigzag array after cleanup
method initialize(point[] zigzag = na, startUp setup = na, int maxSize = 10)=>
newPoint = setup.dirVariables()
zigzag.unshift(newPoint)
if zigzag.size() > maxSize
zigzag.pop()

// @function update zigzag array


// @param setup type containing ternary conditional operator
// @param maxSize maximum array size
// @param dir direction value
// @returns zigzag array after cleanup
method update(point[] zigzag = na, startUp setup = na, maxSize = 10, int dir =
na)=>
if array.size(zigzag) == 0
zigzag.initialize(setup, maxSize)
else
newPoint = setup.dirVariables()
dirOver = dir == 1 and newPoint.y > zigzag.get(0).y
dirLess = dir == -1 and newPoint.y < zigzag.get(0).y
if dirOver or dirLess
zigzag.set(0, newPoint)
point.new(na, na, na, na, na)

// @function compare zigzag


// @param zigzag original array
// @param oldzigzag copied array
// @returns boolOr Or statement
// @returns boolAnd And statement
method boolPoint(point[] zigzag = na, point[] oldzigzag = na, int offset = 0) =>
boolOr = zigzag.get(offset + 0).x != oldzigzag.get(offset + 0).x or
zigzag.get(offset + 0).y != oldzigzag.get(offset + 0).y
boolAnd = zigzag.get(offset + 1).x == oldzigzag.get(offset + 1).x and
zigzag.get(offset + 1).y == oldzigzag.get(offset + 1).y
[boolOr, boolAnd]

// @function create label based on zigzag array


// @param zigzag original array
// @param size font size
// @param offset default value zero
// @returns new label
method createLabel(point[] zigzag = na, string size = na, int offset = 0) =>
label.new( x = int(zigzag.get(offset + 0).x),
y = zigzag.get(offset + 0).y,
text = zigzag.get(offset + 0).str,
xloc = xloc.bar_index,
color = color.new(color.blue, 100),
style = zigzag.get(offset + 0).sty,
textcolor = zigzag.get(offset + 0).col,
size = size,
tooltip = zigzag.get(offset + 0).str + '\n' +
str.tostring(zigzag.get(offset + 0).y))

// @function create line based on zigzag array


// @param zigzag original array
// @param width line thickness
// @param style line style
// @param offset default value zero
// @returns new line
method createLine(point[] zigzag = na, int width = na, string style = na, int
offset = 0) =>
line.new(x1 = int(zigzag.get(offset + 1).x),
y1 = zigzag.get(offset + 1).y,
x2 = int(zigzag.get(offset + 0).x),
y2 = zigzag.get(offset + 0).y,
xloc = xloc.bar_index,
color = zigzag.get(offset + 0).col,
style = style,
width = width)

// @function create line based on zigzag array


// @param zigzag original array
// @param hiLo switch value
// @param offset default value zero
// @returns ternary conditional of hiLo
method compareHL(point[] zigzag = na, HL hiLo = na, int offset = 0) =>
dir == 1 ? zigzag.get(offset + 0).y > zigzag.get(offset + 2).y ? hiLo.Hi :
hiLo.Lo :
zigzag.get(offset + 0).y < zigzag.get(offset + 2).y ? hiLo.Lo :
hiLo.Hi

// @function set text and tooltip for label


// @param this original array
// @param str string value for text
// @param tip string value for tooltip
method textTip(label this = na, string str = na, string tip = na) =>
this.set_text( str)
this.set_tooltip(tip)
//#endregion

//#region ———————————————————— 5. Execution


if Kh or Kl
if dirchanged
zigzag.initialize( varSetup, 4)
else
zigzag.update(varSetup, 4, dir)
//#endregion

//#region ———————————————————— 6. Constructs


if zigzag.size() >= 3
var line dirLine = na
var label dirLabel = na
var string dirString = na
[boolOr, boolAnd] = zigzag.boolPoint(oldzigzag)
if boolOr
if boolAnd
dirLine.delete()
dirLabel.delete()
if Zigzag ?showLabel :na
if disKlayLabel == 'HL' or disKlayLabel == 'HHLL'
dirLabel := zigzag.createLabel(sizeLabel)
if disKlayLabel == 'HHLL' and zigzag.size() >= 4
dirString := zigzag.compareHL(hiLo)
dirLabel.textTip(dirString + zigzag.get(0).str, dirString +
zigzag.get(0).str + '\n' + str.tostring(zigzag.get(0).y))
if colorLabel != 'Trend'
dirLabel.set_textcolor(switchLabelColor)
if Zigzag ? showLine :na
dirLine := zigzag.createLine(width, switchLine)
if colorLine != 'Trend'
dirLine.set_color(switchLineColor)
// //#endregion

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

// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © btc_charlie / @TheParagonGrp

//@version=5
//indicator('Ema Trend Scanner', overlay=true)

// Variables
var ok = 0
var countBuy = 0
var countSell = 0
srck = input(close, title='OHLC Type')
i_fastEMA = input(12, title='Fast EMA')
i_slowEMA = input(25, title='Slow EMA')
i_defEMA = input(25, title='Consolidated EMA')

// Allow the option to show single or double EMA


i_bothEMAs = input(title='Show Both EMAs', defval=true)

// Define EMAs
v_fastEMA = ta.ema(srck, i_fastEMA)
v_slowEMA = ta.ema(srck, i_slowEMA)
v_biasEMA = ta.ema(srck, i_defEMA)

// Color the EMAs


emaColor = v_fastEMA > v_slowEMA ? color.green : v_fastEMA < v_slowEMA ?
color.red : #FF530D

// Plot EMAs
plot(Showema?(i_bothEMAs ? v_biasEMA:na):na, color=emaColor, linewidth=3,
title='Consolidated EMA')
plot(Showema?(i_bothEMAs ? v_fastEMA : na):na, title='Fast EMA', color=emaColor)
plot(Showema?(i_bothEMAs ? v_slowEMA : na):na, title='Slow EMA', color=emaColor)

// Colour the bars


buyk = v_fastEMA > v_slowEMA
sellk = v_fastEMA < v_slowEMA

if buyk
countBuy += 1
countBuy

if buyk
countSell := 0
countSell

if sellk
countSell += 1
countSell

if sellk
countBuy := 0
countBuy

buysignal = countBuy < 2 and countBuy > 0 and countSell < 1 and buyk and not
buyk[1]
sellsignal = countSell > 0 and countSell < 2 and countBuy < 1 and sellk and not
sellk[1]

//barcolor(buysignal ? color.green : na)


//barcolor(sellsignal ? color.red : na)

// Plot Bull/Bear

plotshape(Showema?buysignal:na, title='Bull', text='Bull', style=shape.triangleup,


location=location.belowbar, color=color.new(color.green, 0),
textcolor=color.new(color.black, 0), size=size.tiny)
plotshape(Showema?sellsignal:na, title='Bear', text='Bear',
style=shape.triangledown, location=location.abovebar, color=color.new(color.red,
0), textcolor=color.new(color.black, 0), size=size.tiny)

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

ema1 = input.int(34, minval=1, maxval=300, title='EMA UpTrend')


shema = input(true, title='Show EMA Trend is Based On?')

usedEma = ta.ema(close, ema1)

emaUpColor() =>
hlc3 >= usedEma
emaDownColor() =>
hlc3 < usedEma

col = hlc3 >= usedEma ? color.lime : hlc3 < usedEma ? color.red : color.white

emaDownColor_1 = emaDownColor()
//barcolor(emaUpColor() ? color.lime : emaDownColor_1 ? color.red : na)
plot(Showema?(shema and usedEma ? usedEma : na):na, title='EMA',
style=plot.style_line, linewidth=3, color=col)

You might also like