0% found this document useful (0 votes)
64 views63 pages

Kve - Indicator 20.06

Uploaded by

bhargavboricha4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views63 pages

Kve - Indicator 20.06

Uploaded by

bhargavboricha4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 63

//@version=5

indicator(shorttitle="🔞 Kve_2Smart_trail", title="🔞 Kve_2Smart_trail",


overlay=true, max_labels_count = 500,max_lines_count = 500,max_boxes_count =
500,max_bars_back = 500)

//////////////////////////////////ON/OFF - OPTIONS /////////////////////

ShowSmartTrail = input.bool(false, '➡️ Smart Trail A ', inline =


'overlayLine1', group = '☣️
KVE_SMART TRAIL ON/OFF ')
ShowSmartTrail2 = input.bool(false, '➡️ Smart Trail B ', inline =
'overlayLine1', group = '☣️
KVE_SMART TRAIL ON/OFF ')

ShowSmartemsa = input.bool(false, '➡️ EMA Entry', inline = 'overlayLine1', group =


'☣️
KVE_EMA ON/OFF ')
ShowSonicnoise = input(false, "➡️ 3EMA 18-48-200 ", inline =
'overlayLine3', group = '☣️
KVE_EMA ON/OFF ')

//reversalZone = input(false, "Reversal Zones", inline = 'overlayLine2', group = '🔞


KVE_Reversal Band ON/OFF ☣️')
ShowSDR = input(false, "➡️ Reversal Band ", inline = 'overlayLine1',
group = '☣️
KVE_Reversal Band ON/OFF ')

ShowSR = input(false, "➡️ Supply and Demand ", inline = 'overlayLine2',


group = '☣️
KVE_SUPPLY AND DEMNAD ON/OFF ')
ShowSMC = input(false, "➡️ Smart Money Concepts ", inline =
'overlayLine3', group = '☣️
KVE_SUPPLY AND DEMNAD ON/OFF ')

showtrendline = input(false, '➡️ Show Trendline', inline = 'overlayLine1', group =


'☣️
KVE_FINDER ON/OFF ')
//ShowOB = input(false, "➡️ OrderBlock", inline = 'overlayLine2', group = '🔞
KVE_FINDER ON/OFF ☣️')

ShowSession = input(false, "➡️ Session BreakOut ", inline = 'overlayLine1', group


= '☣️
KVE_LINE ON/OFF ')
Zigzag = input.bool(false, '➡️ Zigzag ', inline = 'overlayLine3', group =
'☣️
KVE_LINE ON/OFF ')
showSession = input(false, '➡️ Show Session Asian', inline = 'overlayLine2', group
= '☣️
KVE_LINE ON/OFF ')

ShowBS = input(true, "➡️ Super TRend Signals ", inline =


'overlayLine2', group = '☣️
KVE_SIGNAL ON/OFF ')
//ShowSignal = input(false, "➡️ ShowSignal ", inline = 'overlayLine3',
group = '☣️
KVE_OPTIONS ON/OFF ')
ShowSonicR = input(false, "➡️ Sonic.R ", inline = 'overlayLine1', group
= '☣️
KVE_EMA ON/OFF ')
//SuperIchi = input.bool(false, '➡️ SuperIchi ', inline = 'overlayLine2',
group = '☣️
KVE_EMA ON/OFF ')
Ichimoku = input.bool(false, '➡️ Ichimoku ', inline = 'overlayLine2',
group = '☣️
KVE_EMA ON/OFF ')
///////////////////////////////////////////////////////////////////////////////////

// Define input variables


emaLengths = input.int(5, minval=1, title='EMA Length')
rsiLengths = input.int(14, minval=1, title='RSI Length')
rsiOverboughts = input(80, title='RSI Overbought Level')
rsiOversolds = input(20, title='RSI Oversold Level')

start = input.float(title='Start', step=0.001, defval=0.05)


increment = input.float(title='Increment', step=0.001, defval=0.05)
maximum = input.float(title='Maximum', step=0.01, defval=0.2)
width = input.int(title='Point Width', minval=1, defval=1)

psar = ta.sar(start, increment, maximum)


dir = psar < close ? 1 : -1

psarColor = dir == 1 ? #3388bb : color.rgb(253, 2, 2)


psarPlot = plot(psar, title='PSAR', style=plot.style_circles, linewidth=width,
color=color.new(psarColor,0),display = display.none)

// Calculate EMA
emaValue = ta.ema(close, emaLengths)

// Calculate RSI
rsiValue = ta.rsi(close, rsiLengths)

// Define variables
var bool strongLongSignal = false
var bool strongShortSignal = false
highlightState = input(title='Highlight State ?', defval=false)
srcs = input(close, title='Source')

// Determine long and short signals based on conditions


strongLongSignal := high[1] < emaValue[1] and high > high[1] and rsiValue >
rsiOversolds and rsiValue > rsiValue[1]
longSignal = strongLongSignal
strongShortSignal := low[1] > emaValue[1] and low < low[1] and rsiValue <
rsiOverboughts and rsiValue < rsiValue[1]
shortSignal = strongShortSignal

// Buy Signal as per PSR


buySignalPSR = dir == 1 and dir[1] == -1
sellSignalPSR = dir == -1 and dir[1] == 1

//5-8-13 Signal
len5 = input.int(5, minval=1, title='5EMA')
out5 = ta.ema(srcs, len5)
emaValue5 = ta.ema(close, len5)

len8 = input.int(8, minval=1, title='8EMA')


out8 = ta.ema(srcs, len8)
emaValue8 = ta.ema(close, len8)

len13 = input.int(13, minval=1, title='13EMA')


out13 = ta.ema(srcs, len13)
emaValue13 = ta.ema(close, len13)

//Plot 5-8-13 EMA on Chart


//plot(ShowSmartemsa?out5:na, title='EMA5', color=color.new(color.green, 0),
linewidth=1)
//plot(ShowSmartemsa?out8:na, title='EMA8', color=color.new(color.blue, 0),
linewidth=1)
//plot(ShowSmartemsa?out13:na, title='EMA13', color=color.new(color.red, 0),
linewidth=1)

// 5-8-13 EMA Buy Sell Signals Calculation


long5813 = ((ta.crossover(emaValue5, emaValue8) or emaValue5 > emaValue8) and
(ta.crossover(emaValue5, emaValue13) or emaValue5 > emaValue13) and
(buySignalPSR or dir == 1) and close > close[1] and
close > emaValue5 and close > emaValue8 and close > emaValue13)

short5813 = (((ta.crossunder(emaValue5, emaValue8) or emaValue5 < emaValue8) and


(ta.crossunder(emaValue5, emaValue13) or emaValue5 < emaValue13)) and
(sellSignalPSR or dir == -1) and close < close[1] and
close < emaValue5 and close < emaValue8 and close < emaValue13)

//Recheck Quick Buy and Sell Signals before plotting


if short5813
longSignal := false

if long5813
shortSignal := false

// Plot long and short signals

plotshape((not long5813[1] ? long5813 : na), title='Strong Buy',


color=color.new(color.green, 0), style=shape.triangleup, text='SB',location
=location.belowbar,display=display.none)

plotshape((not short5813[1] ? short5813 : na), title='Strong Sell',


color=color.new(color.red, 0), style=shape.triangledown, text='SS',
location=location.abovebar,textcolor=color.new(color.red,0),display=display.none)

barcolor(long5813 ? color.lime : short5813 ? color.red : na,title = "Barcolor


Signal",display = display.none)

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

hide = timeframe.isintraday

// Input for EMA period


emaPeriod = input.int(32, title="EMA Period")
emaPeriod2 = input.int(8, title="EME Period 2")
emaPeriod3 = input.int(15, title="EMA Period")

// Input to toggle EMA Cloud


showcloud = input.bool(true, title="Show EMA Cloud")

// EMA calculations
ema = ta.ema(close, emaPeriod)
ema2 = ta.ema(close,emaPeriod2)
ema3 = ta.ema(close, emaPeriod3)
emaColor = close > ema3 ? color.rgb(56, 142, 60, 63) : color.rgb(147, 40, 51, 38)

// Plotting EMA's
plot_ema1 = plot(ShowSmartemsa?(hide ? ema : na):na, style=plot.style_line,
color=color.rgb(255, 255, 255, 100), title="EMA", linewidth=1,editable=false)
plot_ema2 = plot(ShowSmartemsa?(hide ? ema2 : na):na, style=plot.style_line,
color=color.rgb(255, 255, 255, 100), title="EMA", linewidth=1,editable=false)
plot_ema3 = plot(ShowSmartemsa?ema3:na, style=plot.style_line, color=color.rgb(255,
255, 255, 100), title="EMA", linewidth=1,editable=false)

// EMA Cloud
cloudColor = ema2 > ema ? #0f851363 : #a8141450
cloudColor2 = ema2 > ema3 ? color.new(#0f8513, 8) : #ea1818c7
cloudColor := showcloud ? cloudColor : na
fill(plot_ema1, plot_ema2, color=cloudColor, title="EMA Cloud")
fill(plot_ema3, plot_ema2, color=cloudColor, title="EMA Cloud")

/////////////////// 3 EMA CROSS ///////////////////

HiLoLen = input.int(34, minval=2, title='Band Channel',group = " Sonic.R")


pacC = ta.ema(close, HiLoLen)
pacL = ta.ema(low, HiLoLen)
pacH = ta.ema(high, HiLoLen)
DODGERBLUE = #1E90FFFF

//Plot the Price Action Channel (PAC) base on EMA high,low and close
La = plot(ShowSonicR?pacL:na, color=#ff0000, linewidth=1, title='High PAC EMA',
transp=50,editable = false)
Ha = plot(ShowSonicR?pacH:na, color=#0051ff, linewidth=1, title='Low PAC EMA',
transp=50,editable = false)
Ca = plot(ShowSonicR?pacC:na, color=DODGERBLUE, linewidth=2, title='Close PAC EMA',
transp=0,editable = false)
fill(La, Ha, color=color.new(color.green, 80), title='Fill HiLo PAC')

e34 = input(title='Ema 1', defval=34,group = " Sonic.R")


e89 = input(title='Ema 2', defval=89,group = " Sonic.R")
e200 = input(title='Ema 3', defval=200,group = " Sonic.R")
e610 = input(title='Ema 4', defval=610,group = " Sonic.R")

ema34 = ta.ema(close, e34)


ema89 = ta.ema(close, e89)
//ema200 = ta.ema(close, e200)
//ema610 = ta.ema(close, e610)

//////// Plot ///////////

plot(ShowSonicR?ema34:na, color=color.rgb(19, 120, 69), linewidth=1,title='EMA 34',


style=plot.style_line)
plot(ShowSonicR?ema89:na, color=#e90a0aed, title='EMA 89',linewidth=2,
style=plot.style_line)
//plot(ShowSonicR?ema200:na, color=#83024b,title='EMA 200', linewidth=3,
style=plot.style_line,display = display.none)
//plot(ema610, color=color.rgb(14, 176, 74, 2), title='EMA 610',linewidth=1,
style=plot.style_line,display = display.none)

/////////////////// Clutter Filter ///////////////////

e50 =input(title = 'EMA 18',defval = 18,group = " Clutter Filter")


e100 =input(title = 'EMA 48',defval = 48,group = " Clutter Filter")
e200x =input(title = 'EMA200',defval = 200,group = " Clutter Filter")

ema50 = ta.ema(close, e50)


ema100= ta.ema(close, e100)
ema200x = ta.ema(close, e200x)

plot(ShowSonicnoise?ema50:na, color=#0808fb,title='EMA 18', linewidth=1,


style=plot.style_line)
plot(ShowSonicnoise?ema100:na, color=color.rgb(255, 4, 4, 2), title='EMA
48',linewidth=1, style=plot.style_line)
plot(ShowSonicnoise?ema200x:na, color=#ff8a04fa,title='EMA 200x', linewidth=2,
style=plot.style_line)

//plot(ta.crossover(ShowSonicnoise?ema50:na, ShowSonicnoise?ema100:na) ? ema50 :


na, style=plot.style_cross, linewidth=4, color=color.new(#66ff33, 0))
//plot(ta.crossover(ShowSonicnoise?ema50:na, ShowSonicnoise?ema200x:na) ? ema50 :
na, style=plot.style_cross, linewidth=6, color=color.new(#66ff33, 0))
//plot(ta.crossover(ShowSonicnoise?ema100:na, ShowSonicnoise?ema200x:na) ? ema100 :
na, style=plot.style_cross, linewidth=8, color=color.new(#66ff33, 0))

//plot(ta.crossunder(ShowSonicnoise?ema50:na, ShowSonicnoise?ema100:na) ? ema50 :


na, style=plot.style_cross, linewidth=4, color=color.new(#ff0000, 0))
//plot(ta.crossunder(ShowSonicnoise?ema50:na, ShowSonicnoise?ema200x:na) ? ema50 :
na, style=plot.style_cross, linewidth=6, color=color.new(#ff0000, 0))
//plot(ta.crossunder(ShowSonicnoise?ema100:na, ShowSonicnoise?ema200x:na) ?
ema100 : na, style=plot.style_cross, linewidth=8, color=color.new(#ff0000, 0))

//////////////////////////////////////////
// CHUẨN BỊ CÁC THÔNG SỐ CHO SMARTTRAIL //

//{
trailType = input.string('modified', 'Kve Type', options=['modified',
'unmodified'],group = 'Smart Trail')
ATRPeriod = input(200, 'Kve')
ATRFactor = input(5., 'Kve')
show_fib_entries = input(true, 'Kve_Entry')

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)

Up = norm_c - loss
Dn = norm_c + loss

TrendUp = Up
TrendDown = Dn
Trend = 1

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


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

Trend := norm_c > TrendDown[1] ? 1 : norm_c < TrendUp[1] ? -1 : nz(Trend[1], 1)


trail = Trend == 1 ? TrendUp : TrendDown

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

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


//{
//plot(ShowSmartTrail?trail:na, 'ATR STOPA', style=plot.style_line, color=Trend ==
1 ? color.green : Trend == -1 ? color.red : na)
//plot(ShowSmartTrail?ex:na, 'Supply and Demand', style=plot.style_circles,
color=Trend == 1 ? color.lime : Trend == -1 ? color.fuchsia : na,display =
display.none)
//}
////// FIBONACCI LEVELS ///////////
//{
state = Trend == 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, 'Level 1', style=plot.style_line,


color=color.new(color.black, 0),display = display.none)
Fib2 = plot(ShowSmartTrail?f2:na, 'Level 2', style=plot.style_line,
color=color.new(color.black, 0),display = display.none)
Fib3 = plot(ShowSmartTrail?f3:na, 'Level 3', style=plot.style_line,
color=#363a455d)
L100 = plot(ShowSmartTrail?l100:na, 'Ranger ATR', style=plot.style_line,
color=color.new(color.black, 0))

//fill(Fib1, Fib2, color=state == 'long' ? color.green : state == 'short' ?


color.red : na, transp=90,display = display.none)
fill(Fib2, Fib3, color=state == 'long' ? color.new(color.green, 70) : state ==
'short' ? color.new(color.red, 70) : na, transp=90)
fill(Fib3, L100, color=state == 'long' ? color.new(color.green, 60) : state ==
'short' ? color.new(color.red, 60) : na, transp=90)

l1 = state[1] == 'long' and ta.crossunder(norm_c, f1[1])


l2 = state[1] == 'long' and ta.crossunder(norm_c, f2[1])
l3 = state[1] == 'long' and ta.crossunder(norm_c, f3[1])
s1 = state[1] == 'short' and ta.crossover(norm_c, f1[1])
s2 = state[1] == 'short' and ta.crossover(norm_c, f2[1])
s3 = state[1] == 'short' and ta.crossover(norm_c, f3[1])

atr = ta.sma(trueRange, 14)

/////////// FIB PLOTS /////////////////.

plotshape(ShowSmartTrail?(show_fib_entries and l2 ? low - 1.5 * atr : na):na, 'LB',


style=shape.triangleup, location=location.belowbar, color=color.new(color.blue, 0),
size=size.tiny)
plotshape(ShowSmartTrail?(show_fib_entries and l3 ? low - 2 * atr : na):na, 'LC',
style=shape.triangleup, location=location.belowbar, color=color.new(color.blue, 0),
size=size.tiny)
plotshape(ShowSmartTrail?(show_fib_entries and s2 ? high + 1.5 * atr : na):na,
'SB', style=shape.triangledown, location=location.abovebar,
color=color.new(color.blue, 0), size=size.tiny)
plotshape(ShowSmartTrail?(show_fib_entries and s3 ? high + 2 * atr : na):na, 'SC',
style=shape.triangledown, location=location.abovebar, color=color.new(color.blue,
0), size=size.tiny)
//}
////////////////////////////////// Content From Việt NAM ////////////////////////
if barstate.isfirst
var table errorBox = table.new(position.bottom_right, 1, 1, bgcolor =
color.new(#1500f8, 100))
table.cell(errorBox, 0, 0, "© Kve from Việt Nam", text_color =
color.rgb(255, 4, 4), text_halign = text.align_center, text_size = size.normal)

//////////////////SMARTTRAIL 2//////////////////////

// THÔNG SỐ CHO SMART TRAIL BANDWITH 2//

trail11Type1 = input.string('modified', 'Kve Type', options=['modified',


'unmodified'])
atr1Period1 = input(28, 'Kve')
atr1Factor1 = input(5., 'Kve')
show_fib_entries11 = input(true, 'Kve_Entry')

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


timeframe.period, open)
norm_h1 = request.security(ticker.new(syminfo.prefix, syminfo.ticker),
timeframe.period, high)
norm_l11 = request.security(ticker.new(syminfo.prefix, syminfo.ticker),
timeframe.period, low)
norm_c1 = request.security(ticker.new(syminfo.prefix, syminfo.ticker),
timeframe.period, close)
//}

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


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

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


HiLo1 = math.min(norm_h1 - norm_l11, 1.5 * nz(ta.sma(norm_h1 - norm_l11,
atr1Period1)))

HRef11 = norm_l11 <= norm_h1[1] ? norm_h1 - norm_c1[1] : norm_h1 - norm_c1[1] - 0.5


* (norm_l11 - norm_h1[1])

LRef11 = norm_h1 >= norm_l11[1] ? norm_c1[1] - norm_l11 : norm_c1[1] - norm_l11 -


0.5 * (norm_l11[1] - norm_h1)

trueRange1 = trail11Type1 == 'modified' ? math.max(HiLo1, HRef11, LRef11) :


math.max(norm_h1 - norm_l11, math.abs(norm_h1 - norm_c1[1]), math.abs(norm_l11 -
norm_c1[1]))
//}

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


//{
loss11 = atr1Factor1 * Wild_ma(trueRange1, atr1Period1)

Up1 = norm_c1 - loss11


Dn1 = norm_c1 + loss11

Trend1Up1 = Up1
Trend1Down1 = Dn1
Trend1 = 1

Trend1Up1 := norm_c1[1] > Trend1Up1[1] ? math.max(Up1, Trend1Up1[1]) : Up1


Trend1Down1 := norm_c1[1] < Trend1Down1[1] ? math.min(Dn1, Trend1Down1[1]) : Dn1

Trend1 := norm_c1 > Trend1Down1[1] ? 1 : norm_c1 < Trend1Up1[1] ? -1 :


nz(Trend1[1], 1)
trail11 = Trend1 == 1 ? Trend1Up1 : Trend1Down1

ex1 = 0.0
ex1 := ta.crossover(Trend1, 0) ? norm_h1 : ta.crossunder(Trend1, 0) ? norm_l11 :
Trend1 == 1 ? math.max(ex1[1], norm_h1) : Trend1 == -1 ? math.min(ex1[1], norm_l11)
: ex1[1]
//}

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


//{
//plot(ShowSmartTrail?trail11:na, 'ATR STOPB', style=plot.style_line, color=Trend1
== 1 ? color.green : Trend1 == -1 ? color.red : na)
//plot(ShowSmartTrail?ex1:na, 'Supply Demand', style=plot.style_circles,
color=Trend1 == 1 ? color.lime : Trend1 == -1 ? color.fuchsia : na,display =
display.none)
//}

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


//{
state1 = Trend1 == 1 ? 'long' : 'short'

Fib11Level11 = 61.8
Fib21Level11 = 78.6
Fib31Level11 = 88.6

f11 = ex1 + (trail11 - ex1) * Fib11Level11 / 100


f21 = ex1 + (trail11 - ex1) * Fib21Level11 / 100
f31 = ex1 + (trail11 - ex1) * Fib31Level11 / 100
l11001 = trail11 + 0

//Fib11 = plot(ShowSmartTrail?f11:na, 'Level A', style=plot.style_line,


color=color.new(color.black, 0),display = display.none)
Fib21 = plot(ShowSmartTrail2?f21:na, 'Level B', style=plot.style_line,
color=color.new(color.black, 0),display = display.none)
Fib31 = plot(ShowSmartTrail2?f31:na, 'Level C', style=plot.style_line,
color=#363a455d)
Fib11001 = plot(ShowSmartTrail2?l11001:na, 'Ranger ATR', style=plot.style_line,
color=color.new(color.black, 0))

//fill(Fib11, Fib21, color=state1 == 'long' ? color.green : state1 == 'short' ?


color.red : na, transp=90,display = display.none)
fill(Fib21, Fib31, color=state1 == 'long' ? color.new(color.green, 70) : state1 ==
'short' ? color.new(color.red, 70) : na, transp=90)
fill(Fib31, Fib11001, color=state1 == 'long' ? color.new(color.green, 60) : state1
== 'short' ? color.new(color.red, 60) : na, transp=90)

l11 = state1[1] == 'long' and ta.crossunder(norm_c1, f11[1])


l21 = state1[1] == 'long' and ta.crossunder(norm_c1, f21[1])
l31 = state1[1] == 'long' and ta.crossunder(norm_c1, f31[1])
s11 = state1[1] == 'short' and ta.crossover(norm_c1, f11[1])
s21 = state1[1] == 'short' and ta.crossover(norm_c1, f21[1])
s31 = state1[1] == 'short' and ta.crossover(norm_c1, f31[1])

atr1 = ta.sma(trueRange1, 14)

/////////// FIB PLOTS /////////////////.

plotshape(ShowSmartTrail2?(show_fib_entries11 and l21 ? low - 1.5 * atr1 : na):na,


'LB', style=shape.triangleup, location=location.belowbar,
color=color.new(color.purple, 0), size=size.tiny)
plotshape(ShowSmartTrail2?(show_fib_entries11 and l31 ? low - 2 * atr1 : na):na,
'LC', style=shape.triangleup, location=location.belowbar,
color=color.new(color.purple, 0), size=size.tiny)
plotshape(ShowSmartTrail2?(show_fib_entries11 and s21 ? high + 1.5 * atr1 : na):na,
'SB', style=shape.triangledown, location=location.abovebar,
color=color.new(color.purple, 0), size=size.tiny)
plotshape(ShowSmartTrail2?(show_fib_entries11 and s31 ? high + 2 * atr1 : na):na,
'SC', style=shape.triangledown, location=location.abovebar,
color=color.new(color.purple, 0), size=size.tiny)
//}

////////////////////REVERSAL ZONE ///////////////////

ha = input.float(8.,'Ranger Line', minval = 0,group = 'REVERSAL ZONE')


mult = input.float(3.0, minval = 0,title ='Bandwidth A')
mult1 = input.float(4.0, minval = 0,title ='Bandwidth B')
src = input(close, 'Source')

repaint = input(true, 'Repainting Smoothing', tooltip = 'Repainting is an effect


where the indicators historical output is subject to change over time. Disabling
repainting will cause the indicator to output the endpoints of the calculations')

//Style
upCss = input.color(color.teal, 'Colors', inline = 'inline1', group = 'Style')
dnCss = input.color(color.red, '', inline = 'inline1', group = 'Style')

//-----------------------------------------------------------------------------}
//Functions
//-----------------------------------------------------------------------------{
//Gaussian window
gauss(x, ha) => math.exp(-(math.pow(x, 2)/(ha * ha * 2)))

//-----------------------------------------------------------------------------}
//Append lines
//-----------------------------------------------------------------------------{
k = bar_index

var ln = array.new_line(0)

if barstate.isfirst and repaint


for i = 0 to 249
array.push(ln,line.new(na,na,na,na))

//-----------------------------------------------------------------------------}
//End point method
//-----------------------------------------------------------------------------{
var coefs = array.new_float(0)
var den = 0.

if ShowSDR?(barstate.isfirst and not repaint):na


for i = 0 to 249
w = gauss(i, ha)
coefs.push(w)

den := coefs.sum()

out = 0.
if not repaint
for i = 0 to 249
out += src[i] * coefs.get(i)
out /= den
mae = ta.sma(math.abs(src - out), 249) * mult

upper = out + mae


lower = out - mae

//-----------------------------------------------------------------------------}
//Compute and display NWE
//-----------------------------------------------------------------------------{
float y2 = na
float y1 = na

nwe = array.new<float>(0)
if ShowSDR?(barstate.islast and repaint):na
sae = 0.
sae1 = 0.
//Compute and set NWE point
for i = 0 to math.min(249,k - 1)
sum = 0.
sumw = 0.
//Compute weighted mean
for j = 0 to math.min(249,k - 1)
w = gauss(i - j, ha)
sum += src[j] * w
sumw += w

y2 := sum / sumw
sae += math.abs(src[i] - y2)
sae1 += math.abs(src[i] - y2)
nwe.push(y2)

sae := sae / math.min(249,k - 1) * mult


sae1 := sae1 / math.min(249,k - 1) * mult1
for i = 0 to math.min(249,k - 1)
if i%2
line.new(k-i+1, y1 + sae, k-i, nwe.get(i) + sae, color=upCss)
line.new(k-i+1, y1 - sae, k-i, nwe.get(i) - sae, color=upCss)
line.new(k-i+1, y1 + sae1, k-i, nwe.get(i) + sae1, color=dnCss)
line.new(k-i+1, y1 - sae1, k-i, nwe.get(i) - sae1, color=dnCss)
if src[i] > nwe.get(i) + sae and src[i+1] < nwe.get(i) + sae
label.new(k-i, src[i], '▼', color = color(na), style =
label.style_label_down, textcolor = dnCss, textalign = text.align_center,size =
size.large)
if src[i] < nwe.get(i) - sae and src[i+1] > nwe.get(i) - sae
label.new(k-i, src[i], '▲', color = color(na), style =
label.style_label_up, textcolor = upCss, textalign = text.align_center,size =
size.large)

y1 := nwe.get(i)

//-----------------------------------------------------------------------------}
//Plot
//-----------------------------------------------------------------------------}
//Ab= plot(repaint ? na : out + mae, 'Upper', upCss,editable =false)
//Bb = plot(repaint ? na : out - mae, 'Lower', dnCss,editable =false)

//Crossing Arrows
//plotshape(ta.crossunder(close, out - mae) ? low : na, "Crossunder",
shape.labelup, location.absolute, color(na), 0 , text = '🔵', textcolor = upCss,
size = size.tiny,editable =false)
//plotshape(ta.crossover(close, out + mae) ? high : na, "Crossover",
shape.labeldown, location.absolute, color(na), 0 , text = '🔴', textcolor = dnCss,
size = size.tiny,editable =false)

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

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

//Constants
//-----------------------------------------------------------------------------{
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(false, '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(false, '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(false, 'Show Strong/Weak High/Low'


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

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

iob_showlast = input.int(50, ''


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

show_ob = input(true, 'Swing Order Blocks'


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

ob_showlast = input.int(50, ''


, 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(#2067e254, 'Internal Bullish OB'


, group = 'Order Blocks')

ibear_ob_css = input.color(#2067e254, 'Internal Bearish OB'


, group = 'Order Blocks')

bull_ob_css = input.color(#890b4c86, 'Bullish OB'


, group = 'Order Blocks')

bear_ob_css = input.color(#890b4c86, '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(true, '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(3, "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

atrz = 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' ? atrz : cmean_range

//Search for highest/lowest high within the structure interval and get range
if use_max
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
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

//Set line/labels function for previous high/lows


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
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 ShowSMC?top:na
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
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
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 ShowSMC?btm:na
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
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
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
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
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
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
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
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
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
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
if barstate.islast
display_ob(iob_boxes, iob_top, iob_btm, iob_left, iob_type, iob_showlast,
false, iob_size)

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

//-----------------------------------------------------------------------------}
//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 ShowSMC?show_fvg:na
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)))

//-----------------------------------------------------------------------------}
//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
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)

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

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

// INDICATOR SETTINGS
swing_length = input.int(7, title = 'Swing High/Low Length', group = 'Settings',
minval = 1, maxval = 50)
history_of_demand_to_keep = input.int(50, title = 'History To Keep', minval = 5,
maxval = 50)
box_width = input.float(10, title = 'Supply/Demand Box Width', group = 'Settings',
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))))

/////////////////////////// SIGNAL THAM KHẢO ///////////////////////

candle_stability_index_param = input.float(0.5, 'Candle Stability Index', 0, 1,


step=0.1, group='Technical', tooltip='Candle Stability Index measures the ratio
between the body and the wicks of a candle. Higher - more stable.')
rsi_index_param = input.int(50, 'RSI Index', 0, 100, group='Technical',
tooltip='RSI Index measures how overbought/oversold is the market. Higher - more
overbought/oversold.')
candle_delta_length_param = input.int(5, 'Candle Delta Length', 3,
group='Technical', tooltip='Candle Delta Length measures the period over how many
candles the price increased/decreased. Higher - longer period.')
disable_repeating_signals_param = input.bool(false, 'Disable Repeating Signals',
group='Technical', tooltip='Removes repeating signals. Useful for removing clusters
of signals and general clarity')

GREEN = color.rgb(29, 255, 40)


RED = color.rgb(255, 0, 0)
TRANSPARENT = color.rgb(0, 0, 0, 100)

label_size = input.string('normal', 'Label Size', options=['huge', 'large',


'normal', 'small', 'tiny'], group='Cosmetic')
label_style = input.string('text bubble', 'Label Style', ['text bubble',
'triangle', 'arrow'], group='Cosmetic')
buy_label_color = input(GREEN, 'BUY Label Color', inline='Highlight',
group='Cosmetic')
sell_label_color = input(RED, 'SELL Label Color', inline='Highlight',
group='Cosmetic')
label_text_color = input(#000000, 'Label Text Color', inline='Highlight',
group='Cosmetic')

stable_candle = math.abs(close - open) / ta.tr > candle_stability_index_param


rsi = ta.rsi(close, 14)

bullish_engulfing = close[1] < open[1] and close > open and close > open[1]
rsi_below = rsi < rsi_index_param
decrease_over = close < close[candle_delta_length_param]

bull = bullish_engulfing and stable_candle and rsi_below and decrease_over and


barstate.isconfirmed

bearish_engulfing = close[1] > open[1] and close < open and close < open[1]
rsi_above = rsi > 100 - rsi_index_param
increase_over = close > close[candle_delta_length_param]

bear = bearish_engulfing and stable_candle and rsi_above and increase_over and


barstate.isconfirmed

var last_signal = ''

//if ShowSignal?bull:na and (disable_repeating_signals_param ? (last_signal !=


'buy' ? true : na) : true)
//if label_style == 'text bubble'
//label.new(bull ? bar_index : na, low, 'BUY', color=buy_label_color,
style=label.style_label_up, textcolor=label_text_color, size=label_size)
// else if label_style == 'triangle'
//label.new(bull ? bar_index : na, low, 'BUY', yloc=yloc.belowbar,
color=buy_label_color, style=label.style_triangleup, textcolor=TRANSPARENT,
size=label_size)
//else if label_style == 'arrow'
//label.new(bull ? bar_index : na, low, 'BUY', yloc=yloc.belowbar,
color=buy_label_color, style=label.style_arrowup, textcolor=TRANSPARENT,
size=label_size)

//last_signal := 'buy'
//if ShowSignal?bear:na and (disable_repeating_signals_param ? (last_signal !=
'sell' ? true : na) : true)
//if label_style == 'text bubble'
//label.new(bear ? bar_index : na, high, 'SELL', color=sell_label_color,
style=label.style_label_down, textcolor=label_text_color, size=label_size)
//else if label_style == 'triangle'
//label.new(bear ? bar_index : na, high, 'SELL', yloc=yloc.abovebar,
color=sell_label_color, style=label.style_triangledown, textcolor=TRANSPARENT,
size=label_size)
//else if label_style == 'arrow'
//label.new(bear ? bar_index : na, high, 'SELL', yloc=yloc.abovebar,
color=sell_label_color, style=label.style_arrowdown, textcolor=TRANSPARENT,
size=label_size)
//last_signal := 'sell'

//alertcondition(bull, 'BUY Signals', 'New signal: BUY')


//alertcondition(bear, 'SELL Signals', 'New signal: SELL')

/////////////// SMIT AI /////////

bullishCandle = close >= open[1] and close[1] < open[1] //and high >= high[1] and
low <= low[1]
bearishCandle = close <= open[1] and close[1] > open[1] //and high > high[1] and
low < low[1]
// RSI integration
//rsiSource = input(title='rsiSource', defval=close)
//rsiLenghth = input(title='rsi length', defval=14)
//rsiOverBought = input(title='rsi overbought level', defval=70)
//rsiOverSold = input(title='rsi over sold level', defval=30)
//rsiOverBoughtThreshold=input(title="rsiOBThreshold level", type=input.integer,
defval=97)
//rsiOverSoldThreshold=input(title="rsiOSThreshold level", type=input.integer,
defval=18)
//get RSI value
//rsiValue = ta.rsi(rsiSource, rsiLenghth)
//isRSIOB = rsiValue >= rsiOverBought and rsiValue
//isRSIOS = rsiValue <= rsiOverSold and rsiValue

//tradeSignal = (isRSIOS or isRSIOS[1] or isRSIOS[2]) and bullishCandle or (isRSIOB


or isRSIOB[1] or isRSIOB[2]) and bearishCandle
//plot on chart
//plotshape(ShowSignal?(tradeSignal and bullishCandle):na, title='bullish',
location=location.belowbar, color=color.new(color.green, 0),
style=shape.triangleup, text='BUY')
//plotshape(ShowSignal?(tradeSignal and bearishCandle):na, title='bearish',
location=location.abovebar, color=color.new(color.red, 0),
style=shape.triangledown, text='SELL')

