Price & Percentage Change Label
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MYNAMEISBRANDON

//@version=5
indicator("Price Label", "Price Label", overlay=true)

var string maGroup0 = '----------------------------Timeframe Options----------------------------'
resInputMA = input.timeframe(title='MA/RSI/CMO Timeframe', defval='', group=maGroup0)

int in_CMO_length = input.int(title="CMO Length", defval=25, minval=1, group=maGroup0)
int in_RSI_length = input.int(title="RSI Length", defval=14, minval=1, group=maGroup0)


in_volumeTF_daily = input.timeframe(title='Volume Timeframe=Daily', defval='1D', group=maGroup0)

show_ma_timeframe = input.bool(true, "Enable MA timeframe label", group=maGroup0)
resInputMA1 = input.timeframe(title='Conviction Arrows Timeframe', defval='', group=maGroup0)


_get(res, src) =>
    data = res == timeframe.period ? src : src[1]
    request.security(syminfo.tickerid, res, data, lookahead=barmerge.lookahead_on)

get_timeframe_title(simple string tf = "") =>
    chartTf = timeframe.isminutes == true and timeframe.multiplier > 59 ? (timeframe.multiplier/60 % 2 == 0 ? str.tostring(timeframe.multiplier/60)+"h" : str.tostring(timeframe.multiplier)+"m") : timeframe.isminutes == true ? str.tostring(timeframe.multiplier)+"m" : timeframe.period
    result = show_ma_timeframe ? (tf == "" ? "" : request.security(syminfo.tickerid, tf, chartTf)) : ""


_getMany(res, src1, src2, src3, src4, src5) =>
    data1 = src1[1]
    data2 = src2[1]
    data3 = src3[1]
    data4 = src4[1]
    data5 = src5[1]

    if res == timeframe.period
        data1 := src1
        data2 := src2
        data3 := src3
        data4 := src4
        data5 := src5

    [out1, out2, out3, out4, out5] = request.security(syminfo.tickerid, res, [data1, data2, data3, data4, data5], lookahead=barmerge.lookahead_on)
    [out1, out2, out3, out4, out5]

//_get2(res, src) =>
    //out = request.security(syminfo.tickerid, res, src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
    //out

_get2(res, src) =>
    request.security(syminfo.tickerid, res, src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)


//_get3(res, src) =>
    //out = request.security(syminfo.tickerid, res, src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)
    //out

_get3(res, src) =>
    request.security(syminfo.tickerid, res, src[barstate.isrealtime ? 1 : 0], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)


labels = label.all


// Load all labels generated by this script

labelPadding = "                                                                                                                 "
labelPadding1 = "                             "
LabelPadding_Above_Below = "                                                                                                                                     "
labelPadding13_48 = "                                   "                                                        
labelPadding100_200 = "                                  "                 
labelPadding_volume = "                                                                                                                                                                                               "

ma(formula, source, length) =>
    switch formula
        "" => ta.ema(source, length)



var string maGroup7 = '----------------------------Moving Average 7----------------------------'
enableMA7 = input.bool(true, "Enable MA", group=maGroup7)
enableMA7Label = input.bool(true, "Enable MA label", group=maGroup7)
show_ma_prices7 = input.bool(true, "Enable price", group=maGroup7)
ma7Formula = input.string("", options=['', 'HMA', 'SMA','SWMA','RMA','VWAP','VWMA','WMA', 'ZLEMA', 'DEMA', 'TEMA', 'ALMA', 'ZLSMA'], title="Formula", group=maGroup7)
ma7Length = input.int(100,"Length", group=maGroup7)
distance7 = input.int(0, "MA offset", group=maGroup7)
ma7Color = input.color(color.rgb(120, 216, 82, 16), "Color", group=maGroup7)
ma7Text = str.tostring(ma7Formula) + ' ' + str.tostring(ma7Length) 
ma7 = _get(resInputMA, ma(ma7Formula, close, ma7Length))
ma7p = plot(ma7, title="7) EMA 100", color=ma7Color, display=display.none)
showMA7 = enableMA7 ? display.all : display.none
MAtimeframe7Text = get_timeframe_title(resInputMA)
MA7labelXPos = bar_index + math.round(ta.change(bar_index)*distance7)
MA7Price = show_ma_prices7 ? " - "+str.tostring(math.round_to_mintick(ma7)) : ""
ma7LabelText = MAtimeframe7Text == "" ? labelPadding100_200+ma7Formula+" "+str.tostring(ma7Length)+MA7Price : labelPadding100_200+ma7Formula+" "+str.tostring(ma7Length)+" ("+MAtimeframe7Text+")"+MA7Price
 


