Skip to main content

Elite Binary

//@version=6 indicator("RSI TMA", overlay=true) // Arrows on the main chart (overlay=true) // Input parameters rsiLength = input.int(2, title="RSI Length") rsiPrice = input.source(close, title="RSI Price") halfLength = input.int(2, title="Half Length") devPeriod = input.int(100, title="Deviation Period") deviations = input.float(0.7, title="Deviations") noDellArr = input.bool(false, title="No Delete Arrows") arrOtstup = input.int(0, title="Arrow Offset") arrUpColor = input.color(color.lime, title="Arrow Up Color") arrDnColor = input.color(color.red, title="Arrow Down Color") alertsMessage = input.bool(false, title="Alerts Message") alertsSound = input.bool(false, title="Alerts Sound") alertsEmail = input.bool(false, title="Alerts Email") alertsMobile = input.bool(false, title="Alerts Mobile") signalBar = input.int(0, title="Signal Bar") ...

Smart Money Algo Pro E5

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CHADBULL7

//@version=5
indicator(title = "Smart Money Algo Pro E5 - CHADBULL ", overlay = true, max_bars_back = 5000, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500,calc_bars_count = 5000)
showHL = input.bool(false, "Major Pullback", inline = "HL", group = "Pullback", inline = 'smc11')