///////////SIGNAL//////////////

// Fibonacci Levels
fib_0 = input.float(0.236, "Fib Level 0")
fib_1 = input.float(0.79, "Fib Level 1")

// Calculate Fibonacci levels


fib_range = ta.highest(high, 2) - ta.lowest(low, 2)

fib_level_0 = ta.highest(high, 2) - (fib_range * fib_0)


fib_level_1 = ta.highest(high, 2) - (fib_range * fib_1)
// RSI
rsi_length = input(14, "RSI Length")
rsi_overbought = input(70, "RSI Overbought Level")
rsi_oversold = input(30, "RSI Oversold Level")

rsi_value = ta.rsi(close, rsi_length)

// Determine buy and sell conditions


//buy_condition = ta.crossover(rsi_value, rsi_oversold) and close > fib_level_1
//sell_condition = ta.crossunder(rsi_value, rsi_overbought) and close < fib_level_0

// Plot RSI
//plot(rsi_value, "RSI", color=color.blue, linewidth=2)

// Plot buy and sell signals


//plotshape(ShowSignal?buy_condition:na, title="Buy Signal",
location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
//plotshape(ShowSignal?sell_condition:na, title="Sell Signal",
location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")

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

//strategy(title="London BreakOut Classic", overlay=true)


import TradingView/ta/5

