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

// Kaufman's Adaptive Moving Average - Fast and Slow Ends

fastK = 0.666 // KAMA Fast End


slowK = 0.645 // KAMA Slow End
kama(x, t) =>
dist = math.abs(x[0] - x[1])
signal = math.abs(x - x[t])
noise = math.sum(dist, t)
effr = noise != 0 ? signal / noise : 1
sc = math.pow(effr * (fastK - slowK) + slowK, 2)
kama = x
kama := nz(kama[1]) + sc * (x - nz(kama[1]))
kama

ma(MAType, MASource, MAPeriod) =>


if MAPeriod > 0
if MAType == 'SMA'
ta.sma(MASource, MAPeriod)
else if MAType == 'LSMA'
ta.linreg(MASource, MAPeriod, 0)
else if MAType == 'EMA'
ta.ema(MASource, MAPeriod)
else if MAType == 'WMA'
ta.wma(MASource, MAPeriod)
else if MAType == 'RMA'
ta.rma(MASource, MAPeriod)
else if MAType == 'HMA'
ta.hma(MASource, MAPeriod)
else if MAType == 'DEMA'
e = ta.ema(MASource, MAPeriod)
2 * e - ta.ema(e, MAPeriod)
else if MAType == 'TEMA'
e = ta.ema(MASource, MAPeriod)
3 * (e - ta.ema(e, MAPeriod)) + ta.ema(ta.ema(e, MAPeriod), MAPeriod)
else if MAType == 'VWMA'
ta.vwma(MASource, MAPeriod)
else if MAType == 'ALMA'
ta.alma(MASource, MAPeriod, 6, .85)
else if MAType == 'SWMA'
ta.swma(MASource)
else if MAType == 'KAMA'
kama(MASource, MAPeriod)
else if MAType == 'Wild'
wild = MASource
wild := nz(wild[1]) + (MASource - nz(wild[1])) / MAPeriod
wild

emc12 = input(false, title='----EMA cross 1-2---')


emc13 = input(false, title='----EMA cross 1-3---')
emc23 = input(false, title='----EMA cross 2-3---')
emc24 = input(false, title='----EMA cross 2-4---')