var string maGroup9 = '----------------------------Moving Average 9----------------------------'
enableMA9 = input.bool(true, "Enable MA", group=maGroup9)
enableMA9Label = input.bool(true, "Enable MA label", group=maGroup9)
show_ma_prices9 = input.bool(true, "Enable price", group=maGroup9)
ma9Formula = input.string("", options=['', 'HMA', 'SMA','SWMA','RMA','VWAP','VWMA','WMA', 'ZLEMA', 'DEMA', 'TEMA', 'ALMA', 'ZLSMA'], title="Formula", group=maGroup9)
ma9Length = input.int(200,"Length", group=maGroup9)
distance9 = input.int(0, "MA offset", group=maGroup9)
ma9Color = input.color(color.rgb(221, 73, 73), "Color", group=maGroup9)
ma9Text = str.tostring(ma9Formula) + ' ' + str.tostring(ma9Length) 
ma9 = _get(resInputMA, ma(ma9Formula, close, ma9Length))
ma9p = plot(ma9, title="9) EMA 200", color=ma9Color, display=display.none)
showMA9 = enableMA9 ? display.all : display.none
MAtimeframe9Text = get_timeframe_title(resInputMA)
MA9labelXPos = bar_index + math.round(ta.change(bar_index)*distance9)
MA9Price = show_ma_prices9 ? " - "+str.tostring(math.round_to_mintick(ma9)) : ""
ma9LabelText = MAtimeframe9Text == "" ? labelPadding100_200+ma9Formula+" "+str.tostring(ma9Length)+MA9Price : labelPadding100_200+ma9Formula+" "+str.tostring(ma9Length)+" ("+MAtimeframe9Text+")"+MA9Price



var string maGroup13 = '----------------------------Moving Average 13----------------------------'
enableMA13 = input.bool(true, "Enable MA", group=maGroup13)
enableMA13Label = input.bool(true, "Enable MA label", group=maGroup13)
show_ma_prices13 = input.bool(true, "Enable price", group=maGroup13)
ma13Formula = input.string("", options=['', 'HMA', 'SMA','SWMA','RMA','VWAP','VWMA','WMA', 'ZLEMA', 'DEMA', 'TEMA', 'ALMA', 'ZLSMA'], title="Formula", group=maGroup13)
ma13Length = input.int(13,"Length", group=maGroup13)
distance13 = input.int(0, "MA offset", group=maGroup13)
ma13Color = input.color(color.rgb(150, 155, 148, 16), "Color", group=maGroup13)
ma13Text = str.tostring(ma13Formula) + ' ' + str.tostring(ma13Length)
ma13 = _get(resInputMA, ma(ma13Formula, close, ma13Length))
ma13p = plot(ma13, color=ma13Color, title="13) EMA 13", display=display.none)
showMA13 = enableMA13 ? display.all : display.none
MAtimeframe13Text = get_timeframe_title(resInputMA)
MA13labelXPos = bar_index + math.round(ta.change(bar_index)*distance13)
MA13Price = show_ma_prices13 ? " - "+str.tostring(math.round_to_mintick(ma13)) : ""
ma13LabelText = MAtimeframe13Text == "" ? labelPadding13_48+ma13Formula+" "+str.tostring(ma13Length)+MA13Price : labelPadding13_48+ma13Formula+" "+str.tostring(ma13Length)+" ("+MAtimeframe13Text+")"+MA13Price



var string maGroup14 = '----------------------------Moving Average 14----------------------------'
enableMA14 = input.bool(true, "Enable MA", group=maGroup14)
enableMA14Label = input.bool(true, "Enable MA label", group=maGroup14)
show_ma_prices14 = input.bool(true, "Enable price", group=maGroup14)
ma14Formula = input.string("", options=['', 'HMA', 'SMA','SWMA','RMA','VWAP','VWMA','WMA', 'ZLEMA', 'DEMA', 'TEMA', 'ALMA', 'ZLSMA'], title="Formula", group=maGroup14)
ma14Length = input.int(48,"Length", group=maGroup14)
distance14 = input.int(0, "MA offset", group=maGroup14)
ma14Color = input.color(color.rgb(219, 96, 219, 14), "Color", group=maGroup14)
ma14Text = str.tostring(ma14Formula) + ' ' + str.tostring(ma14Length)
ma14 = _get(resInputMA, ma(ma14Formula, close, ma14Length))
ma14p = plot(ma14, color=ma14Color, title="14) EMA 48", display=display.none) 
showMA14 = enableMA14 ? display.all : display.none
MAtimeframe14Text = get_timeframe_title(resInputMA)
MA14labelXPos = bar_index + math.round(ta.change(bar_index)*distance14)
MA14Price = show_ma_prices14 ? " - "+str.tostring(math.round_to_mintick(ma14)) : ""
ma14LabelText = MAtimeframe14Text == "" ? labelPadding13_48+ma14Formula+" "+str.tostring(ma14Length)+MA14Price : labelPadding13_48+ma14Formula+" "+str.tostring(ma14Length)+" ("+MAtimeframe14Text+")"+MA14Price




// 🟦🟦🟦 SimpleCryptoLife version of label input code
labelSizeInput = input.string(title="$/% Label Size-right of candle", options=["Tiny", "Small", "Normal", "Large", "Huge"], defval="Large", group="-----------------------------Current price/% 1----------------------------")
labelSizeInput2 = input.string(title="$/% Label Size-above candle", options=["Tiny", "Small", "Normal", "Large", "Huge"], defval="Normal", group="-----------------------------Current price/% 1----------------------------")
labelSizeInput1 = input.string(title="% Offset Label Size", options=["Tiny", "Small", "Normal", "Large", "Huge"], defval="Normal", group="-----------------------------Current price/% 1----------------------------")

f_labelSizeFromInput(_input) =>
    _size = switch _input
        "Tiny" => size.tiny
        "Small" => size.small
        "Normal" => size.normal
        "Large" => size.large
        "Huge" => size.huge
        => size.normal  // Default if the other conditions aren't met