FilterTradeTime = input.bool(defval=true,title='Filter Entrytime')


rangemalen = input(20, title='Avg Length Range')
rangemult = input(2, title='Avg Multiplier Range')

//------------------------------Coding the
BOX---------------------------------------------------------//

// InSession() returns 'true' when the current bar happens inside


// the specified session, corrected for the given time zone (optional).
// Returns 'false' when the bar doesn't happen in that time period,
// or when the chart's time frame is 1 day or higher.

//*************Asia Session
InSession(sessionTime, sessionTimeZone=syminfo.timezone) =>
not na(time(timeframe.period, sessionTime, sessionTimeZone))

// STEP 1:

// Define custom session trading times with inputs for *************Asia Session
sessionTime = input.session("0000-0655", title="Session time Tokyo")
sessionZone = input.string("UTC", title="Session time zone")

// Other inputs for the boxes' visual appearance *************Asia Session


boxBorderSize = input.int(1, title="Box border size", minval=0)
upBoxColor = input.color(color.new(color.green, 95), title="Up box")
upBorderColor = input.color(color.green, title="Up border")
downBoxColor = input.color(color.new(color.red, 95), title="Down box")
downBorderColor = input.color(color.red, title="Down border")

// Create variables *************Asia Session


var sessionHighPrice = 0.0
var sessionLowPrice = 0.0
var sessionOpenPrice = 0.0
var box sessionBox = na