colorHL = input.color(#000000, "", group = "Pullback", inline='smc11')
showMn = input.bool(false, "Minor pullback", group = "Pullback")

//market structure
showSMC = input.bool(true, "True SMC Market Structure", group = "Market Structure",inline ='smc1')
lengSMC = input.int(40, title=": Lenght", inline="liveSMC", group="Market Structure", inline = 'smc1')
colorIDM = input.color(color.rgb(0, 0, 0, 20), "IDM", group = "Market Structure")
structure_type = input.string ("Choch with IDM",title='Smc Structure Type ', group="Market Structure", options=["Choch without IDM", "Choch with IDM"])
showCircleHL = input.bool(true, "True SMC Swing", inline = "HL", group = "Market Structure")

bull = input.color(color.green, "Bullish", group = "Market Structure",inline = 'smc12')
bear = input.color(color.red  , "Bearish", group = "Market Structure",inline = 'smc12')

// mitatypeTouch =  input.string("Touch","Mitigation Type",options = ["Touch","Break"],group = "Order Block") == "Touch"

//order block
extndBox = input.bool(true,"Extend box on break",group = "Order Block")
showExob = input.bool(true,"Show EXT OB",group = "Order Block")
showIdmob = input.bool(true,"Show IDM OB",group = "Order Block")
showBrkob = input.bool(true,"Show Break EXT OB & IDM OB ",group = "Order Block")
txtsiz = input.string( size.auto ,"EXT OB & IDM OB Text Size",options =  [size.auto,size.tiny,size.small,size.normal,size.large,size.huge],group ='Order Block')

clrtxtextbullbg = input.color(color.rgb(76, 175, 79, 86),"EXT OB BG Color : Demand",group = "Order Block",inline = "clr13")
clrtxtextbearbg = input.color(color.rgb(255, 82, 82, 83),"Supply",group = "Order Block",inline = "clr13")
clrtxtextbulliembg = input.color(color.rgb(76, 175, 79, 86),"IDM OB BG Color : Demand",group = "Order Block",inline = "clr113")
clrtxtextbeariembg = input.color(color.rgb(255, 82, 82, 86),"Supply",group = "Order Block",inline = "clr113")

clrtxtextbull = input.color(color.green,"EXT OB Text Color : Demand",group = "Order Block",inline = "clr1")
clrtxtextbear = input.color(color.red,"Supply",group = "Order Block",inline = "clr1")
clrtxtextbulliem = input.color(color.green,"IDM OB Text Color : Demand",group = "Order Block",inline = "clr11")
clrtxtextbeariem = input.color(color.red,"Supply",group = "Order Block",inline = "clr11")


showPOI = input.bool(true, "(Order + Breaker + Mitigation + propulsion) Block", group="Order Block")
poi_type = input.string ("Mother Bar",title='Zone Type', group="Order Block", options=["---", "Mother Bar"])
colorSupply = input.color(#cd5c4800, 'Bullish', group = "Order Block")
colorDemand = input.color(#2f825f00, 'Bearish', group = "Order Block")
colorMitigated = input.color(#c0c0c000, 'Mitigated', group = "Order Block")

showSCOB = input.bool(true, "Show SCOB", inline = "Bar", group = "Order Block")
scobUp = input.color(#0b3ff9   , "Bullish SCOB", group = "Order Block")
scobDn = input.color(#da781d, "Bearish SCOB", group = "Order Block")

//Demand Zone & Supply Zone

show_order_blocks=input.bool(false,"Demand & Supply Zone",group = 'Demand Zone & Supply Zone', inline = 'smc6')
ibull_ob_css = input.color(#5f6b5d19, 'Demand Zone', inline = 'ob1', group = 'Demand Zone & Supply Zone')
ibear_ob_css = input.color(#ef3a3a19, 'Supply Zone', inline = 'ob1', group = 'Demand Zone & Supply Zone')
ob_type__ = 'All'    //ob_type__= input.string('All', '',options = ['All','Internal','External'], group = 'Order Blocks',inline = 'ob1')
i_tf_ob = input.timeframe("", "Zone Timeframe", group = 'Demand Zone & Supply Zone')
mittigation_filt= 'wick' //input.string('Wicks', "Mitigation Method",options = ['Touch','Wicks','Close','Average'], group = 'Demand Zone & Supply Zone',inline = 'smc6')
overlapping_filt= true //input(false, 'Hide Overlap', inline = 'ob3', group = 'Order Blocks')
max_obs = input.int(8, 'Max OBs', minval = 3, group = 'Demand Zone & Supply Zone', inline = 'ob4')
length_extend_ob = input.int(defval = 20,title = "Length", minval = 0, maxval = 500 ,group = 'Demand Zone & Supply Zone', inline = "ob4")
ob_extend =false  //input.bool(false,"Extend",group = 'Demand Zone & Supply Zone', inline = "ob4")
text_size_ob_ = size.normal
ob_text_color_1 = color.new(#787b86, 0)
volume_text = false //input.bool(false, 'Volume', group='Order Blocks',inline = 'ob1_t')
percent_text = false //input.bool(false, 'Percentage', group='Order Blocks',inline = 'ob1_t')
show_line_ob_1 = false
line_style_ob_1 = line.style_solid


//Order flow
// mitatypeTouchof = input.string("Touch","Mitigation Type",options = ["Touch","Break"],group = "Order Flow") == "Touch"

showMajoinMiner = input.bool(false,"Show Major OF's",group = "Order Flow",inline = "mc")
showISOB = input.bool(true,"Show Minor OF's",group = "Order Flow",inline = "mc1")

showMajoinMinerMax = input.int(10," : Max Count",group = "Order Flow",inline = "mc")
showISOBMax = input.int(10," : Max Count",group = "Order Flow",inline = "mc1")

showTsted = input.bool(false,"Show Break ",inline = "tstd",group = "Order Flow")
maxTested = input.int(20,"OF's Count",inline = "tstd",group = "Order Flow")

ClrMajorOFBull = input.color(color.rgb(33, 149, 243, 71),"Major ORDER FLOW COLOR", group = "Order Flow",inline = "mj")
ClrMajorOFBear = input.color(color.rgb(33, 149, 243, 72),"", group = "Order Flow",inline = "mj")
ClrMinorOFBull = input.color(color.rgb(155, 39, 176, 81),"Minor ORDER FLOW COLOR", group = "Order Flow",inline = "mj1")
ClrMinorOFBear = input.color(color.rgb(155, 39, 176, 86),"", group = "Order Flow",inline = "mj1")
clrObBBTated = input.color(color.rgb(136, 142, 252, 86),"Major/Minor OB Tested", group = "Order Flow")


//Candle
showISB = input.bool(false, 'Inside Bar Candle', inline = "smc3", group = "Candle")
colorOSB_up = input.color(#0b3ff9,'',inline = 'smc3', group = "Candle")

showOSB = input.bool(false, 'Outside Bar Candle', inline = "smc4", group = "Candle")
colorOSB_down = input.color(#da781d,'', group = "Candle", inline = 'smc4')
colorISB = input.color(color.rgb(187, 6, 247, 77),'Inside Bar', group = "Candle")


//fvg
show_fvg = input(false, 'Fair Value Gaps (FVG)', group = 'Fair Value Gaps', inline = 'fvg_css')
i_tf = input.timeframe("", "Timeframe", group = 'Fair Value Gaps',inline = 'smc7')
max_width_fvg = 1.5
remove_small = true //input.bool(true,"Filter FVG",group = 'Fair Value Gaps', inline = "width")
mittigation_filt_fvg= input.string('Touch', 'Mitigation Method',options = ['Touch','Wicks','Close','Average'], group = 'Fair Value Gaps', inline = "smc7")
fvg_color_fill = true // input.bool(true,"Fill",group = 'Fair Value Gaps', inline = "mt")
fvg_shade_fill = false //input.bool(false,"Shade",group = 'Fair Value Gaps', inline = "mt")
max_fvg = input.int(defval = 8,title = ": No", minval = 0, maxval = 50 ,group = 'Fair Value Gaps', inline = 'fvg_css')
length_extend = input.int(defval = 20,title = "Length", minval = 0, maxval = 100 ,group = 'Fair Value Gaps', inline = "OS")
fvg_extend =false  //input.bool(false,"Extend",group = 'Fair Value Gaps', inline = "OS")
i_mtfbearishfvgcolor = input.color(color.yellow, "", group = 'Fair Value Gaps', inline = "fvg_css")
i_mtfbullishfvgcolor = input.color(color.yellow, "", group = 'Fair Value Gaps', inline = "fvg_css")
mid_style = 'Solid'
i_midPointColor = color.rgb(249, 250, 253, 99)
fvg_extend_B = true //input.bool(true,"Extend (Current)",group = 'Fair Value Gaps', inline = "mid")


//liquidity

liquidity_level_group = "Liquidity Levels"

currentTF  = input.bool(false, title = "Liquidity Levels", group=liquidity_level_group, inline="smc8")
displayLimit  = input.int(20, title = ": No", group=liquidity_level_group, inline="smc8")
lowLineColorHTF = input.color(#00bbf94d, "", group = liquidity_level_group, inline = "smc8")
highLineColorHTF = input.color(#e91e624d, "", group = liquidity_level_group, inline = "smc8")

htfTF  = input.timeframe("", title = "Timeframe", inline="smc9",group=liquidity_level_group)
_candleType  = input.string("Close", title = "Mitigation Method", options=["Close", "Wick"], group=liquidity_level_group,inline = 'smc9')

leftBars  = 20 //input.int(8, title = "Pivot Length", group=liquidity_level_group, inline="2")
mitiOptions  = 'Remove' //input.string("Remove", title = "Mitigated",  inline="3", options=["Remove", "Show"], group=liquidity_level_group)


length_extend_liq = input.int(defval = 20,title = "Length", minval = 0, maxval = 500 ,group = liquidity_level_group, inline = "smc10")
extentionMax = false //input.bool(false, title = "Extend", group=liquidity_level_group, inline="4")
_highLineStyleHTF  = "Solid"//input.string("Solid", title = "Line Style", options=["Solid", "Dashed", "Dotted"], group=liquidity_level_group,inline='5')
highLineStyleHTF = _highLineStyleHTF=="Solid" ? line.style_solid : _highLineStyleHTF=="Dashed" ? line.style_dashed : line.style_dotted
box_width  = 2.5//input.float(3.0, title = "Width", group=liquidity_level_group,inline='5', minval = 1, maxval = 10, step = 0.5)
lineWidthHTF=2

liquidity_text_color = input.color(color.black , 'Text Color', inline = 'smc10', group = liquidity_level_group)
highBoxBorderColorHTF = color.new(highLineColorHTF,90)
lowBoxBorderColorHTF = color.new(lowLineColorHTF,90)
displayStyle_liq  = "Boxes"//'Lines'





isOTE = input.bool(false,"Show OTE", inline = "ote", group = "Structure")
ote1 = input.float(0.78,"",inline = "ote",group = "Structure")
ote2 = input.float(0.61,"",inline = "ote",group = "Structure")
oteclr = input.color(#ff95002b,"",inline = "ote",group = "Structure")
 
sizGd = input.string(size.normal,"OTE Zone Size",options = [size.auto,size.tiny,size.small,size.normal,size.large,size.huge],group = "Structure")
// maxOTECount =  input.int(20, title="Max OTE Count", inline = "maxote", group="Structure")

showPdh = input.bool(false,"Show PDH", inline = "PDH", group = "Structure")
lengPdh = input.int(40, title="", inline = "PDH", group="Structure")
showPdl = input.bool(false,"Show PDL", inline = "PDL", group = "Structure")
lengPdl = input.int(40, title="", inline = "PDL", group="Structure")
showMid = input.bool(true, "Show Equilibrium", inline = "mid", group = "Structure")
lengMid = input.int(40, title="", inline = "mid", group="Structure")

showSw = input.bool(true, "Show Swing Sweep", inline = "sweep", group = "Structure")
markX = input.bool(false, 'Mark "X"', inline = "sweep", group = "Structure")
colorSweep  = input.color(color.gray, "", group = "Structure", inline = 'sweep')
showTP = false //input.bool(false, 'Show Target profit',group = 'Structure')
colorTP = color.new(color.purple, 0)  // 0 is full opacity


mergeRatio = 0.1  // Set a default value
maxBarHistory = 2000  // Default value to avoid errors









//#region variable declaration
//Constant
const string IDM_TEXT = "I D M"
const string CHOCH_TEXT = "CHoCH" 
const string BOS_TEXT = "B O S"
const string PDH_TEXT = "PDH"
const string PDL_TEXT = "PDL"
const string MID_TEXT = "0.5"

//line babel
var label idm_label = na
var line idm_line = na
var label choch_label = na
var line choch_line = na
var label bos_label = na
var line bos_line = na
var line pdh_line = na
var label pdh_label = na
var line pdl_line = na
var label pdl_label = na
var line mid_line = na
var line mid_line1 = na
var line mid_line2 = na
var label mid_label = na
var label mid_label1 = na
var label mid_label2 = na

//high low
var puHigh = high
var puLow = low
var puHigh_ = high
var puLow_ = low
var L = low
var H = high
var idmLow = low
var idmHigh = high
var lastH = high
var lastL = low
var H_lastH = high
var L_lastHH = low
var H_lastLL = high
var L_lastL = low
var motherHigh = high[1]
var motherLow = low[1]

//bar indexes
var int motherBar = time[1]
var int puBar = na
var int puHBar = na
var int puLBar = na
var int idmLBar = na
var int idmHBar = na
var int HBar = time
var int LBar = time
var int lastHBar = time
var int lastLBar = time

//structure confirm
var bool mnStrc = na
var bool prevMnStrc = na
var bool isPrevBos = na
var bool findIDM = false
var bool isBosUp = false
var bool isBosDn = false
var bool isCocUp = true
var bool isCocDn = true

//poi
var bool isSweepOBS = false
var int current_OBS = na
var float high_MOBS = na
var float low_MOBS = na

var bool isSweepOBD = false
var int current_OBD = na
var float low_MOBD = na
var float high_MOBD = na

//Array
var arrTopBotBar = array.new_int(1, time)
var arrTop = array.new_float(1, high)
var arrBot = array.new_float(1, low)

var arrPbHBar= array.new_int(0)
var arrPbHigh = array.new_float(0)
var arrPbLBar = array.new_int(0)
var arrPbLow = array.new_float(0)

var demandZone = array.new_box(0)
var supplyZone = array.new_box(0)
var supplyZoneIsMit = array.new_int(0)
var demandZoneIsMit = array.new_int(0)
var arrIdmHigh = array.new_float(0) 
var arrIdmLow = array.new_float(0) 
var arrIdmHBar = array.new_int(0) 
var arrIdmLBar = array.new_int(0) 
var arrLastH = array.new_float(0) 
var arrLastHBar = array.new_int(0) 
var arrLastL = array.new_float(0) 
var arrLastLBar = array.new_int(0) 
var arrIdmLine = array.new_line(0)
var arrIdmLabel = array.new_label(0)
var arrBCLine = array.new_line(0)
var arrBCLabel = array.new_label(0)
var arrHLLabel = array.new_label(0)
var arrHLCircle = array.new_label(0)

//color
color transp = color.new(color.gray,100)

//Caculate
curTf = timeframe.in_seconds(timeframe.period)
dayTf = timeframe.in_seconds("1D")
i_loop = 2*dayTf/curTf
[pdh, pdl]  = request.security(syminfo.tickerid, 'D', [high[1], low[1]])
len = curTf*1000

//#endregion

//#region Inside Bar
isb = motherHigh > high and motherLow < low
if isb
    motherHigh := motherHigh
    motherLow := motherLow
    motherBar := motherBar
else
    motherHigh := high
    motherLow := low
    motherBar := time

//#endregion

//#region drawing function
isGreenBar(int bar) => close[bar] > open[bar]

textCenter(int left, int right) => int(math.avg(left,right))

getStyleLabel(bool style) => style ? label.style_label_down : label.style_label_up

getStyleArrow(bool style) => style ? label.style_arrowdown : label.style_arrowup

getYloc(bool style) =>  style ? yloc.abovebar : yloc.belowbar

getDirection(bool trend, int HBar, int LBar, float H, float L) =>
    x = trend ? HBar : LBar
    y = trend ? H : L
    [x, y]

getTextLabel(float current, float last, string same, string diff) => current > last ? same : diff

getPdhlBar(float value) =>
    int x = na
    if value == pdh
        for i = i_loop to 1 by 1
            if (high[i] == pdh)
                x := time[i]
                break
    else
        for i = i_loop to 1 by 1
            if (low[i] == pdl)
                x := time[i]
                break
    x

updateTopBotValue() =>
    array.push(arrTop, high)
    array.push(arrBot, low) 
    array.push(arrTopBotBar, time) 

updateLastHLValue() =>
    array.push(arrLastH,lastH)
    array.push(arrLastHBar,lastHBar)
    array.push(arrLastL,lastL)
    array.push(arrLastLBar,lastLBar)

updateIdmHigh() =>
    array.push(arrIdmHigh,puHigh)
    array.push(arrIdmHBar,puHBar)

updateIdmLow() =>
    array.push(arrIdmLow,puLow)
    array.push(arrIdmLBar,puLBar)  

getNLastValue(arr, n) =>
    if array.size(arr) > n - 1
        array.get(arr, array.size(arr) - n) 

removeNLastLabel(arr, n) =>
    if array.size(arr) > n - 1
        label.delete(array.get(arr, array.size(arr) - n))

removeNLastLine(arr, n) =>
    if array.size(arr) > n - 1
        line.delete(array.get(arr, array.size(arr) - n))    

removeLastLabel(arr, n) =>
    if array.size(arr) > n - 1
        for i = 1 to n
            label.delete(array.get(arr, array.size(arr) - i))

removeLastLine(arr, n) =>
    if array.size(arr) > n - 1
        for i = 1 to n
            line.delete(array.get(arr, array.size(arr) - i))

var arrmitOBBulla = array.new_bool(0)
var arrmitOBBull = array.new_box(0)
// var arrmitOBBulli = array.new_int(0)
 
var arrmitOBBeara = array.new_bool(0)
var arrmitOBBear = array.new_box(0)
// var arrmitOBBeari = array.new_int(0)

if extndBox
    if arrmitOBBull.size() > 0
        i = 0 
        while i < arrmitOBBull.size()
            bx = arrmitOBBull.get(i)
            bx.set_right(time)
            if close > bx.get_top() and not arrmitOBBulla.get(i)
                arrmitOBBulla.set(i,true)
            if low < bx.get_top() and arrmitOBBulla.get(i)
                //bx.set_right(arrmitOBBulli.get(i))
                //arrmitOBBulli.remove(i)
                arrmitOBBull.remove(i)
                arrmitOBBulla.remove(i)
                i -= 1
            i += 1
    if arrmitOBBear.size() > 0
        i = 0 
        while i < arrmitOBBear.size()
            bx = arrmitOBBear.get(i)
            bx.set_right(time)
            if close < bx.get_bottom() and not arrmitOBBeara.get(i)
                arrmitOBBeara.set(i,true)
            if high > bx.get_bottom() and arrmitOBBeara.get(i)
                //bx.set_right(arrmitOBBeari.get(i))
                //arrmitOBBeari.remove(i)
                arrmitOBBear.remove(i)
                arrmitOBBeara.remove(i)
                i -= 1 
            i += 1
    

removeZone(zoneArray, box zone,zoneArrayisMit,isBull) =>
    index = array.indexof(zoneArray, zone)
    if not showBrkob
        box.delete(zone)
    else
        box.set_right(zone, time)
        box.set_extend(zone,extend.none) 
        // box.set_bgcolor(zone, colorMitigated)
        // box.set_border_color(zone, colorMitigated) 
        if not isBull
            arrmitOBBull.unshift(zone)
            // arrmitOBBulli.unshift(time)
            arrmitOBBulla.unshift(false)
        else
            arrmitOBBear.unshift(zone)
            // arrmitOBBeari.unshift(time)
            arrmitOBBeara.unshift(false)   
        
    array.remove(zoneArray, index)
    array.remove(zoneArrayisMit, index)

fixStrcAfterBos() =>
    removeLastLabel(arrBCLabel, 1)
    removeLastLine(arrBCLine, 1)
    removeLastLabel(arrIdmLabel, 1)
    removeLastLine(arrIdmLine, 1)
    removeLastLabel(arrHLLabel, 2)
    removeLastLabel(arrHLCircle, 2)

fixStrcAfterChoch() =>
    removeLastLabel(arrBCLabel, 2)
    removeLastLine(arrBCLine, 2)
    removeNLastLabel(arrHLLabel, 2)
    removeNLastLabel(arrHLLabel, 3)
    removeNLastLabel(arrHLCircle, 2)
    removeNLastLabel(arrHLCircle, 3)
    removeNLastLabel(arrIdmLabel, 2)
    removeNLastLine(arrIdmLine, 2)

var float lstHlPrs = na
var float lstHlPrsIdm = na
var box lstBxIdm = na

drawIDM(bool trend) =>
    [x, y] = getDirection(trend, idmLBar, idmHBar, idmLow, idmHigh)
    //label.new(bar_index,low)
    box lstBx_ = na
    if trend
        idx = -1
        float lstPrs = na
        if demandZone.size() > 0
            for i = 0 to demandZone.size() -1
                bx = demandZone.get(i)
                if demandZoneIsMit.get(i) == 0 and ((bx.get_top() > lstPrs) or na(lstPrs)) and bx.get_top() <= y  and bx.get_bottom() >= lstHlPrsIdm
                    idx := i
                    lstPrs := bx.get_top()
        if idx != -1
            lstBxIdm.set_text("Hist IDM OB")
            lstBx_ := demandZone.get(idx)
            if showIdmob
                demandZone.get(idx).set_text("IDM OB")
                demandZone.get(idx).set_text_color(clrtxtextbulliem)
                demandZone.get(idx).set_bgcolor(clrtxtextbulliembg)
                demandZoneIsMit.set(idx,1)
            else
                removeZone(demandZone,demandZone.get(idx),demandZoneIsMit,true)
    else
        idx = -1
        float lstPrs = na
        if supplyZone.size() > 0
            for i = 0 to supplyZone.size() -1
                bx = supplyZone.get(i)
                if supplyZoneIsMit.get(i) == 0 and ((bx.get_bottom() < lstPrs) or na(lstPrs)) and bx.get_bottom() >= y  and bx.get_top() <= lstHlPrsIdm
                    idx := i
                    lstPrs := bx.get_top()
        if idx != -1
            lstBxIdm.set_text("Hist IDM OB")
            lstBx_ := supplyZone.get(idx)
            if showIdmob
                supplyZone.get(idx).set_text("IDM OB")
                supplyZone.get(idx).set_text_color(clrtxtextbeariem)
                supplyZone.get(idx).set_bgcolor(clrtxtextbeariembg)
                supplyZoneIsMit.set(idx,1)
            else
                removeZone(supplyZone,supplyZone.get(idx),supplyZoneIsMit,false)


    colorText = trend and H_lastH > L_lastHH or not trend and H_lastLL > L_lastL ? color.red : colorIDM
    if showSMC
        ln = line.new(x, y, time, y, xloc.bar_time, color = colorIDM, style = line.style_dotted)
        lbl = label.new(textCenter(time, x), y, IDM_TEXT, xloc.bar_time, color = transp, textcolor = colorText, style = getStyleLabel(not trend), size = size.small)
        array.push(arrIdmLine,ln)
        array.push(arrIdmLabel,lbl)
    array.clear(trend ? arrIdmLow : arrIdmHigh)    
    array.clear(trend ? arrIdmLBar : arrIdmHBar) 

    lstBx_

var box lstBx = na
 
drawStructure(name, trend) =>
    [x, y] = getDirection(trend, lastHBar, lastLBar, lastH, lastL)
    box lstBx_ = na
    if trend
        // label.new(bar_index,lstHlPrs)
        // label.new(bar_index,y)  
        idx = -1
        float lstPrs = na
        if demandZone.size() > 0
            // var arrlx = array.new_label(0)
            // if arrlx.size() > 0
            //     while arrlx.size() > 0
            //         arrlx.pop().delete()
            for i = 0 to demandZone.size() -1
                bx = demandZone.get(i)
                // if demandZoneIsMit.get(i) == 0  and ((bx.get_top() < lstPrs) or na(lstPrs)) and bx.get_top() <= y
                //     arrlx.unshift(label.new(bar_index,bx.get_top(),color = color.green))
                if demandZoneIsMit.get(i) == 0 and ((bx.get_top() < lstPrs) or na(lstPrs)) and bx.get_top() <= y and bx.get_bottom() >= lstHlPrs
                    idx := i
                    lstPrs := bx.get_top()
        if idx != -1
            lstBx.set_text("Hist EXT OB")
            lstBx_ := demandZone.get(idx)
            if showExob
                demandZone.get(idx).set_text("EXT OB")
                demandZone.get(idx).set_text_color(clrtxtextbull)
                demandZone.get(idx).set_bgcolor(clrtxtextbullbg)
                demandZoneIsMit.set(idx,1)
            else
                removeZone(demandZone,demandZone.get(idx),demandZoneIsMit,true)

            //label.new(bar_index,demandZone.get(idx).get_top(),color = color.red)  
    else
        idx = -1
        float lstPrs = na
        if supplyZone.size() > 0
            for i = 0 to supplyZone.size() -1
                bx = supplyZone.get(i)
                if supplyZoneIsMit.get(i) == 0 and ((bx.get_top() > lstPrs) or na(lstPrs)) and bx.get_bottom() >= y  and bx.get_top() <= lstHlPrs
                    idx := i
                    lstPrs := bx.get_top()
        if idx != -1
            lstBx.set_text("Hist EXT OB")
            lstBx_ := supplyZone.get(idx)
            if showExob
                supplyZone.get(idx).set_text("EXT OB")
                supplyZone.get(idx).set_text_color(clrtxtextbear)
                supplyZone.get(idx).set_bgcolor(clrtxtextbearbg)
                supplyZoneIsMit.set(idx,1)
            else
                removeZone(supplyZone,supplyZone.get(idx),supplyZoneIsMit,false)
            

    color = trend ? bull : bear
    if name == "BOS" and showSMC
        ln = line.new(x, y, time, y, xloc.bar_time, color = color, style = line.style_dashed)
        lbl = label.new(textCenter(time, x), y, BOS_TEXT, xloc.bar_time, color = transp, style = getStyleLabel(trend), textcolor = color, size = size.small)
        array.push(arrBCLine,ln)
        array.push(arrBCLabel,lbl)
    if name == "ChoCh" and showSMC
        ln = line.new(x, y, time, y, xloc.bar_time, color = color, style = line.style_dashed)
        lbl = label.new(textCenter(time, x), y, CHOCH_TEXT, xloc.bar_time, color = transp, style = getStyleLabel(trend), textcolor = color, size = size.small)
        array.push(arrBCLine,ln)
        array.push(arrBCLabel,lbl)

    [lstHlPrs,lstBx_]

drawLiveStrc(bool condition, bool direction, color color1, color color2, string txt, int length, label lbl, line ln) =>
    var line _ln = ln
    var label _lbl = lbl
    if condition
        colorText = direction ? color1 : color2
        [x, y] = if txt == IDM_TEXT
            getDirection(direction, idmHBar, idmLBar, idmHigh, idmLow)
        else
            getDirection(direction, lastHBar, lastLBar, lastH, lastL)
        _txt = txt + " - " + str.tostring(y)
        _ln := line.new(x, y, time + len*length, y, xloc.bar_time, color = colorIDM, style = line.style_dotted),
        _lbl := label.new(time + len*length, y, _txt, xloc.bar_time, color = transp, textcolor = colorText, style = label.style_label_left, size = size.small)
    line.delete(_ln[1])
    label.delete(_lbl[1])

fibo_limit(ratio, range_high, range_low) =>
    range_1 = range_high - range_low
    range_ratio = range_high - range_1 * ratio
    range_ratio

drawPrevStrc(bool condition, string txt, label lbl, line ln,ote) =>
    var float val = na
    var int valiIdx = na
    var line _ln = ln
    var label _lbl = lbl
    idDirUP = lastLBar < lastHBar 
    [x, y, color, x2, style] = switch
        txt == PDH_TEXT => [getPdhlBar(pdh), pdh, bull, time + len*lengPdh, line.style_solid]
        txt == PDL_TEXT => [getPdhlBar(pdl), pdl, bear, time + len*lengPdl, line.style_solid]
        txt == MID_TEXT => [math.min(lastLBar, lastHBar), math.avg(lastL, lastH), colorIDM, time + len*lengMid, line.style_dotted]
        => [math.min(lastLBar, lastHBar), idDirUP ? fibo_limit(ote, lastH,lastL) : fibo_limit(ote, lastL, lastH), colorIDM, time + len, line.style_dotted]
    _txt = txt + " - " + str.tostring(y)
    if condition 
        val := y
        valiIdx := x
        _ln := line.new(x, y, x2, y, xloc.bar_time, color = color, style = style)
        if txt != ""
            _lbl := label.new(x2, y, _txt, xloc.bar_time, color = transp, textcolor = color, style = label.style_label_left, size = size.small)
    line.delete(_ln[1])
    label.delete(_lbl[1])
    [val,valiIdx,idDirUP]
    //_ln

var arrPrevPrsMin = array.new_float(1,0)
var arrPrevIdxMin = array.new_int(1,0)
 
var arrlstHigh = array.new_float(1,0)
var arrlstLow = array.new_float(1,0)
 
var arrOBTstdo = array.new_box(0)

var arrOBTstd = array.new_box(0)
var arrOBTstdTy = array.new_int(0)

i = 0 
while i < arrOBTstd.size()
    bx = arrOBTstd.get(i)
    if arrOBTstdTy.get(i) == 1 and low < bx.get_bottom()
        if showTsted
            arrOBTstdo.unshift(arrOBTstd.remove(i))
        else
            arrOBTstd.remove(i).delete()
        arrOBTstdTy.remove(i)
        i -=1
    else if arrOBTstdTy.get(i) == -1 and high > bx.get_top()
        if showTsted
            arrOBTstdo.unshift(arrOBTstd.remove(i))
        else
            arrOBTstd.remove(i).delete()
        arrOBTstdTy.remove(i)
        i -=1
    i += 1

if arrOBTstdo.size() > maxTested  
    arrOBTstdo.pop().delete()
 

var arrOBBullm = array.new_box(0)
var arrOBBearm = array.new_box(0)
var arrOBBullisVm = array.new_bool(0)
var arrOBBearisVm = array.new_bool(0)

var arrOBBulls = array.new_box(0)
var arrOBBears = array.new_box(0)
var arrOBBullisVs = array.new_bool(0)
var arrOBBearisVs = array.new_bool(0)


getProcess(arrOBBull,arrOBBear,arrOBBullisV,arrOBBearisV)=>    
    alertBullOf = false
    alertBearOf = false
    
    if arrOBBull.size() > 0
        i = 0 
        while i < arrOBBull.size() 
            bx = arrOBBull.get(i)
            bx.set_right(time)
            if not arrOBBullisV.get(i) 
                if low < bx.get_bottom()
                    bx.delete()
                    arrOBBull.remove(i)
                    arrOBBullisV.remove(i)
                    i -=1
                else if high > bx.get_top()
                    arrOBBullisV.set(i,true)
            else
                if low <  bx.get_top() and low[1] >  bx.get_top()
                    alertBullOf := true
                if low <  bx.get_top() 
                    bx.set_bgcolor(clrObBBTated)
                    bx.set_border_color(clrObBBTated)
                    //if showTsted
                    arrOBTstd.unshift(bx)
                    arrOBTstdTy.unshift(1)
                    //     if arrOBTstd.size() > maxTested
                    //         arrOBTstd.pop().delete()
                    // else
                    //     bx.delete()
                    arrOBBull.remove(i)
                    arrOBBullisV.remove(i)
                    i -=1
            i += 1
    if arrOBBear.size() > 0
        i = 0 
        while i < arrOBBear.size() 
            bx = arrOBBear.get(i)
            bx.set_right(time)
            if not arrOBBearisV.get(i) 
                if high > bx.get_top()
                    bx.delete()
                    arrOBBear.remove(i)
                    arrOBBearisV.remove(i)
                    i -=1
                else if low < bx.get_bottom()
                    arrOBBearisV.set(i,true)
            else
                if high > bx.get_bottom() and high[1] < bx.get_bottom()
                    alertBearOf := true
                if high >   bx.get_bottom() 
                    bx.set_bgcolor(clrObBBTated)
                    bx.set_border_color(clrObBBTated)
                    //if showTsted
                    arrOBTstd.unshift(bx)
                    arrOBTstdTy.unshift(-1)
                    //     if arrOBTstd.size() > maxTested
                    //         arrOBTstd.pop().delete()
                    // else
                    //     bx.delete()
                    arrOBBear.remove(i)
                    arrOBBearisV.remove(i)
                    i -=1
            i += 1

    [alertBullOf,alertBearOf]

[alertBullOfMajor,alertBearOfMajor] = getProcess(arrOBBullm,arrOBBearm,arrOBBullisVm,arrOBBearisVm)
[alertBullOfMinor,alertBearOfMinor] = getProcess(arrOBBulls,arrOBBears,arrOBBullisVs,arrOBBearisVs)

alertcondition(alertBullOfMajor,"Major Bullish order flow","Major Bullish order flow")
alertcondition(alertBearOfMajor,"Major Bearish order flow","Major Bearish order flow")
alertcondition(alertBullOfMinor,"Minor Bullish order flow","Minor Bullish order flow")
alertcondition(alertBearOfMinor,"Minor Bearish order flow","Minor Bearish order flow")
 
labelMn(bool trend) =>
    [x, y] = getDirection(trend, puHBar, puLBar, puHigh, puLow)
    color = trend ? bear : bull
    txt = trend ? getTextLabel(puHigh, arrlstHigh.get(0), "HH", "LH") : getTextLabel(puLow, arrlstLow.get(0), "HL", "LL")
    if showMn 
        label.new(x, y, "", xloc.bar_time, getYloc(trend), color, getStyleArrow(trend), size = size.tiny ,textcolor = color.red)
    
    if showISOB
        if txt == "HH" or txt == "LL" 
            arrPrevPrsMin.set(0,y)
            arrPrevIdxMin.set(0,x)
        if txt == "HL" or txt == "LH"
            if arrPrevPrsMin.get(0) != 0
                if txt == "HL"
                    arrOBBulls.unshift(box.new(arrPrevIdxMin.get(0),arrPrevPrsMin.get(0),x,y,bgcolor = ClrMinorOFBull,border_color = ClrMinorOFBull,xloc = xloc.bar_time))
                    arrOBBullisVs.unshift(false)
                    if arrOBBulls.size() > showISOBMax
                        arrOBBulls.pop().delete()
                        arrOBBullisVs.pop()

                else
                    arrOBBears.unshift(box.new(x,y,arrPrevIdxMin.get(0),arrPrevPrsMin.get(0),bgcolor = ClrMinorOFBear,border_color = ClrMinorOFBear,xloc = xloc.bar_time))
                    arrOBBearisVs.unshift(false)
                    if arrOBBears.size() > showISOBMax
                        arrOBBears.pop().delete()
                        arrOBBearisVs.pop()

                arrPrevPrsMin.set(0,0)
                arrPrevIdxMin.set(0,0)

    if trend
        arrlstHigh.set(0,y)
    else
        arrlstLow.set(0,y)

var arrPrevPrs = array.new_float(1,0)
var arrPrevIdx = array.new_int(1,0)

labelHL(bool trend) =>
    [x, y] = getDirection(trend, HBar, LBar, H, L)
    txt = trend ? getTextLabel(H, getNLastValue(arrLastH, 1), "HH", "LH") : getTextLabel(L, getNLastValue(arrLastL, 1), "HL", "LL")
    if showMajoinMiner
        if txt == "HH" or txt == "LL" 
            arrPrevPrs.set(0,y)
            arrPrevIdx.set(0,x)
        if txt == "HL" or txt == "LH"
            if arrPrevPrs.get(0) != 0
                if txt == "HL"
                    arrOBBullm.unshift(box.new(arrPrevIdx.get(0),arrPrevPrs.get(0),x,y,bgcolor = ClrMajorOFBull,border_color = ClrMajorOFBull,xloc = xloc.bar_time))
                    arrOBBullisVm.unshift(false)
                    if arrOBBullm.size() > showMajoinMinerMax
                        arrOBBullm.pop().delete()
                        arrOBBullisVm.pop()

                else
                    arrOBBearm.unshift(box.new(x,y,arrPrevIdx.get(0),arrPrevPrs.get(0),bgcolor = ClrMajorOFBear,border_color = ClrMajorOFBear,xloc = xloc.bar_time))
                    arrOBBearisVm.unshift(false)
                    if arrOBBearm.size() > showMajoinMinerMax
                        arrOBBearm.pop().delete()
                        arrOBBearisVm.pop()


                arrPrevPrs.set(0,0)
                arrPrevIdx.set(0,0)

  

    if showHL
        lbl = label.new(x, y, txt, xloc.bar_time, color = transp, textcolor = colorHL, style = getStyleLabel(trend))
        array.push(arrHLLabel, lbl)
    if showCircleHL
        lbl2 = label.new(x, y, '', xloc.bar_time, getYloc(trend), color = trend ? bull : bear, style = label.style_circle, size = size.tiny)     
        array.push(arrHLCircle, lbl2)
    y
sweepHL(bool trend) =>
    [x, y] = getDirection(trend, lastHBar, lastLBar, lastH, lastL)
    if showSw
        line.new(x, y, time, y, xloc.bar_time, color = colorSweep, style = line.style_dotted)
        if markX
            label.new(textCenter(time, x), y, "X", xloc.bar_time, color = transp, textcolor = colorSweep, style = getStyleLabel(trend), size = size.small)
 


TP(H, L) =>
    target = isCocUp ? high + math.abs(H - L) : low - math.abs(H - L)
    target := target < 0 ? 0 : target
    if showTP
        line.new(bar_index, isCocUp ? high : low, bar_index, target, color = colorTP, style = line.style_arrow_right)  

createBox(left, right, top, bottom, color) => 
    box.new(left=left, right=right, top=top, bottom=bottom, xloc = xloc.bar_time, bgcolor=color, border_color=color,text_color = color.new(color,20),text_halign = text.align_center ,extend = extend.none,text_size = txtsiz)

marginZone(zone) => [box.get_top(zone), box.get_bottom(zone), box.get_left(zone)]

handleZone(zoneArray,zoneArrayisMit, left, top, bot, color,isBull) =>
    _top = top
    _bot = bot
    _left = left    

    zone = getNLastValue(zoneArray, 1)
    //zmt = getNLastValue(zoneArrayisMit, 1)

    [topZone, botZone, leftZone] = marginZone(zone)
    rangeTop = math.abs(_top-topZone)/(topZone-botZone) < mergeRatio
    rangeBot = math.abs(_bot-botZone)/(topZone-botZone) < mergeRatio

    //Merge zone
    if _top >= topZone and _bot <= botZone or rangeTop or rangeBot
        _top := math.max(_top,topZone)
        _bot := math.min(_bot,botZone)
        _left := leftZone 
        removeZone(zoneArray, zone,zoneArrayisMit,isBull)    
         

    if not (_top <= topZone and _bot >= botZone)
        array.push(zoneArray, createBox(_left, time, _top, _bot, color))
        zoneArrayisMit.push(0)

 
processZones(zones, isSupply,zonesmit) =>
    isAlertextidm  = false
    if array.size(zones) > 0
        for i = array.size(zones) - 1 to 0 by 1
            zone = array.get(zones, i)
            if zonesmit.get(i) == 0 or zonesmit.get(i) == 1
                zone.set_right(time)
            [topZone, botZone, leftZone] = marginZone(zone)
            //isTouch =   (isSupply and high >= botZone and high < topZone) or (not isSupply and low <= topZone and low > botZone)
            //Breaker block zones
            if isSupply and low < botZone and close > topZone
                array.push(demandZone,createBox(leftZone, time, topZone, botZone, colorDemand))
                demandZoneIsMit.push(0)
            else if not isSupply and high > topZone and close < botZone
                array.push(supplyZone, createBox(leftZone, time, topZone, botZone, colorSupply))
                supplyZoneIsMit.push(0)
            //Mitigated zones
            else if (isSupply and high >= botZone and high[1] < botZone) or (not isSupply and low <= topZone and low[1] > topZone) //mitatypeTouch ? isTouch : (isSupply and high >= topZone and high[1] < topZone) or (not isSupply and low <= botZone and low[1] > botZone)
                box.set_right(zone, time)
                box.set_extend(zone,extend.none) 
                // box.set_bgcolor(zone, colorMitigated)
                // box.set_border_color(zone, colorMitigated) 

                if extndBox and high >= topZone and low <= botZone
                    if isSupply  
                        arrmitOBBull.unshift(zone)
                        // arrmitOBBulli.unshift(time)
                        arrmitOBBulla.unshift(false)
                    else 
                        arrmitOBBear.unshift(zone)
                        // arrmitOBBeari.unshift(time)
                        arrmitOBBeara.unshift(false)

                if isSupply
                    if  supplyZoneIsMit.get(i) == 1
                        isAlertextidm := true
                    if supplyZoneIsMit.get(i) != 1  
                        box.set_bgcolor(zone, colorMitigated)
                        box.set_border_color(zone, colorMitigated) 
                    supplyZoneIsMit.set(i, supplyZoneIsMit.get(i) == 1 ? 3 : 2)
                else
                    if  demandZoneIsMit.get(i) == 1
                        isAlertextidm := true
                    if demandZoneIsMit.get(i) != 1
                        box.set_bgcolor(zone, colorMitigated)
                        box.set_border_color(zone, colorMitigated) 
                    demandZoneIsMit.set(i, demandZoneIsMit.get(i) == 1 ? 3 : 2)

                if showBrkob
                    zones.remove(i) 
                    zonesmit.remove(i)

                // if not showBrkob
                //     zone.delete()
                    


            // //Delete sweep zones     
            else if (time - leftZone > len*maxBarHistory) or (isSupply and high >= topZone) or (not isSupply and low <= botZone)
                // box.set_bgcolor(zone, colorMitigated)
                // box.set_border_color(zone, colorMitigated)      
               
                removeZone(zones, zone,zonesmit,not isSupply)     
                      
            0

    isAlertextidm

scob(zones, isSupply) =>
    [topZone, botZone, leftZone] = marginZone(getNLastValue(zones, 1))

    if not isb[1]
        if not isSupply and low[1] < low[2] and low[1] < low and close > high[1] and low[1] < topZone and low[1] > botZone
            scobUp
        else if isSupply and high[1] > high[2] and high[1] > high and close < low[1] and high[1] < topZone and high[1] > botZone
            scobDn
        else
            na  
//#endregion

//#region get value from array
top = getNLastValue(arrTop, 1)
bot = getNLastValue(arrBot, 1)
topBotBar = getNLastValue(arrTopBotBar, 1)

top1 = getNLastValue(arrTop, 2)
bot1 = getNLastValue(arrBot, 2)
topBotBar1 = getNLastValue(arrTopBotBar, 2)
//#endregion

//#region Outside Bar
osb = high > top and low < bot

//#endregion

//#region Minor Structure
if high >= top and low <= bot //notrend
    if not na(mnStrc)
        prevMnStrc := mnStrc ? true : false
    else
        if prevMnStrc and isGreenBar(0) and not isGreenBar(1)
            puHigh := top
            puHigh_ := top
            puHBar := topBotBar
            labelMn(true)
            labelMn(false)
            if high > H
                updateIdmLow()   

        if not prevMnStrc and not isGreenBar(0) and isGreenBar(1)
            puLow := bot
            puLow_ := bot
            puLBar := topBotBar
            labelMn(true)
            labelMn(false)
            if low < L
                updateIdmHigh() 

    if low < L and isGreenBar(0)
        updateIdmHigh() 

    if high > H and not isGreenBar(0)
        updateIdmLow()   

    updateTopBotValue()   
    puHigh := high
    puHigh_ := high
    puLow := low
    puLow_ := low
    puHBar := time
    puLBar := time
    mnStrc := na

if high >= top and low > bot //uptrend
    if prevMnStrc and na(mnStrc)
        puHigh := top1
        puHigh_ := top1
        puHBar := topBotBar1
        labelMn(true)
        labelMn(false)
    else if (not prevMnStrc and na(mnStrc)) or not mnStrc
        labelMn(false)   

    if high > H
        updateIdmLow()   

    updateTopBotValue()  
    puHigh := high
    puHigh_ := high
    puHBar := time
    prevMnStrc := na
    mnStrc := true

if high < top and low <= bot //downtrend
    if not prevMnStrc and na(mnStrc)
        puLow := bot1
        puLow_ := bot1
        puLBar := topBotBar1
        labelMn(false)
        labelMn(true)
    else if (prevMnStrc and na(mnStrc)) or mnStrc
        labelMn(true)  

    if low < L
        updateIdmHigh() 
        
    updateTopBotValue()   
    puLow := low  
    puLow_ := low
    puLBar := time 
    prevMnStrc := na
    mnStrc := false
//#endregion

//#region update IDM
if high >= H
    H := high
    HBar := time
    L_lastHH := low  
    idmLow := getNLastValue(arrIdmLow, 1)
    idmLBar := getNLastValue(arrIdmLBar, 1)

if low <= L
    L := low
    LBar := time
    H_lastLL := high
    idmHigh := getNLastValue(arrIdmHigh, 1)
    idmHBar := getNLastValue(arrIdmHBar, 1)

//#endregion

// #region structure mapping
// Check for IDM
if findIDM and isCocUp and isCocUp
    if low < idmLow
        if structure_type == "Choch with IDM" and idmLow == lastL
            if isPrevBos
                fixStrcAfterBos() 
                lastL := getNLastValue(arrLastL, 1)    
                lastLBar := getNLastValue(arrLastLBar, 1)    
            else
                fixStrcAfterChoch()
        findIDM := false
        isBosUp := false
        lastH := H
        lastHBar := HBar
        lstHlPrs := labelHL(true) //Confirm HH
        lstBx_ = drawIDM(true)
        if not na(lstBx_)
            lstBxIdm := lstBx_
        updateLastHLValue()
        H_lastH := getNLastValue(arrLastH, 1)
        L := low
        LBar := time

if findIDM and isCocDn and isBosDn
    if high > idmHigh
        if structure_type == "Choch with IDM" and idmHigh == lastH
            if isPrevBos
                fixStrcAfterBos()
                lastH := getNLastValue(arrLastH, 1)    
                lastHBar := getNLastValue(arrLastHBar, 1)   
            else
                fixStrcAfterChoch()    
        findIDM := false
        isBosDn := false
        lastL := L
        lastLBar := LBar
        lstHlPrs := labelHL(false) //Confirm LL
        updateLastHLValue()
        lstBx_ = drawIDM(false) 
        if not na(lstBx_)
            lstBxIdm := lstBx_
        L_lastL := getNLastValue(arrLastL, 1)
        H := high
        HBar := time

//Check for ChoCh
 
if isCocDn and high > lastH
    if structure_type == "Choch without IDM" and idmHigh == lastH and close > idmHigh
        removeLastLabel(arrIdmLabel, 1)
        removeLastLine(arrIdmLine, 1)
    if close > lastH 
        [lstHlPrsIdm_,lstBx_] = drawStructure("ChoCh", true) //Confirm CocUp 
        lstHlPrsIdm := lstHlPrsIdm_
        if not na(lstBx_)
            lstBx := lstBx_
        findIDM := true
        isBosUp := true
        isCocUp := true
        isBosDn := false
        isCocDn := false
        isPrevBos := false
        L_lastL := getNLastValue(arrLastL, 1) 
        TP(lastH,lastL)
    else
        if idmHigh == lastH
            removeLastLine(arrIdmLine, 1)
        sweepHL(true)
 

if isCocUp and low < lastL
    if structure_type == "Choch without IDM" and idmLow == lastL and close < idmLow
        removeLastLabel(arrIdmLabel, 1)
        removeLastLine(arrIdmLine, 1)
    if close < lastL
        [lstHlPrsIdm_,lstBx_] = drawStructure("ChoCh", false)  //Confirm CocDn
        lstHlPrsIdm := lstHlPrsIdm_
        if not na(lstBx_)
            lstBx := lstBx_
        findIDM := true
        isBosUp := false
        isCocUp := false
        isBosDn := true
        isCocDn := true
        isPrevBos := false
        H_lastH := getNLastValue(arrLastH, 1)
        TP(lastH,lastL)
    else
        if idmLow == lastL
            removeLastLine(arrIdmLine, 1)
        sweepHL(false)
    //sweepHL(false)

//Check for BoS
if not findIDM and not isBosUp and isCocUp
    if high > lastH
        if close > lastH
            findIDM := true
            isBosUp := true
            isCocUp := true
            isBosDn := false
            isCocDn := false
            isPrevBos := true
            lstHlPrs := labelHL(false) //Confirm HL
            [lstHlPrsIdm_,lstBx_] = drawStructure("BOS", true)  //Confirm BosUp
            lstHlPrsIdm := lstHlPrsIdm_
            if not na(lstBx_)
                lstBx := lstBx_

            lastL := L
            lastLBar := LBar
            L_lastL := L
            TP(lastH,lastL)
        else
            sweepHL(true)
    
if not findIDM and not isBosDn and isCocDn 
    if low < lastL
        if close < lastL
            findIDM := true
            isBosUp := false
            isCocUp := false
            isBosDn := true
            isCocDn := true
            isPrevBos := true
            lstHlPrs := labelHL(true) //Confirm LH
            [lstHlPrsIdm_,lstBx_] = drawStructure("BOS", false)  //Confirm BosDn
            lstHlPrsIdm := lstHlPrsIdm_
            if not na(lstBx_)
                lstBx := lstBx_

            lastH := H
            lastHBar := HBar
            H_lastH := H
            TP(lastH,lastL)
        else
            sweepHL(false)
    
//#endregion

//#trigger update High and Low 
if high > lastH
    lastH := high
    lastHBar := time

if low < lastL
    lastL := low
    lastLBar := time

//#endregion
if showPOI
    if not isSweepOBS
        high_MOBS := high[3]
        low_MOBS := low[3]
        current_OBS := time[3]
        if high_MOBS > high[4] and high_MOBS > high[2]
            isSweepOBS := true
    else
        if low_MOBS > high[1]
            handleZone(supplyZone,supplyZoneIsMit, current_OBS, high_MOBS, low_MOBS, colorSupply,false)
            isSweepOBS := false
        else 
            if poi_type == "Mother Bar" and isb[2]
                high_MOBS := math.max(high_MOBS,motherHigh[2])
                low_MOBS := math.min(low_MOBS,motherLow[2])
                current_OBS := math.min(current_OBS,motherBar)    
            else
                high_MOBS := high[2]
                low_MOBS := low[2]
                current_OBS := time[2]        
            
    if not isSweepOBD
        low_MOBD := low[3]
        high_MOBD := high[3]
        current_OBD := time[3]
        if low_MOBD < low[4] and low_MOBD < low[2]
            isSweepOBD := true
    else
        if high_MOBD < low[1]
            handleZone(demandZone,demandZoneIsMit, current_OBD, high_MOBD, low_MOBD, colorDemand,true)
            isSweepOBD := false
        else 
            if poi_type == "Mother Bar" and isb[2]
                high_MOBD := math.max(high_MOBD,motherHigh[2])
                low_MOBD := math.min(low_MOBD,motherLow[2])
                current_OBD := math.min(current_OBD,motherBar)        
            else
                high_MOBD := high[2]
                low_MOBD := low[2]
                current_OBD := time[2]    
//#endregion

//#region run function
barcolor(showSCOB ? scob(supplyZone, true) : na, -1)
barcolor(showSCOB ? scob(demandZone, false) : na, -1)
barcolor(showISB and isb ? colorISB : na, 0,title="InSide Bar")
barcolor(osb and isGreenBar(0) and showOSB ? colorOSB_up : na)
barcolor(osb and not isGreenBar(0) and showOSB ? colorOSB_down : na) 
isAlertextidmSell = processZones(supplyZone, true,supplyZoneIsMit)
isAlertextidmBuy = processZones(demandZone, false,demandZoneIsMit)
drawLiveStrc(showSMC and findIDM, not isCocUp, colorIDM, colorIDM, IDM_TEXT,lengSMC , idm_label, idm_line)
drawLiveStrc(showSMC, not isCocUp, bull, bear, CHOCH_TEXT, lengSMC, choch_label, choch_line)
drawLiveStrc(showSMC and not findIDM, isCocUp, bull, bear, BOS_TEXT,lengSMC , bos_label, bos_line)
drawPrevStrc(showPdh, PDH_TEXT, pdh_label, pdh_line,0.0)
drawPrevStrc(showPdl, PDL_TEXT, pdl_label, pdl_line,0.0)
drawPrevStrc(showMid, MID_TEXT, mid_label, mid_line,0.0)
if isOTE
    // o1 = drawPrevStrc(true, "", mid_label1, mid_line1,ote1)
    // o2 = drawPrevStrc(true, "", mid_label2, mid_line2,ote2)
    // linefill.new(o1,o2,oteclr)
    // var arrOte = array.new_box(0)
    
    var box bxf = na
    bxf.set_right(time)
    var bxty  = 0
    minb = math.min(bxf.get_top(),bxf.get_bottom())
    maxb = math.max(bxf.get_top(),bxf.get_bottom())
    if not  na(bxf)
        // if bxty == 0 
        //     if high < minb  
        //         bxty := -1
        //     if low > maxb  
        //         bxty := 1
        if (bxty == 1 and low < minb) or (bxty == -1 and high > maxb)
            bxf.delete()
            bxf := na
            bxty := 0

     

    [ot,oi1,dir] = drawPrevStrc(true, "", mid_label1, mid_line1,ote1)
    [ob,_,_] = drawPrevStrc(true, "", mid_label2, mid_line2,ote2)
    if not na(oi1) and (bxty == 0 ? oi1 != oi1[1] : true)//and (oi1 != oi1[1] or na(ot[1] or ot != ot[1]))
        // if bxf.get_left() == oi1 and arrOte.size() > 0
        //     arrOte.get(0).delete()
        
        bxf.delete()
        bxf := box.new(oi1,ot,time,ob,xloc = xloc.bar_time,border_color = na,bgcolor = oteclr,text = "Golden zone",text_color = color.new(oteclr,20),text_halign = text.align_center,text_size = sizGd)
        // arrOte.unshift(bxf)
        // if arrOte.size() > maxOTECount  
        //     arrOte.pop().delete()
             
        bxty :=  dir ? 1 : -1 
  
alertcondition(isAlertextidmSell,"IDM EXT Alert Supply","IDM EXT Alert Supply")
alertcondition(isAlertextidmBuy,"IDM EXT Alert Demand","IDM EXT Alert Demand")

//#endregion

  



//2

//indicator(" SMC LEGEND 2 ",overlay = true, max_bars_back = 5000, max_lines_count = 500, max_boxes_count = 500, max_labels_count = 500)

//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------      Input Settings
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//----------------------------------------}
//Order Blocks
//----------------------------------------{



show_order_blocks_mtf = false
ibull_ob_css_2 = color.new(#5d606b, 25)
ibear_ob_css_2 = color.new(#5d606b, 25)
ob_type__mtf = 'All'
i_tf_ob_mtf = '240'

// mitigation_filt_mtf = input.string('Wicks', 'Mitigation Method', options = ['Touch','Wicks','Close','Average'], group = 'Order Blocks', inline = 'mob3')
mittigation_filt_mtf = 'Wicks'

overlapping_filt_mtf = true
max_obs_mtf = 4
length_extend_ob_mtf = 20
ob_extend_mtf = false
// v_filter = true
text_size_ob2 = "Medium"
text_size_ob_2 = text_size_ob2 == "Small" ? size.tiny : text_size_ob2 == "Medium" ? size.small : text_size_ob2 == "Large" ? size.normal : text_size_ob2 == "Medium2" ? size.normal : size.small
ob_text_color_2 = color.new(#787b86, 0)
volume_text_2 = false
percent_text_2 = false
show_line_ob_2 = false
line_style_ob2 = "Solid"
line_style_ob_2 = line_style_ob2 == "Solid" ? line.style_solid : line_style_ob2 == "Dashed" ? line.style_dashed : line.style_dotted



v_buy = #00dbff4d
v_sell = #e91e634d

tf_s1=i_tf_ob_mtf==''?timeframe.period:i_tf_ob_mtf
timeframe_st=not(str.contains(tf_s1,'S')) and not(str.contains(tf_s1,'D')) and not(str.contains(tf_s1,'W')) and not(str.contains(tf_s1,'M')) ? str.tonumber(tf_s1)>=60? str.tostring(str.tonumber(tf_s1)/60) +"H": tf_s1 +"M" : tf_s1

timeframe1=timeframe_st + ' : '
show_iob = ob_type__=='All' or ob_type__=='Internal' //input(true, 'Internal', inline = 'ob', group = 'Order Blocks')
show_ob = ob_type__=='All' or ob_type__=='External' //input(false, 'External', inline = 'ob', group = 'Order Blocks')
show_iob_mtf = ob_type__mtf=='All' or ob_type__mtf=='Internal' //input(true, 'Internal', inline = 'ob', group = 'Order Blocks')
show_ob_mtf = ob_type__mtf=='All' or ob_type__mtf=='External' //input(false, 'External', inline = 'ob', group = 'Order Blocks')
ob_showlast = 5//input.int(10, 'LookBack', minval = 1, inline = 'ob', group = 'Order Blocks')
iob_showlast = 5//input.int(5, 'LookBack', minval = 1, inline = 'iob', group = 'Order Blocks')
max_width_ob = 3//input.float(3, 'Max OB Width', minval = 0.1,maxval = 3, inline = 'close', group = 'Order Blocks')
max_width_ob:=max_width_ob==3?20:max_width_ob

style = 'Colored'
v_lookback= 10
ob_loockback=10
timediff=(time[1]-time[101])/100

//----------------------------------------}
//BOS and MSS
//----------------------------------------{

// Constants
color CLEAR = color.rgb(0,0,0,100)

// Inputs
showms=input(false,title="ICT Market Structure ",inline="0",group = "Market Structure")
bosColor1 = input.color(color.green , '', group="Market Structure",inline="0")
bosColor2 = input.color(color.red , '', group="Market Structure",inline="0")
ms_type =input.string("All", options=["All", "External","Internal"], title="", group="Market Structure",inline="0")
show_equal_highlow = input(false, 'Equal Highs & Lows', group = 'Market Structure',inline = 'equilibrium_zone')
eq_bear_color = input.color(#787b86 , '', group="Market Structure",inline="equilibrium_zone")
eq_bull_color = input.color(#787b86 , '', group="Market Structure",inline="equilibrium_zone")
eq_threshold = input.float(0.3, '', minval = 0, maxval = 0.5, step = 0.1, group = 'Market Structure',inline = 'equilibrium_zone')
showSwing = false           // or false, depending on default behavior
swingSize = 10              // fixed swing point period
label_sizes_s = "Medium"    // fixed label size: "Small", "Medium", or "Large"

label_size_buysell_s = label_sizes_s == "Small" ? size.tiny : label_sizes_s == "Medium" ? size.small : label_sizes_s == "Large" ? size.normal : label_sizes_s == "Medium2" ? size.normal : label_sizes_s == "Large2" ? size.large : size.huge
label_size_buysell = label_sizes_s == "Small" ? size.tiny : label_sizes_s == "Medium" ? size.small : label_sizes_s == "Large" ? size.normal : label_sizes_s == "Medium2" ? size.normal : label_sizes_s == "Large2" ? size.large : size.huge



length_eqh = 3

//----------------------------------------}
//Fair Value Gaps (FVG
//----------------------------------------{



i_bullishfvgcolor = color.new(color.green,100)
i_bearishfvgcolor = color.new(color.green,90)
i_fillByMid = true
i_deleteonfill = true
i_textColor = color.white
i_mtf = "HTF"
i_tfos = 10
i_mtfos = 50
//----------------------------------------}
//Liquidity Levels
//----------------------------------------{


//----------------------------------------}
//Key Levels
//----------------------------------------{
var Show_4H_Levels = input.bool(defval=false, title='4H', group='Key Levels', inline='4H')
Color_4H_Levels = input.color(title='', defval=color.orange, group='Key Levels', inline='4H')
Style_4H_Levels = 'Dotted' //input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group="Key Levels",inline="4H")
Text_4H_Levels = true//input.bool(defval=false, title='Shorten', group='Key Levels', inline='4H')

var Show_Daily_Levels = input.bool(defval=false, title='Daily', group='Key Levels', inline='Daily')
Color_Daily_Levels = input.color(title='', defval=#08bcd4, group='Key Levels', inline='Daily')
Style_Daily_Levels ='Dotted'//input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group="Key Levels",inline="Daily")
Text_Daily_Levels =true //input.bool(defval=false, title='Shorten', group='Key Levels', inline='Daily')

var Show_Monday_Levels = input.bool(defval=false, title='Monday', group='Key Levels', inline='Monday')
Color_Monday_Levels = input.color(title='', defval=color.white, group='Key Levels', inline='Monday')
Style_Monday_Levels = 'Dotted' //input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group="Key Levels",inline="Monday")
Text_Monday_Levels =true // input.bool(defval=false, title='Shorten', group='Key Levels', inline='Monday')

var Show_Weekly_Levels = input.bool(defval=false, title='Weekly', group='Key Levels', inline='Weekly')
WeeklyColor = input.color(title='', defval=#fffcbc, group='Key Levels', inline='Weekly')
Weekly_style ='Dotted'  //input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group="Key Levels",inline="Weekly")
WeeklyTextType =true // input.bool(defval=false, title='Shorten', group='Key Levels', inline='Weekly')

var Show_Monthly_Levels = input.bool(defval=false, title='Monthly', group='Key Levels', inline='Monthly')
MonthlyColor = input.color(title='', defval=#098c30, group='Key Levels', inline='Monthly')
Monthly_style = 'Dotted' //input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group="Key Levels",inline="Monthly")
MonthlyTextType = true //input.bool(defval=false, title='Shorten', group='Key Levels', inline='Monthly')

var Show_Quaterly_Levels = input.bool(defval=false, title='Quarterly', group='Key Levels', inline='Quarterly')
quarterlyColor = input.color(title='', defval=#bcffd0, group='Key Levels', inline='Quarterly')
Quaterly_style = 'Dotted'//input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group="Key Levels",inline="Quarterly")
QuarterlyTextType =true // input.bool(defval=false, title='Shorten', group='Key Levels', inline='Quarterly')

var Show_Yearly_Levels = input.bool(defval=false, title='Yearly', group='Key Levels', inline='Yearly')
YearlyColor = input.color(title='', defval=#ffbcdb, group='Key Levels', inline='Yearly')
Yearly_style = 'Dotted' //input.string('Dotted', '  Style', ['Solid', 'Dashed', 'Dotted'], group="Key Levels",inline="Yearly")
YearlyTextType = true //input.bool(defval=false, title='Shorten', group='Key Levels', inline='Yearly')

labelsize = 'Small' //input.string(defval='Small', title='Text Size', options=['Small', 'Medium', 'Large'],group = "Key Levels", inline='H')

var pdhtext = Text_Daily_Levels ? 'PDH' : 'Prev Day High'
var pdltext = Text_Daily_Levels ? 'PDL' : 'Prev Day Low'
var dotext =  Text_Daily_Levels ? 'DO' : 'Daily Open'
var pdmtext = Text_Daily_Levels ? 'PDM' : 'Prev Day Mid'
var pwhtext = WeeklyTextType ? 'PWH' : 'Prev Week High'
var pwltext = WeeklyTextType ? 'PWL' : 'Prev Week Low'
var wotext =  WeeklyTextType ? 'WO' : 'Weekly Open'
var pwmtext = WeeklyTextType ? 'PWM' : 'Prev Week Mid'
var pmhtext = MonthlyTextType ? 'PMH' : 'Prev Month High'
var pmltext = MonthlyTextType ? 'PML' : 'Prev Month Low'
var motext =  MonthlyTextType ? 'MO' : 'Monthly Open'
var pmmtext = MonthlyTextType ? 'PMM' : 'Prev Month Mid'
var pqhtext = QuarterlyTextType ? 'PQH' : 'Prev Quarter High'
var pqltext = QuarterlyTextType ? 'PQL' : 'Prev Quarter Low'
var qotext =  QuarterlyTextType ? 'QO' : 'Quarterly Open'
var pqmtext = QuarterlyTextType ? 'PQM' : 'Prev Quarter Mid'
var cyhtext = YearlyTextType ? 'CYH' : 'Current Year High'
var cyltext = YearlyTextType ? 'CYL' : 'Current Year Low'
var yotext =  YearlyTextType ? 'YO' : 'Yearly Open'
var cymtext = YearlyTextType ? 'CYM' : 'Current Year Mid'
var pihtext = Text_4H_Levels ? 'P-4H-H' : 'Prev 4H High'
var piltext = Text_4H_Levels ? 'P-4H-L' : 'Prev 4H Low'
var iotext =  Text_4H_Levels ? '4H-O' : '4H Open'
var pimtext = Text_4H_Levels ? 'P-4H-M' : 'Prev 4H Mid'
var pmonhtext = Text_Monday_Levels ? 'MDAY-H' : 'Monday High'
var pmonltext = Text_Monday_Levels ? 'MDAY-L' : 'Monday Low'
var pmonmtext = Text_Monday_Levels ? 'MDAY-M' : 'Monday Mid'

displayStyle = 'Standard'
distanceright = 25
radistance = 250
linesize = 'Small'
linestyle = 'Solid'
var untested_monday = false

//----------------------------------------}
//Session Levels
//----------------------------------------{


var is_londonrange_enabled = input.bool(defval=false, title='London', group='Session Levels', inline='london')
var london_OC = true//input.bool(defval=true, title='O/C', group='Session Levels', inline='london')
var london_HL =true// input.bool(defval=true, title='H/L', group='Session Levels', inline='london')
var is_usrange_enabled = input.bool(defval=false, title='New York', group='Session Levels', inline='US')
var us_OC =true //input.bool(defval=true, title='O/C', group='Session Levels', inline='US')
var us_HL = true//input.bool(defval=true, title='H/L', group='Session Levels', inline='US')
var is_tokyorange_enabled = input.bool(defval=false, title='Tokyo', group='Session Levels', inline='asia')
var asia_OC = true//input.bool(defval=true, title='O/C', group='Session Levels', inline='asia')
var asia_HL = true//input.bool(defval=true, title='H/L', group='Session Levels', inline='asia')
SessionTextType = false//input.bool(defval=false, title='ShortHand', group='Sessions', inline='FXColor')

Londont = "0800-1600"
USt = "1400-2100"
Asiat = "0000-0900"

LondonColor = input.color(title='', defval=color.rgb(15, 13, 13), group='Session Levels', inline='london')
USColor = input.color(title='', defval=color.rgb(190, 8, 236), group='Session Levels', inline='US')
AsiaColor = input.color(title='', defval=color.rgb(33, 5, 241), group='Session Levels', inline='asia')

Short_text_London = true//input.bool(defval=false, title='Shorten', group='Session Levels', inline='london')
Short_text_NY =true// input.bool(defval=false, title='Shorten', group='Session Levels', inline='US')
Short_text_TKY = true//input.bool(defval=false, title='Shorten', group='Session Levels', inline='asia')

var London_high_text = Short_text_London ? 'Lon-H' : 'London High'
var London_low_text = Short_text_London ? 'Lon-L' : 'London Low'
var London_open_text = Short_text_London ? 'Lon-O' : 'London Open'

var NY_high_text = Short_text_NY ? 'NY-H' : 'New York High'
var NY_low_text = Short_text_NY ? 'NY-L' : 'New York Low'
var NY_open_text = Short_text_NY ? 'NY-O' : 'New York Open'

var Tokyo_high_text = Short_text_TKY ? 'TK-H' : 'Tokyo High'
var Tokyo_low_text = Short_text_TKY ? 'TK-L' : 'Tokyo Low'
var Tokyo_open_text = Short_text_TKY ? 'TK-O' : 'Tokyo Open'


//-----------------------------------------------------------------------------}
//Global variables
//-----------------------------------------------------------------------------{
color transparent = #ffffff00
length = 50
is_newbar(res) =>
    t = time(res)
    not na(t) and (na(t[1]) or t > t[1])

Show_MS(x, y, txt, css, dashed, down, lbl_size)=>
    label.new(int(math.avg(x, bar_index)), y, txt, color = transparent, textcolor = css, style = down ? label.style_label_down : label.style_label_up, size = lbl_size)
    line.new(x, y, bar_index, y, color = css, style = dashed ? line.style_dashed : line.style_solid)

f_barssince(_cond, _count) =>
    _barssince = bar_index - ta.valuewhen(_cond, bar_index, _count)
    _barssince

//Swings detection/measurements
calculate_swing_points(length)=>
    var prev = 0
    prev := high[length] > ta.highest(length) ? 0 : low[length] < ta.lowest(length) ? 1 : prev[1]
    t = prev == 0 and prev[1] != 0 ? high[length] : 0
    b = prev == 1 and prev[1] != 1 ? low[length] : 0
    [t, b]

var t_MS = 0, var int_t_MS = 0
var internal_y_up = 0., var internal_x_up = 0, var internal_y_dn = 0., var internal_x_dn = 0
var y_up = 0., var x_up = 0 , var y_dn = 0., var x_dn = 0
var crossed_up = true,  var crossed_down = true
var internal_up_broke = true, var internal_dn_broke = true
var up_trailing = high, var down_trailing = low
var up_trailing_x = 0,  var down_trailing_x = 0
var high_text = '',  var low_text = ''
bullish_OB_Break = false 
bearish_OB_Break = false


//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------       Market Structure
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------



bosConfType = 'Candle High'//input.string('Candle Close', 'BOS Confirmation', ['Candle Close', 'Wicks'], tooltip='Choose whether candle close/wick above previous swing point counts as a BOS.')
MSS = true//input.bool(false, 'Show MSS', tooltip='Renames the first counter t_MS BOS to MSS' )
// showSwing = false//input.bool(true, 'Show Swing Points', tooltip='Show or hide HH, LH, HL, LL')

// Functions
lineStyle(x) =>
    switch x
        'Solid' => line.style_solid
        'Dashed' => line.style_dashed
        'Dotted' => line.style_dotted
pivot_high_found = ta.pivothigh(high, swingSize, swingSize)
pivot_low_found  = ta.pivotlow(low, swingSize, swingSize)



var float prevHigh_s = na,var float prevLow_s = na,var int prevHighIndex_s = na,var int prevLowIndex_s = na
bool higher_highs = false, bool lower_highs = false, bool higher_lows = false, bool lower_lows = false

var int prevSwing_s = 0

if not na(pivot_high_found)
    if pivot_high_found >= prevHigh_s
        higher_highs := true
        prevSwing_s := 2
    else
        lower_highs := true
        prevSwing_s := 1
    prevHigh_s := pivot_high_found
    prevHighIndex_s := bar_index - swingSize


if not na(pivot_low_found)
    if pivot_low_found >= prevLow_s
        higher_lows := true
        prevSwing_s := -1
    else
        lower_lows := true
        prevSwing_s := -2
    prevLow_s := pivot_low_found
    prevLowIndex_s := bar_index - swingSize




//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------       Fair Value Gaps
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

// }

// ———————————————————— Global data {
//Using current bar data for HTF highs and lows instead of security to prevent future leaking
var htfH = open
var htfL = open

if close > htfH 
    htfH:= close
if close < htfL
    htfL := close


//Security Data, used for HTF Bar Data reference


sClose = request.security(ticker.standard(syminfo.tickerid), i_tf, close[1], barmerge.gaps_off, barmerge.lookahead_on)
sHighP2 = request.security(ticker.standard(syminfo.tickerid), i_tf, high[2], barmerge.gaps_off, barmerge.lookahead_on)
sLowP2 = request.security(ticker.standard(syminfo.tickerid), i_tf, low[2], barmerge.gaps_off, barmerge.lookahead_on)
sOpen = request.security(ticker.standard(syminfo.tickerid), i_tf, open[1], barmerge.gaps_off, barmerge.lookahead_on)
sBar = request.security(ticker.standard(syminfo.tickerid), i_tf, bar_index, barmerge.gaps_off, barmerge.lookahead_on)

// }

//var keyword can be used to hold data in memory, with pinescript all data is lost including variables unless the var keyword is used to preserve this data
var bullishgapholder = array.new_box(0)
var bearishgapholder = array.new_box(0)

var bullishgapholder_fill = array.new_box(0)
var bearishgapholder_fill = array.new_box(0)

var bullish_high_holder = array.new_line(0)
var bearish_high_holder = array.new_line(0)
var bullish_low_holder = array.new_line(0)
var bearish_low_holder = array.new_line(0)
var bullishmidholder = array.new_line(0)
var bearishmidholder = array.new_line(0)
var bullishlabelholder = array.new_label(0)
var bearishlabelholder = array.new_label(0)
var transparentcolor = color.new(color.white,100)

var fvg_apper=false
var fvg_break=false


fvg_apper:=false
fvg_break:=false
// ———————————————————— Functions {

//function paramaters best declared with '_' this helps defer from variables in the function scope declaration and elsewhere e.g. close => _close
create_fvg_func(_upperlimit,_lowerlimit,_midlimit,_bar,_boxholder,_boxholder_fill,_midholder,_highholder,_lowholder,_labelholder,_boxcolor,_mtfboxcolor, _htf)=>
    timeholder = str.tostring(i_tf)
    offset = i_mtfos
    boxbgcolor = _mtfboxcolor
    bg_color = color.new(_mtfboxcolor,90)
    if _htf == false
        timeholder := str.tostring(timeframe.period)
        offset := i_tfos
        boxbgcolor := _boxcolor
    array.push(_boxholder,box.new(_bar,_upperlimit,_bar+(timediff)*length_extend,_lowerlimit,border_color=fvg_color_fill? bg_color : na,bgcolor = fvg_color_fill? bg_color : na, extend = fvg_extend ? extend.right:extend.none,xloc = xloc.bar_time,text='',text_color=#787b86,text_halign=text.align_right,text_size=size.small))
    array.push(_boxholder_fill,box.new(_bar,_upperlimit,_bar+(timediff)*length_extend,_lowerlimit,border_color=fvg_color_fill? bg_color : na ,bgcolor = fvg_color_fill? bg_color : na, extend = fvg_extend ? extend.right:extend.none,xloc = xloc.bar_time))
    array.push(_midholder,line.new(_bar,(_lowerlimit+_upperlimit)/2.0,_bar+(timediff)*length_extend,_midlimit,color = i_midPointColor, extend = fvg_extend ? extend.right:extend.none,style=lineStyle(mid_style),width=1,xloc = xloc.bar_time))
    array.push(_lowholder,line.new(_bar,_lowerlimit,_bar+(timediff)*length_extend,_lowerlimit,color = i_fillByMid?boxbgcolor:na, extend = fvg_extend ? extend.right:extend.none,width=1,xloc = xloc.bar_time))
    array.push(_highholder,line.new(_bar,_upperlimit,_bar+(timediff)*length_extend,_upperlimit,color = i_fillByMid?boxbgcolor:na, extend = fvg_extend ? extend.right:extend.none,width=1,xloc = xloc.bar_time))


//checks for gap between current candle and 2 previous candle e.g. low of current candle and high of the candle before last, this is the fair value gap.
check_fvg_func(_close,_high,_highp2,_low,_lowp2,_open,_bar,_htf)=>
    gap=0
    thold_ = (ta.highest(_high,300) - ta.lowest(_low,300)) * math.max(max_width_fvg, 0.1) / 100.
    if _open > _close // red

        if _lowp2>_high
            if not(remove_small) or math.abs(_lowp2 -_high) > thold_
                upperlimit = _high//_close - (_close - _lowp2 )
                lowerlimit = _lowp2//_close - (_close-_high)
                midlimit = lowerlimit + ((upperlimit - lowerlimit) / 2.)
                gap:=1
                create_fvg_func(upperlimit,lowerlimit,midlimit,_bar,bullishgapholder,bullishgapholder_fill,bullishmidholder,bullish_high_holder,bullish_low_holder,bullishlabelholder,i_bullishfvgcolor,i_mtfbullishfvgcolor,_htf)
            
    else
        
        if _low>_highp2
            if not(remove_small) or math.abs(_low - _highp2) > thold_
                upperlimit = _low//_close - (_close-_low)
                lowerlimit = _highp2//_close- (_close - _highp2),
                midlimit = lowerlimit + ((upperlimit - lowerlimit) / 2.)
                gap:=-1
                create_fvg_func(upperlimit,lowerlimit,midlimit,_bar,bearishgapholder,bearishgapholder_fill,bearishmidholder,bearish_high_holder,bearish_low_holder,bearishlabelholder,i_bearishfvgcolor,i_mtfbearishfvgcolor,_htf)
            
    gap

//Used to remove the gap from its relevant array as a result of it being filled.
delete_fvg_func(_currentgap,_currentgap_fill,_i,_boxholder,_boxholder_fill,_midholder,_highholder,_lowholder,_labelholder)=>
   
    array.remove(_boxholder,_i)
    array.remove(_boxholder_fill,_i)

    currentmid=array.get(_midholder,_i)
    currenthigh=array.get(_highholder,_i)
    currentlow=array.get(_lowholder,_i)
    array.remove(_midholder,_i)
    array.remove(_highholder,_i)
    array.remove(_lowholder,_i)
    
    if i_deleteonfill
        line.delete(currentmid)
        line.delete(currenthigh)
        line.delete(currentlow)
    else
        line.set_extend(currentmid, extend.none)
        line.set_x2(currentmid,time)
        line.set_extend(currenthigh, extend.none)
        line.set_x2(currenthigh,time)
        line.set_extend(currentlow, extend.none)
        line.set_x2(currentlow,time)

    if i_deleteonfill
        box.delete(_currentgap)
        box.delete(_currentgap_fill)
        
        
    else
        box.set_extend(_currentgap,extend.none)
        box.set_right(_currentgap,time)


//checks if gap has been filled either by 0.5 fill (i_fillByMid) or SHRINKS the gap to reflect the true value gap left.
validate_fvg_func(_high,_low)=>

    fvg_removed=0
    if array.size(bullishgapholder) > 0

        for i = array.size(bullishgapholder)-1 to 0
            if fvg_extend_B
                currentgap_fill = array.get(bullishgapholder_fill,i)
                currentgap = array.get(bullishgapholder,i)
                cmid = array.get(bullishmidholder,i)
                chigh = array.get(bullish_high_holder,i)
                clow = array.get(bullish_low_holder,i)
                line.set_x2(cmid,timenow+(timediff)*length_extend)
                line.set_x2(chigh,timenow+(timediff)*length_extend)
                line.set_x2(clow,timenow+(timediff)*length_extend)
                box.set_right(currentgap_fill,timenow+(timediff)*length_extend)
                box.set_right(currentgap,timenow+(timediff)*length_extend)

            if mittigation_filt_fvg=='Touch'
                currentgap_fill = array.get(bullishgapholder_fill,i)
                currentgap = array.get(bullishgapholder,i)
                currentmid = array.get(bullishmidholder,i)
                currenthigh = array.get(bullish_high_holder,i)
                currentlow = array.get(bullish_low_holder,i)
                currenttop = box.get_top(currentgap)

                if high > currenttop
                    fvg_removed:=1
                    delete_fvg_func(currentgap,currentgap_fill,i,bullishgapholder,bullishgapholder_fill,bullishmidholder,bullish_high_holder,bullish_low_holder,bullishlabelholder)
            
            if mittigation_filt_fvg=='Wicks'
                currentgap_fill = array.get(bullishgapholder_fill,i)
                currentgap = array.get(bullishgapholder,i)
                currentmid = array.get(bullishmidholder,i)
                currenthigh = array.get(bullish_high_holder,i)
                currentlow = array.get(bullish_low_holder,i)
                currenttop = box.get_bottom(currentgap)
                currentbottom = box.get_top(currentgap_fill)

                if high > currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bullishgapholder_fill,i)
                    cur_bottom=box.get_bottom(currentgap_f)
                    _bottom=box.get_bottom(currentgap)
                    if _bottom==cur_bottom
                        box.set_bottom(currentgap_f,high)
                    else
                        box.set_bottom(currentgap_f,math.max(cur_bottom,high))
                    box.set_bgcolor(currentgap_f,#787b865e)
                    
                if high > currenttop
                    fvg_removed:=1
                    delete_fvg_func(currentgap,currentgap_fill,i,bullishgapholder,bullishgapholder_fill,bullishmidholder,bullish_high_holder,bullish_low_holder,bullishlabelholder)
            
            if mittigation_filt_fvg=='Close'
                currentgap_fill = array.get(bullishgapholder_fill,i)
                currentgap = array.get(bullishgapholder,i)
                currentmid = array.get(bullishmidholder,i)
                currenthigh = array.get(bullish_high_holder,i)
                currentlow = array.get(bullish_low_holder,i)
                currenttop = box.get_bottom(currentgap)
                currentbottom = box.get_top(currentgap_fill)

                if high > currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bullishgapholder_fill,i)
                    cur_bottom=box.get_bottom(currentgap_f)
                    _bottom=box.get_bottom(currentgap)
                    if _bottom==cur_bottom
                        box.set_bottom(currentgap_f,high)
                    else
                        box.set_bottom(currentgap_f,math.max(cur_bottom,high))
                    box.set_bgcolor(currentgap_f,#787b865e)
                if close > currenttop
                    fvg_removed:=1
                    delete_fvg_func(currentgap,currentgap_fill,i,bullishgapholder,bullishgapholder_fill,bullishmidholder,bullish_high_holder,bullish_low_holder,bullishlabelholder)

            if mittigation_filt_fvg=='Average'
                currentgap_fill = array.get(bullishgapholder_fill,i)
                currentgap = array.get(bullishgapholder,i)
                currentmid = array.get(bullishmidholder,i)
                currenthigh = array.get(bullish_high_holder,i)
                currentlow = array.get(bullish_low_holder,i)
                currenttop = line.get_y1(currentmid)
                currentbottom = box.get_top(currentgap_fill)

                if high > currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bullishgapholder_fill,i)
                    cur_bottom=box.get_bottom(currentgap_f)
                    _bottom=box.get_bottom(currentgap)
                    if _bottom==cur_bottom
                        box.set_bottom(currentgap_f,high)
                    else
                        box.set_bottom(currentgap_f,math.max(cur_bottom,high))
                    box.set_bgcolor(currentgap_f,#787b865e)

                if high > currenttop
                    fvg_removed:=1
                    delete_fvg_func(currentgap,currentgap_fill,i,bullishgapholder,bullishgapholder_fill,bullishmidholder,bullish_high_holder,bullish_low_holder,bullishlabelholder)

       
    if array.size(bearishgapholder) > 0
            
        for i = array.size(bearishgapholder)-1 to 0
            if fvg_extend_B
                currentgap_fill = array.get(bearishgapholder_fill,i)
                currentgap = array.get(bearishgapholder,i)
                cmid = array.get(bearishmidholder,i)
                chigh = array.get(bearish_high_holder,i)
                clow = array.get(bearish_low_holder,i)
                line.set_x2(cmid,timenow+(timediff)*length_extend)
                line.set_x2(chigh,timenow+(timediff)*length_extend)
                line.set_x2(clow,timenow+(timediff)*length_extend)
                box.set_right(currentgap_fill,timenow+(timediff)*length_extend)
                box.set_right(currentgap,timenow+(timediff)*length_extend)

            if mittigation_filt_fvg=='Touch'
                currentgap_fill = array.get(bearishgapholder_fill,i)
                currentgap = array.get(bearishgapholder,i)
                currenttop = box.get_top(currentgap)
                currentmid = array.get(bearishmidholder,i)
                currenthigh = array.get(bearish_high_holder,i)
                currentlow = array.get(bearish_low_holder,i)
    
                if low < currenttop
                    fvg_removed:=-1
                    delete_fvg_func(currentgap,currentgap_fill,i,bearishgapholder,bearishgapholder_fill,bearishmidholder,bearish_high_holder,bearish_low_holder,bearishlabelholder)
            if mittigation_filt_fvg=='Wicks'
                currentgap_fill = array.get(bearishgapholder_fill,i)
                currentgap = array.get(bearishgapholder,i)
                currenttop = box.get_bottom(currentgap)
                currentmid = array.get(bearishmidholder,i)
                currenthigh = array.get(bearish_high_holder,i)
                currentlow = array.get(bearish_low_holder,i)
                currentbottom = box.get_top(currentgap_fill)

                if low < currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bearishgapholder_fill,i)
                    cur_bottom=box.get_bottom(currentgap_f)
                    _bottom=box.get_bottom(currentgap)
                    if _bottom==cur_bottom
                        box.set_bottom(currentgap_f,low)
                    else
                        box.set_bottom(currentgap_f,math.min(cur_bottom,low))
                    box.set_bgcolor(currentgap_f,#787b865e)

                if low < currenttop
                    fvg_removed:=-1
                    delete_fvg_func(currentgap,currentgap_fill,i,bearishgapholder,bearishgapholder_fill,bearishmidholder,bearish_high_holder,bearish_low_holder,bearishlabelholder)
            if mittigation_filt_fvg=='Close'
                currentgap_fill = array.get(bearishgapholder_fill,i)
                currentgap = array.get(bearishgapholder,i)
                currenttop = box.get_bottom(currentgap)
                currentmid = array.get(bearishmidholder,i)
                currenthigh = array.get(bearish_high_holder,i)
                currentlow = array.get(bearish_low_holder,i)
                currentbottom = box.get_top(currentgap_fill)

                if low < currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bearishgapholder_fill,i)
                    cur_bottom=box.get_bottom(currentgap_f)
                    _bottom=box.get_bottom(currentgap)
                    if _bottom==cur_bottom
                        box.set_bottom(currentgap_f,low)
                    else
                        box.set_bottom(currentgap_f,math.min(cur_bottom,low))
                    box.set_bgcolor(currentgap_f,#787b865e)

                if close < currenttop
                    fvg_removed:=-1
                    delete_fvg_func(currentgap,currentgap_fill,i,bearishgapholder,bearishgapholder_fill,bearishmidholder,bearish_high_holder,bearish_low_holder,bearishlabelholder)
            if mittigation_filt_fvg=='Average'
                currentgap_fill = array.get(bearishgapholder_fill,i)
                currentgap = array.get(bearishgapholder,i)
                currentmid = array.get(bearishmidholder,i)
                currenttop = line.get_y1(currentmid)
                currenthigh = array.get(bearish_high_holder,i)
                currentlow = array.get(bearish_low_holder,i)
                currentbottom = box.get_top(currentgap_fill)

                if low < currentbottom and fvg_shade_fill
                    currentgap_f = array.get(bearishgapholder_fill,i)
                    cur_bottom=box.get_bottom(currentgap_f)
                    _bottom=box.get_bottom(currentgap)
                    if _bottom==cur_bottom
                        box.set_bottom(currentgap_f,low)
                    else
                        box.set_bottom(currentgap_f,math.min(cur_bottom,low))
                    box.set_bgcolor(currentgap_f,#787b865e)

                if low < currenttop
                    fvg_removed:=-1
                    delete_fvg_func(currentgap,currentgap_fill,i,bearishgapholder,bearishgapholder_fill,bearishmidholder,bearish_high_holder,bearish_low_holder,bearishlabelholder)

    fvg_removed
                
// pine provided function to determine a new bar

if is_newbar(i_tf)
    htfH := high
    htfL := low

// }

fvg_gap=0

// User Input, allow MTF data calculations
if is_newbar(i_tf) and (i_mtf == "Current + HTF" or i_mtf == "HTF") and show_fvg and barstate.isconfirmed
    fvg_gap:=check_fvg_func(sClose,htfH,sHighP2,htfL,sLowP2,sOpen,time[2],true)
    

alertcondition(fvg_gap==1,"Bullish FVG","Bullish FVG Found Ez-SMC")
alertcondition(fvg_gap==-1,"Bearish FVG","Bearish FVG Found Ez-SMC")


fvg_removed=validate_fvg_func(high,low)

alertcondition(fvg_removed==1,"Bullish FVG Break","Bullish FVG Broken Ez-SMC")
alertcondition(fvg_removed==-1,"Bearish FVG Break","Bearish FVG Broken Ez-SMC")

if array.size(bullishgapholder) > max_fvg
    d_box=array.shift(bullishgapholder)
    box.delete(d_box)

if array.size(bullishgapholder_fill) > max_fvg
    d_box=array.shift(bullishgapholder_fill)
    box.delete(d_box)

if array.size(bullishmidholder) > max_fvg
    d_line=array.shift(bullishmidholder)
    line.delete(d_line)

if array.size(bullish_high_holder) > max_fvg
    d_line=array.shift(bullish_high_holder)
    line.delete(d_line)

if array.size(bullish_low_holder) > max_fvg
    d_line=array.shift(bullish_low_holder)
    line.delete(d_line)

if array.size(bearishgapholder) > max_fvg
    d_box_=array.shift(bearishgapholder)
    box.delete(d_box_)

if array.size(bearishgapholder_fill) > max_fvg
    d_box_=array.shift(bearishgapholder_fill)
    box.delete(d_box_)

if array.size(bearishmidholder) > max_fvg
    d_line_=array.shift(bearishmidholder)
    line.delete(d_line_)

if array.size(bearish_high_holder) > max_fvg
    d_line_=array.shift(bearish_high_holder)
    line.delete(d_line_)

if array.size(bearish_low_holder) > max_fvg
    d_line_=array.shift(bearish_low_holder)
    line.delete(d_line_)
    


n=bar_index



//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------       Liquidity Levels
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


// --
highLineColor = highLineColorHTF//input.color(#1f4ef5, "High Line   ", group = liquidity_level_group, inline = "1")
lowLineColor = lowLineColorHTF//input.color(#fd441c, "Low Line", group = liquidity_level_group, inline = "1")
highBoxBgColor = highLineColorHTF//input.color(color.new(#1f4ef5, 80), "High Box Bg ", group = liquidity_level_group, inline = "2")
highBoxBorderColor = highBoxBorderColorHTF//input.color(color.new(#1f4ef5, 80), "Box Border", group = liquidity_level_group, inline = "2")
lowBoxBgColor = lowLineColorHTF//input.color(color.new(#fd441c, 80), "Low Box Bg  ", group = liquidity_level_group, inline = "3")
lowBoxBorderColor = lowBoxBorderColorHTF//input.color(color.new(#fd441c, 80), "Box Border", group = liquidity_level_group, inline = "3")
atr_liq = ta.atr(300)

float thold_liq = atr_liq * (box_width / 10)
// --
// --
// --
// ----------------------------------------------------
// Functions 
// ----------------------------------------------------

tf_multi(tf) =>
    ts = timeframe.in_seconds("")
    htfs = timeframe.in_seconds(tf)
    htfs/ts

display_limit_line(_array) =>
    if array.size(_array) > displayLimit/2
        a = array.shift(_array)
        line.delete(a)

display_limit_box(_array) =>
    if array.size(_array) > displayLimit/2
        a = array.shift(_array)
        box.delete(a)

remove_mitigated_lines(_array, _hl) =>
    m = false
    if array.size(_array) > 0      
        for i = array.size(_array) - 1 to 0 by 1
            l = array.get(_array, i)
            hh = _candleType == "Close" ? close[1] : high
            ll = _candleType == "Close" ? close[1] : low
            if _hl == "High" and hh > line.get_y1(l)
                array.remove(_array, i)
                if mitiOptions == "Show"
                    line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l), xloc=xloc.bar_time, color = highLineColorHTF, style=highLineStyleHTF, width = lineWidthHTF)
                line.delete(l)
                m := true
            if _hl == "Low" and ll < line.get_y1(l)
                array.remove(_array, i)
                if mitiOptions == "Show"
                    line.new(line.get_x1(l),line.get_y1(l),time,line.get_y1(l), xloc=xloc.bar_time, color = lowLineColorHTF, style=highLineStyleHTF, width = lineWidthHTF)
                line.delete(l) 
                m := true  
    display_limit_line(_array) 
    m

remove_mitigated_boxes(_array, _hl) =>
    m = false
    if array.size(_array) > 0
        for i = array.size(_array) - 1 to 0 by 1
            l = array.get(_array, i)
            hh = _candleType == "Close" ? close[1] : high
            ll = _candleType == "Close" ? close[1] : low
            if _hl == "High" and hh > box.get_top(l)
                array.remove(_array, i)
                if mitiOptions == "Show"
                    box.new(box.get_left(l),box.get_top(l),time,box.get_bottom(l), xloc=xloc.bar_time, bgcolor = color.new(highBoxBgColor, 90), border_color = color.new(highBoxBorderColor, 90), border_style = highLineStyleHTF)
                box.delete(l)
                m := true
            if _hl == "Low" and ll < box.get_top(l)
                array.remove(_array, i)
                if mitiOptions == "Show"
                    box.new(box.get_left(l),box.get_top(l),time,box.get_bottom(l), xloc=xloc.bar_time, bgcolor = color.new(lowBoxBgColor, 90), border_color = color.new(lowBoxBorderColor, 90), border_style = highLineStyleHTF)
                box.delete(l)
                m := true
    display_limit_box(_array) 
    m

extend_line_to_current(lineArray) =>
    if array.size(lineArray) > 0
        for i = array.size(lineArray) - 1 to 0 by 1
            l = array.get(lineArray, i)
            timeExt = timenow + ((timediff)*length_extend_liq)
            line.set_x2(l, timeExt)

extend_box_to_current(boxArray) =>
    if array.size(boxArray) > 0
        for i = array.size(boxArray) - 1 to 0 by 1
            b = array.get(boxArray, i)
            timeExt = timenow + ((timediff)*length_extend_liq)
            box.set_right(b, timeExt)

// ----------------------------------------------------
// Higher TimeFrame
// ----------------------------------------------------
// Varibles 
// Lines
var highLineArrayHTF = array.new_line()
var lowLineArrayHTF = array.new_line()

// Boxes
var highBoxArrayHTF = array.new_box()
var lowBoxArrayHTF = array.new_box()

// Get HTF
[_time, _open, _high, _low, _close] = request.security(syminfo.tickerid, htfTF, [time, open, high, low, close])

// Pivots
pivotHighHTF = ta.pivothigh(_high, leftBars*tf_multi(htfTF), leftBars+tf_multi(htfTF))
pivotLowHTF = ta.pivotlow(_low, leftBars*tf_multi(htfTF), leftBars+tf_multi(htfTF))

if currentTF
    timeExt = time+((time[1]-time[2])*10)
    dis = leftBars+tf_multi(htfTF)
    if pivotHighHTF
        if displayStyle_liq == "Lines"
            array.push(highLineArrayHTF, line.new(_time[dis],_high[dis],_time[+1],_high[dis],color = highLineColorHTF, style=highLineStyleHTF, xloc=xloc.bar_time, extend=extentionMax?extend.right:extend.none, width = lineWidthHTF))
        else
            y1 = _high[dis]-thold_liq//math.max(_open[dis], _close[dis])
            array.push(highBoxArrayHTF, box.new(_time[dis],_high[dis],_time[+1],y1,bgcolor = highLineColorHTF, border_color=highBoxBorderColorHTF, xloc=xloc.bar_time, border_style = highLineStyleHTF, extend=extentionMax?extend.right:extend.none, border_width = lineWidthHTF,text="$$$",text_halign = text.align_center,text_color = liquidity_text_color,text_size = size.small))  
    if pivotLowHTF
        if displayStyle_liq == "Lines"
            array.push(lowLineArrayHTF, line.new(_time[dis],_low[dis],_time[+1],_low[dis],color = lowLineColorHTF, style=highLineStyleHTF, xloc=xloc.bar_time, extend=extentionMax?extend.right:extend.none, width = lineWidthHTF))
        else
            y1 = _low[dis]+thold_liq//math.min(_open[dis], _close[dis])
            array.push(lowBoxArrayHTF, box.new(_time[dis],_low[dis],_time[+1],y1,bgcolor = lowLineColorHTF, border_color=lowBoxBorderColorHTF, xloc=xloc.bar_time, border_style = highLineStyleHTF, extend=extentionMax?extend.right:extend.none, border_width = lineWidthHTF,text=" $$$",text_halign = text.align_center,text_color = liquidity_text_color,text_size = size.small))

// ----------------------------------------------------
// Run Functions
// ----------------------------------------------------
highLineAlertHTF = remove_mitigated_lines(highLineArrayHTF, "High")
lowLineAlertHTF = remove_mitigated_lines(lowLineArrayHTF, "Low")
highBoxAlertHTF = remove_mitigated_boxes(highBoxArrayHTF, "High")
lowBoxAlertHTF = remove_mitigated_boxes(lowBoxArrayHTF, "Low")


extend_line_to_current(highLineArrayHTF)
extend_line_to_current(lowLineArrayHTF)
extend_box_to_current(highBoxArrayHTF)
extend_box_to_current(lowBoxArrayHTF)

// Alerts
alertcondition(pivotHighHTF, "High Liquidity Level", "High Liquidity Level Found Ez-SMC")
alertcondition(pivotLowHTF, "Low Liquidity Level", "Low Liquidity Level Found Ez-SMC")

alertcondition(highLineAlertHTF or highBoxAlertHTF, "High Liquidity Level Break", "High Liquidity Level Broken Ez-SMC")
alertcondition(lowLineAlertHTF or lowBoxAlertHTF, "Low Liquidity Level Break", "Low Liquidity Level Broken Ez-SMC")



//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------       Key Levels
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
var monday_time = time
var monday_high = high
var monday_low = low
cdailyh_open = request.security(syminfo.tickerid, 'D', high, lookahead=barmerge.lookahead_on)
cdailyl_open = request.security(syminfo.tickerid, 'D', low, lookahead=barmerge.lookahead_on)
[daily_time, daily_open] = request.security(syminfo.tickerid, 'D', [time, open], lookahead=barmerge.lookahead_on)
[dailyh_time, dailyh_open] = request.security(syminfo.tickerid, 'D', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[dailyl_time, dailyl_open] = request.security(syminfo.tickerid, 'D', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[weekly_time, weekly_open] = request.security(syminfo.tickerid, 'W', [time, open], lookahead=barmerge.lookahead_on)
[weeklyh_time, weeklyh_open] = request.security(syminfo.tickerid, 'W', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[weeklyl_time, weeklyl_open] = request.security(syminfo.tickerid, 'W', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[monthly_time, monthly_open] = request.security(syminfo.tickerid, 'M', [time, open], lookahead=barmerge.lookahead_on)
[monthlyh_time, monthlyh_open] = request.security(syminfo.tickerid, 'M', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[monthlyl_time, monthlyl_open] = request.security(syminfo.tickerid, 'M', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[intra_time, intra_open] = request.security(syminfo.tickerid, '240', [time, open], lookahead=barmerge.lookahead_on)
[intrah_time, intrah_open] = request.security(syminfo.tickerid, '240', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[intral_time, intral_open] = request.security(syminfo.tickerid, '240', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[quarterly_time, quarterly_open] = request.security(syminfo.tickerid, '3M', [time, open], lookahead=barmerge.lookahead_on)
[quarterlyh_time, quarterlyh_open] = request.security(syminfo.tickerid, '3M', [time[1], high[1]], lookahead=barmerge.lookahead_on)
[quarterlyl_time, quarterlyl_open] = request.security(syminfo.tickerid, '3M', [time[1], low[1]], lookahead=barmerge.lookahead_on)
[yearly_time, yearly_open] = request.security(syminfo.tickerid, '12M', [time, open], lookahead=barmerge.lookahead_on)
[yearlyh_time, yearlyh_open] = request.security(syminfo.tickerid, '12M', [time, high], lookahead=barmerge.lookahead_on)
[yearlyl_time, yearlyl_open] = request.security(syminfo.tickerid, '12M', [time, low], lookahead=barmerge.lookahead_on)
if weekly_time != weekly_time[1]
    untested_monday := false
    untested_monday
if Show_Monday_Levels == true and untested_monday == false
    untested_monday := true
    monday_time := daily_time
    monday_high := cdailyh_open
    monday_low := cdailyl_open
    monday_low
linewidthint = 1
if linesize == 'Small'
    linewidthint := 1
    linewidthint
if linesize == 'Medium'
    linewidthint := 2
    linewidthint
if linesize == 'Large'
    linewidthint := 3
    linewidthint
var linewidth_def = linewidthint
fontsize = size.small
if labelsize == 'Small'
    fontsize := size.small
    fontsize
if labelsize == 'Medium'
    fontsize := size.normal
    fontsize
if labelsize == 'Large'
    fontsize := size.large
    fontsize
linestyles = line.style_solid
if linestyle == 'Dashed'
    linestyles := line.style_dashed
    linestyles
if linestyle == 'Dotted'
    linestyles := line.style_dotted
    linestyles
var DEFAULT_LABEL_SIZE = fontsize
var DEFAULT_LABEL_STYLE = label.style_none
var Rigth_Def = distanceright
var arr_price = array.new_float(0)
var arr_label = array.new_label(0)
Combine_Levels(arr_price, arr_label, currentprice, currentlabel, currentcolor) =>
    if array.includes(arr_price, currentprice)
        whichindex = array.indexof(arr_price, currentprice)
        labelhold = array.get(arr_label, whichindex)
        whichtext = label.get_text(labelhold)
        label.set_text(labelhold, label.get_text(currentlabel) + ' / ' + whichtext)
        label.set_text(currentlabel, '')
        label.set_textcolor(labelhold, currentcolor)
    else
        array.push(arr_price, currentprice)
        array.push(arr_label, currentlabel)
extend_to_current(bars) =>
    timenow + (time - time[1]) * bars
if barstate.islast
    arr_price := array.new_float(0)
    arr_label := array.new_label(0)
    if Show_4H_Levels
        limit_4H_right =  extend_to_current(Rigth_Def)
        intrah_limit_right =  extend_to_current(Rigth_Def)
        intral_limit_right =  extend_to_current(Rigth_Def)
        var line_4H = line.new(x1=intra_time, x2=limit_4H_right, y1=intra_open, y2=intra_open, color=Color_4H_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_4H_Levels))
        var label_4H = label.new(x=limit_4H_right, y=intra_open, text=iotext, style=DEFAULT_LABEL_STYLE, textcolor=Color_4H_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var intrah_line = line.new(x1=intrah_time, x2=intrah_limit_right, y1=intrah_open, y2=intrah_open, color=Color_4H_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_4H_Levels))
        var intrah_label = label.new(x=intrah_limit_right, y=intrah_open, text=pihtext, style=DEFAULT_LABEL_STYLE, textcolor=Color_4H_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var intral_line = line.new(x1=intral_time, x2=intral_limit_right, y1=intral_open, y2=intral_open, color=Color_4H_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_4H_Levels))
        var intral_label = label.new(x=intral_limit_right, y=intral_open, text=piltext, style=DEFAULT_LABEL_STYLE, textcolor=Color_4H_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)        
        label.set_text(label_4H, iotext)    
        line.set_xy1(line_4H,intra_time,intra_open)
        line.set_xy2(line_4H,limit_4H_right,intra_open)
        label.set_xy(label_4H,limit_4H_right,intra_open)
        line.set_xy1(intrah_line,intrah_time,intrah_open)
        line.set_xy2(intrah_line,intrah_limit_right,intrah_open)
        label.set_xy(intrah_label,intrah_limit_right,intrah_open)
        label.set_text(intrah_label, pihtext)
        line.set_x1(intral_line, intral_time)
        line.set_x2(intral_line, intral_limit_right)
        line.set_y1(intral_line, intral_open)
        line.set_y2(intral_line, intral_open)
        label.set_x(intral_label, intral_limit_right)
        label.set_y(intral_label, intral_open)
        label.set_text(intral_label, piltext)
        Combine_Levels(arr_price, arr_label, intra_open, label_4H, Color_4H_Levels)
        Combine_Levels(arr_price, arr_label, intrah_open, intrah_label, Color_4H_Levels)
        Combine_Levels(arr_price, arr_label, intral_open, intral_label, Color_4H_Levels)
    if Show_Monday_Levels
        monday_limit_right =  extend_to_current(Rigth_Def)
        mondaym_limit_right =  extend_to_current(Rigth_Def)
        mondaym_open = (monday_high + monday_low) / 2
        var monday_line = line.new(x1=monday_time, x2=monday_limit_right, y1=monday_high, y2=monday_high, color=Color_Monday_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_Monday_Levels))
        var monday_label = label.new(x=monday_limit_right, y=monday_high, text=pmonhtext, style=DEFAULT_LABEL_STYLE, textcolor=Color_Monday_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var mondaym_line = line.new(x1=monday_time, x2=mondaym_limit_right, y1=mondaym_open, y2=mondaym_open, color=Color_Monday_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_Monday_Levels))
        var mondaym_label = label.new(x=mondaym_limit_right, y=mondaym_open, text=pmonmtext, style=DEFAULT_LABEL_STYLE, textcolor=Color_Monday_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var monday_low_line = line.new(x1=monday_time, x2=monday_limit_right, y1=monday_low, y2=monday_low, color=Color_Monday_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_Monday_Levels))
        var monday_low_label = label.new(x=monday_limit_right, y=monday_low, text=pmonltext, style=DEFAULT_LABEL_STYLE, textcolor=Color_Monday_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(monday_line, monday_time)
        line.set_x2(monday_line, monday_limit_right)
        line.set_y1(monday_line, monday_high)
        line.set_y2(monday_line, monday_high)
        label.set_x(monday_label, monday_limit_right)
        label.set_y(monday_label, monday_high)
        label.set_text(monday_label, pmonhtext)
        line.set_x1(monday_low_line, monday_time)
        line.set_x2(monday_low_line, monday_limit_right)
        line.set_y1(monday_low_line, monday_low)
        line.set_y2(monday_low_line, monday_low)
        label.set_x(monday_low_label, monday_limit_right)
        label.set_y(monday_low_label, monday_low)
        label.set_text(monday_low_label, pmonltext)  
        line.set_x1(mondaym_line, monday_time)
        line.set_x2(mondaym_line, mondaym_limit_right)
        line.set_y1(mondaym_line, mondaym_open)
        line.set_y2(mondaym_line, mondaym_open)
        label.set_x(mondaym_label, mondaym_limit_right)
        label.set_y(mondaym_label, mondaym_open)
        label.set_text(mondaym_label, pmonmtext)
        Combine_Levels(arr_price, arr_label, monday_high, monday_label, Color_Monday_Levels)
        Combine_Levels(arr_price, arr_label, monday_low, monday_low_label, Color_Monday_Levels)
        Combine_Levels(arr_price, arr_label, mondaym_open, mondaym_label, Color_Monday_Levels)
    if Show_Daily_Levels
        daily_limit_right =  extend_to_current(Rigth_Def)
        dailyh_limit_right =  extend_to_current(Rigth_Def)
        dailyl_limit_right =  extend_to_current(Rigth_Def)
        var daily_line = line.new(x1=daily_time, x2=daily_limit_right, y1=daily_open, y2=daily_open, color=Color_Daily_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_Daily_Levels))
        var daily_label = label.new(x=daily_limit_right, y=daily_open, text=dotext, style=DEFAULT_LABEL_STYLE, textcolor=Color_Daily_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var dailyh_line = line.new(x1=dailyh_time, x2=dailyh_limit_right, y1=dailyh_open, y2=dailyh_open, color=Color_Daily_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_Daily_Levels))
        var dailyh_label = label.new(x=dailyh_limit_right, y=dailyh_open, text=pdhtext, style=DEFAULT_LABEL_STYLE, textcolor=Color_Daily_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var dailyl_line = line.new(x1=dailyl_time, x2=dailyl_limit_right, y1=dailyl_open, y2=dailyl_open, color=Color_Daily_Levels, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Style_Daily_Levels))
        var dailyl_label = label.new(x=dailyl_limit_right, y=dailyl_open, text=pdltext, style=DEFAULT_LABEL_STYLE, textcolor=Color_Daily_Levels, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(daily_line, daily_time)
        line.set_x2(daily_line, daily_limit_right)
        line.set_y1(daily_line, daily_open)
        line.set_y2(daily_line, daily_open)
        label.set_x(daily_label, daily_limit_right)
        label.set_y(daily_label, daily_open)
        label.set_text(daily_label, dotext)
        line.set_x1(dailyh_line, dailyh_time)
        line.set_x2(dailyh_line, dailyh_limit_right)
        line.set_y1(dailyh_line, dailyh_open)
        line.set_y2(dailyh_line, dailyh_open)
        label.set_x(dailyh_label, dailyh_limit_right)
        label.set_y(dailyh_label, dailyh_open)
        label.set_text(dailyh_label, pdhtext)
        line.set_x1(dailyl_line, dailyl_time)
        line.set_x2(dailyl_line, dailyl_limit_right)
        line.set_y1(dailyl_line, dailyl_open)
        line.set_y2(dailyl_line, dailyl_open)
        label.set_x(dailyl_label, dailyl_limit_right)
        label.set_y(dailyl_label, dailyl_open)
        label.set_text(dailyl_label, pdltext)
        Combine_Levels(arr_price, arr_label, daily_open, daily_label, Color_Daily_Levels)
        Combine_Levels(arr_price, arr_label, dailyh_open, dailyh_label, Color_Daily_Levels)
        Combine_Levels(arr_price, arr_label, dailyl_open, dailyl_label, Color_Daily_Levels)
    if Show_Weekly_Levels
        weekly_limit_right =  extend_to_current(Rigth_Def)
        weeklyh_limit_right =  extend_to_current(Rigth_Def)
        weeklyl_limit_right =  extend_to_current(Rigth_Def)
        cweekly_time = weekly_time
        var weekly_line = line.new(x1=cweekly_time, x2=weekly_limit_right, y1=weekly_open, y2=weekly_open, color=WeeklyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Weekly_style))
        var weekly_label = label.new(x=weekly_limit_right, y=weekly_open, text=wotext, style=DEFAULT_LABEL_STYLE, textcolor=WeeklyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var weeklyh_line = line.new(x1=weeklyh_time, x2=weeklyh_limit_right, y1=weeklyh_open, y2=weeklyh_open, color=WeeklyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Weekly_style))
        var weeklyh_label = label.new(x=weeklyh_limit_right, y=weeklyh_open, text=pwhtext, style=DEFAULT_LABEL_STYLE, textcolor=WeeklyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var weeklyl_line = line.new(x1=weeklyl_time, x2=weeklyl_limit_right, y1=weekly_open, y2=weekly_open, color=WeeklyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Weekly_style))
        var weeklyl_label = label.new(x=weeklyl_limit_right, y=weeklyl_open, text=pwltext, style=DEFAULT_LABEL_STYLE, textcolor=WeeklyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(weekly_line, cweekly_time)
        line.set_x2(weekly_line, weekly_limit_right)
        line.set_y1(weekly_line, weekly_open)
        line.set_y2(weekly_line, weekly_open)
        label.set_x(weekly_label, weekly_limit_right)
        label.set_y(weekly_label, weekly_open)
        label.set_text(weekly_label, wotext)    
        line.set_x1(weeklyh_line, weeklyh_time)
        line.set_x2(weeklyh_line, weeklyh_limit_right)
        line.set_y1(weeklyh_line, weeklyh_open)
        line.set_y2(weeklyh_line, weeklyh_open)
        label.set_x(weeklyh_label, weeklyh_limit_right)
        label.set_y(weeklyh_label, weeklyh_open)
        label.set_text(weeklyh_label, pwhtext) 
        line.set_x1(weeklyl_line, weeklyl_time)
        line.set_x2(weeklyl_line, weeklyl_limit_right)
        line.set_y1(weeklyl_line, weeklyl_open)
        line.set_y2(weeklyl_line, weeklyl_open)
        label.set_x(weeklyl_label, weeklyl_limit_right)
        label.set_y(weeklyl_label, weeklyl_open)
        label.set_text(weeklyl_label, pwltext)
        Combine_Levels(arr_price, arr_label, weekly_open, weekly_label, WeeklyColor)
        Combine_Levels(arr_price, arr_label, weeklyh_open, weeklyh_label, WeeklyColor)
        Combine_Levels(arr_price, arr_label, weeklyl_open, weeklyl_label, WeeklyColor)
    if Show_Yearly_Levels
        yearlyl_limit_right =  extend_to_current(Rigth_Def)
        yearlyh_limit_right =  extend_to_current(Rigth_Def)
        yearly_limit_right =  extend_to_current(Rigth_Def)
        var yearlyl_line = line.new(x1=yearlyl_time, x2=yearlyl_limit_right, y1=yearlyl_open, y2=yearlyl_open, color=YearlyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Yearly_style))
        var yearlyl_label = label.new(x=yearlyl_limit_right, y=yearlyl_open, text=cyltext, style=DEFAULT_LABEL_STYLE, textcolor=YearlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var yearlyh_line = line.new(x1=yearlyh_time, x2=yearlyh_limit_right, y1=yearlyh_open, y2=yearlyh_open, color=YearlyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Yearly_style))
        var yearlyh_label = label.new(x=yearlyh_limit_right, y=yearlyh_open, text=cyhtext, style=DEFAULT_LABEL_STYLE, textcolor=YearlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var yearly_line = line.new(x1=yearly_time, x2=yearly_limit_right, y1=yearly_open, y2=yearly_open, color=YearlyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Yearly_style))
        var yearly_label = label.new(x=yearly_limit_right, y=yearly_open, text=yotext, style=DEFAULT_LABEL_STYLE, textcolor=YearlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(yearlyl_line, yearlyl_time)
        line.set_x2(yearlyl_line, yearlyl_limit_right)
        line.set_y1(yearlyl_line, yearlyl_open)
        line.set_y2(yearlyl_line, yearlyl_open)
        label.set_x(yearlyl_label, yearlyl_limit_right)
        label.set_y(yearlyl_label, yearlyl_open)
        label.set_text(yearlyl_label, cyltext)
        line.set_x1(yearlyh_line, yearlyh_time)
        line.set_x2(yearlyh_line, yearlyh_limit_right)
        line.set_y1(yearlyh_line, yearlyh_open)
        line.set_y2(yearlyh_line, yearlyh_open)
        label.set_x(yearlyh_label, yearlyh_limit_right)
        label.set_y(yearlyh_label, yearlyh_open)
        label.set_text(yearlyh_label, cyhtext)
        line.set_x1(yearly_line, yearly_time)
        line.set_x2(yearly_line, yearly_limit_right)
        line.set_y1(yearly_line, yearly_open)
        line.set_y2(yearly_line, yearly_open)
        label.set_x(yearly_label, yearly_limit_right)
        label.set_y(yearly_label, yearly_open)
        label.set_text(yearly_label, yotext)
        Combine_Levels(arr_price, arr_label, yearlyh_open, yearlyh_label, YearlyColor)
        Combine_Levels(arr_price, arr_label, yearlyl_open, yearlyl_label, YearlyColor)
        Combine_Levels(arr_price, arr_label, yearly_open, yearly_label, YearlyColor)
        
    if Show_Quaterly_Levels
        quarterly_limit_right =  extend_to_current(Rigth_Def)
        quarterlyh_limit_right =  extend_to_current(Rigth_Def)
        quarterlyl_limit_right =  extend_to_current(Rigth_Def)
        var quarterly_line = line.new(x1=quarterly_time, x2=quarterly_limit_right, y1=quarterly_open, y2=quarterly_open, color=quarterlyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Quaterly_style))
        var quarterly_label = label.new(x=quarterly_limit_right, y=quarterly_open, text=qotext, style=DEFAULT_LABEL_STYLE, textcolor=quarterlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var quarterlyh_line = line.new(x1=quarterlyh_time, x2=quarterlyh_limit_right, y1=quarterlyh_open, y2=quarterlyh_open, color=quarterlyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Quaterly_style))
        var quarterlyh_label = label.new(x=quarterlyh_limit_right, y=quarterlyh_open, text=pqhtext, style=DEFAULT_LABEL_STYLE, textcolor=quarterlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var quarterlyl_line = line.new(x1=quarterlyl_time, x2=quarterlyl_limit_right, y1=quarterlyl_open, y2=quarterlyl_open, color=quarterlyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Quaterly_style))
        var quarterlyl_label = label.new(x=quarterlyl_limit_right, y=quarterlyl_open, text=pqltext, style=DEFAULT_LABEL_STYLE, textcolor=quarterlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(quarterly_line, quarterly_time)
        line.set_x2(quarterly_line, quarterly_limit_right)
        line.set_y1(quarterly_line, quarterly_open)
        line.set_y2(quarterly_line, quarterly_open)
        label.set_x(quarterly_label, quarterly_limit_right)
        label.set_y(quarterly_label, quarterly_open)
        label.set_text(quarterly_label, qotext)
        line.set_x1(quarterlyh_line, quarterlyh_time)
        line.set_x2(quarterlyh_line, quarterlyh_limit_right)
        line.set_y1(quarterlyh_line, quarterlyh_open)
        line.set_y2(quarterlyh_line, quarterlyh_open)
        label.set_x(quarterlyh_label, quarterlyh_limit_right)
        label.set_y(quarterlyh_label, quarterlyh_open)
        label.set_text(quarterlyh_label, pqhtext)
        line.set_x1(quarterlyl_line, quarterlyl_time)
        line.set_x2(quarterlyl_line, quarterlyl_limit_right)
        line.set_y1(quarterlyl_line, quarterlyl_open)
        line.set_y2(quarterlyl_line, quarterlyl_open)
        label.set_x(quarterlyl_label, quarterlyl_limit_right)
        label.set_y(quarterlyl_label, quarterlyl_open)
        label.set_text(quarterlyl_label, pqltext)
        Combine_Levels(arr_price, arr_label, quarterlyl_open, quarterlyl_label, quarterlyColor)
        Combine_Levels(arr_price, arr_label, quarterly_open, quarterly_label, quarterlyColor)
        Combine_Levels(arr_price, arr_label, quarterlyh_open, quarterlyh_label, quarterlyColor)


    if Show_Monthly_Levels
        monthly_limit_right =  extend_to_current(Rigth_Def)
        var monthlyLine = line.new(x1=monthly_time, x2=monthly_limit_right, y1=monthly_open, y2=monthly_open, color=MonthlyColor, width=linewidth_def, xloc=xloc.bar_time, style=lineStyle(Monthly_style))
        var monthlyLabel = label.new(x=monthly_limit_right, y=monthly_open, text=motext, style=DEFAULT_LABEL_STYLE, textcolor=MonthlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(monthlyLine, monthly_time)
        line.set_x2(monthlyLine, monthly_limit_right)
        line.set_y1(monthlyLine, monthly_open)
        line.set_y2(monthlyLine, monthly_open)
        label.set_x(monthlyLabel, monthly_limit_right)
        label.set_y(monthlyLabel, monthly_open)
        label.set_text(monthlyLabel, motext)
        Combine_Levels(arr_price, arr_label, monthly_open, monthlyLabel, MonthlyColor)

    

//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------       Sessions
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

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

London = time(timeframe.period, Londont)
US = time(timeframe.period, USt)
Asia = time(timeframe.period, Asiat)

var clondonhigh = 0.0
var clondonlow = close
var londontime = time
var flondonhigh = 0.0
var flondonlow = 0.0
var flondonopen = 0.0

var onelondonfalse = false
if London
    if high > clondonhigh
        clondonhigh := high
        clondonhigh
    if low < clondonlow
        clondonlow := low
        clondonlow
    if onelondonfalse
        londontime := time
        flondonopen := open
        flondonopen
    flondonhigh := clondonhigh
    flondonlow := clondonlow
    onelondonfalse := false
    onelondonfalse
else
    if onelondonfalse == false
        flondonhigh := clondonhigh
        flondonlow := clondonlow
        flondonlow
    onelondonfalse := true

    clondonhigh := 0.0
    clondonlow := close
    clondonlow

//////////////////////////////////
var cushigh = 0.0
var cuslow = close
var ustime = time
var fushigh = 0.0
var fuslow = 0.0
var fusopen = 0.0

var oneusfalse = false
if US
    if high > cushigh
        cushigh := high
        cushigh
    if low < cuslow
        cuslow := low
        cuslow
    if oneusfalse
        ustime := time
        fusopen := open
        fusopen
    fushigh := cushigh
    fuslow := cuslow
    oneusfalse := false
    oneusfalse
else
    if oneusfalse == false
        fushigh := cushigh
        fuslow := cuslow
        fuslow
    oneusfalse := true

    cushigh := 0.0
    cuslow := close
    cuslow

//////////////////////////////////
var casiahigh = 0.0
var casialow = close
var asiatime = time
var fasiahigh = 0.0
var fasialow = 0.0
var fasiaopen = 0.0

var oneasiafalse = false
if Asia
    if high > casiahigh
        casiahigh := high
        casiahigh
    if low < casialow
        casialow := low
        casialow
    if oneasiafalse
        asiatime := time
        fasiaopen := open
        fasiaopen
    fasiahigh := casiahigh
    fasialow := casialow
    oneasiafalse := false
    oneasiafalse
else
    if oneasiafalse == false
        fasiahigh := casiahigh
        fasialow := casialow
        fasialow
    oneasiafalse := true

    casiahigh := 0.0
    casialow := close
    casialow

var high_eqh_pre = 0.,var eq_top_x = 0,var low_eqh_pre = 0.,var eq_btm_x = 0

if show_equal_highlow
    high_eqh = ta.pivothigh(length_eqh, length_eqh)
    low_eqh = ta.pivotlow(length_eqh, length_eqh)
    if low_eqh 
        if math.min(low_eqh, low_eqh_pre) > math.max(low_eqh, low_eqh_pre) - atr * eq_threshold
            eql_line = line.new(eq_btm_x, low_eqh_pre, n-length_eqh, low_eqh, color = eq_bull_color, style = line.style_dotted)
            eql_lbl = label.new(int(math.avg(n-length_eqh, eq_btm_x)), low_eqh, 'EQL', color = #00000000, textcolor = eq_bull_color, style = label.style_label_up, size = label_size_buysell)
        low_eqh_pre := low_eqh
        eq_btm_x := n-length_eqh
    if high_eqh     
        if math.max(high_eqh, high_eqh_pre) < math.min(high_eqh, high_eqh_pre) + atr * eq_threshold
            eqh_line = line.new(eq_top_x, high_eqh_pre, n-length_eqh, high_eqh, color = eq_bear_color, style = line.style_dotted)
            eqh_lbl = label.new(int(math.avg(n-length_eqh, eq_top_x)), high_eqh, 'EQH', color = #00000000, textcolor = eq_bear_color, style = label.style_label_down, size = label_size_buysell)
        high_eqh_pre := high_eqh
        eq_top_x := n-length_eqh

// the following code doesn't need to be processed on every candle
if barstate.islast
    arr_price := array.new_float(0)
    arr_label := array.new_label(0)
    if is_londonrange_enabled
        london_limit_right =  extend_to_current(Rigth_Def)
        var londonh_line = line.new(x1=londontime, x2=london_limit_right, y1=flondonhigh, y2=flondonhigh, color=london_HL?LondonColor:na, width=linewidth_def, xloc=xloc.bar_time, style=linestyles)
        var londonl_line = line.new(x1=londontime, x2=london_limit_right, y1=flondonlow, y2=flondonlow, color=london_HL?LondonColor:na, width=linewidth_def, xloc=xloc.bar_time, style=linestyles)
        var londono_line = line.new(x1=londontime, x2=london_limit_right, y1=flondonopen, y2=flondonopen, color=london_OC?LondonColor:na, width=linewidth_def, xloc=xloc.bar_time, style=linestyles)
        var londonh_label = label.new(x=london_limit_right, y=flondonhigh, text=London_high_text, style=DEFAULT_LABEL_STYLE, textcolor=london_HL?LondonColor:na, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var londonl_label = label.new(x=london_limit_right, y=flondonlow, text=London_low_text, style=DEFAULT_LABEL_STYLE, textcolor=london_HL?LondonColor:na, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var londono_label = label.new(x=london_limit_right, y=flondonopen, text=London_open_text, style=DEFAULT_LABEL_STYLE, textcolor=london_OC?LondonColor:na, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(londonh_line, londontime)
        line.set_x2(londonh_line, london_limit_right)
        line.set_y1(londonh_line, flondonhigh)
        line.set_y2(londonh_line, flondonhigh)
        line.set_x1(londonl_line, londontime)
        line.set_x2(londonl_line, london_limit_right)
        line.set_y1(londonl_line, flondonlow)
        line.set_y2(londonl_line, flondonlow)
        line.set_x1(londono_line, londontime)
        line.set_x2(londono_line, london_limit_right)
        line.set_y1(londono_line, flondonopen)
        line.set_y2(londono_line, flondonopen)
        label.set_x(londonh_label, london_limit_right)
        label.set_y(londonh_label, flondonhigh)
        label.set_text(londonh_label, London_high_text)
        label.set_x(londonl_label, london_limit_right)
        label.set_y(londonl_label, flondonlow)
        label.set_text(londonl_label, London_low_text)
        label.set_x(londono_label, london_limit_right)
        label.set_y(londono_label, flondonopen)
        label.set_text(londono_label, London_open_text)
        Combine_Levels(arr_price, arr_label, flondonhigh, londonh_label, LondonColor)
        Combine_Levels(arr_price, arr_label, flondonlow, londonl_label, LondonColor)
        Combine_Levels(arr_price, arr_label, flondonopen, londono_label, LondonColor)
    if is_usrange_enabled
        us_limit_right =  extend_to_current(Rigth_Def)
        var ush_line = line.new(x1=ustime, x2=us_limit_right, y1=fushigh, y2=fushigh, color=us_HL?USColor:na, width=linewidth_def, xloc=xloc.bar_time, style=linestyles)
        var usl_line = line.new(x1=ustime, x2=us_limit_right, y1=fuslow, y2=fuslow, color=us_HL?USColor:na, width=linewidth_def, xloc=xloc.bar_time, style=linestyles)
        var uso_line = line.new(x1=ustime, x2=us_limit_right, y1=fusopen, y2=fusopen, color=us_OC?USColor:na, width=linewidth_def, xloc=xloc.bar_time, style=linestyles)
        var ush_label = label.new(x=us_limit_right, y=fushigh, text=London_high_text, style=DEFAULT_LABEL_STYLE, textcolor=us_HL?USColor:na, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var usl_label = label.new(x=us_limit_right, y=fuslow, text=London_low_text, style=DEFAULT_LABEL_STYLE, textcolor=us_HL?USColor:na, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var uso_label = label.new(x=us_limit_right, y=fusopen, text=London_open_text, style=DEFAULT_LABEL_STYLE, textcolor=us_OC?USColor:na, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(ush_line, ustime)
        line.set_x2(ush_line, us_limit_right)
        line.set_y1(ush_line, fushigh)
        line.set_y2(ush_line, fushigh)
        line.set_x1(usl_line, ustime)
        line.set_x2(usl_line, us_limit_right)
        line.set_y1(usl_line, fuslow)
        line.set_y2(usl_line, fuslow)
        line.set_x1(uso_line, ustime)
        line.set_x2(uso_line, us_limit_right)
        line.set_y1(uso_line, fusopen)
        line.set_y2(uso_line, fusopen)
        label.set_x(ush_label, us_limit_right)
        label.set_y(ush_label, fushigh)
        label.set_text(ush_label, NY_high_text)
        label.set_x(usl_label, us_limit_right)
        label.set_y(usl_label, fuslow)
        label.set_text(usl_label, NY_low_text)
        label.set_x(uso_label, us_limit_right)
        label.set_y(uso_label, fusopen)
        label.set_text(uso_label, NY_open_text)
        Combine_Levels(arr_price, arr_label, fushigh, ush_label, USColor)
        Combine_Levels(arr_price, arr_label, fuslow, usl_label, USColor)
        Combine_Levels(arr_price, arr_label, fusopen, uso_label, USColor)
    if is_tokyorange_enabled
        asia_limit_right =  extend_to_current(Rigth_Def)
        var asiah_line = line.new(x1=asiatime, x2=asia_limit_right, y1=fasiahigh, y2=fasiahigh, color=asia_HL?AsiaColor:na, width=linewidth_def, xloc=xloc.bar_time, style=linestyles)
        var asial_line = line.new(x1=asiatime, x2=asia_limit_right, y1=fasialow, y2=fasialow, color=asia_HL?AsiaColor:na, width=linewidth_def, xloc=xloc.bar_time, style=linestyles)
        var asiao_line = line.new(x1=asiatime, x2=asia_limit_right, y1=fasiaopen, y2=fasiaopen, color=asia_OC?AsiaColor:na, width=linewidth_def, xloc=xloc.bar_time, style=linestyles)
        var asiah_label = label.new(x=asia_limit_right, y=fasiahigh, text=Tokyo_high_text, style=DEFAULT_LABEL_STYLE, textcolor=asia_HL?AsiaColor:na, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var asial_label = label.new(x=asia_limit_right, y=fasialow, text=Tokyo_low_text, style=DEFAULT_LABEL_STYLE, textcolor=asia_HL?AsiaColor:na, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        var asiao_label = label.new(x=asia_limit_right, y=fasiaopen, text=Tokyo_open_text, style=DEFAULT_LABEL_STYLE, textcolor=asia_OC?AsiaColor:na, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(asiah_line, asiatime)
        line.set_x2(asiah_line, asia_limit_right)
        line.set_y1(asiah_line, fasiahigh)
        line.set_y2(asiah_line, fasiahigh)
        line.set_x1(asial_line, asiatime)
        line.set_x2(asial_line, asia_limit_right)
        line.set_y1(asial_line, fasialow)
        line.set_y2(asial_line, fasialow)
        line.set_x1(asiao_line, asiatime)
        line.set_x2(asiao_line, asia_limit_right)
        line.set_y1(asiao_line, fasiaopen)
        line.set_y2(asiao_line, fasiaopen)
        label.set_x(asiah_label, asia_limit_right)
        label.set_y(asiah_label, fasiahigh)
        label.set_text(asiah_label, Tokyo_high_text)
        label.set_x(asial_label, asia_limit_right)
        label.set_y(asial_label, fasialow)
        label.set_text(asial_label, Tokyo_low_text)
        label.set_x(asiao_label, asia_limit_right)
        label.set_y(asiao_label, fasiaopen)
        label.set_text(asiao_label, Tokyo_open_text)
        Combine_Levels(arr_price, arr_label, fasiahigh, asiah_label, AsiaColor)
        Combine_Levels(arr_price, arr_label, fasialow, asial_label, AsiaColor)
        Combine_Levels(arr_price, arr_label, fasiaopen, asiao_label, AsiaColor)

swing_bull_css = bosColor1
swing_bear_css = bosColor2 
var bullish_col_MSS = swing_bull_css
var bearish_col_MSS = swing_bear_css
var internal_bullish_col_MSS = bosColor1
var internal_bearish_col_MSS = bosColor2
[high_ms, low_ms] = calculate_swing_points(length)
n := bar_index
//HL Output function
hl() => [high, low]
var float thold = (ta.highest(300) - ta.lowest(300)) * math.max(0.5, 0.1) / 100.
internal_structure_lbl_size=label_size_buysell
[int_high_ms, int_low_ms] = calculate_swing_points(swingSize)
swing_structure_lbl_size=label_size_buysell
if low_ms
    crossed_down := true
    y_dn := low_ms
    x_dn := n-length
if high_ms
    crossed_up := true
    y_up := high_ms
    x_up := n - length
if int_low_ms
    internal_dn_broke := true
    internal_y_dn := int_low_ms
    internal_x_dn := n - swingSize
if int_high_ms
    internal_up_broke := true
    internal_y_up := int_high_ms
    internal_x_up := n - swingSize
bull_mss=false,bull_mss_=false,bull_bos=false,bull_bos_=false,bear_mss=false,bear_mss_=false,bear_bos=false,bear_bos_=false
if ta.crossover(close, internal_y_up) and internal_up_broke and y_up != internal_y_up
    bool MSS = na
    MSS := int_t_MS < 0
    internal_up_broke := false
    int_t_MS := 1
    bull_mss:=MSS?true:false
    bull_bos:=MSS?false:true
    if showms and (ms_type=='All' or ms_type=='Internal')
        Show_MS(internal_x_up, internal_y_up, MSS ? 'MSS' : 'BOS', internal_bullish_col_MSS, true, true, internal_structure_lbl_size)
if ta.crossunder(close, internal_y_dn) and internal_dn_broke and y_dn != internal_y_dn 
    bool MSS = false
    MSS := int_t_MS > 0    
    internal_dn_broke := false
    int_t_MS := -1
    bear_mss:=MSS?true:false
    bear_bos:=MSS?false:true
    if showms and (ms_type=='All' or ms_type=='Internal')
        Show_MS(internal_x_dn, internal_y_dn, MSS ? 'MSS' : 'BOS', internal_bearish_col_MSS, true, false, internal_structure_lbl_size)

alertcondition(bull_mss,"Bullish MSS",'Bullish MSS Found Ez-SMC')
alertcondition(bear_mss,"Bearish MSS",'Bearish MSS Found Ez-SMC')
alertcondition(bull_bos,"Bullish BOS",'Bullish BOS Found Ez-SMC')
alertcondition(bear_bos,"Bearish BOS",'Bearish MSS Found Ez-SMC')



if ta.crossover(close, y_up) and crossed_up
    bool MSS = na
    MSS := t_MS < 0
    crossed_up := false
    t_MS := 1
    bull_mss_:=MSS?true:false
    bull_bos_:=MSS?false:true
    if showms or (ms_type=='All' or ms_type=='External')
        Show_MS(x_up, y_up, MSS ? 'MSS+' : 'BOS+', bullish_col_MSS, false, true, swing_structure_lbl_size)
if ta.crossunder(close, y_dn) and crossed_down
    bool MSS = na
    MSS := t_MS > 0
    crossed_down := false
    t_MS := -1
    bear_mss_:=MSS?true:false
    bear_bos_:=MSS?false:true
    if showms and (ms_type=='All' or ms_type=='External')
        Show_MS(x_dn, y_dn, MSS ? 'MSS+' : 'BOS+', bearish_col_MSS, false, false, swing_structure_lbl_size)

alertcondition(bull_mss_,"Bullish MSS+",'Bullish MSS+ Found Ez-SMC')
alertcondition(bear_mss_,"Bearish MSS+",'Bearish MSS+ Found Ez-SMC')
alertcondition(bear_bos_,"Bearish BOS+",'Bearish BOS+ Found Ez-SMC')
alertcondition(bull_bos_,"Bullish BOS+",'Bullish BOS+ Found Ez-SMC')

//-----------------------------------------------------------------------------}
//Order Blocks
//-----------------------------------------------------------------------------{
first_nonzero_digit(n) => 
    s = str.tostring(n)

    int r=int (str.tonumber(s[0]))
    for c=0 to str.length(s)-1
        if s[c] != '0'
            r:=int (str.tonumber(s[c]))
    r 

//Order block coordinates function
ob_found(loc,b_index,show_ob,show_iob)=>
    
    type_obs="none"
    valid=false
    H=high
    L=low
    O=open
    C=close
    V=volume
    idx=1
    volume_=0.0
    b_volume=0
    s_volume=0
    use_max=false
    min = 99999999.
    max = 0.

    if open[5]>close[5] and close[4]>=open[5] and low[1]>high[5] and low>high[5] and show_iob
        if low[5]>low[4]
            type_obs:="Internal Bearish"
            H:=math.min(high[4],high[5])
            L:=low[4]
            O:=open[4]        
            C:=close[4]
            V:=volume[4]
            idx:=time[4]
            valid:=true
            use_max:=false
        else
            type_obs:="Internal Bearish"
            H:=high[5]
            L:=low[5]
            O:=open[5]        
            C:=close[5]
            V:=volume[5]
            idx:=time[5]
            valid:=true
            use_max:=false
    
    else if open[5]<close[5] and close[4]<=open[5] and high[1]<low[5] and high<low[5] and show_iob
        if high[4]>high[5]
            type_obs:="Internal Bullish"
            H:=high[4]
            L:=math.max(low[4],low[5])
            O:=open[4]        
            C:=close[4]
            V:=volume[4]
            idx:=time[4]
            valid:=true
            use_max:=true
        else
            type_obs:="Internal Bullish"
            H:=high[5]
            L:=low[5]
            O:=open[5]        
            C:=close[5]
            V:=volume[5]
            idx:=time[5]
            valid:=true
            use_max:=true

    else if open[5]>close[5] and close[4]>close[5] and close[3]>=open[5] and low>high[5] and show_iob
        if low[5]>low[4]
            type_obs:="Internal Bearish"
            H:=math.min(high[4],high[5])
            L:=low[4]
            O:=open[4]        
            C:=close[4]
            V:=volume[4]
            idx:=time[4]
            valid:=true
            use_max:=false
        else
            type_obs:="Internal Bearish"
            H:=high[5]
            L:=low[5]
            O:=open[5]        
            C:=close[5]
            V:=volume[5]
            idx:=time[5]
            valid:=true
            use_max:=false

    else if open[5]<close[5] and close[4]<close[5] and close[3]<=open[5] and high<low[5] and show_iob
        if high[4]>high[5]
            type_obs:="Internal Bullish"
            H:=high[4]
            L:=math.max(low[4],low[5])
            O:=open[4]        
            C:=close[4]
            V:=volume[4]
            idx:=time[4]
            valid:=true
            use_max:=true
        else
            type_obs:="Internal Bullish"
            H:=high[5]
            L:=low[5]
            O:=open[5]      
            C:=close[5]
            V:=volume[5]
            idx:=time[5]
            valid:=true
            use_max:=true
    else
        valid:=false

    if valid
        
        ind=0
        thold_ = (ta.highest(300) - ta.lowest(300)) * (max_width_ob/2.) / 100.

        buyingVolume = math.round(V * (C - L) / (H - L))
        sellingVolume = math.round(V * (H - C) / (H - L))
        t_volume = (buyingVolume+sellingVolume)/2.
        b_volume:=int ((buyingVolume/ta.highest(t_volume,300))*100)
        s_volume:=int ((sellingVolume/ta.highest(t_volume,300))*100)

        volume_:=V
        //Search for highest/lowest high within the structure interval and get range
        if use_max
            max:=H//[idx]
            min_1=L//[idx]//H[1]-math.min(open[1],close[1])>ob_threshold
            min:=math.max(min_1,max-thold_)
        else
            max_1=H//[idx]//math.max(open[idx],close[idx])
            min:=L//[idx]
            max:=math.min(max_1,min+thold_)

    [valid,volume_,b_volume,s_volume,max,min,idx,use_max ? -1 : 1,type_obs]


//Set order blocks
show_orderblock(boxes,lines, target_top, target_btm, target_left, target_type, show_last, swing, size,vol,col_1,col_2,length_extend_ob,ob_extend,tf_text,tf_text_2,ob_text_size,vol_text,perct_text,text_color_ob,show_line_obs,line_style_obs)=>
    for x = 0 to show_last-1
        get_box = array.get(boxes, x)
        box.set_lefttop(get_box, na, na)
        box.set_rightbottom(get_box, na , na)
        box.set_border_color(get_box, na)
        box.set_bgcolor(get_box, na)
        get_line = array.get(lines, x)
        line.set_color(get_line,na)
        line.set_xy1(get_line,na,na)
        line.set_xy2(get_line,na,na)

    for i = 0 to size-1
        get_box = array.get(boxes, i)
        get_line = array.get(lines, i)
        max_left=bar_index-750
        volume_sum=array.sum(vol)
        volume_=array.get(vol, i)>100000000 ? array.get(vol, i)/100000000.: array.get(vol, i)>1000000 ? array.get(vol, i)/1000000. : array.get(vol, i)/1000.
        volume_per=(array.get(vol, i)/volume_sum)*100
        unit=array.get(vol, i)>100000000 ?' B': array.get(vol, i)>1000000 ?' M' : ' K'
        text_vol=vol_text and perct_text ? tf_text +  str.tostring(volume_,'#.##')+ unit + ' ('+ str.tostring(volume_per,'#.##')+'%)' : vol_text and not(perct_text) ? tf_text +  str.tostring(volume_,'#.##')+ unit : not(vol_text) and perct_text ? tf_text +   ' '+ str.tostring(volume_per,'#.##')+'%' : tf_text_2+  ''
        if true//max_left<array.get(target_left, i)
            box.set_lefttop(get_box, array.get(target_left, i), array.get(target_top, i))
            box.set_rightbottom(get_box,timenow+((timediff)*length_extend_ob) , array.get(target_btm, i))
            box.set_text(get_box,text_vol)
            box.set_text_color(get_box,text_color_ob)
            box.set_border_color(get_box,color.gray)
            box.set_border_width(get_box,2)
            box.set_text_halign(get_box,text.align_right)
            box.set_text_valign(get_box,text.align_center)
            box.set_text_size(get_box,ob_text_size)
            fully_extend=not(vol_text) and not(perct_text) and ob_extend? extend.right : extend.none
            len_ext=not(vol_text) and not(perct_text)?length_extend_ob : length_extend_ob/2
            line.set_extend(get_line,fully_extend)
            line.set_style(get_line,line_style_obs)
            line.set_xy1(get_line,array.get(target_left, i),array.get(target_top, i)-(array.get(target_top, i) - array.get(target_btm, i))/2)
            line.set_xy2(get_line,time+((timediff)*(len_ext)),array.get(target_top, i)-(array.get(target_top, i) - array.get(target_btm, i))/2)
            if show_line_obs
                line.set_color(get_line,color.gray)

            if ob_extend
                box.set_extend(get_box, extend.right)

            color css = na
            css := array.get(target_type, i) == 1 ? col_1 : col_2
            box.set_border_color(get_box, css)
            box.set_bgcolor(get_box, css)
            box.set_border_color(get_box, css)
            

// //Set order blocks
// display_sub_ob_sell(boxes, target_top, target_btm, target_left, target_type, show_last, swing, size,right)=>
//     for x = 0 to show_last-1
//         get_box = array.get(boxes, x)
//         box.set_lefttop(get_box, na, na)
//         box.set_rightbottom(get_box, na , na)
//         box.set_border_color(get_box, na)
//         box.set_bgcolor(get_box, na)

//     for i = 0 to math.min(show_last-1, size-1)
//         get_box = array.get(boxes, i)
//         x=1000000000000
//         max_left=bar_index-750
//         max_right=array.get(target_left, i)+(((timediff)*(array.get(right, i)+5))) //> time+((timediff)*20) ? time+((time[1]-time[2])*20) : array.get(target_left, i)+(time+((time[1]-time[2])*(array.get(right, i)+10)))
//         if true//max_left<array.get(target_left, i)
//             box.set_lefttop(get_box,array.get(target_left, i), array.get(target_top, i))
//             box.set_rightbottom(get_box, math.min(max_right,timenow+((timediff)*20)), array.get(target_top, i)-(array.get(target_top, i) - array.get(target_btm, i))/2)
//             //box.set_extend(get_box, extend.right)
//             color css = na
//             if true//max_left<array.get(target_left, i)
//                 css := array.get(target_type, i) == 1 ? v_buy : v_buy
//                 box.set_border_color(get_box, color.new(css,100))
//                 box.set_bgcolor(get_box, css)
//     // if overlapping_filt
//     //     for i = math.min(show_last-1, size-1) to 0
//     //         get_box = array.get(boxes, i)
//     //         valid=true
//     //         index=0
//     //         //label.new(array.get(target_left,i),array.get(target_top,i),str.tostring(i))
//     //         if i>0
//     //             for x=i-1 to 0
//     //                 if array.get(target_top,i)>=array.get(target_btm,x) and array.get(target_top,i)<=array.get(target_top,x)
//     //                     valid:=false
//     //                 if array.get(target_btm,i)>=array.get(target_btm,x) and array.get(target_btm,i)<=array.get(target_top,x)
//     //                     valid:=false
//     //                 if array.get(target_btm,i)==array.get(target_btm,x) and array.get(target_top,i)==array.get(target_top,x)
//     //                     valid:=false
//     //                 if array.get(target_btm,i)<=array.get(target_btm,x) and array.get(target_top,i)>=array.get(target_top,x)
//     //                     valid:=false
//     //         if not(valid)
//     //             box.set_border_color(get_box, na)
//     //             box.set_bgcolor(get_box, na)



display_sub_ob_buy(boxes, target_top, target_btm, target_left, target_type, show_last, swing, size,right1,right2)=>
    for x = 0 to show_last-1
        get_box = array.get(boxes, x)
        box.set_lefttop(get_box, na, na)
        box.set_rightbottom(get_box, na , na)
        box.set_border_color(get_box, na)
        box.set_bgcolor(get_box, na)

    for i = 0 to math.min(show_last-1, size-1)
        get_box = array.get(boxes, i)
        x=1000000000000
        max_left=bar_index-750
        right=math.max(array.get(right1, i),array.get(right2, i))
        max_right=array.get(target_left, i)+(((timediff)*right+10)) //> time+((time[1]-time[2])*20 ? time+((time[1]-time[2])*20) : array.get(target_left, i)+(time+((time[1]-time[2])*(array.get(right, i)+10))))
        if true//max_left<array.get(target_left, i)
            box.set_lefttop(get_box, math.max(array.get(target_left, i),max_left), array.get(target_top, i)-(array.get(target_top, i) - array.get(target_btm, i))/10)
            box.set_rightbottom(get_box, math.min(max_right,timenow+((timediff)*20)), array.get(target_btm, i)+(array.get(target_top, i) - array.get(target_btm, i))/10)
            //box.set_right(get_box, array.get(target_left, i)+100)
            //box.set_extend(get_box, extend.right)
            color css = na
            if true//max_left<array.get(target_left, i)
                css := array.get(right1, i)>array.get(right2, i)? v_sell : v_buy
                box.set_border_color(get_box, color.new(css,100))
                box.set_bgcolor(get_box, css)

remove_ob(target_top, target_btm, target_left, target_type, show_last, swing, size)=>
    del_index=0
    deleted=false
    for i = 0 to size-1
        if i>0
            for x=i-1 to 0
                if array.get(target_top,i)>=array.get(target_btm,x) and array.get(target_top,i)<=array.get(target_top,x)
                    deleted:=true
                    del_index:=i
                if array.get(target_btm,i)>=array.get(target_btm,x) and array.get(target_btm,i)<=array.get(target_top,x)
                    deleted:=true
                    del_index:=i
                if array.get(target_btm,i)==array.get(target_btm,x) and array.get(target_top,i)==array.get(target_top,x)
                    deleted:=true
                    del_index:=i
                if array.get(target_btm,i)<=array.get(target_btm,x) and array.get(target_top,i)>=array.get(target_top,x)
                    deleted:=true
                    del_index:=i
    [deleted,del_index]

time_diff()=>((time[1]-time[101])/100)



// var iob_h_top = array.new_float(0)
// var iob_l_btm = array.new_float(0)
// var iob_h_left = array.new_int(0)
// var iob_l_left = array.new_int(0)
// var iob_type = array.new_int(0)


// if ta.pivothigh(high,3,1)
//     array.unshift(iob_h_top,high[1])
//     array.unshift(iob_h_left,time)

// if ta.pivotlow(low,3,1)
//     array.unshift(iob_l_btm,low[1])
//     array.unshift(iob_l_left,time)

// if array.size(iob_h_top)>3
//     array.shift(iob_h_top)
//     array.shift(iob_h_left)

// if array.size(iob_l_btm)>3
//     array.shift(iob_l_btm)
//     array.shift(iob_l_left)

// if array.size(iob_h_top)>0
//     for i=0 to array.size(iob_h_top)-1
//         x=array.get(iob_h_left,i)
//         y=array.get(iob_h_top,i)
//         if close>y
//             label.new(int(math.avg(x, time)), y, 'BOS', color = color.gray, textcolor = color.white,style= label.style_label_down, size = size.small,xloc =xloc.bar_time )
//             line.new(x, y, time, y, color = color.gray, style =line.style_dashed,xloc = xloc.bar_time )
//             array.remove(iob_h_top,i)
//             array.remove(iob_h_left,i)
//             break




//-----------------------------------------------------------------------------}
//Order Blocks Arrays
//-----------------------------------------------------------------------------{

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)
var ob_sell_vol = array.new_int(0)
var ob_buy_vol = array.new_int(0)
var ob_vol = array.new_float(0)

var ob_top_mtf = array.new_float(0)
var ob_btm_mtf = array.new_float(0)
var ob_left_mtf = array.new_int(0)
var ob_type_mtf = array.new_int(0)
var ob_sell_vol_mtf = array.new_int(0)
var ob_buy_vol_mtf = array.new_int(0)
var ob_vol_mtf = array.new_float(0)

bar_merge=barmerge.gaps_off
look_bars=barmerge.lookahead_on

[valid_ob,volume_,b_volume,s_volume,top_ob,btm_ob,left_ob,type_ob,_type]=request.security(ticker.standard(syminfo.tickerid), i_tf_ob, ob_found(x_up,bar_index,show_ob,show_iob), bar_merge,look_bars)

[valid_ob_mtf,volume__mtf,b_volume_mtf,s_volume_mtf,top_ob_mtf,btm_ob_mtf,left_ob_mtf,type_ob_mtf,_type_mtf]=request.security(ticker.standard(syminfo.tickerid), i_tf_ob_mtf, ob_found(x_up,bar_index,show_ob_mtf,show_iob_mtf), bar_merge,look_bars)

tf1_time=request.security(ticker.standard(syminfo.tickerid),i_tf_ob,time_diff(), bar_merge,look_bars)
tf2_time=request.security(ticker.standard(syminfo.tickerid),i_tf_ob_mtf,time_diff(), bar_merge,look_bars)

if valid_ob and not(valid_ob[1]) and barstate.isconfirmed
    array.unshift(ob_vol, volume_)
    array.unshift(ob_buy_vol, b_volume)
    array.unshift(ob_sell_vol, s_volume)
    array.unshift(ob_top, top_ob)
    array.unshift(ob_btm, btm_ob)
    array.unshift(ob_left, left_ob)
    array.unshift(ob_type, type_ob)

if valid_ob_mtf and not(valid_ob_mtf[1]) and barstate.isconfirmed
    array.unshift(ob_vol_mtf, volume__mtf)
    array.unshift(ob_buy_vol_mtf, b_volume_mtf)
    array.unshift(ob_sell_vol_mtf, s_volume_mtf)
    array.unshift(ob_top_mtf, top_ob_mtf)
    array.unshift(ob_btm_mtf, btm_ob_mtf)
    array.unshift(ob_left_mtf, time-((tf2_time)*5))
    array.unshift(ob_type_mtf, type_ob_mtf)

// if barstate.islast
//     label.new(bar_index,high,str.tostring(array.size(ob_top)))

alertcondition(_type=="External Bearish",'Bearish External OB','Bearish External OB Found Ez-SMC')
alertcondition(_type=="External Bullish",'Bullish External OB','Bullish External OB Found Ez-SMC')
alertcondition(_type=="Internal Bearish",'Bearish Internal OB','Bearish Internal OB Found Ez-SMC')
alertcondition(_type=="Internal Bullish",'Bullish Internal OB','Bullish Internal OB Found Ez-SMC')

//Set order blocks
var iob_boxes = array.new_box(0)
var ob_boxes = array.new_box(0)

var ob_volume = array.new_line(0)
var ob_volume_labels = array.new_label(0)

var iob_boxes_buy = array.new_box(0)
var ob_boxes_buy = array.new_box(0)

var iob_boxes_sell = array.new_box(0)
var ob_boxes_sell = array.new_box(0)

var iob_boxes_mtf = array.new_box(0)
var ob_boxes_mtf = array.new_box(0)

var ob_volume_mtf = array.new_line(0)
var ob_volume_labels_mtf = array.new_label(0)

var iob_boxes_buy_mtf = array.new_box(0)
var ob_boxes_buy_mtf = array.new_box(0)

var iob_boxes_sell_mtf = array.new_box(0)
var ob_boxes_sell_mtf = array.new_box(0)

if array.size(ob_top_mtf)>max_obs_mtf// or array.get(ob_left_mtf,array.size(ob_left_mtf)-1)>bar_index-400
    array.pop(ob_top_mtf)
    array.pop(ob_btm_mtf)
    array.pop(ob_left_mtf)
    array.pop(ob_type_mtf)
    array.pop(ob_buy_vol_mtf)
    array.pop(ob_sell_vol_mtf)
    array.pop(ob_vol_mtf)

// if array.get(ob_left_mtf,array.size(ob_left_mtf)-1)>bar_index-400
//     array.pop(ob_top_mtf)
//     array.pop(ob_btm_mtf)
//     array.pop(ob_left_mtf)
//     array.pop(ob_type_mtf)
//     array.pop(ob_buy_vol_mtf)
//     array.pop(ob_sell_vol_mtf)
//     array.pop(ob_vol_mtf)


if array.size(ob_top)>max_obs// or array.get(ob_left,array.size(ob_left)-1)>bar_index-400
    array.pop(ob_top)
    array.pop(ob_btm)
    array.pop(ob_left)
    array.pop(ob_type)
    array.pop(ob_buy_vol)
    array.pop(ob_sell_vol)
    array.pop(ob_vol)

// //Delete internal order blocks box coordinates if high_ms/bottom is broken
if array.size(ob_top_mtf)>1
    for index=0 to array.size(ob_top_mtf)-1
        src1=mittigation_filt_mtf=='Wicks' or mittigation_filt_mtf=='Touch'? low : mittigation_filt_mtf=='Close'? close : low
        src2=mittigation_filt_mtf=='Wicks' or mittigation_filt_mtf=='Touch'? high : mittigation_filt_mtf=='Close'? close : high
        up= mittigation_filt_mtf=='Touch' ? array.get(ob_top_mtf, index) : mittigation_filt_mtf=='Average'? array.get(ob_top_mtf, index)-(array.get(ob_top_mtf, index) - array.get(ob_btm_mtf, index))/2  : array.get(ob_btm_mtf, index)
        dn= mittigation_filt_mtf=='Touch' ? array.get(ob_btm_mtf, index) : mittigation_filt_mtf=='Average'? array.get(ob_top_mtf, index)-(array.get(ob_top_mtf, index) - array.get(ob_btm_mtf, index))/2  : array.get(ob_top_mtf, index)

        if (src1 < up or src1[1] < up or (mittigation_filt_mtf!='Touch' and src1[1] < up)) and array.get(ob_type_mtf, index) == 1// and bullish_OB_Break==false
            array.remove(ob_top_mtf, index) 
            array.remove(ob_btm_mtf, index) 
            array.remove(ob_left_mtf, index) 
            array.remove(ob_type_mtf, index)
            array.remove(ob_buy_vol_mtf, index)
            array.remove(ob_sell_vol_mtf, index)
            array.remove(ob_vol_mtf, index)
            bullish_OB_Break := true
            break

        else if (src2 > dn or src2[1] > dn  or (mittigation_filt_mtf!='Touch' and src2[1] > dn)) and array.get(ob_type_mtf, index) == -1// and bearish_OB_Break==false
            array.remove(ob_top_mtf, index) 
            array.remove(ob_btm_mtf, index)
            array.remove(ob_left_mtf, index) 
            array.remove(ob_type_mtf, index)
            array.remove(ob_buy_vol_mtf, index)
            array.remove(ob_sell_vol_mtf, index)
            array.remove(ob_vol_mtf, index)
            bearish_OB_Break := true
            break


if array.size(ob_top)>1
    for index=0 to array.size(ob_top)-1
        src1=mittigation_filt=='Wicks' or mittigation_filt=='Touch'? low : mittigation_filt=='Close'? close : low
        src2=mittigation_filt=='Wicks' or mittigation_filt=='Touch'? high : mittigation_filt=='Close'? close : high
        up= mittigation_filt=='Touch' ? array.get(ob_top, index) : mittigation_filt=='Average'? array.get(ob_top, index)-(array.get(ob_top, index) - array.get(ob_btm, index))/2 : array.get(ob_btm, index)
        dn= mittigation_filt=='Touch' ? array.get(ob_btm, index) : mittigation_filt=='Average'? array.get(ob_top, index)-(array.get(ob_top, index) - array.get(ob_btm, index))/2 : array.get(ob_top, index)

        if (src1 < up or src1[1] < up or (mittigation_filt!='Touch' and src1[2] < up)) and array.get(ob_type, index) == 1// and bullish_OB_Break==false
            array.remove(ob_top, index) 
            array.remove(ob_btm, index) 
            array.remove(ob_left, index) 
            array.remove(ob_type, index)
            array.remove(ob_buy_vol, index)
            array.remove(ob_sell_vol, index)
            array.remove(ob_vol, index)
            bullish_OB_Break := true
            break

        else if (src2 > dn or src2[1] > dn or (mittigation_filt!='Touch' and src2[2] > dn)) and array.get(ob_type, index) == -1// and bearish_OB_Break==false
            array.remove(ob_top, index) 
            array.remove(ob_btm, index)
            array.remove(ob_left, index) 
            array.remove(ob_type, index)
            array.remove(ob_buy_vol, index)
            array.remove(ob_sell_vol, index)
            array.remove(ob_vol, index)
            bearish_OB_Break := true
            break

alertcondition(bullish_OB_Break,'Bullish OB Break','Bullish OB Broken Ez-SMC')
alertcondition(bearish_OB_Break,'Bearish OB Break','Bearish OB Broken Ez-SMC')


ob_size_mtf = array.size(ob_type_mtf)

// iob_size = array.size(iob_type)
ob_size = array.size(ob_type)


if barstate.islast
    if true
        for i = 0 to max_obs-1
            array.push(ob_boxes, box.new(na,na,na,na, xloc = xloc.bar_time))
            array.push(ob_boxes_buy, box.new(na,na,na,na, xloc = xloc.bar_time))
            array.push(ob_boxes_sell, box.new(na,na,na,na, xloc = xloc.bar_time))
            array.push(ob_volume, line.new(na,na,na,na,xloc = xloc.bar_time,color=color.gray,style=line.style_solid,width = 1))

    if true
        for i = 0 to max_obs_mtf-1
            array.push(ob_boxes_mtf, box.new(na,na,na,na, xloc = xloc.bar_time))
            array.push(ob_boxes_buy_mtf, box.new(na,na,na,na, xloc = xloc.bar_time))
            array.push(ob_boxes_sell_mtf, box.new(na,na,na,na, xloc = xloc.bar_time))
            array.push(ob_volume_mtf, line.new(na,na,na,na,xloc = xloc.bar_time,color=color.gray,style=line.style_solid,width = 1))
            // array.push(ob_volume, line.new(na,na,na,na,xloc = xloc.bar_index,color=color.yellow,style=line.style_dashed,width = 3))
            // array.push(ob_volume_labels, label.new(na,na,xloc =xloc.bar_index,color=color.yellow,size=size.small ))

if ob_size > 1 and (overlapping_filt)
    [deleted_ob,del_index]=remove_ob(ob_top, ob_btm, ob_left, ob_type, max_obs, false, ob_size)
    if deleted_ob
        array.remove(ob_top, del_index)
        array.remove(ob_btm, del_index)
        array.remove(ob_left, del_index)
        array.remove(ob_type, del_index)
        array.remove(ob_buy_vol, del_index)
        array.remove(ob_sell_vol, del_index)
        array.remove(ob_vol, del_index)

if ob_size_mtf > 1 and (overlapping_filt_mtf)
    [deleted_ob,del_index]=remove_ob(ob_top_mtf, ob_btm_mtf, ob_left_mtf, ob_type_mtf, max_obs_mtf, false, ob_size_mtf)
    if deleted_ob
        array.remove(ob_top_mtf, del_index)
        array.remove(ob_btm_mtf, del_index)
        array.remove(ob_left_mtf, del_index)
        array.remove(ob_type_mtf, del_index)
        array.remove(ob_buy_vol_mtf, del_index)
        array.remove(ob_sell_vol_mtf, del_index)
        array.remove(ob_vol_mtf, del_index)


ob_size_mtf := array.size(ob_type_mtf)

// iob_size := array.size(iob_type)
ob_size := array.size(ob_type)

if ob_size > 0 and barstate.islast
    if show_order_blocks
        show_orderblock(ob_boxes,ob_volume, ob_top, ob_btm, ob_left, ob_type, max_obs, false, ob_size,ob_vol,ibull_ob_css,ibear_ob_css,length_extend_ob,ob_extend,'','',text_size_ob_,volume_text,percent_text,ob_text_color_1,show_line_ob_1,line_style_ob_1)
        // if v_filter
        //     display_sub_ob_buy(ob_boxes_buy, ob_top, ob_btm, ob_left, ob_type, max_obs, false, ob_size,ob_buy_vol,ob_sell_vol)
        //     display_sub_ob_sell(ob_boxes_sell, ob_top, ob_btm, ob_left, ob_type, max_obs, false, ob_size,ob_sell_vol)


if ob_size_mtf > 0 and barstate.islast
    if show_order_blocks_mtf 
        show_orderblock(ob_boxes_mtf,ob_volume_mtf , ob_top_mtf , ob_btm_mtf , ob_left_mtf , ob_type_mtf , max_obs_mtf , false, ob_size_mtf ,ob_vol_mtf ,ibull_ob_css_2,ibear_ob_css_2,length_extend_ob_mtf,ob_extend_mtf,timeframe1,timeframe_st,text_size_ob_2,volume_text_2,percent_text_2,ob_text_color_2,show_line_ob_2,line_style_ob_2)
        // if v_filter
            // display_sub_ob_buy(ob_boxes_buy_mtf , ob_top_mtf , ob_btm_mtf , ob_left_mtf , ob_type_mtf , max_obs_mtf , false, ob_size_mtf ,ob_buy_vol_mtf ,ob_sell_vol_mtf)
        //     display_sub_ob_sell(ob_boxes_sell_mtf , ob_top_mtf , ob_btm_mtf , ob_left_mtf , ob_type_mtf , max_obs_mtf , false, ob_size_mtf ,ob_sell_vol_mtf )




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


display_third = input.bool(false, title = "Display Third Indicator")
length3 = input.int(20, 'Minimum Range Length', minval = 2)
mult   = input.float(1., 'Range Width', minval = 0, step = 0.1)
atr_Len = input.int(500, 'ATR Length', minval = 1)

//Style
upCss = input(#089981, 'Broken Upward', group = 'Style')
dnCss = input(#f23645, 'Broken Downward', group = 'Style')
unbrokenCss = input(#2157f3, 'Unbroken', group = 'Style')

//-----------------------------------------------------------------------------}
//Detect and highlight ranges
//-----------------------------------------------------------------------------{
//Ranges drawings
var box bx = na
var line lvl = na

//Extensions
var float max2 = na
var float min2 = na

var os = 0
color detect_css = na

atr_ = ta.atr(atr_Len) * mult
ma = ta.sma(close, length3)
n_ = bar_index
count = 0
for i = 0 to length3-1
    count += math.abs(close[i] - ma) > atr_ ? 1 : 0

if count == 0 and count[1] != count
    //Test for overlap and change coordinates
    if n_[length3] <= bx.get_right()
        max2 := math.max(ma + atr_, bx.get_top())
        min2 := math.min(ma - atr_, bx.get_bottom())
        
        //Box new coordinates
        bx.set_top(max2)
        bx.set_rightbottom(n_, min2)
        bx.set_bgcolor(color.new(unbrokenCss, 80))

        //Line new coordinates
        avg = math.avg(max2, min2)
        lvl.set_y1(avg)
        lvl.set_xy2(n_, avg)
        lvl.set_color(unbrokenCss)
    else
        max2 := ma + atr_
        min2 := ma - atr_

        //Set new box and level
        bx := box.new(n_[length3], ma + atr_, n_, ma - atr_, na
          , bgcolor = color.new(unbrokenCss, 100))
        
        lvl := line.new(n_[length3], ma, n_, ma
          , color = unbrokenCss
          , style = line.style_dotted)

        detect_css := color.new(#787b86, 80)
        os := 0

else if count == 0
    bx.set_right(n_)
    lvl.set_x2(n_)

//Set color
if close > bx.get_top()
    bx.set_bgcolor(color.new(#ff5252, 100))
    lvl.set_color(upCss)
    os := 1
else if close < bx.get_bottom()
    bx.set_bgcolor(color.new(#ff5252, 100))
    lvl.set_color(dnCss)
    os := -1

//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
//Range detection bgcolor
bgcolor(detect_css)

plot(display_third ? max2 : na, 'Range Top'
  , max2 != max2[1] ? na : os == 0 ? unbrokenCss : os == 1 ? upCss : dnCss)

plot(display_third ? min2 : na, 'Range Bottom'
  , min2 != min2[1] ? na : os == 0 ? unbrokenCss : os == 1 ? upCss : dnCss)

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

//INPUTS
cooldownPeriod = input.int(10,title="Cooldown Period", minval=0, group = "Settings") 

lbLeft = 20
lbRight = 20

showSwing_ = input.bool(true,title="Show Swings?", inline="s_1", group = 'Swing Detaction')
swingClr = input.color(color.new(color.orange, 0), title='', inline="s_1", group = 'Swing Detaction')

bullWidth = input.int(1, title='Line Width:', group='Bullish Sweep')
bullStyle = input.string('Dashed', title='Line Style:', options=['Solid', 'Dotted', 'Dashed'], group='Bullish Sweep')
bullColor = input.color(color.new(color.teal, 0), title='Bullish Color:', group='Bullish Sweep')

bearWidth = input.int(1, title='Line Width:', group='Bearish Sweep')
bearStyle = input.string('Dashed', title='Line Style:', options=['Solid', 'Dotted', 'Dashed'], group='Bearish Sweep')
bearColor = input.color(color.new(color.maroon, 0), title='Bearish Color:', group='Bearish Sweep')

//FUNCTIONS
lineStyle_(s) =>
    if s == 'Solid'
        line.style_solid
    else if s == 'Dotted'
        line.style_dotted
    else
        line.style_dashed

//VARS
var int bullSignalIndex = 0
var int bearSignalIndex = 0

var line bullLine = na
var line bearLine = na

var line highLine = na
var line lowLine = na

var label swingHighLbl = na
var label swingLowLbl = na
var label swingHighLblTxt = na
var label swingLowLblTxt = na

var float swingLowVal = na
var float swingHighVal = na

//CALCULATIONS
pLow = ta.pivotlow(low, lbLeft, lbRight)
pHigh = ta.pivothigh(high, lbLeft, lbRight)

pLowVal = ta.valuewhen(not na(pLow), low[lbRight], 0) 
pHighVal = ta.valuewhen(not na(pHigh), high[lbRight], 0)

prevLowIndex = ta.valuewhen(not na(pLow), bar_index[lbRight], 0)
prevHighIndex = ta.valuewhen(not na(pHigh), bar_index[lbRight], 0)

lp = ta.lowest(low, lbLeft)
hp = ta.highest(high, lbLeft)

highestClose = ta.highest(close, lbLeft)
lowestClose = ta.lowest(close, lbLeft)

bullishSFP = low < pLowVal and close > pLowVal and open > pLowVal and low == lp and lowestClose >= pLowVal
bearishSFP = high > pHighVal and close < pHighVal and open < pHighVal and high == hp and highestClose <= pHighVal

bullCond = bullishSFP[3] and (close > pLowVal) and  (close[1] > pLowVal[1]) and (close[2] > pLowVal[2]) and bar_index >= bullSignalIndex + cooldownPeriod
bearCond = bearishSFP[3] and (close < pHighVal) and  (close[1] < pHighVal[1]) and (close[2] < pHighVal[2]) and bar_index >= bearSignalIndex + cooldownPeriod

//Check Swing H/L Stopper
var int swingLowCounter = 0
var int swingHighCounter = 0
var bool isSwingLowCheck = false
var bool isSwingHighCheck = false
var bool stopPrintingLow = false
var bool stopPrintingHigh = false

if high < swingLowVal and isSwingLowCheck
    swingLowCounter := swingLowCounter+1

if low > swingHighVal and isSwingHighCheck
    swingHighCounter := swingHighCounter+1

if ta.crossunder(close, swingLowVal) and isSwingLowCheck == false
    isSwingLowCheck := true
    swingLowCounter := 1

if ta.crossover(close, swingHighVal) and isSwingHighCheck == false
    isSwingHighCheck := true
    swingHighCounter := 1

if swingLowCounter == 5 and isSwingLowCheck
    stopPrintingLow := true
    isSwingLowCheck := false
    line.set_x2(lowLine,bar_index[4])

if swingHighCounter == 5 and isSwingHighCheck
    stopPrintingHigh := true
    isSwingHighCheck := false
    line.set_x2(highLine,bar_index[4])

//Draw sweep lines
if bullCond and display_third
    bullSignalIndex := bar_index
    bullLine := line.new(prevLowIndex, pLowVal, bar_index-3, pLowVal, color=bullColor, width=bullWidth, style=lineStyle_(bullStyle))

if bearCond and display_third
    bearSignalIndex := bar_index
    bearLine := line.new(prevHighIndex, pHighVal, bar_index-3, pHighVal, color=bearColor, width=bearWidth, style=lineStyle_(bearStyle))

var swingHighArr = array.new_label(0)
var swingHighTextArr = array.new_label(0)

var swingLowArr = array.new_label(0)
var swingLowTextArr = array.new_label(0)

if array.size(swingHighArr) >= 3
    label.delete(array.shift(swingHighArr))
    label.delete(array.shift(swingHighTextArr))
   
if array.size(swingLowArr) >= 3
    label.delete(array.shift(swingLowArr))
    label.delete(array.shift(swingLowTextArr))

//Draw range lines
if showSwing_ and display_third
    if stopPrintingHigh == false 
        line.set_x2(highLine,bar_index+5)
    if stopPrintingLow == false
        line.set_x2(lowLine,bar_index+5)

if showSwing_ and not na(pHigh) and bearishSFP[lbRight] == false and display_third
    stopPrintingHigh := false
    swingHighVal := high[lbRight]
    line.delete(highLine)
    highLine := line.new(bar_index[lbRight], high[lbRight], bar_index+10, high[lbRight], color = swingClr, width = 2)

    swingHighLbl := label.new(bar_index[lbRight], high[lbRight], text="", yloc=yloc.abovebar, color = swingClr, textcolor = swingClr, style = label.style_triangledown, size = size.auto)
    swingHighLblTxt := label.new(bar_index[lbRight], high[lbRight], text="Swing\nH", yloc=yloc.abovebar, color = swingClr, textcolor = swingClr, style = label.style_none, size = size.small)
    array.push(swingHighArr, swingHighLbl)
    array.push(swingHighTextArr, swingHighLblTxt)

if showSwing_ and not na(pLow) and bullishSFP[lbRight] == false and display_third
    stopPrintingLow := false
    swingLowVal := low[lbRight]
    line.delete(lowLine)
    lowLine := line.new(bar_index[lbRight], low[lbRight], bar_index+10, low[lbRight], color = swingClr, width = 2)

    swingLowLbl := label.new(bar_index[lbRight], low[lbRight], text="", yloc=yloc.belowbar, color = swingClr, textcolor = swingClr, style = label.style_triangleup, size = size.auto)
    swingLowLblTxt := label.new(bar_index[lbRight], low[lbRight], text="Swing\nL", yloc=yloc.belowbar, color = swingClr, textcolor = swingClr, style = label.style_none, size = size.small)
    array.push(swingLowArr, swingLowLbl)
    array.push(swingLowTextArr, swingLowLblTxt) 

//PLOTS
plotshape(display_third ? bullCond : na, text='Sweep', color=bullColor, textcolor=bullColor, location=location.belowbar, offset = -3)
plotshape(display_third ? bearCond : na, text='Sweep', color=bearColor, textcolor=bearColor, location=location.abovebar, offset = -3) 

//ALERTS
alertcondition(bullishSFP, title='Bullish Sweep', message='{{ticker}} Bullish Sweep, Price:{{close}}')
alertcondition(bearishSFP, title='Bearish Sweep', message='{{ticker}} Bearish Sweep, Price:{{close}}')

//------------------------------------------------------------------------------
//  === Zig Zag Channels ===
//------------------------------------------------------------------------------

length1      = input(100)
extend      = input(true,'Extend To Last Bar')
show_ext    = input(true,'Show Extremities') 
show_labels = input(true,'Show Labels') 

//Style

upcol = input(#ff1100,'Upper Extremity Color',group='Style')
midcol = input(#ff5d00,'Zig Zag Color',group='Style')
dncol = input(#2157f3,'Lower Extremity Color',group='Style')
//------------------------------------------------------------------------------
os1 = 0
src1 = close
var float valtop = na
var float valbtm = na

//------------------------------------------------------------------------------
upper = ta.highest(src1,length1)
lower = ta.lowest(src1,length1)
os1 := src1[length1] > upper ? 0 : src1[length1] < lower ? 1 : os1[1]

btm = os1 == 1 and os1[1] != 1
top_ = os1 == 0 and os1[1] != 0

//------------------------------------------------------------------------------
btm_n = ta.valuewhen(btm,n_,0)
top_n = ta.valuewhen(top_,n_,0)
len_ = math.abs(btm_n - top_n)

if btm and display_third 
    max_diff_up = 0.
    max_diff_dn = 0.
    valbtm := low[length1]
    
    for i = 0 to len_-1
        point = low[length1] + i/(len_-1)*(valtop - low[length1])
        max_diff_up := math.max(math.max(src1[length1+i],open[length1+i]) - point,max_diff_up)
        max_diff_dn := math.max(point - math.min(src1[length1+i],open[length1+i]),max_diff_dn)
        
    line.new(n_[len_+length1],valtop,n_[length1],low[length1],color=midcol)
    
    if show_ext
        line.new(n_[len_+length1],valtop+max_diff_up,n_[length1],low[length1]+max_diff_up
          ,color=upcol,style=line.style_dotted)
        line.new(n_[len_+length1],valtop-max_diff_dn,n_[length1],low[length1]-max_diff_dn
          ,color=dncol,style=line.style_dotted)
    if show_labels
        label.new(n_[length1],low[length1],str.tostring(low[length1],'#.####'),color=#00000000
          ,style=label.style_label_up,textcolor=dncol,textalign=text.align_left,size=size.small)

if top_ and display_third 
    max_diff_up = 0.
    max_diff_dn = 0.
    valtop := high[length1]
    
    for i = 0 to len_-1
        point = high[length1] + i/(len_-1)*(valbtm - high[length1])
        max_diff_up := math.max(math.max(src1[length1+i],open[length1+i]) - point,max_diff_up)
        max_diff_dn := math.max(point - math.min(src1[length1+i],open[length1+i]),max_diff_dn)
    
    line.new(n_[len_+length1],valbtm,n_[length1],high[length1],color=midcol)
    
    if show_ext
        line.new(n_[len_+length1],valbtm+max_diff_up,n_[length1],high[length1]+max_diff_up
          ,color=upcol,style=line.style_dotted)
        line.new(n_[len_+length1],valbtm-max_diff_dn,n_[length1],high[length1]-max_diff_dn
          ,color=dncol,style=line.style_dotted)
    if show_labels
        label.new(n_[length1],high[length1],str.tostring(high[length1],'#.####'),color=#00000000
          ,style=label.style_label_down,textcolor=upcol,textalign=text.align_left,size=size.small)

if barstate.islast and extend and display_third 
    max_diff_up = 0.
    max_diff_dn = 0.  
    x1 = 0
    y1 = 0.
    
    if os1 == 1
        x1 := btm_n-length1
        y1 := valbtm
        
        for i = 0 to n_-btm_n+length1-1
            point = src1 + i/(n_-btm_n+length1-1)*(valbtm - src1)
            max_diff_up := math.max(math.max(src1[i],open[i]) - point,max_diff_up)
            max_diff_dn := math.max(point - math.min(src1[i],open[i]),max_diff_dn)

    else 
        x1 := top_n-length1
        y1 := valtop
        
        for i = 0 to n_-top_n+length1-1
            point = src1 + i/(n_-top_n+length1-1)*(valtop - src1)
            max_diff_up := math.max(math.max(src1[i],open[i]) - point,max_diff_up)
            max_diff_dn := math.max(point - math.min(src1[i],open[i]),max_diff_dn)
        
    line.delete(line.new(x1,y1,n_,src1,color=midcol,extend=extend.right)[1])
    
    if show_ext
        line.delete(line.new(x1,y1+max_diff_up,n_,src1+max_diff_up
          ,color=upcol,style=line.style_dotted,extend=extend.right)[1])
        line.delete(line.new(x1,y1-max_diff_dn,n_,src1-max_diff_dn
          ,color=dncol,style=line.style_dotted,extend=extend.right)[1])
          
//------------------------------------------------------------------------------
plot(display_third and btm ? low[length1] : top_ ? high[length1] : na,'Circles'
  ,color = btm ? dncol : upcol
  ,style=plot.style_circles
  ,offset=-length1)

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

C_Len = 14 // ta.ema depth for bodyAvg
C_ShadowPercent = 5.0 // size of shadows
C_ShadowEqualsPercent = 100.0
C_DojiBodyPercent = 5.0
C_Factor = 2.0 // shows the number of times the shadow dominates the candlestick body

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

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

label_color_bearish = input(color.rgb(255, 82, 82, 90), "Label Color Bearish")
label_color_bullish = input(color.rgb(33, 149, 243, 90), "Label Color Bullish")

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

C_DownTrend = true
C_UpTrend = true
var trendRule1 = "SMA50"
var trendRule2 = "SMA50, SMA200"
var trendRule = input.string(trendRule1, "Detect Trend Based On", options=[trendRule1, trendRule2, "No detection"])

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

if trendRule == trendRule2
	sma200 = ta.sma(close, 200)
	sma50 = ta.sma(close, 50)
	C_DownTrend := close < sma50 and sma50 < sma200
	C_UpTrend := close > sma50 and sma50 > sma200


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


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

//-----------------------------------------------------------------------------}
//SUPPORT AND RESISTANCE MTF
//-----------------------------------------------------------------------------{
const bool DEBUG = false
const int timeframeCount = 3
const float touchATR = 1.0 / 30.0
const float retestATR = 1.0 / 30.0
const float labelOffsetY = 1.5
const int labelOffsetsXIndex = 30
const int maxPivotsBackSR = 15
const int retestLabelEveryXBars = 3
const int maxTraverse = 250  // Affects bar history limit. Default value 250.
const int maxRetestLabels = 100
const int maxSupports = 3
const int maxResistances = 3
const int debug_maxPivotLabels = 25

// _____ INPUTS _____
resistanceSupportCount = input.int(3, "Support & Resistance Count", options = [1, 2, 3], group = "General Configuration", display = display.none)
pivotRange = input.int(15, "Pivot Range", options = [5, 15, 30], tooltip = "Increase for more general pivots, decrease for more private pivots.", group = "General Configuration", display = display.none)
strength = input.int(1, "Strength", options = [1, 2, 3, 4], tooltip = "X many times price touched relative price area in order to be considered a support/resistance zone.", group = "General Configuration", display = display.none)
expandLines = input.bool(true,"Expand Lines & Zones", group = "General Configuration", display = display.none)

enableZones = input.bool(false, "Enable Zones", group = "Support & Resistance Zones", display = display.none)
zoneWidthType = input.string("Dynamic", "Zone Width Type", options = ["Fixed", "Dynamic"], group = "Support & Resistance Zones", display = display.none)
zoneWidth = input.int(1, "Fixed Zone Width", options = [1,2,3], group = "Support & Resistance Zones", display = display.none)

timeframe1Enabled = input.bool(true, title = "", group = "Timeframes", inline = "timeframe1", display = display.none)
timeframe1_ = input.timeframe("", title = "", group = "Timeframes", inline = "timeframe1_", display = display.none)
timeframe2Enabled = input.bool(true, title = "", group = "Timeframes", inline = "timeframe2", display = display.none)
timeframe2 = input.timeframe("240", title = "", group = "Timeframes", inline = "timeframe2", display = display.none)
timeframe3Enabled = input.bool(false, title = "", group = "Timeframes", inline = "timeframe3", display = display.none)
timeframe3 = input.timeframe("30", title = "", group = "Timeframes", inline = "timeframe3", display = display.none)

showBreaks = input.bool(true,"Show Breaks", group = "Breaks & Retests", inline = "ShowBR", display = display.none)
showRetests = input.bool(true,"Show Retests", group = "Breaks & Retests", inline = "ShowBR", display = display.none)
avoidFalseBreaks = input.bool(true, "Avoid False Breaks", group = "Breaks & Retests", display = display.none)
falseBreakoutVolumeThresholdOpt = input.float(0.3, "Break Volume Threshold", minval=0.1, maxval=1.0, step=0.1, group = "Breaks & Retests", tooltip = "Only taken into account if Avoid False Breakouts is enabled.\nHigher values mean it's less likely to be a break.", display = display.none)
inverseBrokenLineColor = input.bool(true, "Inverse Color After Broken", tooltip = "Needs Show Breaks & Expand Lines option enabled.", group = "Breaks & Retests", display = display.none)

falseBreakoutVolumeThreshold = falseBreakoutVolumeThresholdOpt * 100.0

lineStyle_ = input.string("....", "Line Style", ["____", "----", "...."], group = "Style", display = display.none)
lineWidth = input.int(1, "Line Width", minval = 1, group = "Style", display = display.none)
supportColor = input.color(#08998180, "Support Color", group = "Style", inline = "RScolors", display = display.none)
resistanceColor = input.color(#f2364580, "Resistance Color", group = "Style", inline = "RScolors", display = display.none)
textColor = input.color(#11101051, "Text Color", group = "Style", inline = "RScolors", display = display.none)
labelsAlign = input.string("Right", "Align Labels", options = ["Right", "Center"], group = "Style", tooltip = "Will only work when zones are disabled.", display = display.none)

enableRetestAlerts = input.bool(true, "Enable Retest Alerts", tooltip = "Needs Show Retests option enabled.", group = "Alerts", display = display.none)
enableBreakAlerts = input.bool(true, "Enable Break Alerts", group = "Alerts", display = display.none)

memoryOptimizatonEnabled = input.bool(true, "Enable Memory Optimization", tooltip = "Enable this option if you encounter memory errors.", group = "Advanced", display = display.none)
// _____ INPUTS END _____

// _____ DEBUG OPTIONS _____
debug_labelPivots = not DEBUG ? "None" : input.string("None", title = "[DBG] Label Pivots", group = "DEBUG", options = ["All", "RS", "None"], tooltip = "All -> Debugs all pivot labels.\nRS -> Debugs RS pivot labels.\nNone -> Debugs none of the last R&S pivots.")
debug_pivotLabelText = not DEBUG ? false : input.bool(false, title = "[DBG] Pivot Label Text", group = "DEBUG")
debug_showBrokenOnLabel = not DEBUG ? false : input.bool(false, "[DBG] Show Broken Text On Label", group = "DEBUG")
debug_removeDuplicateRS = not DEBUG ? true : input.bool(true, "[DBG] Remove Duplicate RS", group = "DEBUG")
debug_lastXResistances = not DEBUG ? 3 : input.int(3, "[DBG] Show Last X Resistances", minval = 0, maxval = maxResistances, group = "DEBUG")
debug_lastXSupports = not DEBUG ? 3 : input.int(3, "[DBG] Show Last X Supports", minval = 0, maxval = maxSupports, group = "DEBUG")
debug_enabledHistory = not DEBUG ? true : input.bool(true, "[DBG] Enable History", group = "DEBUG")
debug_maxHistoryRecords = not DEBUG ? 10 : input.int(10, "[DBG] Max History Records", options =  [1, 2, 5, 10, 25], group = "DEBUG")
// _____ DEBUG OPTIONS END _____

atr_1 = ta.atr(30)

createRSLine (color) =>
    line.new(na, na, na, na, extend = expandLines ? extend.both : extend.none, xloc=xloc.bar_time, color = color, width = lineWidth, style = lineStyle_ == "----" ? line.style_dashed : lineStyle_ == "...." ? line.style_dotted : line.style_solid)

createRSBox (color, xlocType) =>
    box.new(na, na, na, na, text_size = size.normal, xloc = xlocType, extend = extend.both, bgcolor = color, text_color = textColor, text_halign = expandLines ? text.align_right : text.align_center, border_color = #00000000)

createRSLabel () =>
    label.new(na, na, "", style = label.style_none, textcolor = textColor)

createBreakLabel (RSType) =>
    var ttBreakResistance = "Breakout\nA breakout of Support or Resistance."
    label.new(na,na,"B",style = RSType == "Resistance" ? label.style_label_up : label.style_label_down, color=color.rgb(33, 149, 243, 50), textcolor = color.white, xloc = xloc.bar_time, size = size.small,tooltip = ttBreakResistance)

createRetestLabel (RSType) =>
    label.new(na,na,"R",style = RSType == "Resistance" ? label.style_label_down : label.style_label_up, color = RSType == "Resistance" ? resistanceColor : supportColor, textcolor = color.white, xloc = xloc.bar_time, size = size.small)

moveLine(_line, _x, _y, _x2) =>
    line.set_xy1(_line, _x,  _y)
    line.set_xy2(_line, _x2, _y)

moveBox (_box, _topLeftX, _topLeftY, _bottomRightX, _bottomRightY) =>
    box.set_lefttop(_box, _topLeftX, _topLeftY)
    box.set_rightbottom(_box, _bottomRightX, _bottomRightY)

moveRSInfoBox (_box, _startPointX, _price, _endPointX) =>
    zoneWidthPercent = zoneWidth == 1 ? 0.05 : zoneWidth == 2 ? 0.06 : 0.075
    if zoneWidthType == "Dynamic"
        zoneWidthPercent := ((atr_1) / _price) * 100 / 3.0
    topY = _price * (1.0 + (zoneWidthPercent / 2.0 / 100.0))
    bottomY = _price * (1.0 - (zoneWidthPercent / 2.0 / 100.0))
    moveBox(_box, _startPointX, topY, _endPointX, bottomY)

// _____ TYPES _____

type customPoint
    int t
    float price

type RSInfo
    bool isBroken = na
    int brokenTime = na
    string RSType = na
    float price = na
    line line = na
    box box = na
    label priceLabel = na
    customPoint[] points = na
    label[] debugPoints = na
    label breakLabel = na
    label[] retestLabels = na
    line breakLine = na
    box breakBox = na

curTR = ta.tr(true)
lowPivot = ta.pivotlow(low, pivotRange, pivotRange)
highPivot = ta.pivothigh(high, pivotRange, pivotRange)
pivotTime = time[pivotRange]

newRSInfo (RSType) =>
    newRSInfoF = RSInfo.new()
    newRSInfoF.RSType := RSType
    newRSInfoF.price := na
    newRSInfoF.isBroken := false
    newRSInfoF.brokenTime := na

    newRSInfoF.line := enableZones ? na : createRSLine(RSType == "Resistance" ? resistanceColor : supportColor)
    newRSInfoF.box := enableZones ? createRSBox(RSType == "Resistance" ? resistanceColor : supportColor, xloc.bar_time) : na
    newRSInfoF.priceLabel := enableZones ? na : createRSLabel()
    newRSInfoF.points := array.new<customPoint>(0)
    newRSInfoF.debugPoints := array.new<label>(0)
    newRSInfoF.retestLabels := array.new<label>(0)
    newRSInfoF.breakLabel := na
    newRSInfoF.breakLine := na
    newRSInfoF.breakBox := na
    
    newRSInfoF

histRSInfo (RSInfo RSInfoF) =>
    RSType = RSInfoF.RSType
    newRS = RSInfo.new()
    newRS.RSType := RSType
    newRS.price := RSInfoF.price

    newRS.debugPoints := array.new<label>(0)
    newRS.retestLabels := array.new<label>(0)
    newRS.points := array.new<customPoint>(0)

    histText = "History | " + str.tostring(newRS.price, format.mintick)

    startTime = math.min(time, RSInfoF.points.get(RSInfoF.points.size() - 1).t)
    endTime = RSInfoF.isBroken ? RSInfoF.brokenTime : time

    if enableZones 
        newRS.box := createRSBox(RSType == "Resistance" ? resistanceColor : supportColor, xloc.bar_time)
        moveRSInfoBox(newRS.box, startTime, newRS.price, endTime)
        box.set_extend(newRS.box, expandLines ? extend.both : extend.none)
        box.set_text(newRS.box, histText)
    else
        newRS.line := line.copy(RSInfoF.line)
        moveLine(newRS.line, startTime, newRS.price, endTime)
        line.set_extend(newRS.line, expandLines ? extend.both : extend.none)

        newRS.priceLabel := label.copy(RSInfoF.priceLabel)
        label.set_text(newRS.priceLabel, histText)
        label.set_xloc(newRS.priceLabel, (startTime + endTime) / 2, xloc.bar_time)
    
    if not na(newRS.breakLabel)
        newRS.breakLabel := label.copy(RSInfoF.breakLabel)
    
    newRS

derenderRSInfo (RSInfo RSInfoF) =>
    if not na(RSInfoF)
        line.delete(RSInfoF.line)
        box.delete(RSInfoF.box)
        label.delete(RSInfoF.priceLabel)

        if RSInfoF.debugPoints.size() > 0
            for i = 0 to RSInfoF.debugPoints.size() - 1
                label.delete(RSInfoF.debugPoints.get(i))

        if RSInfoF.retestLabels.size() > 0
            for i = 0 to RSInfoF.retestLabels.size() - 1
                label.delete(RSInfoF.retestLabels.get(i))
        
        label.delete(RSInfoF.breakLabel)
        line.delete(RSInfoF.breakLine)
        box.delete(RSInfoF.breakBox)

safeDeleteRSInfo (RSInfo RSInfoF) =>
    if not na(RSInfoF)
        derenderRSInfo(RSInfoF)
        RSInfoF.points.clear()
        RSInfoF.debugPoints.clear()
        RSInfoF.retestLabels.clear()


type timeframeInfo
    int index = na
    string timeframeStr = na
    bool isEnabled = false

    RSInfo[] resistances = na
    RSInfo[] supports = na

    float[] highPivots = na
    float[] highTRs = na
    int[] highTimes = na

    float[] lowPivots = na
    float[] lowTRs = na
    int[] lowTimes = na

newTimeframeInfo (index, timeframeStr, isEnabled) =>
    newTFInfo = timeframeInfo.new()
    newTFInfo.index := index
    newTFInfo.isEnabled := isEnabled
    newTFInfo.timeframeStr := timeframeStr

    newTFInfo.resistances := array.new<RSInfo>(debug_lastXResistances)
    newTFInfo.supports := array.new<RSInfo>(debug_lastXSupports)
    
    newTFInfo.highPivots := array.new<float>()
    newTFInfo.highTRs := array.new<float>()
    newTFInfo.highTimes := array.new<int>()

    newTFInfo.lowPivots := array.new<float>()
    newTFInfo.lowTRs := array.new<float>()
    newTFInfo.lowTimes := array.new<int>()
    
    newTFInfo

// _____ TYPES END _____

// _____ VARS _____

var timeframeInfo[] timeframeInfos = array.from(newTimeframeInfo(1, timeframe1_, timeframe1Enabled), newTimeframeInfo(2, timeframe2, timeframe2Enabled), newTimeframeInfo(3, timeframe3, timeframe3Enabled))
var bool initRun = true

var float[] allLowPivots = array.new<float>(0)
var float[] allHighPivots = array.new<float>(0)

var int[] allLowTimes = array.new<int>(0)
var int[] allHighTimes = array.new<int>(0)

var float[] allHighTR = array.new<float>(0)
var float[] allLowTR = array.new<float>(0)

var RSInfo[] history = array.new<RSInfo>(0)

RSInfo[] curRSList = array.new<RSInfo>(0)
RSInfo[] oldRSList = array.new<RSInfo>(0)

int maxPivotsAllowed = memoryOptimizatonEnabled ? 7 : 15 // Affects memory limit. Default value 15.

// _____ VARS END _____

doValuesTouch (float value1, float value2, float tr) =>
    if math.abs(value1 - value2) <= tr * touchATR
        true
    else
        false

doValuesTouch (float value1, float value2, float tr, float customATRRatio) =>
    if math.abs(value1 - value2) <= tr * customATRRatio
        true
    else
        false

findLatestRS (timeframeInfo timeframeInfoF, string RSType, pivots, times, trs, bannedValues) =>
    RSInfo latestRSF = na
    pivotsCount = pivots.size()
    if pivotsCount > 0
        for i = 0 to pivotsCount - 1
            if i >= maxTraverse
                break
            
            index = pivotsCount - i - 1
            occurances = 0
            invalidValue = false
            pivotValue1 = pivots.get(index)
            if bannedValues.size() > 0
                for a = 0 to bannedValues.size() - 1
                    if doValuesTouch(pivotValue1, bannedValues.get(a), trs.get(index))
                        invalidValue := true
                        break
            
            
            
            for j = 0 to pivotsCount - 1
                if j >= maxTraverse
                    break
                
                index2 = pivotsCount - j - 1
                pivotValue2 = pivots.get(index2)
                if doValuesTouch(pivotValue1, pivotValue2, trs.get(index))
                    occurances += 1
                
                if occurances >= strength
                    latestRSF := newRSInfo(RSType)
                    latestRSF.price := pivotValue1
                    break
                
                
                
            
            
    if not na(latestRSF)
        cnt = 0
        if pivotsCount > 0
            for i = 0 to pivotsCount - 1
                
                index = pivotsCount - i - 1
                pivotValue = pivots.get(index)
                if doValuesTouch(pivotValue, latestRSF.price, trs.get(index))
                    labelTime = times.get(index)
                    latestRSF.points.push(customPoint.new(labelTime, pivotValue))
                    cnt += 1
                

    if not (debug_labelPivots == "None")
        if not (debug_labelPivots == "All")
            if not na(latestRSF)
                cnt = 0
                if pivotsCount > 0
                    for i = 0 to pivotsCount - 1
                        index = pivotsCount - i - 1
                        pivotValue = pivots.get(index)
                        if doValuesTouch(pivotValue, latestRSF.price, trs.get(index))
                            labelTime = times.get(index)
                            latestRSF.debugPoints.push(RSType == "Resistance" ? label.new(labelTime,pivotValue,text=debug_pivotLabelText ? str.tostring(pivotValue) : "",xloc=xloc.bar_time, color=resistanceColor, textcolor=color.white) : label.new(labelTime,pivotValue,text=debug_pivotLabelText ? str.tostring(pivotValue) : "",xloc=xloc.bar_time, color=supportColor,style = label.style_label_up, textcolor=color.white))
                            cnt += 1
                        
        else
            if not na(latestRSF)
                if pivotsCount > 0
                    for i = 0 to pivotsCount - 1
                        index = pivotsCount - i - 1
                        pivotValue = pivots.get(index)
                        labelTime = times.get(index)
                        latestRSF.debugPoints.push(RSType == "Resistance" ? label.new(labelTime,pivotValue,text=debug_pivotLabelText ? str.tostring(pivotValue) : "",xloc=xloc.bar_time, color=resistanceColor, textcolor=color.white) : label.new(labelTime,pivotValue,text=debug_pivotLabelText ? str.tostring(pivotValue) : "",xloc=xloc.bar_time, color=supportColor,style = label.style_label_up, textcolor=color.white))
                        
    latestRSF

findLatestNthRS (timeframeInfo timeframeInfoF, string RSType, pivots, times, trs, n_) =>
    float[] bannedValues = array.new<float>()
    foundRS = 0
    RSInfo foundLatestRS = na
    while foundRS < n_
        foundLatestRS := findLatestRS(timeframeInfoF, RSType, pivots, times, trs, bannedValues)
        if not na(foundLatestRS)
            foundRS += 1
            bannedValues.push(foundLatestRS.price)
        else
            break
    foundLatestRS

isTimeframeLower (timeframe1F, timeframe2F) =>
    timeframe.in_seconds(timeframe1F) < timeframe.in_seconds(timeframe2F)

getMinTimeframe (timeframe1F, timeframe2F) =>
    if isTimeframeLower(timeframe1F, timeframe2F)
        timeframe1F
    else
        timeframe2F

getMaxTimeframe (timeframe1F, timeframe2F) =>
    if isTimeframeLower(timeframe1F, timeframe2F)
        timeframe2F
    

getFirstBreak (RSInfo rsInfo) =>
    if na(rsInfo)
        [na, na]
    
    curIndex = 0
    float foundBreakLevel = na
    int foundBreakTime = na
    float foundBreakTR = na

    while true
        if curIndex >= maxTraverse
            break
        isBarBreak = rsInfo.RSType == "Resistance" ? (close[curIndex + 1] <= rsInfo.price and close[curIndex] > rsInfo.price) : (close[curIndex + 1] >= rsInfo.price and close[curIndex] < rsInfo.price)
        if isBarBreak
            isTrueBreakout = true
            if avoidFalseBreaks
                shortTerm = 2
                longTerm = 15
                
                shortSum = 0.0
                longSum = 0.0
                
                for i = 0 to shortTerm
                    shortSum += volume[curIndex + i]
                
                for i = 0 to longTerm
                    longSum += volume[curIndex + i]
                
                shortVolumeAvg = shortSum / shortTerm
                longVolumeAvg = longSum / longTerm

                volumeRatio = ((shortVolumeAvg - longVolumeAvg) / longVolumeAvg) * 100.0
                isTrueBreakout := (volumeRatio >= falseBreakoutVolumeThreshold)

            if isTrueBreakout
                foundBreakLevel := rsInfo.RSType == "Resistance" ? low[curIndex] : high[curIndex]
                foundBreakTime := time[curIndex]
                foundBreakTR := high[curIndex] - low[curIndex]
            
        curIndex += 1
        if time[curIndex] <= rsInfo.points.get(rsInfo.points.size() - 1).t
            break
    [foundBreakLevel, foundBreakTime, foundBreakTR]

getRetests (RSInfo rsInfo) =>
    if na(rsInfo)
        [na,na]
    
    curIndex = 0
    lastRetestIndex = -999
    int[] retestTimes = array.new<int>()
    float[] retestLevels = array.new<float>()
    float[] retestTRs = array.new<float>()

    while true
        if curIndex >= maxTraverse
            break
        if retestLevels.size() == maxRetestLabels
            break
        if rsInfo.isBroken and time[curIndex] >= rsInfo.brokenTime
            curIndex += 1
            continue

        tr = high[curIndex] - low[curIndex]
        isRetest = (rsInfo.RSType == "Resistance" ? (doValuesTouch(rsInfo.price, close[curIndex], tr, retestATR) or doValuesTouch(rsInfo.price, high[curIndex], tr, retestATR)) : (doValuesTouch(rsInfo.price, close[curIndex], tr, retestATR) or doValuesTouch(rsInfo.price, low[curIndex], tr, retestATR)))
        if isRetest and curIndex - lastRetestIndex >= retestLabelEveryXBars
            retestLevels.push(rsInfo.RSType == "Resistance" ? high[curIndex] : low[curIndex])
            retestTimes.push(time[curIndex])
            retestTRs.push(high[curIndex] - low[curIndex])
            lastRetestIndex := curIndex
        curIndex += 1
        
    [retestLevels, retestTimes, retestTRs]

formatTimeframeString (formatTimeframe) =>
    timeframeF = formatTimeframe == "" ? timeframe.period : formatTimeframe
    
    if str.contains(timeframeF, "D") or str.contains(timeframeF, "W") or str.contains(timeframeF, "S") or str.contains(timeframeF, "M")
        timeframeF
    else
        seconds = timeframe.in_seconds(timeframeF)
        if seconds >= 3600
            hourCount = int(seconds / 3600)
            str.tostring(hourCount) + " Hour" + (hourCount > 1 ? "s" : "")
        else
            timeframeF + " Min"

handleRSInfo (timeframeInfo timeframeInfoF, RSInfo RSInfoF, int index, string RSType) =>
    if not na(RSInfoF)
        if not na(timeframeInfoF)
            curRSList.push(RSInfoF)
        
        [foundBreakLevel, foundBreakTime, foundBreakTR] = getFirstBreak(RSInfoF)
        
        RSInfoF.isBroken := na(foundBreakLevel) ? false : true
        RSInfoF.brokenTime := na(foundBreakLevel) ? na : foundBreakTime

        if not na(foundBreakLevel)
            if showBreaks
                if na(RSInfoF.breakLabel)
                    RSInfoF.breakLabel := createBreakLabel(RSInfoF.RSType)
                label.set_xy(RSInfoF.breakLabel, foundBreakTime, foundBreakLevel + (RSInfoF.RSType == "Resistance" ? (-foundBreakTR / labelOffsetY) : foundBreakTR / labelOffsetY))
            
            if expandLines
                if na(RSInfoF.breakLine) and enableZones == false
                    RSInfoF.breakLine := createRSLine(color.black)
                
                if na(RSInfoF.breakBox) and enableZones == true
                    RSInfoF.breakBox := createRSBox(color.black, xloc.bar_time)

                if not enableZones
                    line.set_extend(RSInfoF.breakLine, extend.right)
                else
                    box.set_extend(RSInfoF.breakBox, extend.right)
                
                if inverseBrokenLineColor and showBreaks
                    if not enableZones
                        line.set_color(RSInfoF.breakLine, RSInfoF.RSType == "Resistance" ? supportColor : resistanceColor)
                    else    
                        box.set_bgcolor(RSInfoF.breakBox, RSInfoF.RSType == "Resistance" ? supportColor : resistanceColor)
                else
                    if not enableZones
                        line.set_color(RSInfoF.breakLine, RSInfoF.RSType == "Resistance" ? resistanceColor : supportColor)
                    else
                        box.set_bgcolor(RSInfoF.breakBox, RSInfoF.RSType == "Resistance" ? resistanceColor : supportColor)

        if showRetests
            [retestLevels, retestTimes, retestTRs] = getRetests(RSInfoF)

            if not na(retestLevels) and retestLevels.size() > 0
                for i = 0 to retestLevels.size() - 1
                    newRetestLabel = createRetestLabel(RSInfoF.RSType)
                    label.set_xy(newRetestLabel, retestTimes.get(i), retestLevels.get(i) + (RSInfoF.RSType == "Support" ? (-retestTRs.get(i) / labelOffsetY) : retestTRs.get(i) / labelOffsetY))
                    RSInfoF.retestLabels.push(newRetestLabel)

        timeSkipOffset = 0
        if enableZones
            zoneEndX = time + timeSkipOffset + timeframe.in_seconds(timeframe.period) * 1000 * labelOffsetsXIndex 
            startTime = math.min(time, RSInfoF.points.get(RSInfoF.points.size() - 1).t)
            moveRSInfoBox(RSInfoF.box, startTime, RSInfoF.price, na(foundBreakTime) ? zoneEndX : foundBreakTime)
            moveRSInfoBox(RSInfoF.breakBox, foundBreakTime, RSInfoF.price, zoneEndX)
        else
            endTime = time + timeSkipOffset + timeframe.in_seconds(timeframe.period) * 1000
            startTime = math.min(time, RSInfoF.points.get(RSInfoF.points.size() - 1).t)
            moveLine(RSInfoF.line, startTime, RSInfoF.price, na(foundBreakTime) ? endTime : foundBreakTime)
            moveLine(RSInfoF.breakLine, foundBreakTime, RSInfoF.price, endTime)
            //log.info(str.tostring(RSInfoF.price) + " | " + str.tostring(RSInfoF.points.get(strength - 1).time) + " = "  + str.tostring(line.get_x1(RSInfoF.line)) + " | " + str.tostring(endTime) + " = " + str.tostring(line.get_x2(RSInfoF.line)))
        
        if expandLines
            if not enableZones
                line.set_extend(RSInfoF.line, (na(foundBreakTime)) ? extend.both : extend.left)
            else    
                box.set_extend(RSInfoF.box, (na(foundBreakTime)) ? extend.both : extend.left)
        else
            if not enableZones
                line.set_extend(RSInfoF.line, na(foundBreakTime) ? extend.right : extend.none)
            else
                box.set_extend(RSInfoF.box, na(foundBreakTime) ? extend.right : extend.none)

        //labelTitleOld = formatTimeframeString(timeframeInfoF.timeframeStr) + " " + RSInfoF.RSType + " " + str.tostring(index + 1) + " (" + str.tostring(RSInfoF.price,format.mintick) + ")" + (RSInfoF.isBroken ? " [Broken]" : "")
        labelTitle = formatTimeframeString(timeframeInfoF.timeframeStr) + " | " + str.tostring(RSInfoF.price,format.mintick) + ((debug_showBrokenOnLabel and RSInfoF.isBroken)  ? " [B]" : "")
        
        if not enableZones
            label.set_text(RSInfoF.priceLabel, enableZones ? "" : labelTitle)
            label.set_y(RSInfoF.priceLabel, RSInfoF.price)
        else
            box.set_text(RSInfoF.box, (RSInfoF.isBroken and expandLines) ? "" : labelTitle)
            box.set_text(RSInfoF.breakBox, labelTitle)
        
        if expandLines or not RSInfoF.isBroken
            if not enableZones
                if labelsAlign == "Right"
                    label.set_xloc(RSInfoF.priceLabel, bar_index + labelOffsetsXIndex, xloc.bar_index)
                else
                    label.set_xloc(RSInfoF.priceLabel, labelsAlign == "Center" ? ((chart.right_visible_bar_time + chart.left_visible_bar_time) / 2) : na, xloc.bar_time)
            else
                box.set_text_halign(RSInfoF.breakBox, text.align_right)
                box.set_text_halign(RSInfoF.box, text.align_right)
        else
            if not enableZones
                label.set_xloc(RSInfoF.priceLabel, (RSInfoF.points.get(RSInfoF.points.size() - 1).t + RSInfoF.brokenTime) / 2, xloc.bar_time)
            else
                box.set_text_halign(RSInfoF.box, text.align_center)
                box.set_text_halign(RSInfoF.breakBox, text.align_center)
    else
        log.error("Couldn't find timeframe " + str.tostring(timeframeInfoF.index) + " " + str.tostring(index + 1) + "th " + RSType + " . Try decreasing pivot range in the settings.")

handleTimeframe (timeframeIndex, lowPivots, highPivots, lowTimes, highTimes, lowTRs, highTRs) =>
    timeframeInfoF = timeframeInfos.get(timeframeIndex - 1)
    
    timeframeInfoF.lowPivots.clear()
    timeframeInfoF.highPivots.clear()

    timeframeInfoF.lowTimes.clear()
    timeframeInfoF.highTimes.clear()

    timeframeInfoF.lowTRs.clear()
    timeframeInfoF.highTRs.clear()

    timeframeInfoF.lowPivots := lowPivots
    timeframeInfoF.highPivots := highPivots

    timeframeInfoF.lowTimes := lowTimes
    timeframeInfoF.highTimes := highTimes

    timeframeInfoF.lowTRs := lowTRs
    timeframeInfoF.highTRs := highTRs

getHigherTFData (timeframeStr) =>
    request.security(syminfo.tickerid, getMaxTimeframe(timeframe.period, timeframeStr), [allLowPivots, allHighPivots, allLowTimes, allHighTimes, allLowTR, allHighTR])

pushHighPivots (timeframeInfoF, highPivotF, timeF, trF) =>
    if not na(highPivotF)
        timeframeInfoF.highPivots.push(highPivotF)
        timeframeInfoF.highTimes.push(timeF)
        timeframeInfoF.highTRs.push(trF)

pushLowPivots (timeframeInfoF, lowPivotF, timeF, trF) =>
    if not na(lowPivotF)
        timeframeInfoF.lowPivots.push(lowPivotF)
        timeframeInfoF.lowTimes.push(timeF)
        timeframeInfoF.lowTRs.push(trF)

handleTimeframeIfLower (timeframeInfo timeframeInfoF, highs, lows, int[] timesF, float[] trsF) =>
    if timeframeInfoF.isEnabled and isTimeframeLower(timeframeInfoF.timeframeStr, timeframe.period)
        if highs.size() > 0
            for i = 0 to highs.size() - 1
                timeF = timesF.get(i)
                pushHighPivots(timeframeInfoF, highs.get(i), timeF, trsF.get(i))
        if lows.size() > 0
            for i = 0 to lows.size() - 1
                timeF = timesF.get(i)
                pushLowPivots(timeframeInfoF, lows.get(i), timeF, trsF.get(i))

getLowerTFData (timeframeStr) =>
    lowPivots = isTimeframeLower(timeframeStr, timeframe.period) ? request.security_lower_tf(syminfo.tickerid, getMinTimeframe(timeframeStr, timeframe.period), ta.pivotlow(low, pivotRange, pivotRange)) : na
    highPivots = isTimeframeLower(timeframeStr, timeframe.period) ? request.security_lower_tf(syminfo.tickerid, getMinTimeframe(timeframeStr, timeframe.period), ta.pivothigh(high, pivotRange, pivotRange)) : na
    times = isTimeframeLower(timeframeStr, timeframe.period) ? request.security_lower_tf(syminfo.tickerid, getMinTimeframe(timeframeStr, timeframe.period), pivotTime) : na
    trs = isTimeframeLower(timeframeStr, timeframe.period) ? request.security_lower_tf(syminfo.tickerid, getMinTimeframe(timeframeStr, timeframe.period), curTR[pivotRange]) : na
    [lowPivots, highPivots, times, times, trs, trs]

getTFData (timeframeStr) =>
    if isTimeframeLower(timeframeStr, timeframe.period)
        getLowerTFData(timeframeStr)
    else
        getHigherTFData(timeframeStr)

checkIfRSAreSame (RSInfo rsInfo1, RSInfo rsInfo2) =>
    if na(rsInfo1) or na(rsInfo2)
        false
    else if rsInfo1.RSType != rsInfo2.RSType
        false
    else if rsInfo1.price != rsInfo2.price
        false
    else
        true

checkIfArrHasRS (RSInfo[] arr, RSInfo rsInfoF) =>
    if na(arr) or na(rsInfoF)
        true
    else if arr.size() == 0
        false
    else
        foundRS = false
        for i = 0 to arr.size() - 1
            arrRS = arr.get(i)
            if checkIfRSAreSame(arrRS, rsInfoF)
                foundRS := true
                break
        if foundRS
            true
        else
            false

clearTimeframeRS (timeframeInfoF) =>
    oldRetestsCount = 0
    oldBreaksCount = 0

    if timeframeInfoF.resistances.size() > 0
        for j = 0 to timeframeInfoF.resistances.size() - 1
            RSInfo RSInfoF = timeframeInfoF.resistances.get(j)
            if not na(RSInfoF)
                if debug_enabledHistory
                    if checkIfArrHasRS(oldRSList, RSInfoF) == false
                        oldRSList.push(RSInfoF)

                oldRetestsCount += RSInfoF.retestLabels.size()
                oldBreaksCount += RSInfoF.isBroken ? 1 : 0
                derenderRSInfo(RSInfoF)
    
    if timeframeInfoF.supports.size() > 0
        for j = 0 to timeframeInfoF.supports.size() - 1
            RSInfo RSInfoF = timeframeInfoF.supports.get(j)
            if not na(RSInfoF)
                if debug_enabledHistory
                    if checkIfArrHasRS(history, RSInfoF) == false
                        oldRSList.push(RSInfoF)
                
                oldRetestsCount += RSInfoF.retestLabels.size()
                oldBreaksCount += RSInfoF.isBroken ? 1 : 0
                derenderRSInfo(RSInfoF)
    
    timeframeInfoF.resistances.clear()
    timeframeInfoF.supports.clear()
    [oldRetestsCount, oldBreaksCount]

findTimeframeRS (timeframeInfoF, RSType, arr, count, pivots, times, trs) =>
    curRetestsCount = 0
    curBreaksCount = 0

    if count > 0
        for j = 0 to count - 1
            foundRS = findLatestNthRS(timeframeInfoF, RSType, pivots, times, trs, j + 1)
            if not na(foundRS)
                notDuplicate = true
                for a = 0 to timeframeInfos.size() - 1
                    aInfo = timeframeInfos.get(a)
                    if na(aInfo) or aInfo.isEnabled == false
                        continue
                    otherTimeframeArray = (RSType == "Resistance" ? aInfo.resistances : aInfo.supports)
                    if otherTimeframeArray.size() > 0
                        for b = 0 to otherTimeframeArray.size() - 1
                            if checkIfRSAreSame(foundRS, otherTimeframeArray.get(b))
                                notDuplicate := false
                                break
                    if notDuplicate == false
                        break
                
                if notDuplicate or not debug_removeDuplicateRS
                    arr.push(foundRS)
        
        if arr.size() > 0
            for j = 0 to arr.size() - 1
                curRS = arr.get(j)
                if not na(curRS)
                    handleRSInfo(timeframeInfoF, curRS, j, RSType)
                    curRetestsCount += curRS.retestLabels.size()
                    curBreaksCount += curRS.isBroken ? 1 : 0
    [curRetestsCount, curBreaksCount]

if not na(lowPivot)
    allLowPivots.push(lowPivot)
    allLowTimes.push(pivotTime)
    allLowTR.push(curTR[pivotRange])
    if allLowPivots.size() > maxPivotsAllowed
        allLowPivots.remove(0)
        allLowTimes.remove(0)
        allLowTR.remove(0)
        
if not na(highPivot)
    allHighPivots.push(highPivot)
    allHighTimes.push(pivotTime)
    allHighTR.push(curTR[pivotRange])
    if allHighPivots.size() > maxPivotsAllowed
        allHighPivots.remove(0)
        allHighTimes.remove(0)
        allHighTR.remove(0)

[lowPivotsTF1, highPivotsTF1, lowTimesTF1, highTimesTF1, lowTRsTF1, highTRsTF1] = getTFData(timeframe1_)
handleTimeframeIfLower(timeframeInfos.get(0), highPivotsTF1, lowPivotsTF1, highTimesTF1, highTRsTF1)

[lowPivotsTF2, highPivotsTF2, lowTimesTF2, highTimesTF2, lowTRsTF2, highTRsTF2] = getTFData(timeframe2)
handleTimeframeIfLower(timeframeInfos.get(1), highPivotsTF2, lowPivotsTF2, highTimesTF2, highTRsTF2)

[lowPivotsTF3, highPivotsTF3, lowTimesTF3, highTimesTF3, lowTRsTF3, highTRsTF3] = getTFData(timeframe3)
handleTimeframeIfLower(timeframeInfos.get(2), highPivotsTF3, lowPivotsTF3, highTimesTF3, highTRsTF3)







 

 

Comments

Popular posts from this blog

Best Survey Apps That Pay Instantly On Mobile

  Best Survey Apps That Pay Instantly On Mobile In today’s fast-paced world, earning extra cash or rewards right from your mobile device is easier than ever—thanks to survey apps! Whether you're looking to make a little extra money or simply want gift cards for your favorite stores, survey apps can provide you with instant payouts for your opinions. Imagine getting paid in cash or gift cards for answering questions while you’re on the go—sounds great, right? We’ve compiled a list of the best survey apps that pay instantly on mobile , so you can start earning right away! 1. Swagbucks Swagbucks is one of the most well-known and trusted survey apps, and it’s known for offering instant rewards. Swagbucks offers users a wide range of ways to earn points, including surveys, shopping online, watching videos, and even searching the web. Key Features: Instant Payment Options : You can redeem your Swagbucks for gift cards to retailers like Amazon, PayPal, and iTunes almost instantly...

Online Dating VS Traditional Dating: Which Is Right for You?

  Online Dating VS Traditional Dating: Which Is Right for You? In the age of smartphones, social media, and instant messaging, online dating has revolutionized the way we meet potential partners. But how does it compare to traditional dating? With both offering unique opportunities and challenges, the debate between online dating and traditional dating continues to grow. In this article, we’ll explore the differences between the two, and help you decide which one is best suited for your personal preferences and dating goals. 1. Convenience and Accessibility Online Dating : One of the biggest advantages of online dating is convenience. With just a few taps, you can browse hundreds (if not thousands) of profiles without leaving the comfort of your home. Online dating apps and websites are available 24/7, allowing you to meet potential partners at any time, from anywhere. Whether you’re busy with work, school, or other commitments, online dating provides flexibility for people w...

Best Apps That Give You Free Bitcoin on Mobile

  Best Apps That Give You Free Bitcoin on Mobile In a world where cryptocurrency is becoming more popular by the day, Bitcoin remains the king of digital currencies. With Bitcoin’s rise, people everywhere are looking for ways to get in on the action without spending their hard-earned cash. Fortunately, there are several apps out there that offer ways to earn free Bitcoin directly on your mobile device. Whether you’re a seasoned crypto enthusiast or just dipping your toes into the world of digital currency, these apps provide an easy way to get started. Here are some of the best apps that give you free Bitcoin on mobile! 1. Coinbase Earn Best for: Beginners looking for easy education and rewards Coinbase is one of the most popular and user-friendly cryptocurrency exchanges globally. Its "Coinbase Earn" feature allows you to earn free Bitcoin (and other cryptocurrencies) by completing educational tasks. These tasks typically involve watching short videos, reading articles,...