st = input(false, title='ShowTrend')
upTrend = ma(type3, close, MA3) >= ma(type4, close, MA4)
downTrend = ma(type3, close, MA3) < ma(type4, close, MA4)
t1 = ma(type1, close, MA1)
t2 = ma(type2, close, MA2)
t3 = ma(type3, close, MA3)
t4 = ma(type4, close, MA4)
t11 = plot(show_Emas ? t1 : na, color=color.new(#3b78eb, 0), linewidth=1,
title='MA1')
t22 = plot(show_Emas ? t2 : na, color=color.new(#B45F04, 0), linewidth=2,
title='MA2')
t33 = plot(show_Emas ? t3 : na, color=st and upTrend ? color.lime : st and
downTrend ? color.red : #b83d27, linewidth=1, title='MA3')
t44 = plot(show_Emas ? t4 : na, color=st and upTrend ? color.lime : st and
downTrend ? color.red : #b83d27, linewidth=3, title='MA4')

bgcolor(color=ta.cross(t1, t2) and emc12 ? color.new(color.red,90) : na,


title='cross 1-2')
bgcolor(color=ta.cross(t2, t3) and emc13 ? color.new(color.green,90) : na,
title='cross 1-3')
bgcolor(color=ta.cross(t2, t3) and emc23 ? color.new(color.purple,90) : na,
title='cross 2-3')
bgcolor(color=ta.cross(t2, t4) and emc24 ? color.new(color.yellow,90) : na,
title='cross 2-4')

fill(t11, t22, color=st ? color.new(color.gray,75) : na, title='trend fill')


plotshape(st and upTrend ? upTrend : na, title='Conservative Buy Entry Triangle',
style=shape.triangleup, location=location.bottom, color=color.new(color.lime, 0),
offset=0)
plotshape(st and downTrend ? downTrend : na, title='Conservative Short Entry
Triangle', style=shape.triangledown, location=location.top,
color=color.new(color.red, 0), offset=0)

ShowBuySellArrows = input(false, title='-----------Show Buy/Sell TL--------')


ShowBuySellArrowsK = input(false, title='-----------Show Buy/Sell
Koncorde--------')
lpwn = input(false, title='-----------Lupown señal----------')
show_whalec = input(false, title='----------- Show whale -----------')
show_adminc = input(false, title='-------- Show whale invert --------')
show_nada = input(false, title='-------- Show nadaraya signals --------')

////////////////////////
showhbs = input(false, title='------ Show heikin BuySell -----')
EMAlength = input(55, 'EMA LENGTH?')

srch = ohlc4
haOpen = 0.0
haOpen := (srch + nz(haOpen[1])) / 2
haC = (ohlc4 + nz(haOpen) + math.max(high, nz(haOpen)) + math.min(low, nz(haOpen)))
/ 4
EMA1 = ta.ema(haC, EMAlength)
EMA2 = ta.ema(EMA1, EMAlength)
EMA3 = ta.ema(EMA2, EMAlength)
TMA1 = 3 * EMA1 - 3 * EMA2 + EMA3
EMA4 = ta.ema(TMA1, EMAlength)
EMA5 = ta.ema(EMA4, EMAlength)
EMA6 = ta.ema(EMA5, EMAlength)
TMA2 = 3 * EMA4 - 3 * EMA5 + EMA6
IPEK = TMA1 - TMA2
YASIN = TMA1 + IPEK
EMA7 = ta.ema(hlc3, EMAlength)
EMA8 = ta.ema(EMA7, EMAlength)
EMA9 = ta.ema(EMA8, EMAlength)
TMA3 = 3 * EMA7 - 3 * EMA8 + EMA9
EMA10 = ta.ema(TMA3, EMAlength)
EMA11 = ta.ema(EMA10, EMAlength)
EMA12 = ta.ema(EMA11, EMAlength)
TMA4 = 3 * EMA10 - 3 * EMA11 + EMA12
IPEK1 = TMA3 - TMA4
YASIN1 = TMA3 + IPEK1

mavi = YASIN1
kirmizi = YASIN

longCond = mavi > kirmizi and mavi[1] <= kirmizi[1]


shortCond = mavi < kirmizi and mavi[1] >= kirmizi[1]

last_signal = 0
long_final = longCond and (nz(last_signal[1]) == 0 or nz(last_signal[1]) == -1)
short_final = shortCond and (nz(last_signal[1]) == 0 or nz(last_signal[1]) == 1)

last_signal := long_final ? 1 : short_final ? -1 : last_signal[1]

plotshape(long_final and showhbs, style=shape.triangleup,


location=location.belowbar, color=color.new(color.blue, 0), size=size.tiny,
title='buy label', text='BUY', textcolor=color.new(color.white, 0))
plotshape(short_final and showhbs, style=shape.triangledown,
location=location.abovebar, color=color.new(color.red, 0), size=size.tiny,
title='sell label', text='SELL', textcolor=color.new(color.white, 0))

/////////PARABOLIC SAR
show_ps = input(false, title='----------Show Parabolic SAR---------')
start = input(0.02)
increment = input(0.02)
maximum = input(0.2, 'Max Value')
out = ta.sar(start, increment, maximum)
plot(show_ps ? out : na, 'ParabolicSAR', style=plot.style_cross,
color=color.new(#2962FF, 0))
///// END PARABOLIC SAR

srcTprice = input(ohlc4, title='Fuente para Precio Total')


srcMfi = input.source(hlc3, title='Fuente MFI', group='Money Flow Index')
tprice = srcTprice

//lengthEMA = input(255, minval=1)

scaleK = input(8, title='Koncorde scale')


m = input(15, title='Media Exponencial')
longitudPVI = input(90, title='Longitud PVI')
longitudNVI = input(90, title='Longitud NVI')
longitudMFI = input(14, title='Longitud MFI')
multK = input.float(2.0, title='Multiplicador para derivacion estandar',
group='Bollinger Oscillator')
boLength = input.int(25, title='Calculation length ', group='Bollinger Oscillator')
mult = input.float(2.0, title='Multiplicador para derivacion estandar',
group='Bollinger Oscillator')
pvim = ta.ema(ta.pvi, m)
pvimax = ta.highest(pvim, longitudPVI)
pvimin = ta.lowest(pvim, longitudPVI)
oscp = (ta.pvi - pvim) * 100 / (pvimax - pvimin)

nvim = ta.ema(ta.nvi, m)
nvimax = ta.highest(nvim, longitudNVI)
nvimin = ta.lowest(nvim, longitudNVI)
azul = (ta.nvi - nvim) * 100 / (nvimax - nvimin)

xmf = ta.mfi(srcMfi, longitudMFI)

// Bands Calculation
basisK = ta.sma(tprice, boLength) //Find the 20-day moving average average (n1 +
n2 ... + n20)/20
devK = mult * ta.stdev(tprice, boLength) //Find the standard deviation of the 20-
days
upperK = basisK + devK //Upper Band = 20-day Moving Average + (2 x standard
deviation of the 20-days)
lowerK = basisK - devK //Lower Band = 20-day Moving Average - (2 x standard
deviation of the 20-days)
OB1 = (upperK + lowerK) / 2.0
OB2 = upperK - lowerK

BollOsc = (tprice - OB1) / OB2 * 100 // percent b


xrsi = ta.rsi(tprice, 14)

calc_stoch(src, length, smoothFastD) =>


ll = ta.lowest(low, length)
hh = ta.highest(high, length)
k = 100 * (src - ll) / (hh - ll)
ta.sma(k, smoothFastD)

stoc = calc_stoch(tprice, 21, 3)


marron = (xrsi + xmf + BollOsc + stoc / 3) / 2
verde = marron + oscp
media = ta.ema(marron, m)
bandacero = 0
//scaleK1 = (ni/scale)/scaleK

buy_cK = ta.crossover(marron, media)


sell_cK = ta.crossunder(marron, media)
plotshape(ShowBuySellArrowsK and buy_cK, 'Buy', shape.triangleup,
location.belowbar, color.new(color.green, 0), text='Buy',
textcolor=color.new(color.green, 0))
plotshape(ShowBuySellArrowsK and sell_cK, 'Sell', shape.triangledown,
location.abovebar, color.new(color.red, 0), text='Sell',
textcolor=color.new(color.red, 0))

////BOLLINGER BANDS
////////////////////
show_BB = input(false, title='--------- Show Bollinger ---------')
lengthB = input.int(20, minval=1)
srcB = input(close, title='Source')
//mult = input(2.0, minval=0.001, maxval=50, title="StdDev")
basis = ta.sma(srcB, lengthB)
dev = mult * ta.stdev(srcB, lengthB)
upper = basis + dev
lower = basis - dev
offsetB = input.int(0, 'Offset', minval=-500, maxval=500)
plot(show_BB ? basis : na, 'Basis', color=color.new(#919191, 0), offset=offsetB)
p1 = plot(show_BB ? upper : na, 'Upper', color=color.new(#ff0059, 0),
offset=offsetB)
p2 = plot(show_BB ? lower : na, 'Lower', color=color.new(#ff0059, 0),
offset=offsetB)
fill(p1, p2, title='Background', color=color.rgb(255, 205, 222, 95))
//////////////////
//// ICHIMOKU
///////////////////////////

//Input
show_ich = input(false, title='--------Show Ichimoku---------')
tenkanIN = input.int(9, minval=1, title='Tenkan')
kijunIN = input.int(26, minval=1, title='Kijun')
spanBIN = input.int(52, minval=1, title='Span B')
chikouIN = input.int(26, minval=1, title='Chikou')
srcI = input(close, title='Source')

//Setting
donchian(len) =>
math.avg(ta.lowest(len), ta.highest(len))
tenkan = donchian(tenkanIN)
kijun = donchian(kijunIN)
spanA = math.avg(tenkan, kijun)
spanB = donchian(spanBIN)
chikou = srcI
offset = -chikouIN

Color00 = #f57f17 //Orange


Color02 = #f57f17ff //Orange 100%
Color10 = #006400 //Green
Color13 = #388e3c //Light Green
Color20 = #8B0000 //Red
Color23 = #b71c1c //Light Red
Color30 = #ffffff //White

colorKumo = spanA > spanB ? Color10 : Color20

//Drawing
plot(show_ich ? tenkan : na, title='Tenkan', color=color.new(Color10, 0))
plot(show_ich ? kijun : na, title='Kijun', color=color.new(Color20, 0))
plot(show_ich ? srcI : na, offset=-chikouIN + 1, title='Chikou',
color=color.new(Color00, 0), linewidth=2)
kumoA = plot(show_ich ? spanA : na, offset=chikouIN - 1, title='Span A', color=na)
kumoB = plot(show_ich ? spanB : na, offset=chikouIN - 1, title='Span B', color=na)
fill(kumoA, kumoB, title='Kumo', color=show_ich ? colorKumo : na, transp=75)

///// END ICHIMOKU

var vartooltip = 'Indicator to help identifying instituational Order Blocks. Often


these blocks signal the beginning of a strong move, but there is a high
probability, that these prices will be revisited at a later point in time again and
therefore are interesting levels to place limit orders. \nBullish Order block is
the last down candle before a sequence of up candles. \nBearish Order Block is the
last up candle before a sequence of down candles. \nIn the settings the number of
required sequential candles can be adjusted. \nFurthermore a %-threshold can be
entered which the sequential move needs to achieve in order to validate a relevant
Order Block. \nChannels for the last Bullish/Bearish Block can be shown/hidden.'

version = 'v3.0'
int mbp = 1000

showFVG = input.bool(false, '----------- Show FVG------------')


max_bars_back(time, mbp)
max_bars_back(low, mbp)
max_bars_back(close, mbp)
max_bars_back(open, mbp)
max_bars_back(high, mbp)

FvgCat = 'Release ' + version

defFvgColor = color.new(#721010, 90)


defFvgColor2 = color.new(#107228, 90)
noColor = color.new(color.white, 100)
beName = 'Be'
buName = 'Bu'
maxImbs = input.int(10, 'Max', group = FvgCat, minval = 1, maxval = 100, inline =
'gen')
fvg_middleBar = input.bool(true, 'Mid Bar Start', group = FvgCat, inline = 'gen')
fvg_borders = input.bool(false, 'Borders', tooltip = 'Max - Maximum bearish and
bullish FVGs to show\n\nMid Bar Start - Starts drawing FVG zone from the middle
candle otherwise it starts drawing it from previous candle\n\nBorders - Displays
FVG area borders', group = FvgCat, inline = 'gen')

colorTip = ':\n ' + beName + ' - bearish FVG color\n ' + buName + ' - bullish
FVG color'
fvg_be_shared = input.color(color.new(#ff2525, 80), 'Shared Colors: ' + beName +
'/' + buName, group = FvgCat, inline = '0')
fvg_bu_shared = input.color(color.new(color.green, 80), '/', group = FvgCat, inline
= '0', tooltip = 'Shared Colors' + colorTip)

CurrentCat = 'Current TimeFrame'


UWName = 'UBars'
extendName = 'Extend'
eo_Unextended = 'Unextended'
eo_BySceen = 'By Screen'
eo_ByLastBar = 'By Last Bar'

eo_None = 'None'
eo_ByFilledBar = 'Filling Candle'
custColorName = 'Cust Colors'
onTip = 'Shows/Hides chosen TF'
custColorTip = custColorName + colorTip
extendTip = extendName + ':\n ' + eo_Unextended + ' - shows fixed FVG area\n '
+ eo_BySceen + ' - extends FVG area all the way to the right\n ' + eo_ByLastBar +
' - extends FVG area to the last bar\n\nEnables/Disables custom colors\n\n' +
custColorTip

chooseColor2(con, shc, c) => con ? c : shc


fvgVisible = input.bool(true, 'On', group = CurrentCat, inline = CurrentCat)
fvg_uw = input.int(0, UWName, group = CurrentCat, minval = -100, maxval = 100,
inline = CurrentCat, tooltip = onTip + '\n\n' + UWName + ' - additonal bars for the
unextended area')
customColorName = custColorName + ': ' + beName + '/' + buName
fvg_ext = input.string(eo_BySceen, extendName, options = [eo_Unextended,
eo_BySceen, eo_ByLastBar], group = CurrentCat, inline = '1')
fvg_custcolor = input.bool(false, customColorName, group = CurrentCat, inline =
'1')
fvg_bec = chooseColor2(fvg_custcolor, fvg_be_shared, input.color(defFvgColor, '',
group = CurrentCat, inline = '1'))
fvg_buc = chooseColor2(fvg_custcolor, fvg_bu_shared, input.color(defFvgColor2, '/',
group = CurrentCat, inline = '1', tooltip = extendTip))

filledName = 'Filled'
fvg_f = input.bool(false, filledName, group = CurrentCat, inline = '0')
fvg_cc = input.bool(false, customColorName, group = CurrentCat, inline = '0')
fvg_f_bec = chooseColor2(fvg_cc, fvg_bec, input.color(defFvgColor, '', group =
CurrentCat, inline = '0'))
fvg_f_buc = chooseColor2(fvg_cc, fvg_buc, input.color(defFvgColor2, '/', group =
CurrentCat, inline = '0', tooltip = filledName + ' - shows/hides filled area\n\n' +
custColorTip))
//fvg_f = input.bool(false, 'filled', group = CurrentCat, inline = '0')
ff_FilledFVGsBack = 'Max Fills'
ff_FVGsBack = 'Last Unfilled'
fTip = 'From:\n ' + ff_FVGsBack + ' - shows filled FVGs by the first unfilled
FVG\n ' + ff_FilledFVGsBack + ' - sets max filled FVGs to show\n\nMax fills, used
when ' + ff_FilledFVGsBack+ ' option is chosen\n\nTo:\n ' + eo_ByFilledBar + '-
filled area is clipped by filling bar\n ' + eo_Unextended + ' - show fixed FVG
area\n\n'
fvg_ff = input.string(ff_FVGsBack, 'From', options = [ff_FVGsBack,
ff_FilledFVGsBack], group = CurrentCat, inline = '2')
fvg_fmax = input.int(10, '', minval = 1, maxval = 250, group = CurrentCat, inline =
'2')
fvg_ft = input.string(eo_ByFilledBar, 'To', options = [eo_ByFilledBar,
eo_Unextended], group = CurrentCat, inline = '2', tooltip = fTip)

labelName = 'Name'
timeframeTip = onTip + '\n\nTimeframe to display'
labelsTip = UWName + ' - additonal bars for the unextended area\n\n' + labelName +
' - displays the time frame name\n\nAdds extra text data to the label'

var imbHighs = array.new<box>()


var imbLows = array.new<box>()
var labels = array.new<label>()

maxBars = mbp - 1
if maxBars >= bar_index
maxBars := bar_index - 1

//}

FindCurTFImb(on, be_col, bu_col, m, uw, sh_be_col, sh_bu_col) =>


if barstate.islast and on and showFVG
maxLows = maxImbs
maxHighs = maxImbs
ml = low[0]
mh = high[0]
max = m
t0 = bar_index
int bear0 = max - 2
int bull0 = max - 2
for i = 1 to max - 2
t = bar_index[i + 1]
l = low[i]
nl = low[i + 1]
h = high[i]
nh = high[i + 1]
if maxLows > 0
if nh < ml
lowImb = box.new(fvg_middleBar ? t + 1 : t, ml, fvg_ext ==
eo_ByLastBar ? bar_index + uw : t + 2 + uw, nh, border_color = fvg_borders ? bu_col
: na, bgcolor = bu_col, extend = fvg_ext == eo_BySceen ? extend.right :
extend.none)
array.push(imbLows, lowImb)
maxLows -= 1
bull0 := i
if ml > nh and nh < l//for the gap
ml := nh
if l < ml
ml := l
if maxHighs > 0
if nl > mh
highImb = box.new(fvg_middleBar ? t + 1 : t, nl, fvg_ext ==
eo_ByLastBar ? bar_index + uw : t + 2 + uw, mh, border_color = fvg_borders ? be_col
: na, bgcolor = be_col, extend = fvg_ext == eo_BySceen ? extend.right :
extend.none)
array.push(imbHighs, highImb)
maxHighs -= 1
bear0 := i
if mh < nl and nl > h
mh := nl
if mh < h
mh := h
if maxHighs <= 0 and maxLows <= 0
break
if fvg_f
if fvg_ff == ff_FVGsBack
i = bull0
while i > 0
nl = low[i - 1]//from the right
ph = high[i + 1]//from the left
if ph < nl and i > 1
ml := nl
left = bar_index - i - 1
for j = i - 2 to 0
if low[j] < ml
right = bar_index - j
if fvg_ft == eo_Unextended
right := left + uw + 2
lowImb = box.new(left + (fvg_middleBar ? 1 : 0),
ml, right, math.max(ph, low[j]), border_color = fvg_borders ? sh_bu_col : na,
bgcolor = sh_bu_col, extend = extend.none)
array.push(imbLows, lowImb)
ml := low[j]
if ml <= ph
break
i -= 1
i := bear0
while i > 0
nh = high[i - 1]//from the right
pl = low[i + 1]//from the left
if nh < pl and i > 1
mh := nh
left = bar_index - i - 1
for j = i - 2 to 0
if high[j] > mh
right = bar_index - j
if fvg_ft == eo_Unextended
right := left + uw + 2
highImb = box.new(left + (fvg_middleBar ? 1 : 0),
mh, right, math.min(pl, high[j]), border_color = fvg_borders ? sh_be_col : na,
bgcolor = sh_be_col, extend = extend.none)
array.push(imbHighs, highImb)
mh := high[j]
if mh >= pl
break
i -= 1
else
i = 1
fvgs = 0
while fvgs < fvg_fmax and i < mbp
nl = low[i - 1]//from the right
ph = high[i + 1]//from the left
if ph < nl and i > 1
ml := nl
left = bar_index - i - 1
fills = 0
for j = i - 2 to 0
if low[j] < ml
right = bar_index - j
if fvg_ft == eo_Unextended
right := left + uw + 2
lowImb = box.new(left + (fvg_middleBar ? 1 : 0),
ml, right, math.max(ph, low[j]), border_color = fvg_borders ? sh_bu_col : na,
bgcolor = sh_bu_col, extend = extend.none)
array.push(imbLows, lowImb)
ml := low[j]
fills += 1
if ml <= ph
break
if fills > 0
fvgs += 1
i += 1
i := 1
fvgs := 0
while fvgs < fvg_fmax and i < mbp
nh = high[i - 1]//from the right
pl = low[i + 1]//from the left
if nh < pl and i > 1
mh := nh
left = bar_index - i - 1
fills = 0
for j = i - 2 to 0
if high[j] > mh
right = bar_index - j
if fvg_ft == eo_Unextended
right := left + uw + 2
highImb = box.new(left + (fvg_middleBar ? 1 : 0),
mh, right, math.min(pl, high[j]), border_color = fvg_borders ? sh_be_col : na,
bgcolor = sh_be_col, extend = extend.none)
array.push(imbHighs, highImb)
mh := high[j]
fills += 1
if mh >= pl
break
if fills > 0
fvgs += 1
i += 1

createTextLabel(tf) =>
r = tf
if str.contains(tf, 'M') or str.contains(tf, 'D') or str.contains(tf, 'Y') or
str.contains(tf, 'W') or str.contains(tf, 's')
r := tf
else
s = timeframe.in_seconds(tf)
s /= 60
if s / 60 >= 1
r := str.tostring(s / 60) + 'H'
else
r := tf + 'm'
r

createLabel(x, y, txt, tcol, extend) =>


label.new(x, y, txt, size = size.small, textcolor = tcol, color = noColor,
style = label.style_label_left)

FindLtfImb(tf, on, be_col, bu_col, max, extend, uw, showlabel, labeltxt) =>
wrongltf = not on or timeframe.in_seconds(tf) >=
timeframe.in_seconds(timeframe.period)
ts = request.security_lower_tf(syminfo.tickerid, wrongltf ? timeframe.period :
tf, time)
hs = request.security_lower_tf(syminfo.tickerid, wrongltf ? timeframe.period :
tf, high)
ls = request.security_lower_tf(syminfo.tickerid, wrongltf ? timeframe.period :
tf, low)

if barstate.islast and not wrongltf


txt = createTextLabel(tf) + labeltxt
maxLows = maxImbs
maxHighs = maxImbs
float ml = na
float mh = na
float h = na
float nh = na
float l = na
float nl = na
int t = na
int nt = na
int t0 = na

for j = 0 to max - 1
s = array.size(ts[j])
if (maxHighs == 0 and maxLows == 0) or s == 0
break
for i = 0 to s - 1
if not na(nl)
l := nl
h := nh
t := nt
nl := array.get(ls[j], s - 1 - i)
nh := array.get(hs[j], s - 1 - i)
nt := array.get(ts[j], s - 1 - i)
if na(t0)
t0 := nt

if na(t)
continue
left = bar_index - j
right = extend == eo_ByLastBar ? bar_index + uw : bar_index - j +
uw
if maxLows > 0
//if l < ml and h > ml
if nh < ml
lowImb = box.new(left, ml, right, nh, border_color =
fvg_borders ? bu_col : na, bgcolor = bu_col, extend = extend == eo_BySceen ?
extend.right : extend.none)
array.push(imbLows, lowImb)
if showlabel
array.push(labels, createLabel(right, (ml + nh) / 2,
txt, color.new(bu_col, color.t(bu_col) / 2), extend))
maxLows -= 1
if ml > nh and nh < l//for the gap
ml := nh
if na(ml) or l < ml
ml := l
if maxHighs > 0
//if l < mh and h > mh
if nl > mh
highImb = box.new(left, nl, right, mh, border_color =
fvg_borders ? be_col : na, bgcolor = be_col, extend = extend == eo_BySceen ?
extend.right : extend.none)
array.push(imbHighs, highImb)
if showlabel
array.push(labels, createLabel(right, (nl + mh) / 2,
txt, color.new(be_col, color.t(be_col) / 2), extend))
maxHighs -= 1
if mh < nl and nl > h
mh := nl
if na(mh) or mh < h
mh := h
if maxHighs <= 0 and maxLows <= 0
break

FindHtfImb(tf, on, be_col, bu_col, max, extend, uw, showlabel, labeltxt) =>
wronghtf = not on or timeframe.in_seconds(tf) <=
timeframe.in_seconds(timeframe.period)
[ts, hs, ls] = request.security(syminfo.tickerid, wronghtf ? timeframe.period :
tf, [time, high, low], barmerge.gaps_off, barmerge.lookahead_on)

if barstate.islast and not wronghtf


txt = createTextLabel(tf) + labeltxt
maxLows = maxImbs
maxHighs = maxImbs
float ml = na
float mh = na
float h = na
float nh = na
float l = na
float nl = na
int t = na
int nj = na
int cj = na
j = 0
while j < max
if maxHighs <= 0 and maxLows <= 0
break
if t != ts[j]
if not na(nl)
l := nl
h := nh
cj := nj
nl := ls[j]
nh := hs[j]
t := ts[j]
nj := j
j += 1
else
if na(t)
nl := ls[j]
nh := hs[j]
t := ts[j]
nj := j
ml := nl
mh := nh
j += 1
continue

left = bar_index - nj + 1
right = extend == eo_ByLastBar ? bar_index + uw : bar_index - cj + uw
if maxLows > 0
if nh < ml
lowImb = box.new(left, ml, right, nh, border_color =
fvg_borders ? bu_col : na, bgcolor = bu_col, extend = extend == eo_BySceen ?
extend.right : extend.none)
array.push(imbLows, lowImb)
if showlabel
array.push(labels, createLabel(right, (ml + nh) / 2, txt,
color.new(bu_col, color.t(bu_col) / 2), extend))
maxLows -= 1
if ml > nh and nh < l//for the gap
ml := nh
if l < ml
ml := l
if maxHighs > 0
if nl > mh
highImb = box.new(left, nl, right, mh, border_color =
fvg_borders ? be_col : na, bgcolor = be_col, extend = extend == eo_BySceen ?
extend.right : extend.none)
array.push(imbHighs, highImb)
if showlabel
array.push(labels, createLabel(right, (nl + mh) / 2, txt,
color.new(be_col, color.t(be_col) / 2), extend))
maxHighs -= 1
if mh < nl and nl > h
mh := nl
if mh < h
mh := h
if barstate.islast
while array.size(imbLows) > 0
box.delete(array.pop(imbLows))
while array.size(imbHighs) > 0
box.delete(array.pop(imbHighs))
while array.size(labels) > 0
label.delete(array.pop(labels))

FindCurTFImb(fvgVisible, fvg_bec, fvg_buc, maxBars, fvg_uw, fvg_f_bec, fvg_f_buc)

group_support_and_resistance = 'Consecutively Increasing Volume / Price'


tooltip_support_and_resistance = 'Moments where\n' +
'- price is bullish or bearish
consecutively for minimum 3 bars and on increasing volume with at least one bar\'s
volume is above volume moving average\n' +
'or\n' +
'- price is bullish or bearish
consecutively on increasing/decreasing price for minimum 3 bars'

group_volume_spike_sign_of_exhaustion = 'Volume Spike - Sign of Exhaustion'


tooltip_volume_spike_sign_of_exhaustion = 'Moments where\n' +
'huge volume detected : current volume is
grater than the product of the theshold value and volume moving average\n' +
'presents idea : huge volume may be a
sign of exhaustion and may lead to sharp reversals'

group_high_volatility = 'High Volatility'


tooltip_high_volatility = 'Moments where\n' +
'price range of the current bar is
grater than the product of the theshold value and average true range value of
defined period'

group_volume_weighted_colored_bars = 'Volume Weighted Colored Bars'


tooltip_volume_weighted_colored_bars = 'Colors bars based on the bar\'s volume
relative to volume moving average\n' +
'trading tip : a potential breakout
trading opportunity may occur when price moves above a resistance level or moves
below a support level on increasing volume'

tooltip_volume_moving_average = 'Volume simple moving average, serves as


reference to\n' +
'- Support and Resistance,\n' +
'- Volume Weighted Colored Bars,\n' +
'- Volume Spike - Sign of Exhaustion\
ncalculations'

// User Input Declarations


---------------------------------------------------------------------- //

//
-----------------------------------------------------------------------------------
----------- //
// Consecutively Increasing Volume / Price
----------------------------------------------------- //

group_volume_profile = 'Volume Profile / Price by Volume'


tooltip_volume_profile = 'Volume Profile (also known as Price by Volume) is an
charting study that displays trading activity over a specified time period at
specific price levels'

volumeProfile = input.bool(true, '-----------------Volume


Profile---------------------', group = group_volume_profile, tooltip =
tooltip_volume_profile)

vpLookbackRange = input.string('Fixed Range', 'VP and SD Lookback Range', options


= ['Fixed Range', 'Visible Range'], group = group_volume_profile)
lookbackLength = input.int(200, 'VP and SD Fixed Range : Lookback Length',
minval = 10, maxval = 5000, step = 10 , group = group_volume_profile)
avgVolNodeCol = input.color(color.new(#787b86, 25), 'Volume Nodes : AVN'
, inline='col', group = group_volume_profile)
highVolNodeCol = input.color(color.new(#f57c00, 50), 'HVN'
, inline='col', group = group_volume_profile)
lowVolNodeCol = input.color(color.new(#787b86, 75), 'LVN'
, inline='col', group = group_volume_profile)
isValueArea = input.float(68, "Value Area Volume %", minval = 0, maxval = 100
, group = group_volume_profile) / 100
valueAreaHigh = input.bool(false, 'VAH'
, inline='VA' , group = group_volume_profile)
vahColor = input.color(color.new(#ffeb3b, 0), ''
, inline='VA' , group = group_volume_profile)
pointOfControl = input.bool(true, 'POC'
, inline='VA' , group = group_volume_profile)
pocColor = input.color(color.new(#ff0000, 0), ''
, inline='VA' , group = group_volume_profile)
valueAreaLow = input.bool(false, 'VAL'
, inline='VA' , group = group_volume_profile)
valColor = input.color(color.new(#ffeb3b, 0), ''
, inline='VA' , group = group_volume_profile)
priceLevels = false// input.bool(true, 'Show Profile Price Levels '
, inline='BBe', group = group_volume_profile)
labelColor = input.color(color.new(#8c92a4, 0), ''
, inline='BBe', group = group_volume_profile)
profileLevels = input.int(100, 'Number of Rows' , minval = 10, maxval = 170 ,
step = 10 , group = group_volume_profile)
horizontalOffset = input.int(1, 'Horizontal Offset', minval = 0 , maxval = 100
, group = group_volume_profile)

tooltip_sd = 'Defines the relationship between the price of a given asset


and the willingness of traders to either buy or sell it'
group_supply_demand = 'Supply and Demand Settings'
supplyDemand = input.bool(false, 'Supply and Demand Zones'
, inline='low2', group = group_supply_demand, tooltip = tooltip_sd)
lowVolNodesVal = input.int(15, '' , minval = 0, maxval = 50, step = 1
, inline='low2', group = group_supply_demand) / 100
supplyDemandCol = input.color(color.new(#512da8, 80), ''
, inline='low2', group = group_supply_demand)

priceHighestFR = ta.highest(high, lookbackLength)


priceLowestFR = ta.lowest (low , lookbackLength)

//
-----------------------------------------------------------------------------------
----------- //
// Definitions
----------------------------------------------------------------------------------
//

nzVolume = nz(volume)
risingVol = nzVolume >= nzVolume[1]

bullCandle = close > open


bearCandle = close < open

risingPrice = close > close[1]


fallingPrice = close < close[1]

lwstPrice = ta.lowest (low , 3)


hstPrice = ta.highest(high, 3)

//weightedATR = i_atrMult * ta.atr(i_atrLength)


range_1 = math.abs(high - low)

x2 = timenow + 7 * math.round(ta.change(time))

var startBarIndexX = 0
if time == chart.left_visible_bar_time and vpLookbackRange == 'Visible Range'
startBarIndexX := bar_index

if vpLookbackRange == 'Visible Range'


lookbackLength := last_bar_index - startBarIndexX
f_drawLabelX(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor, _size,
_textalign, _tooltip) =>
var id = label.new(_x, _y, _text, _xloc, _yloc, _color, _style, _textcolor,
_size, _textalign, _tooltip)
label.set_xy(id, _x, _y)
label.set_text(id, _text)
label.set_tooltip(id, _tooltip)
label.set_textcolor(id, _textcolor)

f_drawLineX(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width) =>
var id = line.new(_x1, _y1, _x2, _y2, _xloc, _extend, _color, _style, _width)
line.set_xy1(id, _x1, _y1)
line.set_xy2(id, _x2, _y2)
line.set_color(id, _color)

f_getHighLow() =>
var htf_h = 0., var htf_l = 0.

if vpLookbackRange == 'Visible Range'


if time == chart.left_visible_bar_time
htf_l := low
htf_h := high
else if time > chart.left_visible_bar_time
htf_l := math.min(low , htf_l)
htf_h := math.max(high, htf_h)
else
htf_h := priceHighestFR
htf_l := priceLowestFR

[htf_h, htf_l]

[priceHighest, priceLowest] = f_getHighLow()


priceStep = (priceHighest - priceLowest) / profileLevels
barPriceLow = low
barPriceHigh = high
var levelAbovePoc = 0
var levelBelowPoc = 0
var pocLevel = 0

volumeStorage = array.new_float(profileLevels + 1, 0.)


volumeStorageB = array.new_float(profileLevels + 1, 0.)
var a_profile = array.new_box()

if barstate.islast and bool(nzVolume)


if array.size(a_profile) > 0
for i = 1 to array.size(a_profile)
box.delete(array.shift(a_profile))

for barIndex = 0 to lookbackLength - 1


level = 0
for priceLevel = priceLowest to priceHighest by priceStep
if barPriceHigh[barIndex] >= priceLevel and barPriceLow[barIndex] <
priceLevel + priceStep
array.set(volumeStorage, level, array.get(volumeStorage, level) +
nzVolume[barIndex] * ((barPriceHigh[barIndex] - barPriceLow[barIndex]) == 0 ? 1 :
priceStep / (barPriceHigh[barIndex] - barPriceLow[barIndex])) )

if bullCandle[barIndex]
array.set(volumeStorageB, level, array.get(volumeStorageB,
level) + nzVolume[barIndex] * ((barPriceHigh[barIndex] - barPriceLow[barIndex]) ==
0 ? 1 : priceStep / (barPriceHigh[barIndex] - barPriceLow[barIndex])) )
level += 1

pocLevel := array.indexof(volumeStorage, array.max(volumeStorage))


totalVolumeTraded = array.sum(volumeStorage) * isValueArea
valueArea = array.get(volumeStorage, pocLevel)

levelAbovePoc := pocLevel
levelBelowPoc := pocLevel

while valueArea < totalVolumeTraded


if levelBelowPoc == 0 and levelAbovePoc == profileLevels - 1
break

volumeAbovePoc = 0.
if levelAbovePoc < profileLevels - 1
volumeAbovePoc := array.get(volumeStorage, levelAbovePoc + 1)

volumeBelowPoc = 0.
if levelBelowPoc > 0
volumeBelowPoc := array.get(volumeStorage, levelBelowPoc - 1)

if volumeAbovePoc >= volumeBelowPoc


valueArea += volumeAbovePoc
levelAbovePoc += 1
else
valueArea += volumeBelowPoc
levelBelowPoc -= 1

f_drawLineX(bar_index - lookbackLength + 1, priceLowest + (levelAbovePoc +


1.00) * priceStep, volumeProfile ? bar_index + horizontalOffset + 50 : bar_index +
7, priceLowest + (levelAbovePoc + 1.00) * priceStep, xloc.bar_index, extend.none,
valueAreaHigh ? vahColor : #00000000, line.style_solid, 2)
f_drawLineX(bar_index - lookbackLength + 1, priceLowest + (pocLevel +
0.50) * priceStep, volumeProfile ? bar_index + horizontalOffset + 50 : bar_index +
7, priceLowest + (pocLevel + 0.50) * priceStep, xloc.bar_index, extend.none,
pointOfControl ? pocColor : #00000000, line.style_solid, 2)
f_drawLineX(bar_index - lookbackLength + 1, priceLowest + (levelBelowPoc +
0.00) * priceStep, volumeProfile ? bar_index + horizontalOffset + 50 : bar_index +
7, priceLowest + (levelBelowPoc + 0.00) * priceStep, xloc.bar_index, extend.none,
valueAreaLow ? valColor : #00000000, line.style_solid, 2)

if priceLevels
f_drawLabelX(volumeProfile ? bar_index + horizontalOffset + 50 : bar_index
+ 7, priceHighest, str.tostring(priceHighest, format.mintick), xloc.bar_index,
yloc.price, labelColor, label.style_label_down, labelColor, size.normal,
text.align_left, 'Profile High - during last ' + str.tostring(lookbackLength) + '
bars\n %' + str.tostring((priceHighest - priceLowest) / priceLowest * 100, '#.##')
+ ' higher than the Profile Low')
f_drawLabelX(volumeProfile ? bar_index + horizontalOffset + 50 : bar_index
+ 7, priceLowest , str.tostring(priceLowest , format.mintick), xloc.bar_index,
yloc.price, labelColor, label.style_label_up , labelColor, size.normal,
text.align_left, 'Profile Low - during last ' + str.tostring(lookbackLength) + '
bars\n %' + str.tostring((priceHighest - priceLowest) / priceHighest * 100, '#.##')
+ ' lower than the Profile High')
f_drawLabelX(volumeProfile ? bar_index + horizontalOffset + 57 : bar_index
+ 13, priceLowest + (levelAbovePoc + 1.00) * priceStep, str.tostring(priceLowest +
(levelAbovePoc + 1.00) * priceStep, format.mintick), xloc.bar_index, yloc.price,
valueAreaHigh ? labelColor : #00000000, label.style_label_left, valueAreaHigh ?
labelColor : #00000000, size.normal, text.align_left, 'Value Area High Price')
f_drawLabelX(volumeProfile ? bar_index + horizontalOffset + 57 : bar_index
+ 13, priceLowest + (pocLevel + 0.50) * priceStep, str.tostring(priceLowest +
(pocLevel + 0.50) * priceStep, format.mintick), xloc.bar_index, yloc.price,
pointOfControl ? labelColor : #00000000, label.style_label_left, pointOfControl ?
labelColor : #00000000, size.normal, text.align_left, 'Point Of Control Price')
f_drawLabelX(volumeProfile ? bar_index + horizontalOffset + 57 : bar_index
+ 13, priceLowest + (levelBelowPoc + 0.00) * priceStep, str.tostring(priceLowest +
(levelBelowPoc + 0.00) * priceStep, format.mintick), xloc.bar_index, yloc.price,
valueAreaLow ? labelColor : #00000000, label.style_label_left, valueAreaLow ?
labelColor : #00000000, size.normal, text.align_left, 'Value Area Low Price')

for level = 0 to profileLevels - 1


if volumeProfile
levelColor = array.get(volumeStorage, level) /
array.max(volumeStorage) > .8 ? highVolNodeCol : array.get(volumeStorage, level) /
array.max(volumeStorage) < .2 ? lowVolNodeCol : avgVolNodeCol
array.push(a_profile, box.new( bar_index + horizontalOffset + 49 - int(
array.get(volumeStorage, level) / array.max(volumeStorage) * 41), priceLowest +
(level + 0.25) * priceStep,
bar_index + horizontalOffset + 50,
priceLowest + (level + 0.75) * priceStep, levelColor, bgcolor = levelColor ))
bullBearPower = 2 * array.get(volumeStorageB, level) -
array.get(volumeStorage, level)
//array.push(a_profile, box.new(bar_index + horizontalOffset + 51 ,
priceLowest + (level + 0.25) * priceStep,
// bar_index + horizontalOffset + 51 +
(bullBearPower > 0 ? 1 : -1) * int( bullBearPower / array.max(volumeStorage) * 73),
priceLowest + (level + 0.75) * priceStep, bullBearPower > 0 ? color.new(#26a69a,
50) : color.new(#ef5350, 50), bgcolor = bullBearPower > 0 ? color.new(#26a69a,
50) : color.new(#ef5350, 50) ))
if supplyDemand
if array.get(volumeStorage, level) / array.max(volumeStorage) <
lowVolNodesVal
array.push(a_profile, box.new(bar_index - lookbackLength + 1,
priceLowest + (level + 0.00) * priceStep, bar_index + 7, priceLowest + (level +
1.00) * priceStep, #00000000, bgcolor = supplyDemandCol ))

if volumeProfile
array.push(a_profile, box.new(bar_index - lookbackLength + 1, priceLowest,
bar_index + horizontalOffset + 50, priceHighest, color.new(color.gray, 37), 1,
line.style_dotted, bgcolor=#00000000 ))

//------------------------SMART MONEY
-----------------------------------------------------
show_SMC = input(false, title='--------- Show SMART MONEY ---------')
color TRANSP_CSS = #ffffff00

//Tooltips
string MODE_TOOLTIP = 'Allows to display historical Structure or only the
recent ones'
string STYLE_TOOLTIP = 'Indicator color theme'
string COLOR_CANDLES_TOOLTIP = 'Display additional candles with a color reflecting
the current trend detected by structure'
string SHOW_INTERNAL = 'Display internal market structure'
string CONFLUENCE_FILTER = 'Filter non significant internal structure
breakouts'
string SHOW_SWING = 'Display swing market Structure'
string SHOW_SWING_POINTS = 'Display swing point as labels on the chart'
string SHOW_SWHL_POINTS = 'Highlight most recent strong and weak high/low
points on the chart'
string INTERNAL_OB = 'Display internal order blocks on the chart\n\
nNumber of internal order blocks to display on the chart'
string SWING_OB = 'Display swing order blocks on the chart\n\nNumber
of internal swing blocks to display on the chart'
string FILTER_OB = 'Method used to filter out volatile order blocks \n\
nIt is recommended to use the cumulative mean range method when a low amount of
data is available'
string SHOW_EQHL = 'Display equal highs and equal lows on the chart'
string EQHL_BARS = 'Number of bars used to confirm equal highs and
equal lows'
string EQHL_THRESHOLD = 'Sensitivity threshold in a range (0, 1) used for
the detection of equal highs & lows\n\nLower values will return fewer but more
pertinent results'
string SHOW_FVG = 'Display fair values gaps on the chart'
string AUTO_FVG = 'Filter out non significant fair value gaps'
string FVG_TF = 'Fair value gaps timeframe'
string EXTEND_FVG = 'Determine how many bars to extend the Fair Value
Gap boxes on chart'
string PED_ZONES = 'Display premium, discount, and equilibrium zones on
chart'

//-----------------------------------------------------------------------------{
//Settings
//-----------------------------------------------------------------------------{
//General
//----------------------------------------{
mode = input.string('Historical'
, options = ['Historical', 'Present']
, group = 'Smart Money Concepts'
, tooltip = MODE_TOOLTIP)

style = input.string('Colored'
, options = ['Colored', 'Monochrome']
, group = 'Smart Money Concepts'
, tooltip = STYLE_TOOLTIP)

show_trend = input(false, 'Color Candles'


, group = 'Smart Money Concepts'
, tooltip = COLOR_CANDLES_TOOLTIP)

//----------------------------------------}
//Internal Structure
//----------------------------------------{
show_internals = input(true, 'Show Internal Structure'
, group = 'Real Time Internal Structure'
, tooltip = SHOW_INTERNAL)

show_ibull = input.string('All', 'Bullish Structure'


, options = ['All', 'BOS', 'CHoCH']
, inline = 'ibull'
, group = 'Real Time Internal Structure')

swing_ibull_css = input(#089981, ''


, inline = 'ibull'
, group = 'Real Time Internal Structure')

//Bear Structure
show_ibear = input.string('All', 'Bearish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'ibear'
, group = 'Real Time Internal Structure')

swing_ibear_css = input(#f23645, ''


, inline = 'ibear'
, group = 'Real Time Internal Structure')

ifilter_confluence = input(false, 'Confluence Filter'


, group = 'Real Time Internal Structure'
, tooltip = CONFLUENCE_FILTER)

internal_structure_size = input.string('Tiny', 'Internal Label Size'


, options = ['Tiny', 'Small', 'Normal']
, group = 'Real Time Internal Structure')

//----------------------------------------}
//Swing Structure
//----------------------------------------{
show_Structure = input(true, 'Show Swing Structure'
, group = 'Real Time Swing Structure'
, tooltip = SHOW_SWING)

//Bull Structure
show_bull = input.string('All', 'Bullish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'bull'
, group = 'Real Time Swing Structure')
swing_bull_css = input(#089981, ''
, inline = 'bull'
, group = 'Real Time Swing Structure')

//Bear Structure
show_bear = input.string('All', 'Bearish Structure'
, options = ['All', 'BOS', 'CHoCH']
, inline = 'bear'
, group = 'Real Time Swing Structure')

swing_bear_css = input(#f23645, ''


, inline = 'bear'
, group = 'Real Time Swing Structure')

swing_structure_size = input.string('Small', 'Swing Label Size'


, options = ['Tiny', 'Small', 'Normal']
, group = 'Real Time Swing Structure')

//Swings
show_swings = input(false, 'Show Swings Points'
, inline = 'swings'
, group = 'Real Time Swing Structure'
, tooltip = SHOW_SWING_POINTS)

length = input.int(50, ''


, minval = 10
, inline = 'swings'
, group = 'Real Time Swing Structure')

show_hl_swings = input(true, 'Show Strong/Weak High/Low'


, group = 'Real Time Swing Structure'
, tooltip = SHOW_SWHL_POINTS)

//----------------------------------------}
//Order Blocks
//----------------------------------------{
show_iob = input(true, 'Internal Order Blocks'
, inline = 'iob'
, group = 'Order Blocks'
, tooltip = INTERNAL_OB)

iob_showlast = input.int(5, ''


, minval = 1
, inline = 'iob'
, group = 'Order Blocks')

show_ob = input(false, 'Swing Order Blocks'


, inline = 'ob'
, group = 'Order Blocks'
, tooltip = SWING_OB)

ob_showlast = input.int(5, ''


, minval = 1
, inline = 'ob'
, group = 'Order Blocks')

ob_filter = input.string('Atr', 'Order Block Filter'


, options = ['Atr', 'Cumulative Mean Range']
, group = 'Order Blocks'
, tooltip = FILTER_OB)

ibull_ob_css = input.color(color.new(#3179f5, 80), 'Internal Bullish OB'


, group = 'Order Blocks')

ibear_ob_css = input.color(color.new(#f77c80, 80), 'Internal Bearish OB'


, group = 'Order Blocks')

bull_ob_css = input.color(color.new(#1848cc, 80), 'Bullish OB'


, group = 'Order Blocks')

bear_ob_css = input.color(color.new(#b22833, 80), 'Bearish OB'


, group = 'Order Blocks')

//----------------------------------------}
//EQH/EQL
//----------------------------------------{
show_eq = input(true, 'Equal High/Low'
, group = 'EQH/EQL'
, tooltip = SHOW_EQHL)

eq_len = input.int(3, 'Bars Confirmation'


, minval = 1
, group = 'EQH/EQL'
, tooltip = EQHL_BARS)

eq_threshold = input.float(0.1, 'Threshold'


, minval = 0
, maxval = 0.5
, step = 0.1
, group = 'EQH/EQL'
, tooltip = EQHL_THRESHOLD)

eq_size = input.string('Tiny', 'Label Size'


, options = ['Tiny', 'Small', 'Normal']
, group = 'EQH/EQL')

//----------------------------------------}
//Fair Value Gaps
//----------------------------------------{
show_fvg = input(false, 'Fair Value Gaps'
, group = 'Fair Value Gaps'
, tooltip = SHOW_FVG)

fvg_auto = input(true, "Auto Threshold"


, group = 'Fair Value Gaps'
, tooltip = AUTO_FVG)

fvg_tf = input.timeframe('', "Timeframe"


, group = 'Fair Value Gaps'
, tooltip = FVG_TF)

bull_fvg_css = input.color(color.new(#00ff68, 70), 'Bullish FVG'


, group = 'Fair Value Gaps')

bear_fvg_css = input.color(color.new(#ff0008, 70), 'Bearish FVG'


, group = 'Fair Value Gaps')

fvg_extend = input.int(1, "Extend FVG"


, minval = 0
, group = 'Fair Value Gaps'
, tooltip = EXTEND_FVG)

//----------------------------------------}
//Previous day/week high/low
//----------------------------------------{
//Daily
show_pdhl = input(false, 'Daily'
, inline = 'daily'
, group = 'Highs & Lows MTF')

pdhl_style = input.string('⎯⎯⎯', ''


, options = ['⎯⎯⎯', '----', '····']
, inline = 'daily'
, group = 'Highs & Lows MTF')

pdhl_css = input(#2157f3, ''


, inline = 'daily'
, group = 'Highs & Lows MTF')

//Weekly
show_pwhl = input(false, 'Weekly'
, inline = 'weekly'
, group = 'Highs & Lows MTF')

pwhl_style = input.string('⎯⎯⎯', ''


, options = ['⎯⎯⎯', '----', '····']
, inline = 'weekly'
, group = 'Highs & Lows MTF')

pwhl_css = input(#2157f3, ''


, inline = 'weekly'
, group = 'Highs & Lows MTF')

//Monthly
show_pmhl = input(false, 'Monthly'
, inline = 'monthly'
, group = 'Highs & Lows MTF')

pmhl_style = input.string('⎯⎯⎯', ''


, options = ['⎯⎯⎯', '----', '····']
, inline = 'monthly'
, group = 'Highs & Lows MTF')

pmhl_css = input(#2157f3, ''


, inline = 'monthly'
, group = 'Highs & Lows MTF')

//----------------------------------------}
//Premium/Discount zones
//----------------------------------------{
show_sd = input(false, 'Premium/Discount Zones'
, group = 'Premium & Discount Zones'
, tooltip = PED_ZONES)

premium_css = input.color(#f23645, 'Premium Zone'


, group = 'Premium & Discount Zones')
eq_css = input.color(#b2b5be, 'Equilibrium Zone'
, group = 'Premium & Discount Zones')

discount_css = input.color(#089981, 'Discount Zone'


, group = 'Premium & Discount Zones')

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

atr = ta.atr(200)
cmean_range = ta.cum(high - low) / n

//HL Output function


hl() => [high, low]

//Get ohlc values function


get_ohlc()=> [close[1], open[1], high, low, high[2], low[2]]

//Display Structure function


display_Structure(x, y, txt, css, dashed, down, lbl_size)=>
structure_line = line.new(x, y, n, y
, color = css
, style = dashed ? line.style_dashed : line.style_solid)

structure_lbl = label.new(int(math.avg(x, n)), y, txt


, color = TRANSP_CSS
, textcolor = css
, style = down ? label.style_label_down : label.style_label_up
, size = lbl_size)

if mode == 'Present'
line.delete(structure_line[1])
label.delete(structure_lbl[1])

//Swings detection/measurements
swings(len)=>
var os = 0

upper = ta.highest(len)
lower = ta.lowest(len)

os := high[len] > upper ? 0 : low[len] < lower ? 1 : os[1]

top = os == 0 and os[1] != 0 ? high[len] : 0


btm = os == 1 and os[1] != 1 ? low[len] : 0

[top, btm]

//Order block coordinates function


ob_coord(use_max, loc, target_top, target_btm, target_left, target_type)=>
min = 99999999.
max = 0.
idx = 1

ob_threshold = ob_filter == 'Atr' ? atr : cmean_range

//Search for highest/lowest high within the structure interval and get range
if use_max and show_SMC
for i = 1 to (n - loc)-1
if (high[i] - low[i]) < ob_threshold[i] * 2
max := math.max(high[i], max)
min := max == high[i] ? low[i] : min
idx := max == high[i] ? i : idx
else
for i = 1 to (n - loc)-1
if (high[i] - low[i]) < ob_threshold[i] * 2
min := math.min(low[i], min)
max := min == low[i] ? high[i] : max
idx := min == low[i] ? i : idx

array.unshift(target_top, max)
array.unshift(target_btm, min)
array.unshift(target_left, time[idx])
array.unshift(target_type, use_max ? -1 : 1)

//Set order blocks


display_ob(boxes, target_top, target_btm, target_left, target_type, show_last,
swing, size)=>
for i = 0 to math.min(show_last-1, size-1)
get_box = array.get(boxes, i)

box.set_lefttop(get_box, array.get(target_left, i), array.get(target_top,


i))
box.set_rightbottom(get_box, array.get(target_left, i),
array.get(target_btm, i))
box.set_extend(get_box, extend.right)

color css = na

if swing and show_SMC


if style == 'Monochrome'
css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) :
color.new(#5d606b, 80)
border_css = array.get(target_type, i) == 1 ? #b2b5be : #5d606b
box.set_border_color(get_box, border_css)
else
css := array.get(target_type, i) == 1 ? bull_ob_css : bear_ob_css
box.set_border_color(get_box, css)

box.set_bgcolor(get_box, css)
else
if style == 'Monochrome'
css := array.get(target_type, i) == 1 ? color.new(#b2b5be, 80) :
color.new(#5d606b, 80)
else
css := array.get(target_type, i) == 1 ? ibull_ob_css : ibear_ob_css

box.set_border_color(get_box, css)
box.set_bgcolor(get_box, css)

//Line Style function


get_line_style(style) =>
out = switch style
'⎯⎯⎯' => line.style_solid
'----' => line.style_dashed
'····' => line.style_dotted
phl(h, l, tf, css)=>
var line high_line = line.new(na,na,na,na
, xloc = xloc.bar_time
, color = css
, style = get_line_style(pdhl_style))

var label high_lbl = label.new(na,na


, xloc = xloc.bar_time
, text = str.format('P{0}H', tf)
, color = TRANSP_CSS
, textcolor = css
, size = size.small
, style = label.style_label_left)

var line low_line = line.new(na,na,na,na


, xloc = xloc.bar_time
, color = css
, style = get_line_style(pdhl_style))

var label low_lbl = label.new(na,na


, xloc = xloc.bar_time
, text = str.format('P{0}L', tf)
, color = TRANSP_CSS
, textcolor = css
, size = size.small
, style = label.style_label_left)

hy = ta.valuewhen(h != h[1], h, 1)
hx = ta.valuewhen(h == high, time, 1)

ly = ta.valuewhen(l != l[1], l, 1)
lx = ta.valuewhen(l == low, time, 1)

if barstate.islast and show_SMC


ext = time + (time - time[1])*20

//High
line.set_xy1(high_line, hx, hy)
line.set_xy2(high_line, ext, hy)

label.set_xy(high_lbl, ext, hy)

//Low
line.set_xy1(low_line, lx, ly)
line.set_xy2(low_line, ext, ly)

label.set_xy(low_lbl, ext, ly)

//-----------------------------------------------------------------------------}
//Global variables
//-----------------------------------------------------------------------------{
var trend = 0, var itrend = 0

var top_y = 0., var top_x = 0


var btm_y = 0., var btm_x = 0

var itop_y = 0., var itop_x = 0


var ibtm_y = 0., var ibtm_x = 0

var trail_up = high, var trail_dn = low


var trail_up_x = 0, var trail_dn_x = 0

var top_cross = true, var btm_cross = true


var itop_cross = true, var ibtm_cross = true

var txt_top = '', var txt_btm = ''

//Alerts
bull_choch_alert = false
bull_bos_alert = false

bear_choch_alert = false
bear_bos_alert = false

bull_ichoch_alert = false
bull_ibos_alert = false

bear_ichoch_alert = false
bear_ibos_alert = false

bull_iob_break = false
bear_iob_break = false

bull_ob_break = false
bear_ob_break = false

eqh_alert = false
eql_alert = false

//Structure colors
var bull_css = style == 'Monochrome' ? #b2b5be
: swing_bull_css

var bear_css = style == 'Monochrome' ? #b2b5be


: swing_bear_css

var ibull_css = style == 'Monochrome' ? #b2b5be


: swing_ibull_css

var ibear_css = style == 'Monochrome' ? #b2b5be


: swing_ibear_css

//Labels size
var internal_structure_lbl_size = internal_structure_size == 'Tiny'
? size.tiny
: internal_structure_size == 'Small'
? size.small
: size.normal

var swing_structure_lbl_size = swing_structure_size == 'Tiny'


? size.tiny
: swing_structure_size == 'Small'
? size.small
: size.normal

var eqhl_lbl_size = eq_size == 'Tiny'


? size.tiny
: eq_size == 'Small'
? size.small
: size.normal

//Swings
[top, btm] = swings(length)

[itop, ibtm] = swings(5)

//-----------------------------------------------------------------------------}
//Pivot High
//-----------------------------------------------------------------------------{
var line extend_top = na

var label extend_top_lbl = label.new(na, na


, color = TRANSP_CSS
, textcolor = bear_css
, style = label.style_label_down
, size = size.tiny)

if top and show_SMC


top_cross := true
txt_top := top > top_y ? 'HH' : 'LH'

if show_swings
top_lbl = label.new(n-length, top, txt_top
, color = TRANSP_CSS
, textcolor = bear_css
, style = label.style_label_down
, size = swing_structure_lbl_size)

if mode == 'Present'
label.delete(top_lbl[1])

//Extend recent top to last bar


line.delete(extend_top[1])
extend_top := line.new(n-length, top, n, top
, color = bear_css)

top_y := top
top_x := n - length

trail_up := top
trail_up_x := n - length

if itop and show_SMC


itop_cross := true

itop_y := itop
itop_x := n - 5

//Trailing maximum
trail_up := math.max(high, trail_up)
trail_up_x := trail_up == high ? n : trail_up_x

//Set top extension label/line


if barstate.islast and show_hl_swings and show_SMC
line.set_xy1(extend_top, trail_up_x, trail_up)
line.set_xy2(extend_top, n + 20, trail_up)

label.set_x(extend_top_lbl, n + 20)
label.set_y(extend_top_lbl, trail_up)
label.set_text(extend_top_lbl, trend < 0 ? 'Strong High' : 'Weak High')

//-----------------------------------------------------------------------------}
//Pivot Low
//-----------------------------------------------------------------------------{
var line extend_btm = na

var label extend_btm_lbl = label.new(na, na


, color = TRANSP_CSS
, textcolor = bull_css
, style = label.style_label_up
, size = size.tiny)

if btm and show_SMC


btm_cross := true
txt_btm := btm < btm_y ? 'LL' : 'HL'

if show_swings
btm_lbl = label.new(n - length, btm, txt_btm
, color = TRANSP_CSS
, textcolor = bull_css
, style = label.style_label_up
, size = swing_structure_lbl_size)

if mode == 'Present'
label.delete(btm_lbl[1])

//Extend recent btm to last bar


line.delete(extend_btm[1])
extend_btm := line.new(n - length, btm, n, btm
, color = bull_css)

btm_y := btm
btm_x := n-length

trail_dn := btm
trail_dn_x := n-length

if ibtm and show_SMC


ibtm_cross := true

ibtm_y := ibtm
ibtm_x := n - 5

//Trailing minimum
trail_dn := math.min(low, trail_dn)
trail_dn_x := trail_dn == low ? n : trail_dn_x

//Set btm extension label/line


if barstate.islast and show_hl_swings and show_SMC
line.set_xy1(extend_btm, trail_dn_x, trail_dn)
line.set_xy2(extend_btm, n + 20, trail_dn)

label.set_x(extend_btm_lbl, n + 20)
label.set_y(extend_btm_lbl, trail_dn)
label.set_text(extend_btm_lbl, trend > 0 ? 'Strong Low' : 'Weak Low')

//-----------------------------------------------------------------------------}
//Order Blocks Arrays
//-----------------------------------------------------------------------------{
var iob_top = array.new_float(0)
var iob_btm = array.new_float(0)
var iob_left = array.new_int(0)
var iob_type = array.new_int(0)

var ob_top = array.new_float(0)


var ob_btm = array.new_float(0)
var ob_left = array.new_int(0)
var ob_type = array.new_int(0)

//-----------------------------------------------------------------------------}
//Pivot High BOS/CHoCH
//-----------------------------------------------------------------------------{
//Filtering
var bull_concordant = true

if ifilter_confluence and show_SMC


bull_concordant := high - math.max(close, open) > math.min(close, open - low)

//Detect internal bullish Structure


if ta.crossover(close, itop_y) and itop_cross and top_y != itop_y and
bull_concordant and show_SMC
bool choch = na

if itrend < 0
choch := true
bull_ichoch_alert := true
else
bull_ibos_alert := true

txt = choch ? 'CHoCH' : 'BOS'

if show_internals
if show_ibull == 'All' or (show_ibull == 'BOS' and not choch) or
(show_ibull == 'CHoCH' and choch)
display_Structure(itop_x, itop_y, txt, ibull_css, true, true,
internal_structure_lbl_size)

itop_cross := false
itrend := 1

//Internal Order Block


if show_iob
ob_coord(false, itop_x, iob_top, iob_btm, iob_left, iob_type)

//Detect bullish Structure


if ta.crossover(close, top_y) and top_cross and show_SMC
bool choch = na

if trend < 0
choch := true
bull_choch_alert := true
else
bull_bos_alert := true
txt = choch ? 'CHoCH' : 'BOS'

if show_Structure
if show_bull == 'All' or (show_bull == 'BOS' and not choch) or (show_bull
== 'CHoCH' and choch)
display_Structure(top_x, top_y, txt, bull_css, false, true,
swing_structure_lbl_size)

//Order Block
if show_ob
ob_coord(false, top_x, ob_top, ob_btm, ob_left, ob_type)

top_cross := false
trend := 1

//-----------------------------------------------------------------------------}
//Pivot Low BOS/CHoCH
//-----------------------------------------------------------------------------{
var bear_concordant = true

if ifilter_confluence and show_SMC


bear_concordant := high - math.max(close, open) < math.min(close, open - low)

//Detect internal bearish Structure


if ta.crossunder(close, ibtm_y) and ibtm_cross and btm_y != ibtm_y and
bear_concordant and show_SMC
bool choch = false

if itrend > 0
choch := true
bear_ichoch_alert := true
else
bear_ibos_alert := true

txt = choch ? 'CHoCH' : 'BOS'

if show_internals
if show_ibear == 'All' or (show_ibear == 'BOS' and not choch) or
(show_ibear == 'CHoCH' and choch)
display_Structure(ibtm_x, ibtm_y, txt, ibear_css, true, false,
internal_structure_lbl_size)

ibtm_cross := false
itrend := -1

//Internal Order Block


if show_iob
ob_coord(true, ibtm_x, iob_top, iob_btm, iob_left, iob_type)

//Detect bearish Structure


if ta.crossunder(close, btm_y) and btm_cross and show_SMC
bool choch = na

if trend > 0
choch := true
bear_choch_alert := true
else
bear_bos_alert := true
txt = choch ? 'CHoCH' : 'BOS'

if show_Structure
if show_bear == 'All' or (show_bear == 'BOS' and not choch) or (show_bear
== 'CHoCH' and choch)
display_Structure(btm_x, btm_y, txt, bear_css, false, false,
swing_structure_lbl_size)

//Order Block
if show_ob
ob_coord(true, btm_x, ob_top, ob_btm, ob_left, ob_type)

btm_cross := false
trend := -1

//-----------------------------------------------------------------------------}
//Order Blocks
//-----------------------------------------------------------------------------{
//Set order blocks
var iob_boxes = array.new_box(0)
var ob_boxes = array.new_box(0)

//Delete internal order blocks box coordinates if top/bottom is broken


for element in iob_type
index = array.indexof(iob_type, element)

if close < array.get(iob_btm, index) and element == 1


array.remove(iob_top, index)
array.remove(iob_btm, index)
array.remove(iob_left, index)
array.remove(iob_type, index)
bull_iob_break := true

else if close > array.get(iob_top, index) and element == -1


array.remove(iob_top, index)
array.remove(iob_btm, index)
array.remove(iob_left, index)
array.remove(iob_type, index)
bear_iob_break := true

//Delete internal order blocks box coordinates if top/bottom is broken


for element in ob_type
index = array.indexof(ob_type, element)

if close < array.get(ob_btm, index) and element == 1


array.remove(ob_top, index)
array.remove(ob_btm, index)
array.remove(ob_left, index)
array.remove(ob_type, index)
bull_ob_break := true

else if close > array.get(ob_top, index) and element == -1


array.remove(ob_top, index)
array.remove(ob_btm, index)
array.remove(ob_left, index)
array.remove(ob_type, index)
bear_ob_break := true
iob_size = array.size(iob_type)
ob_size = array.size(ob_type)

if barstate.isfirst and show_SMC


if show_iob
for i = 0 to iob_showlast-1
array.push(iob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time))
if show_ob
for i = 0 to ob_showlast-1
array.push(ob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time))

if iob_size > 0 and show_SMC


if barstate.islast
display_ob(iob_boxes, iob_top, iob_btm, iob_left, iob_type, iob_showlast,
false, iob_size)

if ob_size > 0 and show_SMC


if barstate.islast
display_ob(ob_boxes, ob_top, ob_btm, ob_left, ob_type, ob_showlast, true,
ob_size)

//-----------------------------------------------------------------------------}
//EQH/EQL
//-----------------------------------------------------------------------------{
var eq_prev_top = 0.
var eq_top_x = 0

var eq_prev_btm = 0.
var eq_btm_x = 0

if show_eq and show_SMC


eq_top = ta.pivothigh(eq_len, eq_len)
eq_btm = ta.pivotlow(eq_len, eq_len)

if bool(eq_top)
max = math.max(eq_top, eq_prev_top)
min = math.min(eq_top, eq_prev_top)

if max < min + atr * eq_threshold


eqh_line = line.new(eq_top_x, eq_prev_top, n-eq_len, eq_top
, color = bear_css
, style = line.style_dotted)

eqh_lbl = label.new(int(math.avg(n-eq_len, eq_top_x)), eq_top, 'EQH'


, color = #00000000
, textcolor = bear_css
, style = label.style_label_down
, size = eqhl_lbl_size)

if mode == 'Present'
line.delete(eqh_line[1])
label.delete(eqh_lbl[1])

eqh_alert := true

eq_prev_top := eq_top
eq_top_x := n-eq_len

if bool(eq_btm)
max = math.max(eq_btm, eq_prev_btm)
min = math.min(eq_btm, eq_prev_btm)

if min > max - atr * eq_threshold


eql_line = line.new(eq_btm_x, eq_prev_btm, n-eq_len, eq_btm
, color = bull_css
, style = line.style_dotted)

eql_lbl = label.new(int(math.avg(n-eq_len, eq_btm_x)), eq_btm, 'EQL'


, color = #00000000
, textcolor = bull_css
, style = label.style_label_up
, size = eqhl_lbl_size)

eql_alert := true

if mode == 'Present'
line.delete(eql_line[1])
label.delete(eql_lbl[1])

eq_prev_btm := eq_btm
eq_btm_x := n-eq_len

//-----------------------------------------------------------------------------}
//Fair Value Gaps
//-----------------------------------------------------------------------------{
var bullish_fvg_max = array.new_box(0)
var bullish_fvg_min = array.new_box(0)

var bearish_fvg_max = array.new_box(0)


var bearish_fvg_min = array.new_box(0)

float bullish_fvg_avg = na
float bearish_fvg_avg = na

bullish_fvg_cnd = false
bearish_fvg_cnd = false

[src_c1, src_o1, src_h, src_l, src_h2, src_l2] =


request.security(syminfo.tickerid, fvg_tf, get_ohlc())

if show_fvg and show_SMC


delta_per = (src_c1 - src_o1) / src_o1 * 100

change_tf = timeframe.change(fvg_tf)

threshold = fvg_auto ? ta.cum(math.abs(change_tf ? delta_per : 0)) / n * 2


: 0

//FVG conditions
bullish_fvg_cnd := src_l > src_h2
and src_c1 > src_h2
and delta_per > threshold
and change_tf

bearish_fvg_cnd := src_h < src_l2


and src_c1 < src_l2
and -delta_per > threshold
and change_tf
//FVG Areas
if bullish_fvg_cnd
array.unshift(bullish_fvg_max, box.new(n-1, src_l, n + fvg_extend,
math.avg(src_l, src_h2)
, border_color = bull_fvg_css
, bgcolor = bull_fvg_css))

array.unshift(bullish_fvg_min, box.new(n-1, math.avg(src_l, src_h2), n +


fvg_extend, src_h2
, border_color = bull_fvg_css
, bgcolor = bull_fvg_css))

if bearish_fvg_cnd
array.unshift(bearish_fvg_max, box.new(n-1, src_h, n + fvg_extend,
math.avg(src_h, src_l2)
, border_color = bear_fvg_css
, bgcolor = bear_fvg_css))

array.unshift(bearish_fvg_min, box.new(n-1, math.avg(src_h, src_l2), n +


fvg_extend, src_l2
, border_color = bear_fvg_css
, bgcolor = bear_fvg_css))

for bx in bullish_fvg_min
if low < box.get_bottom(bx)
box.delete(bx)
box.delete(array.get(bullish_fvg_max, array.indexof(bullish_fvg_min,
bx)))

for bx in bearish_fvg_max
if high > box.get_top(bx)
box.delete(bx)
box.delete(array.get(bearish_fvg_min, array.indexof(bearish_fvg_max,
bx)))

//-----------------------------------------------------------------------------}
//Previous day/week high/lows
//-----------------------------------------------------------------------------{
//Daily high/low
[pdh, pdl] = request.security(syminfo.tickerid, 'D', hl()
, lookahead = barmerge.lookahead_on)

//Weekly high/low
[pwh, pwl] = request.security(syminfo.tickerid, 'W', hl()
, lookahead = barmerge.lookahead_on)

//Monthly high/low
[pmh, pml] = request.security(syminfo.tickerid, 'M', hl()
, lookahead = barmerge.lookahead_on)

//Display Daily
if show_pdhl
phl(pdh, pdl, 'D', pdhl_css)

//Display Weekly
if show_pwhl and show_SMC
phl(pwh, pwl, 'W', pwhl_css)
//Display Monthly
if show_pmhl and show_SMC
phl(pmh, pml, 'M', pmhl_css)

//-----------------------------------------------------------------------------}
//Premium/Discount/Equilibrium zones
//-----------------------------------------------------------------------------{
var premium = box.new(na, na, na, na
, bgcolor = color.new(premium_css, 80)
, border_color = na)

var premium_lbl = label.new(na, na


, text = 'Premium'
, color = TRANSP_CSS
, textcolor = premium_css
, style = label.style_label_down
, size = size.small)

var eq = box.new(na, na, na, na


, bgcolor = color.rgb(120, 123, 134, 80)
, border_color = na)

var eq_lbl = label.new(na, na


, text = 'Equilibrium'
, color = TRANSP_CSS
, textcolor = eq_css
, style = label.style_label_left
, size = size.small)

var discount = box.new(na, na, na, na


, bgcolor = color.new(discount_css, 80)
, border_color = na)

var discount_lbl = label.new(na, na


, text = 'Discount'
, color = TRANSP_CSS
, textcolor = discount_css
, style = label.style_label_up
, size = size.small)

//Show Premium/Discount Areas


if barstate.islast and show_sd and show_SMC
avg = math.avg(trail_up, trail_dn)

box.set_lefttop(premium, math.max(top_x, btm_x), trail_up)


box.set_rightbottom(premium, n, .95 * trail_up + .05 * trail_dn)

label.set_xy(premium_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_up)

box.set_lefttop(eq, math.max(top_x, btm_x), .525 * trail_up + .475*trail_dn)


box.set_rightbottom(eq, n, .525 * trail_dn + .475 * trail_up)

label.set_xy(eq_lbl, n, avg)

box.set_lefttop(discount, math.max(top_x, btm_x), .95 * trail_dn + .05 *


trail_up)
box.set_rightbottom(discount, n, trail_dn)
label.set_xy(discount_lbl, int(math.avg(math.max(top_x, btm_x), n)), trail_dn)
//-----------------------------------------------------------------------------}
//Trend
//-----------------------------------------------------------------------------{
var color trend_css = na

if show_trend and show_SMC


if style == 'Colored'
trend_css := itrend == 1 ? bull_css : bear_css
else if style == 'Monochrome'
trend_css := itrend == 1 ? #b2b5be : #5d606b

plotcandle(open, high, low, close


, color = trend_css
, wickcolor = trend_css
, bordercolor = trend_css
, editable = false)

//-----------------------------------------------------------------------------}
//Alerts
//-----------------------------------------------------------------------------{
//Internal Structure
alertcondition(bull_ibos_alert, 'Internal Bullish BOS', 'Internal Bullish BOS
formed')
alertcondition(bull_ichoch_alert, 'Internal Bullish CHoCH', 'Internal Bullish CHoCH
formed')

alertcondition(bear_ibos_alert, 'Internal Bearish BOS', 'Internal Bearish BOS


formed')
alertcondition(bear_ichoch_alert, 'Internal Bearish CHoCH', 'Internal Bearish CHoCH
formed')

//Swing Structure
alertcondition(bull_bos_alert, 'Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(bull_choch_alert, 'Bullish CHoCH', 'Internal Bullish CHoCH formed')

alertcondition(bear_bos_alert, 'Bearish BOS', 'Bearish BOS formed')


alertcondition(bear_choch_alert, 'Bearish CHoCH', 'Bearish CHoCH formed')

//order Blocks
alertcondition(bull_iob_break, 'Bullish Internal OB Breakout', 'Price broke bullish
internal OB')
alertcondition(bear_iob_break, 'Bearish Internal OB Breakout', 'Price broke bearish
internal OB')

alertcondition(bull_ob_break, 'Bullish Swing OB Breakout', 'Price broke bullish


swing OB')
alertcondition(bear_ob_break, 'Bearish Swing OB Breakout', 'Price broke bearish
swing OB')

//EQH/EQL
alertcondition(eqh_alert, 'Equal Highs', 'Equal highs detected')
alertcondition(eql_alert, 'Equal Lows', 'Equal lows detected')

//FVG
alertcondition(bullish_fvg_cnd, 'Bullish FVG', 'Bullish FVG formed')
alertcondition(bearish_fvg_cnd, 'Bearish FVG', 'Bearish FVG formed')

//-----------------------------------------------------------------------------}
////////////////////////////////////
///////DIVERGENCIAS/////////////////
////////////////////////////////////
show_DIV = input(false, title='--------- Show DIVERGENCIAS ---------')
prd = input.int(defval=5, title='Pivot Period', minval=1, maxval=50)
source = input.string(defval='Close', title='Source for Pivot Points',
options=['Close', 'High/Low'])
searchdiv = input.string(defval='Regular', title='Divergence Type',
options=['Regular', 'Hidden', 'Regular/Hidden'])
showindis = input.string(defval='Full', title='Show Indicator Names',
options=['Full', 'First Letter', 'Don\'t Show'])
showlimit = input.int(1, title='Minimum Number of Divergence', minval=1, maxval=11)
maxpp = input.int(defval=10, title='Maximum Pivot Points to Check', minval=1,
maxval=20)
maxbars = input.int(defval=100, title='Maximum Bars to Check', minval=30,
maxval=200)
shownum = input(defval=true, title='Show Divergence Number')
showlast = input(defval=false, title='Show Only Last Divergence')
dontconfirm = input(defval=false, title='Don\'t Wait for Confirmation')
showlines = input(defval=true, title='Show Divergence Lines')
showpivot = input(defval=false, title='Show Pivot Points')
calcmacd = input(defval=true, title='MACD')
calcmacda = input(defval=true, title='MACD Histogram')
calcrsi = input(defval=true, title='RSI')
calcstoc = input(defval=true, title='Stochastic')
calccci = input(defval=true, title='CCI')
calcmom = input(defval=true, title='Momentum')
calcobv = input(defval=true, title='OBV')
calcvwmacd = input(true, title='VWmacd')
calccmf = input(true, title='Chaikin Money Flow')
calcmfi = input(true, title='Money Flow Index')
calcext = input(false, title='Check External Indicator')
externalindi = input(defval=close, title='External Indicator')
pos_reg_div_col = input(defval=color.yellow, title='Positive Regular Divergence')
neg_reg_div_col = input(defval=color.navy, title='Negative Regular Divergence')
pos_hid_div_col = input(defval=color.lime, title='Positive Hidden Divergence')
neg_hid_div_col = input(defval=color.red, title='Negative Hidden Divergence')
pos_div_text_col = input(defval=color.black, title='Positive Divergence Text
Color')
neg_div_text_col = input(defval=color.white, title='Negative Divergence Text
Color')
reg_div_l_style_ = input.string(defval='Solid', title='Regular Divergence Line
Style', options=['Solid', 'Dashed', 'Dotted'])
hid_div_l_style_ = input.string(defval='Dashed', title='Hdden Divergence Line
Style', options=['Solid', 'Dashed', 'Dotted'])
reg_div_l_width = input.int(defval=2, title='Regular Divergence Line Width',
minval=1, maxval=5)
hid_div_l_width = input.int(defval=1, title='Hidden Divergence Line Width',
minval=1, maxval=5)
showmas = input.bool(defval=false, title='Show MAs 50 & 200', inline='ma12')
cma1col = input.color(defval=color.lime, title='', inline='ma12')
cma2col = input.color(defval=color.red, title='', inline='ma12')
plot(showmas ? ta.sma(close, 50) : na, color=showmas ? cma1col : na)
plot(showmas ? ta.sma(close, 200) : na, color=showmas ? cma2col : na)
// set line styles
var reg_div_l_style = reg_div_l_style_ == 'Solid' ? line.style_solid :
reg_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
var hid_div_l_style = hid_div_l_style_ == 'Solid' ? line.style_solid :
hid_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
// get indicators
rsi = ta.rsi(close, 14) // RSI
[macd, signal, deltamacd] = ta.macd(close, 12, 26, 9) // MACD
moment = ta.mom(close, 10) // Momentum
cci = ta.cci(close, 10) // CCI
Obv = ta.obv // OBV
stk = ta.sma(ta.stoch(close, high, low, 14), 3) // Stoch
maFast = ta.vwma(close, 12) // volume weighted macd
maSlow = ta.vwma(close, 26)
vwmacd = maFast - maSlow
Cmfm = (close - low - (high - close)) / (high - low) // Chaikin money flow
Cmfv = Cmfm * volume
cmf = ta.sma(Cmfv, 21) / ta.sma(volume, 21)
Mfi = ta.mfi(close, 14) // Moneyt Flow Index

// keep indicators names and colors in arrays


var indicators_name = array.new_string(11)
var div_colors = array.new_color(4)
if barstate.isfirst and show_DIV
// names
array.set(indicators_name, 0, showindis == 'Full' ? 'MACD' : 'M')
array.set(indicators_name, 1, showindis == 'Full' ? 'Hist' : 'H')
array.set(indicators_name, 2, showindis == 'Full' ? 'RSI' : 'E')
array.set(indicators_name, 3, showindis == 'Full' ? 'Stoch' : 'S')
array.set(indicators_name, 4, showindis == 'Full' ? 'CCI' : 'C')
array.set(indicators_name, 5, showindis == 'Full' ? 'MOM' : 'M')
array.set(indicators_name, 6, showindis == 'Full' ? 'OBV' : 'O')
array.set(indicators_name, 7, showindis == 'Full' ? 'VWMACD' : 'V')
array.set(indicators_name, 8, showindis == 'Full' ? 'CMF' : 'C')
array.set(indicators_name, 9, showindis == 'Full' ? 'MFI' : 'M')
array.set(indicators_name, 10, showindis == 'Full' ? 'Extrn' : 'X')
//colors
array.set(div_colors, 0, pos_reg_div_col)
array.set(div_colors, 1, neg_reg_div_col)
array.set(div_colors, 2, pos_hid_div_col)
array.set(div_colors, 3, neg_hid_div_col)

// Check if we get new Pivot High Or Pivot Low


float ph = ta.pivothigh(source == 'Close' ? close : high, prd, prd)
float pl = ta.pivotlow(source == 'Close' ? close : low, prd, prd)
plotshape(ph and showpivot, text='H', style=shape.labeldown,
color=color.new(color.white, 100), textcolor=color.new(color.red, 0),
location=location.abovebar, offset=-prd)
plotshape(pl and showpivot, text='L', style=shape.labelup,
color=color.new(color.white, 100), textcolor=color.new(color.lime, 0),
location=location.belowbar, offset=-prd)

// keep values and positions of Pivot Highs/Lows in the arrays


var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)

// add PHs to the array


if ph and show_DIV
array.unshift(ph_positions, bar_index)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > maxarraysize
array.pop(ph_positions)
array.pop(ph_vals)

// add PLs to the array


if pl and show_DIV
array.unshift(pl_positions, bar_index)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > maxarraysize
array.pop(pl_positions)
array.pop(pl_vals)

// functions to check Regular Divergences and Hidden Divergences

// function to check positive regular or negative hidden divergence


// cond == 1 => positive_regular, cond == 2=> negative_hidden
positive_regular_positive_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? close : low
// if indicators higher than last value and close price is higher than las
close
if dontconfirm or src > src[1] or close > close[1] and show_DIV
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1 by 1
len = bar_index - array.get(pl_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous
bars then we don't search more
if array.get(pl_positions, x) == 0 or len > maxbars
break
if len > 5 and (cond == 1 and src[startpoint] > src[len] and
prsc[startpoint] < nz(array.get(pl_vals, x)) or cond == 2 and src[startpoint] <
src[len] and prsc[startpoint] > nz(array.get(pl_vals, x)))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - close[len]) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1 by 1
if src[y] < virtual_line1 or nz(close[y]) < virtual_line2
arrived := false
break
virtual_line1 -= slope1
virtual_line2 -= slope2
virtual_line2

if arrived
divlen := len
break
divlen

// function to check negative regular or positive hidden divergence


// cond == 1 => negative_regular, cond == 2=> positive_hidden
negative_regular_negative_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? close : high
// if indicators higher than last value and close price is higher than las
close
if dontconfirm or src < src[1] or close < close[1] and show_DIV
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1 by 1
len = bar_index - array.get(ph_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous
bars then we don't search more
if array.get(ph_positions, x) == 0 or len > maxbars
break
if len > 5 and (cond == 1 and src[startpoint] < src[len] and
prsc[startpoint] > nz(array.get(ph_vals, x)) or cond == 2 and src[startpoint] >
src[len] and prsc[startpoint] < nz(array.get(ph_vals, x)))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)
virtual_line2 = close[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1 by 1
if src[y] > virtual_line1 or nz(close[y]) > virtual_line2
arrived := false
break
virtual_line1 -= slope1
virtual_line2 -= slope2
virtual_line2

if arrived
divlen := len
break
divlen

// calculate 4 types of divergence if enabled in the options and return divergences


in an array
calculate_divs(cond, indicator_1) =>
divs = array.new_int(4, 0)
array.set(divs, 0, cond and (searchdiv == 'Regular' or searchdiv ==
'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 1) :
0)
array.set(divs, 1, cond and (searchdiv == 'Regular' or searchdiv ==
'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 1) :
0)
array.set(divs, 2, cond and (searchdiv == 'Hidden' or searchdiv ==
'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 2) :
0)
array.set(divs, 3, cond and (searchdiv == 'Hidden' or searchdiv ==
'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 2) :
0)
divs

// array to keep all divergences


var all_divergences = array.new_int(44) // 11 indicators * 4 divergence = 44
elements
// set related array elements
array_set_divs(div_pointer, index) =>
for x = 0 to 3 by 1
array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))

// set divergences array


array_set_divs(calculate_divs(calcmacd, macd), 0)
array_set_divs(calculate_divs(calcmacda, deltamacd), 1)
array_set_divs(calculate_divs(calcrsi, rsi), 2)
array_set_divs(calculate_divs(calcstoc, stk), 3)
array_set_divs(calculate_divs(calccci, cci), 4)
array_set_divs(calculate_divs(calcmom, moment), 5)
array_set_divs(calculate_divs(calcobv, Obv), 6)
array_set_divs(calculate_divs(calcvwmacd, vwmacd), 7)
array_set_divs(calculate_divs(calccmf, cmf), 8)
array_set_divs(calculate_divs(calcmfi, Mfi), 9)
array_set_divs(calculate_divs(calcext, externalindi), 10)

// check minimum number of divergence, if less than showlimit then delete all
divergence
total_div = 0
for x = 0 to array.size(all_divergences) - 1 by 1
total_div += math.round(math.sign(array.get(all_divergences, x)))
total_div

if total_div < showlimit and show_DIV


array.fill(all_divergences, 0)

// keep line in an array


var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)

// remove old lines and labels if showlast option is enabled


delete_old_pos_div_lines() =>
if array.size(pos_div_lines) > 0
for j = 0 to array.size(pos_div_lines) - 1 by 1
line.delete(array.get(pos_div_lines, j))
array.clear(pos_div_lines)

delete_old_neg_div_lines() =>
if array.size(neg_div_lines) > 0
for j = 0 to array.size(neg_div_lines) - 1 by 1
line.delete(array.get(neg_div_lines, j))
array.clear(neg_div_lines)

delete_old_pos_div_labels() =>
if array.size(pos_div_labels) > 0
for j = 0 to array.size(pos_div_labels) - 1 by 1
label.delete(array.get(pos_div_labels, j))
array.clear(pos_div_labels)

delete_old_neg_div_labels() =>
if array.size(neg_div_labels) > 0
for j = 0 to array.size(neg_div_labels) - 1 by 1
label.delete(array.get(neg_div_labels, j))
array.clear(neg_div_labels)

// delete last creted lines and labels until we met new PH/PV
delete_last_pos_div_lines_label(n) =>
if n > 0 and array.size(pos_div_lines) >= n
asz = array.size(pos_div_lines)
for j = 1 to n by 1
line.delete(array.get(pos_div_lines, asz - j))
array.pop(pos_div_lines)
if array.size(pos_div_labels) > 0
label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))
array.pop(pos_div_labels)
delete_last_neg_div_lines_label(n) =>
if n > 0 and array.size(neg_div_lines) >= n
asz = array.size(neg_div_lines)
for j = 1 to n by 1
line.delete(array.get(neg_div_lines, asz - j))
array.pop(neg_div_lines)
if array.size(neg_div_labels) > 0
label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))
array.pop(neg_div_labels)

// variables for Alerts


pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false

// to remove lines/labels until we met new // PH/PL


var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl and show_DIV
remove_last_pos_divs := false
last_pos_div_lines := 0
last_pos_div_lines
if ph and show_DIV
remove_last_neg_divs := false
last_neg_div_lines := 0
last_neg_div_lines
// draw divergences lines and labels
divergence_text_top = ''
divergence_text_bottom = ''
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
startpoint = dontconfirm ? 0 : 1 // used for don't confirm option
for x = 0 to 10 by 1
div_type = -1
for y = 0 to 3 by 1
if array.get(all_divergences, x * 4 + y) > 0 and show_DIV // any
divergence?
div_type := y
if y % 2 == 1
dnumdiv_top += 1
top_label_col := array.get(div_colors, y)
top_label_col
if y % 2 == 0
dnumdiv_bottom += 1
bottom_label_col := array.get(div_colors, y)
bottom_label_col
if not array.includes(distances, array.get(all_divergences, x * 4 + y))
// line not exist ?
array.push(distances, array.get(all_divergences, x * 4 + y))
new_line = showlines ? line.new(x1=bar_index -
array.get(all_divergences, x * 4 + y), y1=source == 'Close' ?
close[array.get(all_divergences, x * 4 + y)] : y % 2 == 0 ?
low[array.get(all_divergences, x * 4 + y)] : high[array.get(all_divergences, x * 4
+ y)], x2=bar_index - startpoint, y2=source == 'Close' ? close[startpoint] : y % 2
== 0 ? low[startpoint] : high[startpoint], color=array.get(div_colors, y), style=y
< 2 ? reg_div_l_style : hid_div_l_style, width=y < 2 ? reg_div_l_width :
hid_div_l_width) : na
if y % 2 == 0
if old_pos_divs_can_be_removed
old_pos_divs_can_be_removed := false
if not showlast and remove_last_pos_divs
delete_last_pos_div_lines_label(last_pos_div_lines)
last_pos_div_lines := 0
last_pos_div_lines
if showlast
delete_old_pos_div_lines()
array.push(pos_div_lines, new_line)
last_pos_div_lines += 1
remove_last_pos_divs := true
remove_last_pos_divs
if y % 2 == 1
if old_neg_divs_can_be_removed
old_neg_divs_can_be_removed := false
if not showlast and remove_last_neg_divs
delete_last_neg_div_lines_label(last_neg_div_lines)
last_neg_div_lines := 0
last_neg_div_lines
if showlast
delete_old_neg_div_lines()
array.push(neg_div_lines, new_line)
last_neg_div_lines += 1
remove_last_neg_divs := true
remove_last_neg_divs
// set variables for alerts
if y == 0
pos_reg_div_detected := true
pos_reg_div_detected
if y == 1
neg_reg_div_detected := true
neg_reg_div_detected
if y == 2
pos_hid_div_detected := true
pos_hid_div_detected
if y == 3
neg_hid_div_detected := true
neg_hid_div_detected
// get text for labels
if div_type >= 0 and show_DIV
divergence_text_top += (div_type % 2 == 1 ? showindis != 'Don\'t Show' ?
array.get(indicators_name, x) + '\n' : '' : '')
divergence_text_bottom += (div_type % 2 == 0 ? showindis != 'Don\'t Show' ?
array.get(indicators_name, x) + '\n' : '' : '')
divergence_text_bottom
// draw labels
if showindis != 'Don\'t Show' or shownum and show_DIV
if shownum and dnumdiv_top > 0
divergence_text_top += str.tostring(dnumdiv_top)
divergence_text_top
if shownum and dnumdiv_bottom > 0
divergence_text_bottom += str.tostring(dnumdiv_bottom)
divergence_text_bottom
if divergence_text_top != ''
if showlast
delete_old_neg_div_labels()
array.push(neg_div_labels, label.new(x=bar_index, y=math.max(high,
high[1]), text=divergence_text_top, color=top_label_col,
textcolor=neg_div_text_col, style=label.style_label_down))

if divergence_text_bottom != ''
if showlast
delete_old_pos_div_labels()
array.push(pos_div_labels, label.new(x=bar_index, y=math.min(low, low[1]),
text=divergence_text_bottom, color=bottom_label_col, textcolor=pos_div_text_col,
style=label.style_label_up))
alertcondition(pos_reg_div_detected, title='Positive Regular Divergence Detected',
message='Positive Regular Divergence Detected')
alertcondition(neg_reg_div_detected, title='Negative Regular Divergence Detected',
message='Negative Regular Divergence Detected')
alertcondition(pos_hid_div_detected, title='Positive Hidden Divergence Detected',
message='Positive Hidden Divergence Detected')
alertcondition(neg_hid_div_detected, title='Negative Hidden Divergence Detected',
message='Negative Hidden Divergence Detected')
alertcondition(pos_reg_div_detected or pos_hid_div_detected, title='Positive
Divergence Detected', message='Positive Divergence Detected')
alertcondition(neg_reg_div_detected or neg_hid_div_detected, title='Negative
Divergence Detected', message='Negative Divergence Detected')

show_LIQ= input(false, title='--------- Show LIQUIDACIONES ---------')

length2 = input(14, 'Pivot Lookback')

area2 = input.string('Wick Extremity', 'Swing area2', options = ['Wick Extremity',


'Full Range'])

intraPrecision2 = input(false, 'Intrabar Precision', inline = 'intrabar')


intrabarTf2 = input.timeframe('1', '' , inline = 'intrabar')

filterOptions2 = input.string('Count', 'Filter area2s By', options = ['Count',


'Volume'], inline = 'filter')
filterValue2 = input.float(0, '' ,
inline = 'filter')

//Style
showTop2 = input(true, 'Swing High' , inline = 'top', group =
'Style')
topCss2 = input(color.red, '' , inline = 'top', group =
'Style')
toparea2Css2 = input(color.new(color.red, 50), 'area2', inline = 'top', group =
'Style')

showBtm2 = input(true, 'Swing Low' , inline = 'btm', group =


'Style')
btmCss2 = input(color.teal, '' , inline = 'btm', group =
'Style')
btmarea2Css2 = input(color.new(color.teal, 50), 'area2', inline = 'btm', group =
'Style')

labelSize2 = input.string('Tiny', 'Labels Size', options = ['Tiny', 'Small',


'Normal'], group = 'Style')
//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
n2 = bar_index

get_data()=> [high, low, volume]

[h, l, v] = request.security_lower_tf(syminfo.tickerid, intrabarTf2, get_data())

get_counts(condition, top, btm)=>


var count = 0
var vol = 0.

if condition and show_LIQ


count := 0
vol := 0.
else
if intraPrecision2
if n2 > length2
if array.size(v[length2]) > 0
for [index, element] in v[length2]
vol += array.get(l[length2], index) < top and
array.get(h[length2], index) > btm ? element : 0
else
vol += low[length2] < top and high[length2] > btm ? volume[length2] : 0

count += low[length2] < top and high[length2] > btm ? 1 : 0

[count, vol]

set_label(count, vol, x, y, css, lbl_style)=>


var label lbl = na
var label_size = switch labelSize2
'Tiny' => size.tiny
'Small' => size.small
'Normal' => size.normal

target = switch filterOptions2


'Count' => count
'Volume' => vol

if ta.crossover(target, filterValue2) and show_LIQ


lbl := label.new(x, y, str.tostring(vol, format.volume)
, style = lbl_style
, size = label_size
, color = #00000000
, textcolor = css)

if target > filterValue2 and show_LIQ


label.set_text(lbl, str.tostring(vol, format.volume))

set_level(condition, crossed, value, count, vol, css)=>


var line lvl = na

target = switch filterOptions2


'Count' => count
'Volume' => vol
if condition and show_LIQ
if target[1] < filterValue2[1]
line.delete(lvl[1])
else if not crossed[1]
line.set_x2(lvl, n2 - length2)

lvl := line.new(n2 - length2, value, n2, value


, color = na)

if not crossed[1] and show_LIQ


line.set_x2(lvl, n2+3)

if crossed and not crossed[1] and show_LIQ


line.set_x2(lvl, n2)
line.set_style(lvl, line.style_dashed)

if target > filterValue2 and show_LIQ


line.set_color(lvl, css)

set_zone(condition, x, top, btm, count, vol, css)=>


var box bx = na

target = switch filterOptions2


'Count' => count
'Volume' => vol

if ta.crossover(target, filterValue2) and show_LIQ


bx := box.new(x, top, x + count, btm
, border_color = na
, bgcolor = css)

if target > filterValue2 and show_LIQ


box.set_right(bx, x + count)

//-----------------------------------------------------------------------------}
//Global variables
//-----------------------------------------------------------------------------{
//Pivot high
var float ph_top = na
var float ph_btm = na
var bool ph_crossed = na
var ph_x1 = 0
var box ph_bx = box.new(na,na,na,na
, bgcolor = color.new(toparea2Css2, 80)
, border_color = na)

//Pivot low
var float pl_top = na
var float pl_btm = na
var bool pl_crossed = na
var pl_x1 = 0
var box pl_bx = box.new(na,na,na,na
, bgcolor = color.new(btmarea2Css2, 80)
, border_color = na)

//-----------------------------------------------------------------------------}
//Display pivot high levels/blocks
//-----------------------------------------------------------------------------{
ph2 = ta.pivothigh(length2, length2)
//Get ph2 counts
[ph_count, ph_vol] = get_counts(ph2, ph_top, ph_btm)

//Set ph2 area2 and level


if bool(ph2) and showTop2 and show_LIQ
ph_top := high[length2]
ph_btm := switch area2
'Wick Extremity' => math.max(close[length2], open[length2])
'Full Range' => low[length2]

ph_x1 := n2 - length2
ph_crossed := false

box.set_lefttop(ph_bx, ph_x1, ph_top)


box.set_rightbottom(ph_bx, ph_x1, ph_btm)
else
ph_crossed := close > ph_top ? true : ph_crossed

if ph_crossed
box.set_right(ph_bx, ph_x1)
else
box.set_right(ph_bx, n2+3)

if showTop2 and show_LIQ


//Set ph2 zone
set_zone(ph2, ph_x1, ph_top, ph_btm, ph_count, ph_vol, toparea2Css2)

//Set ph2 level


set_level(ph2, ph_crossed, ph_top, ph_count, ph_vol, topCss2)

//Set ph2 label


set_label(ph_count, ph_vol, ph_x1, ph_top, topCss2, label.style_label_down)

//-----------------------------------------------------------------------------}
//Display pivot low levels/blocks
//-----------------------------------------------------------------------------{
pl2 = ta.pivotlow(length2, length2)

//Get pl2 counts


[pl_count, pl_vol] = get_counts(pl2, pl_top, pl_btm)

//Set pl2 area2 and level


if bool(pl2) and showBtm2 and show_LIQ
pl_top := switch area2
'Wick Extremity' => math.min(close[length2], open[length2])
'Full Range' => high[length2]
pl_btm := low[length2]

pl_x1 := n2 - length2
pl_crossed := false

box.set_lefttop(pl_bx, pl_x1, pl_top)


box.set_rightbottom(pl_bx, pl_x1, pl_btm)
else
pl_crossed := close < pl_btm ? true : pl_crossed

if pl_crossed
box.set_right(pl_bx, pl_x1)
else
box.set_right(pl_bx, n2+3)

if showBtm2 and show_LIQ


//Set pl2 zone
set_zone(pl2, pl_x1, pl_top, pl_btm, pl_count, pl_vol, btmarea2Css2)

//Set pl2 level


set_level(pl2, pl_crossed, pl_btm, pl_count, pl_vol, btmCss2)

//Set pl2 labels


set_label(pl_count, pl_vol, pl_x1, pl_btm, btmCss2, label.style_label_up)

//-----------------------------------------------------------------------------}

You might also like