// STEP 2:
// See if the session is currently active and just started *************Asia
Session
inSession = InSession(sessionTime, sessionZone) and timeframe.isintraday
sessionStart = inSession and not inSession[1]
SessionEnd = inSession[1] and not inSession

// STEP 3:
// When a new session starts, set the session high and low to the data
// of the bar in the session. *************Asia Session
if sessionStart
sessionHighPrice := high
sessionLowPrice := low
sessionOpenPrice := open
// Else, during the session, track the highest high and lowest low
else if inSession
sessionHighPrice := math.max(sessionHighPrice, high)
sessionLowPrice := math.min(sessionLowPrice, low)

// STEP 4:
// When a session begins, make a new box for that session *************Asia Session
if ShowSession?sessionStart:na
sessionBox := box.new(left=bar_index, top=na, right=na, bottom=na,
border_width=boxBorderSize)

// STEP 5:
// During the session, update that session's existing box *************Asia Session
if ShowSession?inSession:na
box.set_top(sessionBox, sessionHighPrice)
box.set_bottom(sessionBox, sessionLowPrice)

box.set_right(sessionBox, bar_index + 1)

// See if bar closed higher than session open. When it did, make
// box green (and use red otherwise).
if close > sessionOpenPrice
box.set_bgcolor(sessionBox, upBoxColor)
box.set_border_color(sessionBox, upBorderColor)
else
box.set_bgcolor(sessionBox, downBoxColor)
box.set_border_color(sessionBox, downBorderColor)

//------------------------------End of Coding the


BOX---------------------------------------------------------//

// Save Previous Max & Min Asia Session


Minpreday = ta.valuewhen(SessionEnd,sessionLowPrice,0)
Maxpreday = ta.valuewhen(SessionEnd,sessionHighPrice,0)
// Identify last bar in box
Lastbarinbox = ta.valuewhen(SessionEnd,close,0)

