BTMM V2
// // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//CREDIT: © Texmoonbeam
// Original pattern formation by plasmapug, rise retrace continuation to the upside by infernix, peshocore and xtech5192
//Initial Balance session by  © boitoki
//////INITIAL BALANCE by © noop42
//@version=5
indicator("BTMM R.NOODLE", overlay=true, max_bars_back=300,max_boxes_count=500, max_lines_count=500, max_labels_count=500)



//timeframe = input.timeframe(defval = '240')

abr = input.bool(defval = true, title="Abbreviate Labels", group="Mondays, Weekly, Monthly", inline="0")


zone = input.string('GMT-4', title='Timezone', options=['GMT-11', 'GMT-10', 'GMT-9', 'GMT-8', 'GMT-7', 'GMT-6', 'GMT-5', 'GMT-4', 'GMT-3', 'GMT-2', 'GMT-1', 'GMT', 'GMT+1', 'GMT+2', 'GMT+3', 'GMT+330', 'GMT+4', 'GMT+430', 'GMT+5', 'GMT+530', 'GMT+6', 'GMT+7', 'GMT+8', 'GMT+9', 'GMT+10', 'GMT+11', 'GMT+12'], tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-4\', \'GMT+9\'...', group="Sessions")

ShowAsia = input.bool(defval = true, title="Show Asia Session   ", group="Sessions", inline="1")
ExtendAsia = input.bool(defval = false, title="Extend?", group="Sessions", inline="1")
AsiaOpen = input.bool(defval = false, title="Show Open?", group="Sessions", inline="1")
AsiaOpenCol = input.color(color.new(color.green,25), title="Open Colour", group="Sessions", inline="1")
AsiaSession = input.session("2000-2300:1234567", "Asia Session   ", group="Sessions", inline="2")
AsiaCol = input.color(color.new(color.black,90), "Colour", group="Sessions", inline="2")

ShowLon = input.bool(defval = true, title="Show London Session", group="Sessions", inline="4")
ExtendLon = input.bool(defval = false, title="Extend?", group="Sessions", inline="4")
LonOpen = input.bool(defval = false, title="Show Open?", group="Sessions", inline="4")
LonOpenCol = input.color(color.new(color.red,25), title="Open Colour", group="Sessions", inline="4")
LonSession = input.session("0300-0600:1234567", "London Session", group="Sessions", inline="5")
LonCol = input.color(color.new(color.red,90), "Colour", group="Sessions", inline="5")

ShowNY = input.bool(defval = true, title="Show NY Session    ", group="Sessions", inline="7")
ExtendNY = input.bool(defval = false, title="Extend?", group="Sessions", inline="7")
NYOpen = input.bool(defval = false, title="Show Open?", group="Sessions", inline="7")
NYOpenCol = input.color(color.new(color.aqua,25), title="Open Colour", group="Sessions", inline="7")
NYSession = input.session("0930-1230:1234567", "NY Session    ", group="Sessions", inline="8")
NYCol = input.color(color.new(color.aqua,90), "Colour", group="Sessions", inline="8")

i_show_history = input.bool(defval=false, title='History?', group="Sessions", inline="A")
i_sess_border_style = input.string(line.style_solid, 'Line Style', options=[line.style_solid, line.style_dotted, line.style_dashed], group="Sessions", inline="B")
i_sess_border_width = input.int(1, 'Line Width', minval=0, group="Sessions", inline="B")
i_sess_bgopacity = input.int(80, 'Background Transparency', minval=0, maxval=100, step=1, group="Sessions", tooltip='100 = No Background', inline="C")

Custom1 = input.bool(defval = false, title="Show Custom Level 1  ", group="Custom Levels", inline="1")
Custom1Label = input.string(defval="", title="Label", group="Custom Levels", inline="1")
Custom1Type = input.string('high', title='  Level', options=["high", "low", "open"], group="Custom Levels", inline="1")
Custom1Time = input.session("0000-2345", "Custom Time Range", group="Custom Levels", inline="2")
Custom1Days = input.string("23456", title="Days Included     ", tooltip="Enter a digit for each day of the week\n1 = Sunday, 2 = Monday, 3 = Tuesday, etc\nFor example Monday to Friday would be 23456.\nFor a continous line through all included days, use time 00:00 - 00:00\nFor a separate line per day, use any time from 00:00 - 23:45.", group="Custom Levels", inline="2")
Custom1Col = input.color(defval = color.black, title="Custom Level 1 Colour", group="Custom Levels", inline="3")
ExtendCustom1 = input.bool(defval = false, title="Extend?", group="Custom Levels", inline="3")
Custom1History = input.bool(defval=false, title='History?', group="Custom Levels", inline="3")

Custom2 = input.bool(defval = false, title="Show Custom Level 2  ", group="Custom Levels", inline="4")
Custom2Label = input.string(defval="", title="Label", group="Custom Levels", inline="4")
Custom2Type = input.string('high', title='  Level', options=["high", "low", "open"], group="Custom Levels", inline="4")
Custom2Time = input.session("0015-2345", "Custom Time Range",  tooltip="", group="Custom Levels", inline="5")
Custom2Days = input.string("23456", title="Days Included     ", tooltip="Enter a digit for each day of the week\n1 = Sunday, 2 = Monday, 3 = Tuesday, etc\nFor example Monday to Friday would be 23456.\nFor a continous line through all included days, use time 00:00 - 00:00\nFor a separate line per day, use any time from 00:00 - 23:45.", group="Custom Levels", inline="5")
Custom2Col = input.color(defval = color.black, title="Custom Level 2 Colour", group="Custom Levels", inline="6")
ExtendCustom2 = input.bool(defval = false, title="Extend?", group="Custom Levels", inline="6")
Custom2History = input.bool(defval=false, title='History?', group="Custom Levels", inline="6")

Custom3 = input.bool(defval = false, title="Show Custom Level 3  ", group="Custom Levels", inline="7")
Custom3Label = input.string(defval="", title="Label", group="Custom Levels", inline="7")
Custom3Type = input.string('high', title='  Level', options=["high", "low", "open"], group="Custom Levels", inline="7")
Custom3Time = input.session("1200-1400", "Custom Time Range", group="Custom Levels", inline="8")
Custom3Days = input.string("23456", title="Days Included     ", tooltip="Enter a digit for each day of the week\n1 = Sunday, 2 = Monday, 3 = Tuesday, etc\nFor example Monday to Friday would be 23456.\nFor a continous line through all included days, use time 00:00 - 00:00\nFor a separate line per day, use any time from 00:00 - 23:45.", group="Custom Levels", inline="8")
Custom3Col = input.color(defval = color.black, title="Custom Level 3 Colour", group="Custom Levels", inline="9")
ExtendCustom3 = input.bool(defval = false, title="Extend?", group="Custom Levels", inline="9")
Custom3History = input.bool(defval=false, title='History?', group="Custom Levels", inline="9")

Custom1Session = Custom1Time+":"+Custom1Days
Custom2Session = Custom2Time+":"+Custom2Days
Custom3Session = Custom3Time+":"+Custom3Days