labelSize = f_labelSizeFromInput(labelSizeInput)
labelSize2 = f_labelSizeFromInput(labelSizeInput2)
labelSize1 = f_labelSizeFromInput(labelSizeInput1)


// Code related to real price.
regularCandles = ticker.new(syminfo.prefix, syminfo.ticker)
[o,h,l,c] = request.security(regularCandles, timeframe.period, [open,high,low,close])
settlementClose = request.security(regularCandles, "D", close, barmerge.gaps_off, barmerge.lookahead_on)
evenClose = request.security(regularCandles, "60", close, barmerge.gaps_off, barmerge.lookahead_on)


lines = line.all
enableRealClose = input.bool(true, "Current $/% - (right of candle)", group="-----------------------------Current price/% 1----------------------------")
realPriceDistance = input.int(0, "$/% offset - (right of candle)", group="-----------------------------Current price/% 1----------------------------")
plotMarketChangeLabel = input.bool(false, "Current $/% (above candle)", group="-----------------------------Current price/% 1----------------------------")
//realPriceDistance1 = input.int(6, "$/% offset - (above candle)", group="-----------------------------Current price/% 1----------------------------")
plotLevelChange = input.string("Settlement", "Measure change from:", options=['Open', 'Close', 'Settlement'], group="-----------------------------Current price/% 1----------------------------")
enableRealClose0 = input.bool(false, "Current $ - yellow", group="-----------------------------Current price/% 1----------------------------")
enableRealClose01 = input.bool(false, "Current $ - R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose02 = input.bool(false, "$ line - 50", group="-----------------------------Current price/% 1----------------------------")
enableRealClose022 = input.bool(false, "$ line - 50", group="-----------------------------Current price/% 1----------------------------")
enableRealClose03 = input.bool(false, "$ line - 50-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose033 = input.bool(false, "$ line - 50-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose0333 = input.bool(false, "$ line - 75", group="-----------------------------Current price/% 1----------------------------")
enableRealClose03333 = input.bool(false, "$ line - 75", group="-----------------------------Current price/% 1----------------------------")
enableRealClose033333 = input.bool(false, "$ line - 75-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose0333333 = input.bool(false, "$ line - 75-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose04 = input.bool(false, "$ line - 100", group="-----------------------------Current price/% 1----------------------------")
enableRealClose044 = input.bool(false, "$ line - 100", group="-----------------------------Current price/% 1----------------------------")
enableRealClose05 = input.bool(false, "$ line - 100-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose055 = input.bool(false, "$ line - 100-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose06 = input.bool(false, "$ line - 200", group="-----------------------------Current price/% 1----------------------------")
enableRealClose07 = input.bool(false, "$ line - 200-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose09 = input.bool(true, "$ line - 500-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose11 = input.bool(true, "$ line - 500-R/G", group="-----------------------------Current price/% 1----------------------------")
enableRealClose10 = input.bool(false, "$ line - 500", group="-----------------------------Current price/% 1----------------------------")
enableRealClose08 = input.bool(false, "$ line - 500", group="-----------------------------Current price/% 1----------------------------")
enablePercentage_Above = input.bool(false, "% above current price", group="-----------------------------Current price/% 1----------------------------")
enablePercentage_Below = input.bool(false, "% below current price", group="-----------------------------Current price/% 1----------------------------")
percentage = input.float(2, "% from current $", group="-----------------------------Current price/% 1----------------------------")
PercentageDistance = input.int(0, "% offset", group="-----------------------------Current price/% 1----------------------------")
//in_atrMultiplier = input.float(title="Spacing as a multiple of ATR", defval=2.0, step=0.5, minval=0.1, maxval=10.0, tooltip="How far above/below the close should the % labels appear? This value is a multiplier of the Average True Range.")  // 🟦🟦🟦 
enableRealCloseOnPriceScale = input.bool(true, "Show on price scale", group="-----------------------------Current price/% 1----------------------------")


percentageAboveLevel = math.round_to_mintick(c*(1+percentage/100)) 
percentageBelowLevel = math.round_to_mintick(c/(1+percentage/100))
percentageAboveLabelText = LabelPadding_Above_Below + str.tostring(percentageAboveLevel) + "\n " + LabelPadding_Above_Below + "-" + str.tostring(percentage)   +  "%-   " 
percentageBelowLabelText = LabelPadding_Above_Below + str.tostring(percentageBelowLevel) + "\n "  + LabelPadding_Above_Below + "-" + str.tostring(percentage)   +  "%- "

var marketOpen = 0.0
var marketClose = 0.0
var settlementPrice = 0.0

if session.isfirstbar
    marketOpen := o
    marketClose := c[1]
    settlementPrice := session.ismarket ? settlementClose[1] : settlementClose
    if barstate.islast
        settlementPrice := c
    // if not(timeframe.isintraday)
    //     settlementPrice := c[1]

//if session.isfirstbar and bar_index == last_bar_index and not(timeframe.isintraday)
//    settlementPrice := settlementClose
//plot(marketOpen, color=color.fuchsia, style=plot.style_stepline, display=plotOpen ? display.all : display.none)
//plot(marketClose, color=color.lime, style=plot.style_stepline, display=plotClose ? display.all : display.none)
openLevel = nz(marketOpen)
closeLevel = nz(marketClose)
settlementLevel = nz(settlementPrice)


float rsiChart = ta.rsi(close,14)  // 🟦🟦🟦 You can search and replace rsiEMATF with rsiChart if you want to simply use the "normal" RSI
// float rsiEMATF = request.security(syminfo.tickerid, resInputMA, ta.rsi(close,14), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off) // The RSI based on the EMA timeframe. This uses the current returned value. This is ok for just showing current RSI but would cause problems if used historically.

f_CMO(_CMO_length, _RSI_length) =>
    float _momm = ta.change(close)
    float _m1 = _momm >= 0.0 ? _momm : 0.0
    float _m2 = _momm >= 0.0 ? 0.0 : -_momm
    float _sm1 = math.sum(_m1, _CMO_length)
    float _sm2 = math.sum(_m2, _CMO_length)
    float _nom = _sm1-_sm2
    float _div = _sm1+_sm2
    float _chandeMO = math.round(100 * _nom / _div,2)
    float _RSI = ta.rsi(close,_RSI_length)
    [_chandeMO, _RSI]

// [chandeMO, rsiEMATF] = f_CMO(_CMO_length=in_CMO_length, _RSI_length=in_RSI_length)

[chandeMO, rsiEMATF] = request.security(syminfo.tickerid, resInputMA, f_CMO(_CMO_length=in_CMO_length, _RSI_length=in_RSI_length), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)

changeLevel = plotLevelChange == "Open" ? openLevel : plotLevelChange == "Close" ? closeLevel : settlementLevel
changePrice = ((math.round_to_mintick(evenClose)/changeLevel)*100)-100

changeSinceLevel = str.tostring(changePrice, format=format.percent)


// 🟦🟦🟦 Display buy-sell volume, formatted nicely
type OHLCVol  // Create User-Defined Type composed of volume + OHLC
    float volume = volume
    float open = open
    float high = high
    float low = low
    float close = close

f_OHLCVol_chart() => OHLCVol.new()  // Create a new object of type OHLCVol by calling a function. This way it's more efficient to get it from security()

OHLCVol_sec_daily = request.security(syminfo.tickerid, in_volumeTF_daily, f_OHLCVol_chart(), gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)  // Get volume, OHLC all at once from the daily timeframe


var float dailyVolume_daily = na
var float dailyClose_daily = na
var float dailyHigh_daily = na
var float dailyOpen_daily = na
var float dailyLow_daily = na

if barstate.islast

    dailyVolume_daily := OHLCVol_sec_daily.volume
    dailyOpen_daily := OHLCVol_sec_daily.open
    dailyHigh_daily := OHLCVol_sec_daily.high
    dailyLow_daily := OHLCVol_sec_daily.low
    dailyClose_daily := OHLCVol_sec_daily.close


float dailyBuyVolume_daily = dailyHigh_daily == dailyLow_daily ? 0 : nz(dailyVolume_daily) * (dailyClose_daily - dailyLow_daily) / (dailyHigh_daily - dailyLow_daily)
float dailySellVolume_daily = dailyHigh_daily==dailyLow_daily ? 0 : nz(dailyVolume_daily) * (dailyHigh_daily - dailyClose_daily) / (dailyHigh_daily - dailyLow_daily)

float dailyBuyVolumePercent_daily = dailyBuyVolume_daily / dailyVolume_daily * 100
float dailySellVolumePercent_daily = dailySellVolume_daily / dailyVolume_daily * 100

f_formatNumberWithCommas(float _number) =>
    string _numberAsCurrency = str.format("{0, number, currency}", math.round(_number,0))
    string _numberWithCommas = str.replace(_numberAsCurrency, "$", "")
    string _numberWithoutTrailingZeroes = str.replace(_numberWithCommas, ".00", "")

f_formatNumberWithLetters(float _number) =>
    float _roundNumber = math.round(_number,0)
    string _formattedNumber = na
    float _dividedNumber = na 
    if _roundNumber > 1000 and _roundNumber < 1000000
        _dividedNumber := _roundNumber/1000
        _formattedNumber := str.tostring(_dividedNumber) + "k"
    else if _roundNumber > 1000000 and _roundNumber < 1000000000
        _dividedNumber := _roundNumber/1000000
        _formattedNumber := str.tostring(_dividedNumber) + "m"    
    else if _roundNumber > 1000000000 
        _dividedNumber := _roundNumber/1000000000
        _formattedNumber := str.tostring(_dividedNumber) + "b"    
    else
        _formattedNumber := str.tostring(_roundNumber)
    _formattedNumber


string dailyVolumeString_daily = f_formatNumberWithCommas(_number=dailyVolume_daily) + " " + "(" + str.tostring(value=dailyBuyVolumePercent_daily, format='#') + "/" + str.tostring(value=dailySellVolumePercent_daily, format='#') + ")"

// debugLabel = label.new(bar_index,close, style = label.style_label_left, text=debugText, textcolor=color.white, color=color.black, size=size.normal)
// label.delete(debugLabel[1])

float priceChangeAmount = c-changeLevel  // 🟦🟦🟦

// New section to make the text lines a bit more organised
string text_CMO_RSI = str.tostring(chandeMO) + " * " + str.tostring(math.round(rsiEMATF,2))
string strike = "\n" + labelPadding + "⚡" + "\n"
string strike1 = "\n" + labelPadding_volume + "⚡" + "\n"

string text_volume_daily = labelPadding + dailyVolumeString_daily + " d"
string text_above_percentage = str.tostring(percentage)  +  "% " + "(" + str.tostring(percentageAboveLevel) + ")"
string text_below_percentage = "-" + str.tostring(percentage)  +  "% " + "(" + str.tostring(percentageBelowLevel) + ")"
string text_priceChange = labelPadding + str.tostring(c) + " (" + str.tostring(priceChangeAmount) + " (" + changeSinceLevel + "))" 

// This is the "main" bit, which is enabled by the enableRealClose option  // 🟦🟦🟦
string closeLabelText =  text_volume_daily + strike + labelPadding + text_CMO_RSI + strike + labelPadding + text_above_percentage + strike  + labelPadding + text_below_percentage + strike + text_priceChange 

//string closeLabelText_volumeprofiles = text_volume + strike1 + text_volume_10m + strike1 + text_volume_30m + strike1 + text_volume_1h + strike1 + text_volume_4h + strike1 + text_volume_daily

////below script manipulates yellow and R/G price change, RSI and percentage below value
string extraLabelText = text_CMO_RSI + strike + labelPadding + text_above_percentage + strike  + labelPadding + text_below_percentage + strike  // This is the one that gets shown or hidden by the input enableRealClose0 // 🟦🟦🟦

//below manipulates yellow but not R/G
string text_price = labelPadding + str.tostring(c) + " * " + str.tostring(priceChangeAmount)
closeLabelText1 = extraLabelText + text_price

//if barstate.islast and plotMarketChangeLabel
    //label.new(bar_index,close,yloc=c > changeLevel ? yloc.abovebar : yloc.abovebar, style = c > changeLevel ? label.style_label_up : label.style_label_up,  text=marketOpenLabelText1, textcolor=percLabelColor1, color=percLabelColor, size=labelSize)
    

//below manipulates current price R/G but not yellow 
closeLabelText2 = extraLabelText + labelPadding + str.tostring(c) + " * " + str.tostring(priceChangeAmount)  // 🟦🟦🟦


marketOpenLabelText = str.tostring(c) + "\n" + changeSinceLevel
marketOpenLabelText1 = str.tostring(c) + "\n" 
//marketOpenLabelText2 = str.tostring(c) + "\n" 



plot(c, display=enableRealCloseOnPriceScale ? display.price_scale : display.none)
percLabelColor = c > changeLevel ? color.rgb(0, 0, 0, 100) : color.rgb(0, 0, 0, 100)
percLabelColor1 = c > changeLevel ? color.green : color.rgb(247, 21, 21)
percLabelColor2 = c > changeLevel ? color.white : color.white
percLabelColor3 = c > changeLevel ? color.rgb(255, 235, 59, 25) : color.rgb(255, 235, 59, 25)


var label marketChangeLabel = na
if barstate.islast and plotMarketChangeLabel
    marketChangeLabel := label.new(bar_index,close,yloc=c > changeLevel ? yloc.abovebar : yloc.abovebar, style = c > changeLevel ? label.style_label_up : label.style_label_up,  text=marketOpenLabelText, textcolor=percLabelColor1, color=percLabelColor, size=labelSize2)
    label.delete(marketChangeLabel[1])


var label marketChangeLabel2 = na
if barstate.islast and plotMarketChangeLabel
    marketChangeLabel2 := label.new(bar_index,close,yloc=c > changeLevel ? yloc.abovebar : yloc.abovebar, style = c > changeLevel ? label.style_label_up : label.style_label_up,  text=marketOpenLabelText1, textcolor=percLabelColor1, color=percLabelColor, size=labelSize2)
    label.delete(marketChangeLabel2[1])
    


// ------ PRICE LABELS -------
labelXPosAboveBelow = bar_index + math.round(ta.change(bar_index)*PercentageDistance)
labelXPosRealClose = bar_index + math.round(ta.change(bar_index)*realPriceDistance)
priceStringCurrent = str.tostring(c)
priceStringCurrentPerc = changeSinceLevel


styleline = line.new(bar_index, c, bar_index+0, c, color=color.white)
//styleline2 = line.new(bar_index, c, bar_index+0, c, color=color.white)
//styleline3 = line.new(bar_index, c, bar_index+0, c, color=color.white)
line.set_style(styleline, style=line.style_dotted)
//line.set_style(styleline2, style=line.style_arrow_both)
//line.set_style(styleline3, style=line.style_arrow_left)


// 🟦🟦🟦 Changed the vertical spacing to ATR-based
//float atrAbove = c+(ta.atr(14)*in_atrMultiplier)
//float atrBelow = c-(ta.atr(14)*in_atrMultiplier)



if barstate.islast
    // Uncomment these lines if you move this part to a separate indicator
    // if array.size(labels) > 0
    //     for i = 0 to array.size(labels) - 1
    //         oldLabel = array.get(labels, i)
    //         label.delete(oldLabel)

    if array.size(lines) > 0
        for i = 0 to array.size(lines) - 1
            oldLine = array.get(lines, i)
            line.delete(oldLine)
    // and then create new ones

    
    var label ma7Label = na
    var label ma9Label = na
    var label ma13Label = na
    var label ma14Label = na
    var label labelRealClose = na
    var label labelRealClose_volume = na
    var label labelRealClose0 = na
    var label labelRealClose01 = na
    var label labelRealClose5 = na
    var label labelRealClose6 = na
    var label labelRealClose7 = na
    var label labelRealClose8 = na
    var label percentageAboveLabel = na
    var label percentageBelowLabel = na
    var label text_above_percentage_label = na
    var label text_below_percentage_label = na 

    //if plotMarketChangeLabel  //follow price and % above candle
        //line.new(bar_index, c, bar_index+0, c, color=color.white, style=line.style_dotted)
        //regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, textalign = text.align_left)
        //marketChangeLabel2 := label.new(labelXPosRealClose, c, text = closeLabelText, xloc=xloc.bar_index, color = percLabelColor1, textcolor = percLabelColor1, style = label.style_none, size=labelSize)
        //label.delete(marketChangeLabel2[1])

    if enableMA7 and enableMA7Label
        ma7Label := label.new(MA7labelXPos, ma7, ma7LabelText, xloc=xloc.bar_index, style=label.style_label_center, color=color.rgb(0, 0, 0, 100), textcolor = ma7Color)
        label.delete(ma7Label[1])
    
    if enableMA9 and enableMA9Label
        ma9Label := label.new(MA9labelXPos, ma9, ma9LabelText, xloc=xloc.bar_index, style=label.style_label_center, color=color.rgb(0, 0, 0, 100), textcolor = ma9Color)
        label.delete(ma9Label[1])

    if enableMA13 and enableMA13Label
        ma13Label := label.new(MA13labelXPos, ma13, ma13LabelText, xloc=xloc.bar_index, style=label.style_label_center, color=color.rgb(0, 0, 0, 100), textcolor = ma13Color)
        label.delete(ma13Label[1])

    if enableMA14 and enableMA14Label
        ma14Label := label.new(MA14labelXPos, ma14, ma14LabelText, xloc=xloc.bar_index, style=label.style_label_center, color=color.rgb(0, 0, 0, 100), textcolor = ma14Color)
        label.delete(ma14Label[1])

    


    if enableRealClose  //follow price and %
        line.new(bar_index, c, bar_index+0, c, color=color.white, style=line.style_dotted)
        //regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, textalign = text.align_left)
        labelRealClose := label.new(labelXPosRealClose, c, text = closeLabelText, xloc=xloc.bar_index, color = percLabelColor1, textcolor = percLabelColor1, style = label.style_none, size=labelSize)
        label.delete(labelRealClose[1])
        
    //if enableRealClose_volumeprofiles  //follow price and %
        //line.new(bar_index, c, bar_index+0, c, color=color.white, style=line.style_dotted)
        //regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, textalign = text.align_left)
        //labelRealClose_volume := label.new(labelXPosRealClose, c, text = closeLabelText_volumeprofiles, xloc=xloc.bar_index, color = percLabelColor1, textcolor = percLabelColor1, style = label.style_none, size=labelSize)
        //label.delete(labelRealClose_volume[1])


    if enableRealClose0  //follow price and %
        line.new(bar_index, c, bar_index+0, c, color=color.rgb(255, 235, 59, 25), style=line.style_dotted)
        //regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText1, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor2, textalign = text.align_left)
        labelRealClose0 := label.new(labelXPosRealClose, c, text = labelPadding+closeLabelText1, xloc=xloc.bar_index, color = percLabelColor3, textcolor = percLabelColor3, style = label.style_none, size=labelSize)
        label.delete(labelRealClose0[1])
    
    if enableRealClose01  //follow price and %
        line.new(bar_index, c, bar_index+0, c, color=color.white, style=line.style_dotted)
        //regularCloseLabel = label.new(bar_index+realPriceDistance, c, closeLabelText2, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, textalign = text.align_left)
        labelRealClose01 := label.new(labelXPosRealClose, c, text = labelPadding+closeLabelText2, xloc=xloc.bar_index, color = percLabelColor1, textcolor = percLabelColor1, style = label.style_none, size=labelSize)
        label.delete(labelRealClose01[1])

    if enableRealClose02 //yellow line length 50
        line.new(bar_index, c, bar_index+50, c, color=color.rgb(255, 235, 59), style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)

    if enableRealClose022 //yellow line length 50
        line.new(bar_index, c, bar_index+50, c, color=color.rgb(255, 235, 59), style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor3, textalign = text.align_left)

    if enableRealClose03 //red green option length 50
        line.new(bar_index, c, bar_index+50, c, color=percLabelColor1, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)

    if enableRealClose033 //red green option length 50
        line.new(bar_index, c, bar_index+50, c, color=percLabelColor1, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)

    if enableRealClose0333 //length 75 white line
        line.new(bar_index, c, bar_index+75, c, color=color.rgb(255, 235, 59), style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)

    if enableRealClose03333 //length 75 white line
        line.new(bar_index, c, bar_index+75, c, color=color.yellow, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)

    if enableRealClose033333 //red green option length 75
        line.new(bar_index, c, bar_index+75, c, color=percLabelColor1, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)

    if enableRealClose0333333 //red green option length 75
        line.new(bar_index, c, bar_index+75, c, color=percLabelColor1, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)

    if enableRealClose04 //white line length 100
        line.new(bar_index, c, bar_index+100, c, color=color.yellow, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)
    
    if enableRealClose044 //white line length 100
        line.new(bar_index, c, bar_index+100, c, color=color.yellow, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)

    if enableRealClose05 //red green option length 100
        line.new(bar_index, c, bar_index+100, c, color=percLabelColor1, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)

    if enableRealClose055 //red green option length 100
        line.new(bar_index, c, bar_index+100, c, color=percLabelColor1, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)

    if enableRealClose06 //white line length 200
        line.new(bar_index, c, bar_index+200, c, color=color.yellow, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)

    if enableRealClose07 //red green option length 200
        line.new(bar_index, c, bar_index+200, c, color=percLabelColor1, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)

    if enableRealClose08 //white line length 500
        line.new(bar_index, c, bar_index+500, c, color=color.yellow, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)

    if enableRealClose09 //red green option length 500
        line.new(bar_index, c, bar_index+500, c, color=percLabelColor1, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
        
    if enableRealClose10 //white line length 500 - to highlight line
        line.new(bar_index, c, bar_index+500, c, color=color.yellow, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor, textalign = text.align_left)

    if enableRealClose11 //red green option length 500 - to highlight line
        line.new(bar_index, c, bar_index+500, c, color=percLabelColor1, style=line.style_dotted)
        //regularCloseLabel1 = label.new(bar_index+realPriceDistance, c, yloc=yloc.price, style=label.style_none, textcolor=percLabelColor1, color=percLabelColor, textalign = text.align_left)
        






var string arrowGroup = '----------------------------Conviction Arrows----------------------------'
//arrowsResInput = input.timeframe(title='Timeframe', defval='', group=arrowGroup)
//resInputMA1 = input.timeframe(title='Conviction Arrows TF', defval='', group=maGroup0)
show_conviction_arrows = input.bool(true, 'Enable Conviction Arrows', group=arrowGroup)
fast_conviction_ema = input.int(13, 'Fast Conviction EMA Length', group=arrowGroup)
slow_conviction_ema = input.int(48, 'Slow Conviction EMA Length', group=arrowGroup)
fast_conviction_ema1 = input.int(100, 'Fast Conviction EMA Length', group=arrowGroup)
slow_conviction_ema1 = input.int(200, 'Slow Conviction EMA Length', group=arrowGroup)
bullish_conviction_color_13_48 = input.color(color.rgb(167, 180, 180, 16), 'Bullish Conviction 13/48 Color', group=arrowGroup)
bearish_conviction_color_13_48 = input.color(color.rgb(179, 93, 153), 'Bearish Conviction 13/48 Color', group=arrowGroup)
bullish_conviction_color_100_200 = input.color(color.rgb(120, 216, 82, 16), 'Bullish 100/200 Arrow Color', group=arrowGroup)
bearish_conviction_color_100_200 = input.color(color.rgb(160, 52, 52), 'Bearish 100/200 Arrow Color', group=arrowGroup)

fast_conviction_ema_value = _get2(resInputMA1, ta.ema(close, fast_conviction_ema))
slow_conviction_ema_value = _get2(resInputMA1, ta.ema(close, slow_conviction_ema))

fast_conviction_ema_value1 = _get3(resInputMA1, ta.ema(close, fast_conviction_ema1))
slow_conviction_ema_value1 = _get3(resInputMA1, ta.ema(close, slow_conviction_ema1))



// Conviction Arrows (default based on 13/48)
bullish_conviction = fast_conviction_ema_value >= slow_conviction_ema_value
bearish_conviction = fast_conviction_ema_value < slow_conviction_ema_value
bullish_conviction_confirmed = bullish_conviction[0] == true and bullish_conviction[1] == false
bearish_conviction_confirmed = bearish_conviction[0] == true and bearish_conviction[1] == false

plotshape(bullish_conviction_confirmed and show_conviction_arrows, color=bullish_conviction_color_13_48, location=location.top, size=size.tiny, title='13/48 top', text='13/48', textcolor=color.rgb(189, 190, 194), display=display.none)
plotshape(bullish_conviction_confirmed and show_conviction_arrows, style=shape.triangleup, color=bullish_conviction_color_13_48, location=location.belowbar, size=size.tiny, title='13/48 bull arrow up', textcolor=color.rgb(189, 190, 194), display=display.none)

plotshape(bearish_conviction_confirmed and show_conviction_arrows, color=bearish_conviction_color_13_48, location=location.top, size=size.tiny, title='48/13 top', text='48/13', textcolor=color.purple, display=display.none) 
plotshape(bearish_conviction_confirmed and show_conviction_arrows, style=shape.triangledown, color=bearish_conviction_color_13_48, location=location.abovebar, size=size.tiny, title='48/13 bear arrow down', textcolor=color.purple, display=display.none) 


// Conviction Arrows (default based on 100/200)
bullish_conviction1 = fast_conviction_ema_value1 >= slow_conviction_ema_value1
bearish_conviction1 = fast_conviction_ema_value1 < slow_conviction_ema_value1
bullish_conviction_confirmed1 = bullish_conviction1[0] == true and bullish_conviction1[1] == false
bearish_conviction_confirmed1 = bearish_conviction1[0] == true and bearish_conviction1[1] == false

plotshape(bullish_conviction_confirmed1 and show_conviction_arrows, color=bullish_conviction_color_100_200, location=location.top, size=size.small, title='100/200 top', text='100/200', textcolor=color.rgb(120, 216, 82, 16), display=display.none)
plotshape(bullish_conviction_confirmed1 and show_conviction_arrows, style=shape.triangleup, color=bullish_conviction_color_100_200, location=location.belowbar, size=size.small, title='100/200 bull arrow up', textcolor=color.rgb(120, 216, 82, 16), display=display.none)

plotshape(bearish_conviction_confirmed1 and show_conviction_arrows, color=bearish_conviction_color_100_200, location=location.top, size=size.small, title='200/100 top', text='200/100', textcolor=color.rgb(221, 73, 73, 75), display=display.none)
plotshape(bearish_conviction_confirmed1 and show_conviction_arrows, style=shape.triangledown, color=bearish_conviction_color_100_200, location=location.abovebar, size=size.small, title='200/100 bear arrow down', textcolor=color.rgb(221, 73, 73, 75), display=display.none)




// Everything inside this is done only when last bar is loaded, no point in writing and deleting
// labels for the whole history


ma1(formula, source, length) =>
    switch formula
        "EMA" => ta.ema(source, length)
// Input options
//EMA_13 = input.int(title="EMA 1", defval=13)
//EMA_48 = input.int(title="EMA 2", defval=48)
//EMA_100 = input.int(title="EMA 3", defval=100)
//EMA_200 = input.int(title="EMA 4", defval=200)

// Calculate values
Alert_EMA_13 = ta.ema(close, ma13Length)
Alert_EMA_48 = ta.ema(close, ma14Length)
Alert_EMA_100 = ta.ema(close, ma7Length)
Alert_EMA_200 = ta.ema(close, ma9Length)

// Create Buy/Sell Arrows
//plotshape(Buy, color=green, style=shape.arrowup, text="Buy", location=location.bottom)
//plotshape(Sell, color=red, style=shape.arrowdown, text="Sell", location=location.top)

// Show on Chart
//plot(Alert_EMA_13, color=color.rgb(150, 155, 148, 16), title="EMA 13", display=display.none)
//plot(Alert_EMA_48, color=color.rgb(219, 96, 219, 14), title="EMA 48", display=display.none)
//plot(Alert_EMA_100, color=color.rgb(120, 216, 82, 16), title="EMA 100", display=display.none)
//plot(Alert_EMA_200, color=color.rgb(221, 73, 73), title="EMA 200", display=display.none)


// Create alert conditions
//alertcondition(condition=crossover(Alert_EMA_13, Alert_EMA_48), 
     //title="EMA 21 Cross Above",
     //message="EMA 21 crossed over EMA 55."
     
     //)
    

//alertcondition(condition=crossunder(Alert_EMA_13, Alert_EMA_48),
     //title="EMA 13 Cross Above",
     //message="EMA 13 crossed over EMA 48."
    
     //)
     


// 13/48 
TrendingUp1() => Alert_EMA_13 > Alert_EMA_48 
TrendingDown2() => Alert_EMA_13 < Alert_EMA_48 
//barcolor(TrendingUp() ? color.green : TrendingDown() ? color.red : color.blue)
// EMA cross background color alert to chart (Tall Candle)
Uptrend1() => TrendingUp1() and TrendingDown2()[1]
Downtrend1() => TrendingDown2() and TrendingUp1()[1]
bgcolor(Uptrend1() ? color.rgb(173, 173, 173, 70) : Downtrend1() ? color.rgb(211, 121, 211, 70) : na, title="13/48 crossover")


// 100/200 
TrendingUp3() => Alert_EMA_100 > Alert_EMA_200 
TrendingDown4() => Alert_EMA_100 < Alert_EMA_200 
//barcolor(TrendingUp() ? color.green : TrendingDown() ? color.red : color.blue)
// EMA cross background color alert to chart (Tall Candle)
Uptrend2() => TrendingUp3() and TrendingDown4()[1]
Downtrend2() => TrendingDown4() and TrendingUp3()[1]
bgcolor(Uptrend2() ? color.rgb(113, 224, 113, 70) : Downtrend2() ? color.rgb(221, 73, 73, 70) : na, title="100/200 crossover")


//13/48
//Buy = Uptrend1() and close > close[1]
//Sell = Downtrend1() and close < close[1]
//plotshape(Buy, color=color.gray, style=shape.triangleup, text="13/48", location=location.top, textcolor=color.rgb(173, 173, 173))
//plotshape(Sell, color=color.purple, style=shape.triangledown, text="13/48", location=location.top, textcolor=color.rgb(211, 121, 211))

//100/200
//Buy_1 = Uptrend2() and close > close[1]
//Sell_1 = Downtrend2() and close < close[1]
//plotshape(Buy_1, color=color.green, style=shape.triangleup, text="100/200", location=location.top, textcolor=color.rgb(113, 224, 113, 3))
//plotshape(Sell_1, color=color.red, style=shape.triangledown, text="100/200", location=location.top, textcolor= color.rgb(243, 95, 95))