//Entry Long London BreakOut


Conditionlong = if (high >= Maxpreday)
1
else
0

//Entry Short London BreakOut


Conditionshort = if (low <= Minpreday)
1
else
0

//-------------------------Define TP & SL------------------------//

// Define Stoploss = Midrange Box


Stoploss = ((Maxpreday-Minpreday)/2) + Minpreday
plot(ShowSession?Stoploss:na,title = "Entryline", color = color.rgb(231, 10, 10),
style = plot.style_line,linewidth = 1)

//Trading Session from X until Y


tradinghours = time(timeframe.period, "0700-1600", "UTC")
time_condition = FilterTradeTime ? not na(tradinghours) : true
//bgcolor(not na(tradinghours) ? color.rgb(73, 196, 78, 90) : na,display =
display.none,title = "Background Session")

//////////////////////////////////////// TRENDLINE //////////////////////////////

//Price Action Concepts


//----------------------------------------{
activateliquidity = input.bool(false, inline = "Sweeps", group = "Liquidity
Concepts", title = "Liquidity Sweeps")
len12345 = input.int(3, '', options = [1, 2, 3, 4, 5], group = 'Liquidity
Concepts', inline = "Sweeps")
opt = 'Only Wicks'
len12345 := len12345 * 2

colBl = input.color(#0044ff, "", inline = "Sweeps", group = "Liquidity Concepts")


colBr = input.color(#ff2b00, "", inline = "Sweeps", group = "Liquidity Concepts")
colBl2 = colBl
colBr2 = colBr

extend = false
maxB = 300
colBl3 = colBl
colBr3 = colBr

oW = opt == 'Only Wicks'


oO = opt == 'Only Outbreaks & Retest'
WO = opt == 'Wicks + Outbreaks & Retest'

nk = bar_index

//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type piv
float prc // price
int bix // bar_index
bool brk // broken
bool mit // mitigated
bool tak // taken
bool wic // wick
line lin

type boxBr
box bx
line ln
bool br
int dr

//-----------------------------------------------------------------------------}
//Variables
//-----------------------------------------------------------------------------{
var array< piv >aPivH = array.new< piv >(1, piv.new ())
var array< piv >aPivL = array.new< piv >(1, piv.new ())
var array<boxBr>aBoxBr = array.new<boxBr>(1, boxBr.new())

//-----------------------------------------------------------------------------}
//Methods - functions
//-----------------------------------------------------------------------------{
method n(float piv) => bool out = not na(piv)

method p(piv piv, float val) => float out = (100 / piv.prc * val) - 100

method l(piv get, color c, string s='sd') =>


style = switch s
'dt' => line.style_dotted
'ds' => line.style_dashed
=> line.style_solid
line.new(get.bix, get.prc, n, get.prc, color=c, style = style)
method br(piv get, color c3, color c, int d) =>
y1 = d == 1 ? high : get.prc
y2 = d == 1 ? get.prc : low
boxBr.new(
box.new(n -1, y1, n +1, y2
, border_color
= color.new(
na, na )
, bgcolor=c3)
, line.new(n , y1, n, y2, color=c, width=3)
, false
, d)

lnDot(y, c) => line.new(n, y, n+3, y, color=c, style=line.style_dotted)

//-----------------------------------------------------------------------------}
//Execution
//-----------------------------------------------------------------------------{
ph = ta.pivothigh(len12345, len12345)
pl = ta.pivotlow (len12345, len12345)

if ph.n()
aPivH.unshift(piv.new(ph, n -len12345, false, false, false, false))

if pl.n()
aPivL.unshift(piv.new(pl, n -len12345, false, false, false, false))
bool bullcandle = false
bool bearcandle = false

for i = aPivH.size() -1 to 0
get = aPivH.get(i)
if not get.mit
if not get.brk
if close > get.prc
if not oW
get.brk := true
else
get.mit := true
if not oO and not get.wic
if high > get.prc and close < get.prc
bearcandle := true

get.wic := true
else
if close < get.prc
get.mit := true
if not oW and low < get.prc and close > get.prc

get.tak := true

if n - get.bix > 2000 or get.mit or get.tak


aPivH.remove(i).lin.delete()
for i = aPivL.size() -1 to 0
get = aPivL.get(i)
if not get.mit
if not get.brk
if close < get.prc
if not oW
get.brk := true
else
get.mit := true
if not oO and not get.wic
if low < get.prc and close > get.prc
bullcandle := true

get.wic := true
else
if close > get.prc
get.mit := true
if not oW and high > get.prc and close < get.prc

get.tak := true

if n - get.bix > 2000 or get.mit or get.tak


aPivL.remove(i).lin.delete()

//plotcandle(math.max(close, open), high, math.max(close, open), high, "",


color(na), color(na), bordercolor = bearcandle and activateliquidity ? colBr3 :
color(na), editable = false)
//plotcandle(math.min(close, open), math.min(close, open), low, low, "", color(na),
color(na), false, bordercolor = bullcandle and activateliquidity? colBl3 :
color(na))
if showtrendline?extend:na
for bx in aBoxBr
if not bx.br and n - bx.bx.get_left() -1 <= maxB
bx.bx.set_right(bar_index)
if bx.dr == -1 and close < bx.bx.get_bottom()
bx.br := true
if bx.dr == 1 and close > bx.bx.get_top ()
bx.br := true

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

len = input.int (5 , "Period " , tooltip = "Lookback period",


inline = "a", group = "SETTINGS")
cup = input.color(#0044ff, "" , "" ,
inline = "a", group = "SETTINGS")
cdn = input.color(#ff2b00, "" , "" ,
inline = "a", group = "SETTINGS")
space = input.float(2 , "Padding" , tooltip = "Padding distance",
inline = "b", group = "SETTINGS", step = 0.1)
shs = input.bool (true , "Show Breakouts",
inline = "z", group = "SETTINGS")

pha = ta.pivothigh(high, len, len)


pla = ta.pivotlow (low , len, len)

type store
float src
int n

type bar
float o = open
float h = high
float l = low
float c = close
int n = bar_index
float v = volume

type draw
line[] upln
line[] dnln

var store[] upbin = array.new<store>()


var store[] dnbin = array.new<store>()

var draw d = draw.new(array.new<line>(), array.new<line>())

bar b = bar.new()
atrt = ta.atr(200)

method slope(line ln) =>


x = ln.get_x2() - ln.get_x1()
y = ln.get_y2() - ln.get_y1()
y / x

vol() =>
math.min(atrt * 0.1, close * (0.1/100))

var bool broken = false


color active = na
bool plup = false
bool pldn = false

if showtrendline?pha:na
bool remove = false
var bool valid = false

upbin.unshift(store.new(b.h[len], b.n[len]))
if upbin.size() > 1
current = upbin.get(0)
before = upbin.get(1)
if current.src < before.src
if broken
valid := true

else
valid := false
if upbin.size() > 3
pastold = upbin.get(3)
pastcur = upbin.get(2)
now = upbin.get(1)
late = upbin.get(0)
if now.src < pastcur.src and now.src < pastold.src and late.src
< pastcur.src and late.src < pastold.src
valid := true
else
valid := false

else
valid := false

if valid

d.upln.unshift(line.new(x1 = before.n, x2 = current.n, y1 =


before.src , y2 = current.src , color = cdn))
d.upln.unshift(line.new(x1 = before.n, x2 = current.n, y1 =
before.src - vol() * space, y2 = current.src - vol() * space, color = cdn))

ln = d.upln.get(1)
for i = 0 to (b.n - before.n)
slope = ln.slope()
ln.set_x2(b.n[i])
ln.set_y2(ln.get_y2() - slope)
if low[i] > ln.get_y2()
remove := true
break

if remove
d.upln.get(0).delete()
d.upln.get(1).delete()
d.upln .clear()
upbin .clear()
broken := true

else
d.upln.get(0).delete()
d.upln.get(1).delete()
d.upln .clear ()

d.upln.unshift(line.new(x1 = before.n, x2 = current.n, y1 =


before.src , y2 = current.src , color = cdn))
d.upln.unshift(line.new(x1 = before.n, x2 = current.n, y1 =
before.src - vol() * space, y2 = current.src - vol() * space, color = cdn))

linefill.new(d.upln.get(0), d.upln.get(1), color =


color.new(cdn, 75))
upbin.clear()
broken := false

if d.upln.size() > 1

btm = d.upln.get(0)
top = d.upln.get(1)

if b.l > top.get_y2()


d.upln.clear()
broken := true
upbin.clear()
plup := true

if d.upln.size() > 1

slup = top.slope()
sldn = btm.slope()

top.set_x2(b.n)
top.set_y2(top.get_y2() + slup)

btm.set_x2(b.n)
btm.set_y2(btm.get_y2() + sldn)

if showtrendline?pla:na
bool remove = false
var bool valid = false

dnbin.unshift(store.new(b.l[len], b.n[len]))
if dnbin.size() > 1
current = dnbin.get(0)
before = dnbin.get(1)
if current.src > before.src
if broken
valid := true

else
valid := false
if dnbin.size() > 3
pastold = dnbin.get(3)
pastcur = dnbin.get(2)
now = dnbin.get(1)
late = dnbin.get(0)

if now.src > pastcur.src and now.src > pastold.src and late.src


> pastcur.src and late.src > pastold.src
valid := true

else
valid := false

else
valid := false

if valid
d.dnln.unshift(line.new(x1 = before.n, x2 = current.n, y1 =
before.src , y2 = current.src , color = cup))
d.dnln.unshift(line.new(x1 = before.n, x2 = current.n, y1 =
before.src + vol() * space, y2 = current.src + vol() * space, color = cup))

ln = d.dnln.get(1)

for i = 0 to (b.n - before.n)


slope = ln.slope()
ln.set_x2(b.n[i])
ln.set_y2(ln.get_y2() - slope)
if high[i] < ln.get_y2()
remove := true
break

if remove
d.dnln.get(0).delete()
d.dnln.get(1).delete()
d.dnln .clear ()
dnbin .clear ()
broken := true

else
d.dnln.get(0).delete()
d.dnln.get(1).delete()
d.dnln .clear ()

d.dnln.unshift(line.new(x1 = before.n, x2 = current.n, y1 =


before.src, y2 = current.src, color = cup))
d.dnln.unshift(line.new(x1 = before.n, x2 = current.n, y1 =
before.src + vol() * space, y2 = current.src + vol() * space, color = cup))

linefill.new(d.dnln.get(0), d.dnln.get(1), color =


color.new(cup, 75))
dnbin.clear()
broken := false

if d.dnln.size() > 1

btm = d.dnln.get(0)
top = d.dnln.get(1)

if b.h < btm.get_y2()


d.dnln.clear()
broken := true
dnbin.clear()
pldn := true

if d.dnln.size() > 1

slup = top.slope()
sldn = btm.slope()

top.set_x2(b.n)
top.set_y2(top.get_y2() + slup)

btm.set_x2(b.n)
btm.set_y2(btm.get_y2() + sldn)

plotshape(pldn and shs ? b.h[1] : na, "Breaking Down", shape.triangledown, location


= location.abovebar, color = cdn , offset = -1, size = size.tiny)
plotshape(plup and shs ? b.l[1] : na, "Breaking Up" , shape.triangleup , location
= location.belowbar, color = cup, offset = -1, size = size.tiny)

///////////////////////////////////////////
bool ontrendline = input.bool(true, "Auto-Trendlines", group = "Price Action
Concepts", inline = "133")
atr10 = ta.atr(200)/2
int autotrendlinesens = input.int(3, "", [1, 2, 3, 4, 5], group = "Price Action
Concepts", inline = "133")
length11111 = 5*autotrendlinesens+5
length111112 = 5*autotrendlinesens+5
astart = 2
aend = 0
bstart = 2
bend = 0
csrcsrcsrc = false
srcsrcsrc = close

//Conditions
upupup = ta.pivothigh(csrcsrcsrc ? srcsrcsrc : high, length11111, length11111)
dndndn = ta.pivotlow(csrcsrcsrc ? srcsrcsrc : low, length111112, length111112)

a1 = ta.valuewhen(not na(upupup), n, astart)


b1 = ta.valuewhen(not na(dndndn), n, bstart)
a2 = ta.valuewhen(not na(upupup), n, aend)
b2 = ta.valuewhen(not na(dndndn), n, bend)

//Colors
color111 = #a53e48
color222 = #5b8d5e

//Plots
if showtrendline?ontrendline:na
line upupupper1 = line.new(n[n - a1 + length11111], upupup[n - a1]+atr10, n[n -
a2 + length11111], upupup[n - a2]+atr10, extend=extend.right,
color=color.new(color111, 10),width=1)
line lower11 = line.new(n[n - b1 + length111112], dndndn[n - b1], n[n - b2 +
length111112], dndndn[n - b2], extend=extend.right, color=color.new(color222, 10),
width=1)
line upupupper2 = line.new(n[n - a1 + length11111], upupup[n - a1], n[n - a2 +
length11111], upupup[n - a2], extend=extend.right, color=color.new(color111, 10),
width=1)
line lower21 = line.new(n[n - b1 + length111112], dndndn[n - b1]-atr10, n[n -
b2 + length111112], dndndn[n - b2]-atr10, extend=extend.right,
color=color.new(color222, 10), width=1)
linefill t = linefill.new(upupupper1, upupupper2, color.new(color111, 75))
linefill y = linefill.new(lower11, lower21, color.new(color222, 75))
line.delete(upupupper1[1])
line.delete(lower11[1])
line.delete(upupupper2[1])
line.delete(lower21[1])

////////////////////////////////////////// TRENDLINE
END //////////////////////////////
/////////////////////////////// ORDER BLOCK
FINDER /////////////////////////////////////

colors = input.string(title='Color Scheme', defval='BRIGHT', options=['DARK',


'BRIGHT'])
periods = input(5, 'Relevant Periods to identify OB') // Required number of
subsequent candles in the same direction to identify Order Block
threshold = input.float(0.0, 'Min. Percent move to identify OB', step=0.1) //
Required minimum % move (from potential OB close to last subsequent candle to
identify Order Block)
usewicks = input(false, 'Use whole range [High/Low] for OB marking?') // Display
High/Low range for each OB instead of Open/Low for Bullish / Open/High for Bearish
showbull = input(true, 'Show latest Bullish Channel?') // Show Channel for latest
Bullish OB?
showbear = input(true, 'Show latest Bearish Channel?') // Show Channel for latest
Bearish OB?
showdocu = input(false, 'Show Label for documentation tooltip?') // Show Label
which shows documentation as tooltip?
info_pan = input(false, 'Show Latest OB Panel?') // Show Info Panel with latest OB
Stats

ob_period = periods + 1 // Identify location of relevant Order Block candle


absmove = math.abs(close[ob_period] - close[1]) / close[ob_period] * 100 //
Calculate absolute percent move from potential OB to last candle of subsequent
candles
relmove = absmove >= threshold // Identify "Relevant move" by comparing the
absolute move to the threshold

// Color Scheme
bullcolor = colors == 'DARK' ? color.rgb(249, 13, 13) : #1000ed
bearcolor = colors == 'DARK' ? color.blue : #ff0000

// Bullish Order Block Identification


//OB_bull_high = OB_bull ? usewicks ? high[ob_period] : open[ob_period] : na //
Determine OB upper limit (Open or High depending on input)
//OB_bull_low = OB_bull ? low[ob_period] : na // Determine OB lower limit (Low)
//OB_bull_avg = (OB_bull_high + OB_bull_low) / 2 // Determine OB middle line

// Bearish Order Block Identification


//bearishOB = close[ob_period] > open[ob_period] // Determine potential Bearish OB
candle (green candle)

//int downcandles = 0
//for i = 1 to periods by 1
//downcandles += (close[i] < open[i] ? 1 : 0) // Determine color of subsequent
candles (must all be red to identify a valid Bearish OB)
//downcandles
//OB_bear = bearishOB and downcandles == periods and relmove // Identification
logic (green OB candle & subsequent green candles)
//OB_bear_high = OB_bear ? high[ob_period] : na // Determine OB upper limit (High)
//OB_bear_low = OB_bear ? usewicks ? low[ob_period] : open[ob_period] : na //
Determine OB lower limit (Open or Low depending on input)
//OB_bear_avg = (OB_bear_low + OB_bear_high) / 2 // Determine OB middle line

// Plotting

//plotshape(ShowOB?OB_bull:na, title='Bullish OB', style=shape.triangleup,


color=bullcolor, textcolor=bullcolor, size=size.tiny, location=location.belowbar,
offset=-ob_period, text='Order Block') // Bullish OB Indicator
//bull1 = plot(ShowOB ?OB_bull_high:na, title='Bullish OB High',
style=plot.style_linebr, color=bullcolor, offset=-ob_period, linewidth=3,editable =
false) // Bullish OB Upper Limit
//bull2 = plot(ShowOB ?OB_bull_low:na, title='Bullish OB Low',
style=plot.style_linebr, color=bullcolor, offset=-ob_period, linewidth=3,editable =
false) // Bullish OB Lower Limit
//fill(bull1, bull2, color=bullcolor, title='Bullish OB fill', transp=0) // Fill
Bullish OB
//plotshape(ShowOB?OB_bull_avg:na, title='Bullish OB Average', style=shape.cross,
color=bullcolor, size=size.normal, location=location.absolute, offset=-
ob_period,editable = false) // Bullish OB Average