ResolutionToSec(res)=>
    mins = res == "1" ? 1 :
           res == "3" ? 3 :
           res == "5" ? 5 :
           res == "10" ? 10 :
           res == "15" ? 15 :
           res == "30" ? 30 :
           res == "45" ? 45 :
           res == "60" ? 60 :
           res == "120" ? 120 :
           res == "180" ? 180 :
           res == "240" ? 240 :
           res == "D" or res == "1D" ? 1440 :
           res == "W" or res == "1W" ? 10080 :
           res == "M" or res == "1M" ? 43200 : 0
    ms = mins * 60 * 1000

bar = ResolutionToSec(timeframe.period) 

   
get_Sessions()=>
    highs= array.new_float(0)
    lows= array.new_float(0)
    starttimes= array.new_int(0)
    for n = 0 to 96
        array.push(highs, high[n])
        array.push(lows, low[n])
        array.push(starttimes, time[n])
    [highs, lows, starttimes]
    

    
///////////////
// Defined
///////////////
show = true
pips = syminfo.mintick * 10
max_bars = 500

fmt_price = '{0,number,#.#####}'
fmt_pips  = '{0,number,#.#}'

icon_separator = ' • '

c_none = color.new(color.black, 100)

is_weekends = dayofweek == 7 or dayofweek == 1

f_get_time_by_bar(bar_count) => timeframe.multiplier * bar_count * 60 * 1000

f_get_period (_session, _start, _lookback) =>
    result = math.max(_start, 1)
    for i = result to _lookback
        if na(_session[i+1]) and _session[i]
            result := i+1
            break
    result

f_get_label_position (_y, _side) =>
    switch _y
        'top'    => _side == 'outside' ? label.style_label_lower_left : label.style_label_upper_left
        'bottom' => _side == 'outside' ? label.style_label_upper_left : label.style_label_lower_left

f_get_day (n) =>
    switch n
        1 => 'Sun'
        2 => 'Mon'
        3 => 'Tue'
        4 => 'Wed'
        5 => 'Thu'
        6 => 'Fri'
        7 => 'Sat'

f_get_started (_session) => na(_session[1]) and _session

f_get_ended (_session) => na(_session) and _session[1]

i_lookback = 12 * 60

f_render_session (_show, _session, _showOpen, _is_started, _is_ended, _color, _openColor, _top, _bottom, _is_extend, _delete_history) =>
    var box my_box = na
    var line my_line = na
    var label my_label = na
    
    x0_1 = ta.valuewhen(na(_session[1]) and _session, bar_index, 1)
    x0_2 = ta.valuewhen(na(_session) and _session[1], bar_index, 0)
    var x1 = 0
    var x2 = 0
    var session_open  = 0.0
    var session_high  = 0.0
    var session_low   = 0.0

    if _show
        if _is_started
            diff = math.abs(x0_2 - x0_1)
            x1 := bar_index
            x2 := bar_index + (math.min(diff, max_bars))
            my_box := box.new(x1, _top, x2, _bottom, color.new(_color, i_sess_bgopacity/1.1), i_sess_border_width, i_sess_border_style, bgcolor=color.new(_color, i_sess_bgopacity))
            
            if (_showOpen == true)
                my_line := line.new(x1, open, x2, open, color = _openColor, extend= extend.none, style= i_sess_border_style, width=i_sess_border_width)
                my_label := label.new(x=x2-2, y=open, text=(abr == true?"O":"Open"), color=color.white, style=label.style_none, textcolor=_openColor, size=size.small, textalign=text.align_left)
            
            session_open := open
            session_high := _top
            session_low  := _bottom

            if _is_extend
                box.set_extend(my_box, extend.right)
                line.set_extend(my_line, extend.right)
                
            if _delete_history
                box.delete(my_box[1])
                line.delete(my_line[1])
                label.delete(my_label[1])
                
        else if _session
            box.set_top(my_box, _top)
            box.set_bottom(my_box, _bottom)

            session_high := _top
            session_low  := _bottom
        
        else if _is_ended
            session_open := na
            box.set_right(my_box, bar_index)

    [x1, x2, session_open, session_high, session_low]
    
f_render_custom (_show, _session, _is_started, _is_ended, _color, _label, _type, _top, _bottom, _is_extend, _delete_history) =>
    var line my_line = na
    var label my_label = na
    
    x0_1 = ta.valuewhen(na(_session[1]) and _session, bar_index, 1)
    x0_2 = ta.valuewhen(na(_session) and _session[1], bar_index, 0)
    var x1 = 0
    var x2 = 0
    var session_open  = 0.0
    var session_high  = 0.0
    var session_low   = 0.0
    var level = 0.0
    if _show
        level := _type == "high" ? _top : _type == "low" ? _bottom : session_open 
        if _is_started
            diff = math.abs(x0_2 - x0_1)
            x1 := bar_index
            x2 := bar_index + (math.min(diff, max_bars))
            my_line := line.new(x1, level, x2, level, color = _color, extend= extend.none, style= i_sess_border_style, width=i_sess_border_width)
            my_label := label.new(x=x2-2, y=level, text=_label, color=color.white, style=label.style_none, textcolor=_color, size=size.normal, textalign=text.align_left)
            
            session_open := open
            session_high := _top
            session_low  := _bottom

            if _is_extend
                line.set_extend(my_line, extend.right)
                
            if _delete_history
                line.delete(my_line[1])
                label.delete(my_label[1])
                
        else if _session
            line.set_y1(my_line, level)
            line.set_y2(my_line, level)
            label.set_y(my_label, level)
            

            session_high := _top
            session_low  := _bottom
        
        else if _is_ended
            session_open := na
            line.set_x2(my_line, bar_index)
            label.set_x(my_label, bar_index)

    [x1, x2, session_open, session_high, session_low]

    
draw (_show,_showOpen, _session, _color, _openColor, is_extend, _lookback) =>
    max = f_get_period(_session, 1, _lookback)
    top = ta.highest(high, max)
    bottom = ta.lowest(low, max)
    
    is_started = f_get_started(_session)
    is_ended = f_get_ended(_session)
    
    delete_history = (not i_show_history) or is_extend

    [x1, x2, _open, _high, _low] = f_render_session(_show, _session, _showOpen, is_started, is_ended, _color, _openColor, top, bottom, is_extend, delete_history)

    [_session, _open, _high, _low]
    
drawcustom (_show, _session, _color, _label, _type, is_extend, _lookback, custom_history) =>
    max = f_get_period(_session, 1, _lookback)
    top = ta.highest(high, max)
    bottom = ta.lowest(low, max)
    
    is_started = f_get_started(_session)
    is_ended = f_get_ended(_session)
    
    delete_history = (not custom_history) or is_extend

    [x1, x2, _open, _high, _low] = f_render_custom(_show, _session, is_started, is_ended,  _color, _label, _type, top, bottom, is_extend, delete_history)

    [_session, _open, _high, _low]
    


int sess1 = time(timeframe.period, AsiaSession, zone)
int sess2 = time(timeframe.period, LonSession, zone)
int sess3 = time(timeframe.period, NYSession, zone)