//plotshape(ShowOB?OB_bear:na, title='Bearish OB', style=shape.triangledown,


color=bearcolor, textcolor=bearcolor, size=size.tiny, location=location.abovebar,
offset=-ob_period, text='Order Block') // Bearish OB Indicator
//bear1 = plot(ShowOB?OB_bear_low:na, title='Bearish OB Low',
style=plot.style_linebr, color=bearcolor, offset=-ob_period, linewidth=3,editable =
false) // Bearish OB Lower Limit
//bear2 = plot(ShowOB?OB_bear_high:na, title='Bearish OB High',
style=plot.style_linebr, color=bearcolor, offset=-ob_period, linewidth=3,editable =
false) // Bearish OB Upper Limit
//fill(bear1, bear2, color=bearcolor, title='Bearish OB fill', transp=0) // Fill
Bearish OB
//plotshape(ShowOB?OB_bear_avg:na, title='Bearish OB Average', style=shape.cross,
color=bearcolor, size=size.normal, location=location.absolute, offset=-
ob_period,editable = false) // Bullish OB Average

//var line linebull1 = na // Bullish OB average


//var line linebull2 = na // Bullish OB open
//var line linebull3 = na // Bullish OB low
//var line linebear1 = na // Bearish OB average
//var line linebear2 = na // Bearish OB high
//var line linebear3 = na // Bearish OB open

//if ShowOB ?(OB_bull and showbull):na


//line.delete(linebull1)
//linebull1 := line.new(x1=bar_index, y1=OB_bull_avg, x2=bar_index - 1,
y2=OB_bull_avg, extend=extend.left, color=bullcolor, style=line.style_solid,
width=1)

//line.delete(linebull2)
//linebull2 := line.new(x1=bar_index, y1=OB_bull_high, x2=bar_index - 1,
y2=OB_bull_high, extend=extend.left, color=bullcolor, style=line.style_dashed,
width=1)

//line.delete(linebull3)
//linebull3 := line.new(x1=bar_index, y1=OB_bull_low, x2=bar_index - 1,
y2=OB_bull_low, extend=extend.left, color=bullcolor, style=line.style_dashed,
width=1)
//linebull3

//if ShowOB ? (OB_bear and showbear):na


//line.delete(linebear1)
//linebear1 := line.new(x1=bar_index, y1=OB_bear_avg, x2=bar_index - 1,
y2=OB_bear_avg, extend=extend.left, color=bearcolor, style=line.style_solid,
width=1)

//line.delete(linebear2)
//linebear2 := line.new(x1=bar_index, y1=OB_bear_high, x2=bar_index - 1,
y2=OB_bear_high, extend=extend.left, color=bearcolor, style=line.style_dashed,
width=1)

//line.delete(linebear3)
//linebear3 := line.new(x1=bar_index, y1=OB_bear_low, x2=bar_index - 1,
y2=OB_bear_low, extend=extend.left, color=bearcolor, style=line.style_dashed,
width=1)
//linebear3

// Alerts for Order Blocks Detection

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

///////////////////////////////////////// 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( 12, 'LENGTH ZIGZAG ', minval = 2, maxval =
50, tooltip = K0,group = " ZIGZAG HIGH - LOW")
colorUp = input.color(#1607ee,'Trend Color', inline = '0')
colorDn = input.color( #ec0606, '', 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'])
widtha = 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
[Hz, Lz] = 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 dirk = 0, dirk := Kh and na(Kl) ? 1 : Kl and na(Kh) ? -1 : dirk
var zigzag = array.new<point>(0)
oldzigzag = zigzag.copy()
dirchanged = ta.change(dirk)
hiLo = HL.new(Hi, Lo)
varSetup = startUp.new(Kh, Kl, colorUp, colorDn, Hz, Lz)
//#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 = dirk == 1 ? setup.hi : setup.lo
sty = dirk == 1 ? label.style_label_down : label.style_label_up
col = dirk == 1 ? setup.colorHi : setup.colorLo
str = dirk == 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 dirk =
na)=>
if array.size(zigzag) == 0
zigzag.initialize(setup, maxSize)
else
newPoint = setup.dirVariables()
dirOver = dirk == 1 and newPoint.y > zigzag.get(0).y
dirLess = dirk == -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) =>
dirk == 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, dirk)
//#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(widtha, switchLine)
if colorLine != 'Trend'
dirLine.set_color(switchLineColor)
// //#endregion

///////////////////////////////////////////////////////
//////////////////////// SuperIchi //////////////////

tenkan_len = input(365,'Tenkan ',inline='tenkan')


tenkan_mult = input(4.,'',inline='tenkan')

kijun_len = input(365,'Kijun ',inline='kijun')


kijun_mult = input(7.,'',inline='kijun')

spanB_len = input(365,'Senkou Span B ',inline='span')


spanB_mult = input(11.,'',inline='span')

offset = input(2,'Displacement')
//------------------------------------------------------------------------------
avg(src,length,mult)=>
atr = ta.atr(length)*mult
up = hl2 + atr
dn = hl2 - atr
upper = 0.,lower = 0.
upper := src[1] < upper[1] ? math.min(up,upper[1]) : up
lower := src[1] > lower[1] ? math.max(dn,lower[1]) : dn

os = 0,max = 0.,min = 0.
os := src > upper ? 1 : src < lower ? 0 : os[1]
spt = os == 1 ? lower : upper
max := ta.cross(src,spt) ? math.max(src,max[1]) : os == 1 ?
math.max(src,max[1]) : spt
min := ta.cross(src,spt) ? math.min(src,min[1]) : os == 0 ?
math.min(src,min[1]) : spt
math.avg(max,min)
//------------------------------------------------------------------------------
tenkan = avg(close,tenkan_len,tenkan_mult)
kijun = avg(close,kijun_len,kijun_mult)

senkouA = math.avg(kijun,tenkan)
senkouB = avg(close,spanB_len,spanB_mult)
//------------------------------------------------------------------------------
//tenkan_css = #1bd007
//kijun_css = #8d0292

//cloud_a = color.new(color.teal,80)
//cloud_b = color.new(color.red,80)

//chikou_css = #7b1fa2

//plot(SuperIchi?tenkan:na,'Tenkan-Sen',tenkan_css,linewidth =
1,display=display.none)
//plot(SuperIchi?kijun:na,'Kijun-Sen',kijun_css,linewidth = 2,display=display.none)

//plot(SuperIchi?(ta.crossover(tenkan,kijun) ? kijun :
na):na,'Crossover',color.rgb(0, 72, 255),4,plot.style_circles,display=display.none)
//plot(SuperIchi?(ta.crossunder(tenkan,kijun) ? kijun :
na):na,'Crossunder',color.rgb(255, 0, 0),4,plot.style_circles,display=display.none)

//A = plot(SuperIchi?senkouA:na,'Senkou Span A',na,offset=offset-1)


//B = plot(SuperIchi?senkouB:na,'Senkou Span B',na,offset=offset-1)
//fill(A,B,senkouA > senkouB ? cloud_a : cloud_b,title = " Ichicloud")

//plot(close,'Chikou',chikou_css,offset=-offset+1,display=display.none)
// REV ZONES
//
***********************************************************************************
*************************

lengt = input.int(20, minval=1,title = "BAND",group = " Reversal Band")


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

basis = ma(sr, lengt, maType)


dev = mul * ta.stdev(sr, lengt)
uppe = basis + dev
lowr = basis - dev
offset11 = input.int(0, "Offset", minval = -500, maxval = 500)
//plot(basis, "Mid Band BB", color=#00332a, offset = offset11,linewidth = 2,display
= display.none)
//A1 = plot(reversalZone?(ta.sma(uppe, Smoothing1)):na, "Upper", color=#00000063,
offset = offset11, editable = false)
//B1 = plot(reversalZone?(ta.sma(lowr, Smoothing1)):na, "Lower", color=#00000063,
offset = offset11, editable = false)

m = input.float(3, minval=0.001, maxval=50, title="StdDev")

basis1 = ma(sr, lengt, maType)


dev1 = m * ta.stdev(sr, lengt)
upper1 = basis1 + dev1
lower1 = basis1 - dev1
offset12 = input.int(0, "Offset", minval = -500, maxval = 500)
//plot(basis1, "Mid Band", color=#FF6D00,title='Mid Band', offset =
offset12,display = display.none)
//A11 = plot(reversalZone?(ta.sma(upper1, Smoothing1)) : na, "Upper",
color=#080000, offset = offset12,linewidth = 1, editable = false)
//B11 = plot(reversalZone?(ta.sma(lower1, Smoothing1)) : na, "Lower",
color=#070000, offset = offset12,linewidth = 1, editable = false)

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


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

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

////////////Ichimoku Cloud"//////////////

conversionPeriods = input.int(9, minval=1, title="Conversion Line Length")


basePeriods = input.int(26, minval=1, title="Base Line Length")
laggingSpan2Periods = input.int(52, minval=1, title="Leading Span B Length")
displacement = input.int(26, minval=1, title="Lagging Span")
donchian(len) => math.avg(ta.lowest(len), ta.highest(len))
conversionLine = donchian(conversionPeriods)
baseLine = donchian(basePeriods)
leadLine1 = math.avg(conversionLine, baseLine)
leadLine2 = donchian(laggingSpan2Periods)
//plot(Ichimoku?conversionLine:na, color=#2962FF, title="Conversion Line",display =
display.none)
//plot(Ichimoku?baseLine:na, color=#B71C1C, title="Base Line",display =
display.none)
plot(Ichimoku?close:na, offset = -displacement + 1, color=#43A047, title="Lagging
Span",display = display.none)
p1 = plot(Ichimoku?leadLine1:na, offset = displacement - 1, color=#A5D6A7,
title="Leading Span A")
p2 = plot(Ichimoku?leadLine2:na, offset = displacement - 1, color=#EF9A9A,
title="Leading Span B")
//plot(leadLine1 > leadLine2 ? leadLine1 : leadLine2, offset = displacement - 1,
title = "Kumo Cloud Upper Line", display = display.none)
//plot(leadLine1 < leadLine2 ? leadLine1 : leadLine2, offset = displacement - 1,
title = "Kumo Cloud Lower Line", display = display.none)
fill(p1, p2, color = leadLine1 > leadLine2 ? color.rgb(67, 160, 71, 90) :
color.rgb(244, 67, 54, 90))

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

////////////////////SUPERTREND////////////////////////

Periods07 = input(title='ATR Period', defval=7)


src07 = input(hlcc4, title='Source')
Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=4.0)
changeATR = input(title='Change ATR Calculation Method ?', defval=true)
showsignals = input(title='Show Buy/Sell Signals ?', defval=true)
highlighting = input(title='Highlighter On/Off ?', defval=false)
atr21 = ta.sma(ta.tr, Periods07)
atr12 = changeATR ? ta.atr(Periods07) : atr21
upa = src07 - Multiplier * atr12
up1a = nz(upa[1], upa)
upa := close[1] > up1a ? math.max(upa, up1a) : upa
dna = src07 + Multiplier * atr12
dn1a = nz(dna[1], dna)
dna := close[1] < dn1a ? math.min(dna, dn1a) : dna
trends = 1
trends := nz(trends[1], trends)
trends := trends == -1 and close > dn1a ? 1 : trends == 1 and close < up1a ? -1 :
trends

upPlot = plot(ShowBS?(trends == 1 ? upa : na):na, title='Up Trend',


style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0))
//buySignal = trends == 1 and trends[1] == -1
//plotshape(ShowBS?(buySignal ? upa : na):na, title='UpTrend Begins',
location=location.absolute, style=shape.circle, size=size.tiny,
color=color.new(color.green, 0))
//plotshape(ShowBS?(buySignal and showsignals ? upa : na):na, title='Buy',
text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny,
color=color.new(color.green, 0), textcolor=color.new(color.white, 0))