int customsess1 = time(timeframe.period, Custom1Session, zone)
int customsess2 = time(timeframe.period, Custom2Session, zone)
int customsess3 = time(timeframe.period, Custom3Session, zone)

draw(ShowAsia, AsiaOpen, sess1, AsiaCol, AsiaOpenCol, ExtendAsia, i_lookback)
draw(ShowLon, LonOpen, sess2, LonCol, LonOpenCol,ExtendLon, i_lookback)
draw(ShowNY, NYOpen, sess3, NYCol, NYOpenCol,ExtendNY, i_lookback)

drawcustom(Custom1, customsess1, Custom1Col, Custom1Label, Custom1Type, ExtendCustom1, i_lookback, Custom1History)
drawcustom(Custom2, customsess2, Custom2Col, Custom2Label, Custom2Type, ExtendCustom2, i_lookback, Custom2History)
drawcustom(Custom3, customsess3, Custom3Col, Custom3Label, Custom3Type, ExtendCustom3, i_lookback, Custom3History)


//1stfriday + monday
c = #fc1687

final_color = if dayofmonth < 8 and dayofweek == 6
    color.new(#fc1687, 70)
else
    color_1 = color.new(c, 90)
    color_2 = color.new(c, 100)
    color_3 = color.new(c, 100)
    color_4 = color.new(c, 100)
    color_5 = color.new(c, 100)
    color_6 = color.new(color.black, 0)
    dayofweek == dayofweek.monday ? color_1 : dayofweek == dayofweek.tuesday ? color_2 : dayofweek == dayofweek.wednesday ? color_3 : dayofweek == dayofweek.thursday ? color_4 : dayofweek == dayofweek.friday ? color_5 : color_6

bgcolor(color=final_color, transp=90)




//35 works
displayStyle = input.string(defval='Standard', title='Display Style', options=['Standard', 'Right Anchored'], inline='Display')
mergebool = input.bool(defval=true, title='Merge Levels?', inline='Display')
distanceright = input.int(defval=30, title='Distance', minval=5, maxval=500, inline='Dist')
radistance = input.int(defval=250, title='Anchor Distance', minval=5, maxval=500, inline='Dist')
labelsize = input.string(defval='Medium', title='Text Size', options=['Small', 'Medium', 'Large'])
linesize = input.string(defval='Small', title='Line Width', options=['Small', 'Medium', 'Large'], inline='Line')
linestyle = input.string(defval='Solid', title='Line Style', options=['Solid', 'Dashed', 'Dotted'], inline='Line')



GlobalTextType = input.bool(defval=false, title='Global Text ShortHand', tooltip='Enable for shorthand text on all text')
var globalcoloring = input.bool(defval=false, title='Global Coloring', tooltip='Enable for all color controls via one color', inline='GC')
GlobalColor = input.color(title='', defval=color.white, inline='GC')
//var show_tails = input(defval = false, title = "Always Show", type = input.bool)


[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)

cdailyh_open = request.security(syminfo.tickerid, 'D', high, lookahead=barmerge.lookahead_on)
cdailyl_open = request.security(syminfo.tickerid, 'D', low, lookahead=barmerge.lookahead_on)
var monday_time = time
var monday_high = high
var monday_low = low

[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)


[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)


[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)

//------------------------------ Inputs -------------------------------



var is_intra_enabled = input.bool(defval=false, title='Open', group='4H', inline='4H')
var is_intrarange_enabled = input.bool(defval=false, title='Prev H/L', group='4H', inline='4H')
var is_intram_enabled = input.bool(defval=false, title='Prev Mid', group='4H', inline='4H')
IntraTextType = input.bool(defval=false, title='ShortHand', group='4H', inline='4Hsh')

var is_daily_enabled = input.bool(defval=true, title='Open', group='Daily', inline='Daily')
var is_dailyrange_enabled = input.bool(defval=false, title='Prev H/L', group='Daily', inline='Daily')
var is_dailym_enabled = input.bool(defval=false, title='Prev Mid', group='Daily', inline='Daily')
DailyTextType = input.bool(defval=false, title='ShortHand', group='Daily', inline='Dailysh')

var is_monday_enabled = input.bool(defval=true, title='Range', group='Monday Range', inline='Monday')
var is_monday_mid = input.bool(defval=true, title='Mid', group='Monday Range', inline='Monday')
var untested_monday = false
MondayTextType = input.bool(defval=false, title='ShortHand', group='Monday Range', inline='Mondaysh')

var is_weekly_enabled = input.bool(defval=true, title='Open', group='Weekly', inline='Weekly')
var is_weeklyrange_enabled = input.bool(defval=true, title='Prev H/L', group='Weekly', inline='Weekly')
var is_weekly_mid = input.bool(defval=true, title='Prev Mid', group='Weekly', inline='Weekly')
WeeklyTextType = input.bool(defval=false, title='ShortHand', group='Weekly', inline='Weeklysh')

var is_monthly_enabled = input.bool(defval=true, title='Open', group='Monthly', inline='Monthly')
var is_monthlyrange_enabled = input.bool(defval=true, title='Prev H/L', group='Monthly', inline='Monthly')
var is_monthly_mid = input.bool(defval=true, title='Prev Mid', group='Monthly', inline='Monthly')
MonthlyTextType = input.bool(defval=false, title='ShortHand', group='Monthly', inline='Monthlysh')

var is_quarterly_enabled = input.bool(defval=true, title='Open', group='Quarterly', inline='Quarterly')
var is_quarterlyrange_enabled = input.bool(defval=false, title='Prev H/L', group='Quarterly', inline='Quarterly')
var is_quarterly_mid = input.bool(defval=true, title='Prev Mid', group='Quarterly', inline='Quarterly')
QuarterlyTextType = input.bool(defval=false, title='ShortHand', group='Quarterly', inline='Quarterlysh')

var is_yearly_enabled = input.bool(defval=true, title='Open', group='Yearly', inline='Yearly')
var is_yearlyrange_enabled = input.bool(defval=false, title='Current H/L', group='Yearly', inline='Yearly')
var is_yearly_mid = input.bool(defval=true, title='Mid', group='Yearly', inline='Yearly')
YearlyTextType = input.bool(defval=false, title='ShortHand', group='Yearly', inline='Yearlysh')


DailyColor = input.color(title='', defval=#08bcd4, group='Daily', inline='Dailysh')
MondayColor = input.color(title='', defval=color.white, group='Monday Range', inline='Mondaysh')
WeeklyColor = input.color(title='', defval=#fffcbc, group='Weekly', inline='Weeklysh')
MonthlyColor = input.color(title='', defval=#08d48c, group='Monthly', inline='Monthlysh')
YearlyColor = input.color(title='', defval=color.red, group='Yearly', inline='Yearlysh')
quarterlyColor = input.color(title='', defval=color.red, group='Quarterly', inline='Quarterlysh')
IntraColor = input.color(title='', defval=color.orange, group='4H', inline='4Hsh')
var pdhtext = GlobalTextType or DailyTextType ? 'PDH' : 'Prev Day High'
var pdltext = GlobalTextType or DailyTextType ? 'PDL' : 'Prev Day Low'
var dotext = GlobalTextType or DailyTextType ? 'DO' : 'Daily Open'
var pdmtext = GlobalTextType or DailyTextType ? 'PDM' : 'Prev Day Mid'

var pwhtext = GlobalTextType or WeeklyTextType ? 'PWH' : 'Prev Week High'
var pwltext = GlobalTextType or WeeklyTextType ? 'PWL' : 'Prev Week Low'
var wotext = GlobalTextType or WeeklyTextType ? 'WO' : 'Weekly Open'
var pwmtext = GlobalTextType or WeeklyTextType ? 'PWM' : 'Prev Week Mid'

var pmhtext = GlobalTextType or MonthlyTextType ? 'PMH' : 'Prev Month High'
var pmltext = GlobalTextType or MonthlyTextType ? 'PML' : 'Prev Month Low'
var motext = GlobalTextType or MonthlyTextType ? 'MO' : 'Monthly Open'
var pmmtext = GlobalTextType or MonthlyTextType ? 'PMM' : 'Prev Month Mid'

var pqhtext = GlobalTextType or QuarterlyTextType ? 'PQH' : 'Prev Quarter High'
var pqltext = GlobalTextType or QuarterlyTextType ? 'PQL' : 'Prev Quarter Low'
var qotext = GlobalTextType or QuarterlyTextType ? 'QO' : 'Quarterly Open'
var pqmtext = GlobalTextType or QuarterlyTextType ? 'PQM' : 'Prev Quarter Mid'

var cyhtext = GlobalTextType or YearlyTextType ? 'CYH' : 'Current Year High'
var cyltext = GlobalTextType or YearlyTextType ? 'CYL' : 'Current Year Low'
var yotext = GlobalTextType or YearlyTextType ? 'YO' : 'Yearly Open'
var cymtext = GlobalTextType or YearlyTextType ? 'CYM' : 'Current Year Mid'

var pihtext = GlobalTextType or IntraTextType ? 'P-4H-H' : 'Prev 4H High'
var piltext = GlobalTextType or IntraTextType ? 'P-4H-L' : 'Prev 4H Low'
var iotext = GlobalTextType or IntraTextType ? '4H-O' : '4H Open'
var pimtext = GlobalTextType or IntraTextType ? 'P-4H-M' : 'Prev 4H Mid'

var pmonhtext = GlobalTextType or MondayTextType ? 'MDAY-H' : 'Monday High'
var pmonltext = GlobalTextType or MondayTextType ? 'MDAY-L' : 'Monday Low'
var pmonmtext = GlobalTextType or MondayTextType ? 'MDAY-M' : 'Monday Mid'

if globalcoloring == true
    DailyColor := GlobalColor
    MondayColor := GlobalColor
    WeeklyColor := GlobalColor
    MonthlyColor := GlobalColor
    YearlyColor := GlobalColor
    quarterlyColor := GlobalColor
    IntraColor := GlobalColor
    IntraColor


if weekly_time != weekly_time[1]
    untested_monday := false
    untested_monday

if is_monday_enabled == 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 DEFAULT_LINE_WIDTH = linewidthint
var DEFAULT_TAIL_WIDTH = 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 DEFAULT_EXTEND_RIGHT = distanceright



//------------------------------ Plotting ------------------------------
var pricearray = array.new_float(0)
var labelarray = array.new_label(0)
f_LevelMerge(pricearray, labelarray, currentprice, currentlabel, currentcolor) =>
    if array.includes(pricearray, currentprice)
        whichindex = array.indexof(pricearray, currentprice)
        labelhold = array.get(labelarray, 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(pricearray, currentprice)
        array.push(labelarray, currentlabel)


var can_show_daily = is_daily_enabled and timeframe.isintraday
var can_show_weekly = is_weekly_enabled and not timeframe.isweekly and not timeframe.ismonthly
var can_show_monthly = is_monthly_enabled and not timeframe.ismonthly

get_limit_right(bars) =>
    timenow + (time - time[1]) * bars

// the following code doesn't need to be processed on every candle
if barstate.islast
    is_weekly_open = dayofweek == dayofweek.monday
    is_monthly_open = dayofmonth == 1
    can_draw_daily = (is_weekly_enabled ? not is_weekly_open : true) and (is_monthly_enabled ? not is_monthly_open : true)
    can_draw_weekly = is_monthly_enabled ? not(is_monthly_open and is_weekly_open) : true
    can_draw_intra = is_intra_enabled
    can_draw_intrah = is_intrarange_enabled
    can_draw_intral = is_intrarange_enabled
    can_draw_intram = is_intram_enabled
    pricearray := array.new_float(0)
    labelarray := array.new_label(0)

    /////////////////////////////////
           
            
//////////////////////////////////////////////////////////////////////////////////
    if can_draw_intra
        intra_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            intra_time := get_limit_right(radistance)
            intra_time


        var intra_line = line.new(x1=intra_time, x2=intra_limit_right, y1=intra_open, y2=intra_open, color=IntraColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var intra_label = label.new(x=intra_limit_right, y=intra_open, text=iotext, style=DEFAULT_LABEL_STYLE, textcolor=IntraColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)

        line.set_x1(intra_line, intra_time)
        line.set_x2(intra_line, intra_limit_right)
        line.set_y1(intra_line, intra_open)
        line.set_y2(intra_line, intra_open)
        label.set_x(intra_label, intra_limit_right)
        label.set_y(intra_label, intra_open)
        label.set_text(intra_label, iotext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, intra_open, intra_label, IntraColor)


//////////////////////////////////////////////////////////////////////////////////
//HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH HIGH
    if can_draw_intrah
        intrah_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            intrah_time := get_limit_right(radistance)
            intrah_time



        var intrah_line = line.new(x1=intrah_time, x2=intrah_limit_right, y1=intrah_open, y2=intrah_open, color=IntraColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var intrah_label = label.new(x=intrah_limit_right, y=intrah_open, text=pihtext, style=DEFAULT_LABEL_STYLE, textcolor=IntraColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)

        line.set_x1(intrah_line, intrah_time)
        line.set_x2(intrah_line, intrah_limit_right)
        line.set_y1(intrah_line, intrah_open)
        line.set_y2(intrah_line, intrah_open)
        label.set_x(intrah_label, intrah_limit_right)
        label.set_y(intrah_label, intrah_open)
        label.set_text(intrah_label, pihtext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, intrah_open, intrah_label, IntraColor)

//////////////////////////////////////////////////////////////////////////////////
//LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW LOW
    if can_draw_intral
        intral_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            intral_time := get_limit_right(radistance)
            intral_time



        var intral_line = line.new(x1=intral_time, x2=intral_limit_right, y1=intral_open, y2=intral_open, color=IntraColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var intral_label = label.new(x=intral_limit_right, y=intral_open, text=piltext, style=DEFAULT_LABEL_STYLE, textcolor=IntraColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, intral_open, intral_label, IntraColor)

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

    if can_draw_intram
        intram_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        intram_time = intrah_time
        intram_open = (intral_open + intrah_open) / 2
        if displayStyle == 'Right Anchored'
            intram_time := get_limit_right(radistance)
            intram_time

        var intram_line = line.new(x1=intram_time, x2=intram_limit_right, y1=intram_open, y2=intram_open, color=IntraColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var intram_label = label.new(x=intram_limit_right, y=intram_open, text=pimtext, style=DEFAULT_LABEL_STYLE, textcolor=IntraColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(intram_line, intram_time)
        line.set_x2(intram_line, intram_limit_right)
        line.set_y1(intram_line, intram_open)
        line.set_y2(intram_line, intram_open)
        label.set_x(intram_label, intram_limit_right)
        label.set_y(intram_label, intram_open)
        label.set_text(intram_label, pimtext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, intram_open, intram_label, IntraColor)

////////////////////////////////////////// MONDAY

    if is_monday_enabled
        monday_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            monday_time := get_limit_right(radistance)
            monday_time

        var monday_line = line.new(x1=monday_time, x2=monday_limit_right, y1=monday_high, y2=monday_high, color=MondayColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var monday_label = label.new(x=monday_limit_right, y=monday_high, text=pmonhtext, style=DEFAULT_LABEL_STYLE, textcolor=MondayColor, 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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, monday_high, monday_label, MondayColor)


    if is_monday_enabled
        monday_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            monday_time := get_limit_right(radistance)
            monday_time



        var monday_low_line = line.new(x1=monday_time, x2=monday_limit_right, y1=monday_low, y2=monday_low, color=MondayColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var monday_low_label = label.new(x=monday_limit_right, y=monday_low, text=pmonltext, style=DEFAULT_LABEL_STYLE, textcolor=MondayColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, monday_low, monday_low_label, MondayColor)



    if is_monday_mid
        mondaym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)

        mondaym_open = (monday_high + monday_low) / 2
        if displayStyle == 'Right Anchored'
            monday_time := get_limit_right(radistance)
            monday_time

        var mondaym_line = line.new(x1=monday_time, x2=mondaym_limit_right, y1=mondaym_open, y2=mondaym_open, color=MondayColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var mondaym_label = label.new(x=mondaym_limit_right, y=mondaym_open, text=pmonmtext, style=DEFAULT_LABEL_STYLE, textcolor=MondayColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, mondaym_open, mondaym_label, MondayColor)


//////////////////////////////////////////////////////////////////////////////////
////////////////////////DAILY OPEN DAILY OPEN DAILY OPEN DAILY OPEN DAILY OPEN DAILY OPEN DAILY OPEN

    if is_daily_enabled
        daily_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            daily_time := get_limit_right(radistance)
            daily_time

        var daily_line = line.new(x1=daily_time, x2=daily_limit_right, y1=daily_open, y2=daily_open, color=DailyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var daily_label = label.new(x=daily_limit_right, y=daily_open, text=dotext, style=DEFAULT_LABEL_STYLE, textcolor=DailyColor, 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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, daily_open, daily_label, DailyColor)

//////////////////////////////////////////////////////////////////////////////////
//////////////////DAILY HIGH DAILY HIGH DAILY HIGH DAILY HIGH DAILY HIGH DAILY HIGH DAILY HIGH 

    if is_dailyrange_enabled
        dailyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            dailyh_time := get_limit_right(radistance)
            dailyh_time
        // draw tails before lines for better visual


        var dailyh_line = line.new(x1=dailyh_time, x2=dailyh_limit_right, y1=dailyh_open, y2=dailyh_open, color=DailyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var dailyh_label = label.new(x=dailyh_limit_right, y=dailyh_open, text=pdhtext, style=DEFAULT_LABEL_STYLE, textcolor=DailyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, dailyh_open, dailyh_label, DailyColor)


//////////////////////////////////////////////////////////////////////////////////
//////////////////DAILY LOW DAILY LOW DAILY LOW DAILY LOW DAILY LOW DAILY LOW DAILY LOW DAILY LOW 

    if is_dailyrange_enabled
        dailyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            dailyl_time := get_limit_right(radistance)
            dailyl_time


        var dailyl_line = line.new(x1=dailyl_time, x2=dailyl_limit_right, y1=dailyl_open, y2=dailyl_open, color=DailyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var dailyl_label = label.new(x=dailyl_limit_right, y=dailyl_open, text=pdltext, style=DEFAULT_LABEL_STYLE, textcolor=DailyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, dailyl_open, dailyl_label, DailyColor)



//////////////////////////////////////////////////////////////////////////////// Daily MID

    if is_dailym_enabled
        dailym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        dailym_time = dailyh_time
        dailym_open = (dailyl_open + dailyh_open) / 2
        if displayStyle == 'Right Anchored'
            dailym_time := get_limit_right(radistance)
            dailym_time
        var dailym_line = line.new(x1=dailym_time, x2=dailym_limit_right, y1=dailym_open, y2=dailym_open, color=DailyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var dailym_label = label.new(x=dailym_limit_right, y=dailym_open, text=pdmtext, style=DEFAULT_LABEL_STYLE, textcolor=DailyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(dailym_line, dailym_time)
        line.set_x2(dailym_line, dailym_limit_right)
        line.set_y1(dailym_line, dailym_open)
        line.set_y2(dailym_line, dailym_open)
        label.set_x(dailym_label, dailym_limit_right)
        label.set_y(dailym_label, dailym_open)
        label.set_text(dailym_label, pdmtext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, dailym_open, dailym_label, DailyColor)


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


    if is_weekly_enabled
        weekly_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        cweekly_time = weekly_time
        if displayStyle == 'Right Anchored'
            cweekly_time := get_limit_right(radistance)
            cweekly_time


        var weekly_line = line.new(x1=cweekly_time, x2=weekly_limit_right, y1=weekly_open, y2=weekly_open, color=WeeklyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        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)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, weekly_open, weekly_label, WeeklyColor)
        // the weekly open can be the daily open too (monday)
        // only the weekly will be draw, in these case we update its label
    // if is_weekly_open and can_show_daily
            // label.set_text(weekly_label, "DO / WO            ")

//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// WEEKLY HIGH WEEKLY HIGH WEEKLY HIGH


    if is_weeklyrange_enabled
        weeklyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            weeklyh_time := get_limit_right(radistance)
            weeklyh_time


        var weeklyh_line = line.new(x1=weeklyh_time, x2=weeklyh_limit_right, y1=weeklyh_open, y2=weeklyh_open, color=WeeklyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        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)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, weeklyh_open, weeklyh_label, WeeklyColor)

//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// WEEKLY LOW WEEKLY LOW WEEKLY LOW


    if is_weeklyrange_enabled
        weeklyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            weeklyl_time := get_limit_right(radistance)
            weeklyl_time


        var weeklyl_line = line.new(x1=weeklyl_time, x2=weeklyl_limit_right, y1=weekly_open, y2=weekly_open, color=WeeklyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        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(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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, weeklyl_open, weeklyl_label, WeeklyColor)



//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// Weekly MID

    if is_weekly_mid
        weeklym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        weeklym_time = weeklyh_time
        weeklym_open = (weeklyl_open + weeklyh_open) / 2
        if displayStyle == 'Right Anchored'
            weeklym_time := get_limit_right(radistance)
            weeklym_time

        var weeklym_line = line.new(x1=weeklym_time, x2=weeklym_limit_right, y1=weeklym_open, y2=weeklym_open, color=WeeklyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var weeklym_label = label.new(x=weeklym_limit_right, y=weeklym_open, text=pwmtext, style=DEFAULT_LABEL_STYLE, textcolor=WeeklyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(weeklym_line, weeklym_time)
        line.set_x2(weeklym_line, weeklym_limit_right)
        line.set_y1(weeklym_line, weeklym_open)
        line.set_y2(weeklym_line, weeklym_open)
        label.set_x(weeklym_label, weeklym_limit_right)
        label.set_y(weeklym_label, weeklym_open)
        label.set_text(weeklym_label, pwmtext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, weeklym_open, weeklym_label, WeeklyColor)
////////////////////////////////////////////////////////////////////////////////// YEEEAARRLLYY LOW LOW LOW


    if is_yearlyrange_enabled
        yearlyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            yearlyl_time := get_limit_right(radistance)
            yearlyl_time


        var yearlyl_line = line.new(x1=yearlyl_time, x2=yearlyl_limit_right, y1=yearlyl_open, y2=yearlyl_open, color=YearlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        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)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, yearlyl_open, yearlyl_label, YearlyColor)



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


////////////////////////////////////////////////////////////////////////////////// YEEEAARRLLYY HIGH HIGH HIGH


    if is_yearlyrange_enabled
        yearlyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            yearlyh_time := get_limit_right(radistance)
            yearlyh_time


        var yearlyh_line = line.new(x1=yearlyh_time, x2=yearlyh_limit_right, y1=yearlyh_open, y2=yearlyh_open, color=YearlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        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)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, yearlyh_open, yearlyh_label, YearlyColor)



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

////////////////////////////////////////////////////////////////////////////////// YEEEAARRLLYY OPEN


    if is_yearly_enabled
        yearly_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            yearly_time := get_limit_right(radistance)
            yearly_time


        var yearly_line = line.new(x1=yearly_time, x2=yearly_limit_right, y1=yearly_open, y2=yearly_open, color=YearlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)

        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(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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, yearly_open, yearly_label, YearlyColor)



//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// yearly MID

    if is_yearly_mid
        yearlym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        yearlym_time = yearlyh_time
        yearlym_open = (yearlyl_open + yearlyh_open) / 2
        if displayStyle == 'Right Anchored'
            yearlym_time := get_limit_right(radistance)
            yearlym_time

        var yearlym_line = line.new(x1=yearlym_time, x2=yearlym_limit_right, y1=yearlym_open, y2=yearlym_open, color=YearlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var yearlym_label = label.new(x=yearlym_limit_right, y=yearlym_open, text=cymtext, style=DEFAULT_LABEL_STYLE, textcolor=YearlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(yearlym_line, yearlym_time)
        line.set_x2(yearlym_line, yearlym_limit_right)
        line.set_y1(yearlym_line, yearlym_open)
        line.set_y2(yearlym_line, yearlym_open)
        label.set_x(yearlym_label, yearlym_limit_right)
        label.set_y(yearlym_label, yearlym_open)
        label.set_text(yearlym_label, cymtext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, yearlym_open, yearlym_label, YearlyColor)


////////////////////////////////////////////////////////////////////////////////// QUATERLLYYYYY OPEN


    if is_quarterly_enabled
        quarterly_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            quarterly_time := get_limit_right(radistance)
            quarterly_time


        var quarterly_line = line.new(x1=quarterly_time, x2=quarterly_limit_right, y1=quarterly_open, y2=quarterly_open, color=quarterlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        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)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, quarterly_open, quarterly_label, quarterlyColor)



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


////////////////////////////////////////////////////////////////////////////////// QUATERLLYYYYY High


    if is_quarterlyrange_enabled
        quarterlyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            quarterlyh_time := get_limit_right(radistance)
            quarterlyh_time


        var quarterlyh_line = line.new(x1=quarterlyh_time, x2=quarterlyh_limit_right, y1=quarterlyh_open, y2=quarterlyh_open, color=quarterlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        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)

        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, quarterlyh_open, quarterlyh_label, quarterlyColor)



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


////////////////////////////////////////////////////////////////////////////////// QUATERLLYYYYY Low


    if is_quarterlyrange_enabled
        quarterlyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            quarterlyl_time := get_limit_right(radistance)
            quarterlyl_time


        var quarterlyl_line = line.new(x1=quarterlyl_time, x2=quarterlyl_limit_right, y1=quarterlyl_open, y2=quarterlyl_open, color=quarterlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        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(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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, quarterlyl_open, quarterlyl_label, quarterlyColor)



//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////// QUATERLLYYYYY MID

    if is_quarterly_mid
        quarterlym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        quarterlym_time = quarterlyh_time
        quarterlym_open = (quarterlyl_open + quarterlyh_open) / 2
        if displayStyle == 'Right Anchored'
            quarterlym_time := get_limit_right(radistance)
            quarterlym_time
        var quarterlym_line = line.new(x1=quarterlym_time, x2=quarterlym_limit_right, y1=quarterlym_open, y2=quarterlym_open, color=quarterlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var quarterlym_label = label.new(x=quarterlym_limit_right, y=quarterlym_open, text=pqmtext, style=DEFAULT_LABEL_STYLE, textcolor=quarterlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(quarterlym_line, quarterlym_time)
        line.set_x2(quarterlym_line, quarterlym_limit_right)
        line.set_y1(quarterlym_line, quarterlym_open)
        line.set_y2(quarterlym_line, quarterlym_open)
        label.set_x(quarterlym_label, quarterlym_limit_right)
        label.set_y(quarterlym_label, quarterlym_open)

        label.set_text(quarterlym_label, pqmtext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, quarterlym_open, quarterlym_label, quarterlyColor)

////////////////////////////////////////////////////////////////////////////////// Monthly LOW LOW LOW


    if is_monthlyrange_enabled
        monthlyl_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            monthlyl_time := get_limit_right(radistance)
            monthlyl_time


        var monthlyl_line = line.new(x1=monthlyl_time, x2=monthlyl_limit_right, y1=monthlyl_open, y2=monthlyl_open, color=MonthlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var monthlyl_label = label.new(x=monthlyl_limit_right, y=monthlyl_open, text=pmltext, style=DEFAULT_LABEL_STYLE, textcolor=MonthlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)

        line.set_x1(monthlyl_line, monthlyl_time)
        line.set_x2(monthlyl_line, monthlyl_limit_right)
        line.set_y1(monthlyl_line, monthlyl_open)
        line.set_y2(monthlyl_line, monthlyl_open)
        label.set_x(monthlyl_label, monthlyl_limit_right)
        label.set_y(monthlyl_label, monthlyl_open)
        label.set_text(monthlyl_label, pmltext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, monthlyl_open, monthlyl_label, MonthlyColor)
        // the weekly open can be the daily open too (monday)
        // only the weekly will be draw, in these case we update its label


//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// MONTHLY HIGH HIGH HIGH



    if is_monthlyrange_enabled
        monthlyh_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            monthlyh_time := get_limit_right(radistance)
            monthlyh_time


        var monthlyh_line = line.new(x1=monthlyh_time, x2=monthlyh_limit_right, y1=monthlyh_open, y2=monthlyh_open, color=MonthlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var monthlyh_label = label.new(x=monthlyh_limit_right, y=monthlyh_open, text=pmhtext, style=DEFAULT_LABEL_STYLE, textcolor=MonthlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)

        line.set_x1(monthlyh_line, monthlyl_time)
        line.set_x2(monthlyh_line, monthlyh_limit_right)
        line.set_y1(monthlyh_line, monthlyh_open)
        line.set_y2(monthlyh_line, monthlyh_open)
        label.set_x(monthlyh_label, monthlyh_limit_right)
        label.set_y(monthlyh_label, monthlyh_open)
        label.set_text(monthlyh_label, pmhtext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, monthlyh_open, monthlyh_label, MonthlyColor)
        // the weekly open can be the daily open too (monday)
        // only the weekly will be draw, in these case we update its label

//////////////////////////////////////////////////////////////////////////////// MONTHLY MID

    if is_monthly_mid
        monthlym_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        monthlym_time = monthlyh_time
        monthlym_open = (monthlyl_open + monthlyh_open) / 2
        if displayStyle == 'Right Anchored'
            monthlym_time := get_limit_right(radistance)
            monthlym_time
        var monthlym_line = line.new(x1=monthlym_time, x2=monthlym_limit_right, y1=monthlym_open, y2=monthlym_open, color=MonthlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        var monthlym_label = label.new(x=monthlym_limit_right, y=monthlym_open, text=pmmtext, style=DEFAULT_LABEL_STYLE, textcolor=MonthlyColor, size=DEFAULT_LABEL_SIZE, xloc=xloc.bar_time)
        line.set_x1(monthlym_line, monthlym_time)
        line.set_x2(monthlym_line, monthlym_limit_right)
        line.set_y1(monthlym_line, monthlym_open)
        line.set_y2(monthlym_line, monthlym_open)
        label.set_x(monthlym_label, monthlym_limit_right)
        label.set_y(monthlym_label, monthlym_open)
        label.set_text(monthlym_label, pmmtext)
        if mergebool
            f_LevelMerge(pricearray, labelarray, monthlym_open, monthlym_label, MonthlyColor)
//////////////////////////////////////////////////////////////////////////////////



    if is_monthly_enabled
        monthly_limit_right = get_limit_right(DEFAULT_EXTEND_RIGHT)
        if displayStyle == 'Right Anchored'
            monthly_time := get_limit_right(radistance)
            monthly_time

        var monthlyLine = line.new(x1=monthly_time, x2=monthly_limit_right, y1=monthly_open, y2=monthly_open, color=MonthlyColor, width=DEFAULT_LINE_WIDTH, xloc=xloc.bar_time, style=linestyles)
        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)
        if mergebool
            f_LevelMerge(pricearray, labelarray, monthly_open, monthlyLabel, MonthlyColor)


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

        // the monthly open can be the weekly open (monday 1st) and/or daily open too
        // only the monthly will be draw, in these case we update its label
        // if is_monthly_open
        //     if can_show_daily
        //         label.set_text(monthlyLabel, "DO / MO            ")
        //     if is_weekly_open
        //         if can_show_weekly
        //             label.set_text(monthlyLabel, "WO / MO            ")
        //         if can_show_daily and can_show_weekly
        //             label.set_text(monthlyLabel, "DO / WO / MO                ")

        // the start of the line is drew from the first week of the month
        // if the first day of the weekly candle (monday) is the 2nd of the month
        // we fix the start of the line position on the Prev weekly candle
        if timeframe.isweekly and dayofweek(monthly_time) != dayofweek.monday
            line.set_x1(monthlyLine, monthly_time - (weekly_time - weekly_time[1]))







var picoLines = 10
var femtoLines = 6
var femtoLines1 = 6
StepSize = input.float(1000, title='Step Size [pip]', step=0.00001, tooltip = 'The value That should be entered here is 1000 pips. e.g. FX = 1000, BTC(depends on decimal point)- 10 000/ 100 000, ETH(depends on decimal point) - 1 000/10 000')
var picoStep = syminfo.mintick * (StepSize*1)
var FemtoStep1 = syminfo.mintick * (StepSize*0.50)
var FemtoStep = syminfo.mintick * (StepSize*0.25)

line ln = na
lstyle1 = input.string(title='Resistance Line Style', defval='Solid', options=['Solid', 'Dotted', 'Dashed'], group='Resistance')
lstyle2 = input.string(title='Support Line Style', defval='Solid', options=['Solid', 'Dotted', 'Dashed'], group='Support')

lstyle3 = input.string(title='25R Style', defval='Dotted', options=['Solid', 'Dotted', 'Dashed'], group='Resistance')
lstyle4 = input.string(title='25S Style', defval='Dotted', options=['Solid', 'Dotted', 'Dashed'], group='Support')

lstyle5 = input.string(title='50R Style', defval='Dashed', options=['Solid', 'Dotted', 'Dashed'], group='Resistance')
lstyle6 = input.string(title='50S Style', defval='Dashed', options=['Solid', 'Dotted', 'Dashed'], group='Support')

resistanceStyle = lstyle1 == 'Solid' ? line.style_solid : lstyle1 == 'Dotted' ? line.style_dotted : line.style_dashed
supportStyle = lstyle2 == 'Solid' ? line.style_solid : lstyle2 == 'Dotted' ? line.style_dotted : line.style_dashed

resistanceStyle1 = lstyle3 == 'Solid' ? line.style_solid : lstyle3 == 'Dotted' ? line.style_dotted : line.style_dashed
supportStyle1 = lstyle4 == 'Solid' ? line.style_solid : lstyle4 == 'Dotted' ? line.style_dotted : line.style_dashed

resistanceStyle2 = lstyle5 == 'Solid' ? line.style_solid : lstyle5 == 'Dotted' ? line.style_dotted : line.style_dashed
supportStyle2 = lstyle6 == 'Solid' ? line.style_solid : lstyle6 == 'Dotted' ? line.style_dotted : line.style_dashed

LineCol5 = input.color(color.new(#000000, 50), title='100 pip', inline='LineCol5', group='Resistance')
lineWidth5 = input.int(2, title='', minval=1, maxval=4, inline='LineCol5', group='Resistance')

LineCol6 = input.color(color.new(#000000, 50), title='100 pip', inline='LineCol6', group='Support')
lineWidth6 = input.int(2, title='', minval=1, maxval=4, inline='LineCol6', group='Support')

LineCol7 = input.color(color.new(#000000, 50), title='25 pip', inline='LineCol7', group='Resistance')
lineWidth7 = input.int(1, title='', minval=1, maxval=4, inline='LineCol7', group='Resistance')

LineCol8 = input.color(color.new(#000000, 50), title='25 pip', inline='LineCol8', group='Support')
lineWidth8 = input.int(1, title='', minval=1, maxval=4, inline='LineCol8', group='Support')

LineCol9 = input.color(color.new(#000000, 50), title='50 pip', inline='LineCol9', group='Resistance')
lineWidth9 = input.int(1, title='', minval=1, maxval=4, inline='LineCol9', group='Resistance')

LineCol10 = input.color(color.new(#000000, 50), title='50 pip', inline='LineCol10', group='Support')
lineWidth10 = input.int(1, title='', minval=1, maxval=4, inline='LineCol10', group='Support')


ll_offset3 = timenow + math.round(ta.change(time) * 30)
ll_offset4 = timenow + math.round(ta.change(time) * 10)
ll_offset5 = timenow + math.round(ta.change(time) * 20)


if barstate.islast and timeframe.isintraday
    for counter = 0 to picoLines - 1 by 1
        stepUp = math.ceil(close / picoStep) * picoStep + counter * picoStep
        line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, color=LineCol5, width=lineWidth5, style=resistanceStyle)
        label.new(ll_offset3, stepUp, '100' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol5, tooltip = 'Minor Whole')
        stepDown = math.floor(close / picoStep) * picoStep - counter * picoStep
        line.new(bar_index, stepDown, bar_index - 1, stepDown, xloc=xloc.bar_index, extend=extend.both, color=LineCol6, width=lineWidth6, style=supportStyle)
        label.new(ll_offset3, stepDown, '100' , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol6, tooltip = 'Minor Whole')

if barstate.islast and timeframe.isminutes
    for counter = 0 to femtoLines1 - 1 by 1
        stepUp = math.ceil(close / FemtoStep) * FemtoStep + counter * FemtoStep
        line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, color=LineCol7, width=lineWidth7, style=resistanceStyle1)
        label.new(ll_offset4, stepUp, na , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol7, tooltip = 'Minor quarter')
        stepDown = math.floor(close / FemtoStep) * FemtoStep - counter * FemtoStep
        line.new(bar_index, stepDown, bar_index - 1, stepDown, xloc=xloc.bar_index, extend=extend.both, color=LineCol8, width=lineWidth8, style=supportStyle1)
        label.new(ll_offset4, stepDown, na , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol8, tooltip = 'Minor quarter')

if barstate.islast and timeframe.isminutes
    for counter = 0 to femtoLines1 - 1 by 1
        stepUp = math.ceil(close / FemtoStep1) * FemtoStep1 + counter * FemtoStep1
        line.new(bar_index, stepUp, bar_index - 1, stepUp, xloc=xloc.bar_index, extend=extend.both, color=LineCol9, width=lineWidth9, style=resistanceStyle2)
        label.new(ll_offset5, stepUp, na , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol9, tooltip = 'Minor half')
        stepDown = math.floor(close / FemtoStep1) * FemtoStep1 - counter * FemtoStep1
        line.new(bar_index, stepDown, bar_index - 1, stepDown, xloc=xloc.bar_index, extend=extend.both, color=LineCol10, width=lineWidth10, style=supportStyle2)
        label.new(ll_offset5, stepDown, na , xloc.bar_time, yloc.price, color.white, label.style_none, LineCol10, tooltip = 'Minor half')




// Options

/// Daily IB only on 1hr & below
bool show2 = timeframe.isminutes and timeframe.multiplier <= 60 and timeframe.multiplier >= 1
time_now_exchange = timestamp(year, month, dayofmonth, hour, minute, second)
ib_session = input.session("0300-0430", title="Calculation period for the initial balance", group="Calculation period")

show2_delta_analytics = input.bool(true, "Display IB delta analytics", group="Information")


high_col = input.color(color.green, "Initial balance high levels color", group="Drawings")
low_col = input.color(color.red, "Initial balance low levels color", group="Drawings")
middle_col = input.color(#ffa726, "50% initial balance color", group="Drawings")
var delta_history = array.new_float(20)

inSession(sess) => na(time(timeframe.period, sess)) == false

get_line_style(s) =>
    s == "Solid" ? line.style_solid : s == "Dotted" ? line.style_dotted : line.style_dashed

get_levels(n) =>
    h = high[1]
    l = low[1]
    for i=1 to n
        if low[i] < l
            l := low[i]
        if high[i] > h
            h := high[i]
    [h, l, (h+l)/2]

var line ibh = na
var line ibl = na
var line ibm = na
var line ib_plus = na
var line ib_minus = na
var line ib_plus2 = na
var line ib_minus2 = na
var line ibm_plus = na
var line ibm_minus = na

var label labelh = na
var label labell = na
var label labelm = na
var label label_plus = na
var label label_minus = na
var label label_plus2 = na
var label label_minus2 = na
var label labelm_plus = na
var label labelm_minus = na
var box ib_area = na



var offset = 0

ins = inSession(ib_session)


var float ib_delta = na

if ins
    offset += 1
if ins[1] and not ins
    [h, l, m] = get_levels(offset)
    ib_delta := h - l
    if array.size(delta_history) >= 20
        array.shift(delta_history)
    array.push(delta_history, ib_delta)
    
 

 

if (not ins) and (not ins[1])
    line.set_x2(ibh, bar_index)
    line.set_x2(ibl, bar_index)
  

var table ib_analytics = table.new(position.bottom_left, 2, 6)

ib_sentiment() =>
    h = array.max(delta_history)
    l = array.min(delta_history)
    a = array.avg(delta_history)
    
    h_comp = ib_delta > h ? ib_delta - h : (ib_delta - h) * -1
    l_comp = ib_delta > l ? ib_delta - l : (ib_delta - l) * -1
    a_comp = ib_delta > a ? ib_delta - a : (ib_delta - a) * -1
    (h_comp < l_comp and h_comp < a_comp) ? "Huge" : (l_comp < h_comp and l_comp < a_comp) ? "Small" : "Medium"
    
if show2_delta_analytics
    table.cell(ib_analytics, 0, 0, "IB Delta", bgcolor=color.black, text_color=color.white)
    table.cell(ib_analytics, 0, 1, "20D MAX", bgcolor=color.black, text_color=color.white)
    table.cell(ib_analytics, 1, 1, str.tostring(array.max(delta_history), "#.####"), bgcolor=color.black, text_color=high_col)
    table.cell(ib_analytics, 0, 2, "20D AVG", bgcolor=color.black, text_color=color.white)
    table.cell(ib_analytics, 1, 2, str.tostring(array.avg(delta_history), "#.####"), bgcolor=color.black, text_color=middle_col)
    table.cell(ib_analytics, 0, 3, "20D MIN", bgcolor=color.black, text_color=color.white)
    table.cell(ib_analytics, 1, 3, str.tostring(array.min(delta_history), "#.####"), bgcolor=color.black, text_color=low_col)
    table.cell(ib_analytics, 0, 4, "Today", bgcolor=color.black, text_color=color.white)
    table.cell(ib_analytics, 1, 4, str.tostring(ib_delta), bgcolor=color.black, text_color=color.blue)
    table.cell(ib_analytics, 0, 5, "Status", bgcolor=color.black, text_color=color.white)
    table.cell(ib_analytics, 1, 5, ib_sentiment() , bgcolor=color.black, text_color=color.white)