dnPlot = plot(ShowBS?(trends == 1 ? na : dna):na, title='Down Trend',


style=plot.style_linebr, linewidth=2, color=color.new(color.red, 0))
//sellSignal = trends == -1 and trends[1] == 1
//plotshape(ShowBS?(sellSignal ? dna : na):na, title='DownTrend Begins',
location=location.absolute, style=shape.circle, size=size.tiny,
color=color.new(color.red, 0))
//plotshape(ShowBS?(sellSignal and showsignals ? dna : na):na, title='Sell',
text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny,
color=color.new(color.red, 0), textcolor=color.new(color.white, 0))
//mPlot = plot(ShowBS?ohlc4:na, title='MPlor', style=plot.style_circles,
linewidth=0,display = display.none)
//longFillColor = highlighting ? trends == 1 ? color.rgb(76, 175, 79, 73) :
color.white : color.white
//shortFillColor = highlighting ? trends == -1 ? #f8515134 : color.white :
color.white
//fill(mPlot, upPlot, title='UpTrend Highligter', color=longFillColor, transp=90)
//fill(mPlot, dnPlot, title='DownTrend Highligter', color=shortFillColor,
transp=90)

//@version=5
//indicator(title = "SuperTrend ATR + RSI", shorttitle = "SuperTrend ATR + RSI",
overlay = true)

//Mode
Factor=input.int(title="Super Trend", defval=4, minval=1,maxval = 100)
ATR=input.int(title="ATR", defval=7, minval=1,maxval = 100)
RSI = input.int(title="RSI", defval=7, minval=1, maxval = 100)

//Super Trend ATR


Upe=hl2-(Factor*ta.atr(ATR))
Dne=hl2+(Factor*ta.atr(ATR))
TUp = 0.0
TDown = 0.0
Trende = 1
TUp := close[1]>TUp[1]? math.max(Upe,TUp[1]) : Upe
TDown := close[1]<TDown[1]? math.min(Dne,TDown[1]) : Dne

Trende := close > TDown[1] ? 1: close< TUp[1]? -1: nz(Trende[1],1)


Tsl = Trende==1? TUp: TDown

linecolor = Trende == 1 ? color.green : color.red

//RSI
srce = close,

ep = 2 * RSI - 1
auc = ta.ema( math.max( srce - srce[1], 0 ), ep )
adc = ta.ema( math.max( srce[1] - srce, 0 ), ep )
x1 = (RSI - 1) * ( adc * 70 / (100-70) - auc)
ub = x1 >= 0? srce + x1: srce + x1 * (100-70)/70
x2 = (RSI - 1) * ( adc * 30 / (100-30) - auc)
lb = x2 >= 0? srce + x2: srce + x2 * (100-30)/30

//Affichage

plot(ShowBS?Tsl:na, color = linecolor , style = plot.style_line , linewidth =


1,title = "SuperTrend ATR")

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

/////////////// B52 TP Ranger ///////////////////////////

show_sesc = input(true, '', inline = 'sesc', group = 'Session C')


sesc_txt = input('Tokyo', '', inline = 'sesc', group = 'Session C')
sesc_ses = input.session('0700-1200', '', inline = 'sesc', group = 'Session C')
sesc_css = input.color(color.rgb(138, 141, 147, 84), '', inline = 'sesc', group =
'Session C')
onlyTody = input(true,'hien ngay hom nay', inline = 'sesc', group = 'Session C')
sesc_range = input(true, 'Range', inline = 'sesc_overlays', group = 'Session C')
sesc_maxmin = input(true, 'Max/Min', inline = 'sesc_overlays', group = 'Session C')

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

//Ranges Options
bg_transp = input.float(90, 'Range Area Transparency', group = 'Ranges Settings')
show_outline = input(false, 'Range Outline', group = 'Ranges Settings')
show_txt = input(false, '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
isValidResolution() => timeframe.isdwm == true or timeframe.period == "120" or
timeframe.period == "240" or timeframe.period == "180" or timeframe.period == "360"
? 0 : 1
isBelowHourValidResolution() => timeframe.isdwm == true or timeframe.period ==
"120" or timeframe.period == "240" or timeframe.period == "180" or timeframe.period
== "360" ? 0 : 1

//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_sesc = math.sign(nz(time(tf, sesc_ses, tz)))


//-----------------------------------------------------------------------------}
//Overlays
//-----------------------------------------------------------------------------{

var float max_sesc = na


var float min_sesc = na

//Ranges
if show_sesc and sesc_range and showSession
[max, min] = get_range(is_sesc, sesc_txt, sesc_css)
max_sesc := max
min_sesc := min

//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
// Plot max/min
// Tính toán mức Fibonacci
fibonacci_target3 = max_sesc + (max_sesc - min_sesc) * 3.236
fibonacci_target2 = max_sesc + (max_sesc - min_sesc) * 1.618
fibonacci_target1 = max_sesc + (max_sesc - min_sesc) * 0.618
fibonacci_target3_down = min_sesc - (max_sesc - min_sesc) * 3.236
fibonacci_target2_down = min_sesc - (max_sesc - min_sesc) * 1.618
fibonacci_target1_down = min_sesc - (max_sesc - min_sesc) * 0.618

isToday = year == year(timenow) and month == month(timenow) and dayofmonth ==


dayofmonth(timenow)
isToday := onlyTody?isToday:true
drawnArrow = false
// // Vẽ đường line target của Asian Range
// line.new(x1=bar_index[1], y1=max_sesc, x2=bar_index, y2=fibonacci_high,
color=color.blue, width=2, extend=extend.both, style=line.style_dotted)
bardaaw = 0
bardaaw := bardaaw[1] != 0 ?bardaaw[1]:0
if hour == 1 and minute == 00
bardaaw := time

uptrend = -1
uptrend := close > max_sesc? 2 :close < min_sesc?1:0

if close < min_sesc and isToday


var isDraw = line.new(x1=bardaaw, y1=min_sesc, x2=bardaaw,
y2=fibonacci_target1_down, color=#e91e63, width=1,
style=line.style_arrow_right,xloc = xloc.bar_time)
line.new(x1=bardaaw, y1=min_sesc, x2=bardaaw, y2=fibonacci_target2_down,
color=#e91e63, width=1, style=line.style_arrow_right,xloc = xloc.bar_time)
// if close < fibonacci_target1_down
line.new(x1=bardaaw, y1=fibonacci_target1_down, x2=time,
y2=fibonacci_target1_down, color=#e91e6245, width=1, style=line.style_solid,xloc =
xloc.bar_time)
line.new(x1=bardaaw, y1=fibonacci_target2_down, x2=time,
y2=fibonacci_target2_down, color=#e91e6233, width=1, style=line.style_solid,xloc =
xloc.bar_time)
string tp2 = 'Tp2: ' + str.tostring(fibonacci_target2_down)
string tp1 = 'Tp1: ' + str.tostring(fibonacci_target1_down)
label.new(x=bardaaw, y=fibonacci_target2_down,
style=label.style_label_right,color=color.rgb(223, 64, 251, 100),
size=size.small,xloc = xloc.bar_time,text = tp2)
label.new(x=bardaaw, y=fibonacci_target1_down,
style=label.style_label_right,color=color.rgb(223, 64, 251, 100),
size=size.small,xloc = xloc.bar_time,text = tp1)
if close < fibonacci_target2_down
line.new(x1=bardaaw, y1=fibonacci_target2_down, x2=bardaaw,
y2=fibonacci_target3_down, color=#e91e63, width=1,
style=line.style_arrow_right,xloc = xloc.bar_time)
line.new(x1=bardaaw, y1=fibonacci_target3_down, x2=time,
y2=fibonacci_target3_down, color=#e91e6249, width=1, style=line.style_solid,xloc =
xloc.bar_time)

if close > max_sesc and isToday


isDraw = line.new(x1=bardaaw, y1=max_sesc, x2=bardaaw, y2=fibonacci_target1,
color=#e91e63, width=1, style=line.style_arrow_right,xloc = xloc.bar_time)
line.new(x1=bardaaw, y1=max_sesc, x2=bardaaw, y2=fibonacci_target2,
color=#e91e63, width=1, style=line.style_arrow_right,xloc = xloc.bar_time)
line.new(x1=bardaaw, y1=fibonacci_target1, x2=time, y2=fibonacci_target1,
color=#e91e623f, width=1, style=line.style_solid,xloc = xloc.bar_time)
line.new(x1=bardaaw, y1=fibonacci_target2, x2=time, y2=fibonacci_target2,
color=#e91e6247, width=1, style=line.style_solid,xloc = xloc.bar_time)
// if na(1)
string tp2 = 'Tp2: ' + str.tostring(fibonacci_target2)
string tp1 = 'Tp1: ' + str.tostring(fibonacci_target1)
label.new(x=bardaaw, y=fibonacci_target2,
style=label.style_label_right,color=color.rgb(223, 64, 251, 100),
size=size.small,xloc = xloc.bar_time,text = tp2)
label.new(x=bardaaw, y=fibonacci_target1,
style=label.style_label_right,color=color.rgb(223, 64, 251, 100),
size=size.small,xloc = xloc.bar_time,text = tp1)
if close > fibonacci_target2
line.new(x1=bardaaw, y1=fibonacci_target2, x2=bardaaw,
y2=fibonacci_target3, color=#e91e63, width=1, style=line.style_arrow_right,xloc =
xloc.bar_time)
line.new(x1=bardaaw, y1=fibonacci_target3, x2=time, y2=fibonacci_target3,
color=#e91e6240, width=1, style=line.style_solid,xloc = xloc.bar_time)

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


plot.style_linebr)
plot(sesc_maxmin ? min_sesc : na, 'Session C Minimum', sesc_css, 1,
plot.style_linebr)
/// Session ADD END

You might also like