YTD & Drawdown
//This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//©ChartingCycles
//@version=5

indicator('YTD', scale=scale.none, overlay=true, precision=0, format=format.percent)

//YTD % Calc
specificDate = time >= timestamp(year(timenow), 1, 1, 00, 00)
var float closeOnDate = na
if specificDate and not specificDate[1]
    closeOnDate := close[1] // Get the close of the last day of the prior year

// Check if closeOnDate is still na, if so, use the first available close price
if na(closeOnDate)
    closeOnDate := close[0]

YTD = (close - closeOnDate) / closeOnDate

//ATH % Calc
GetATH(dataSeries = high) =>
    var float ATH = -1e10
    if dataSeries > ATH
        ATH := dataSeries
    ATH

// Calculate drawdown
athValue = GetATH()
drawdown = -1*(athValue - close) / athValue

//Panel
var string GP2 = 'Display'
show_header = timeframe.isdaily ? input.bool(true, title='Show Table Header', inline='10', group=GP2) : false
string i_tableYpos = input.string('top', 'Panel Position', inline='11', options=['top', 'middle', 'bottom'], group=GP2)
string i_tableXpos = input.string('right', '', inline='11', options=['left', 'center', 'right'], group=GP2)
string textsize = input.string('normal', 'Text Size', inline='12', options=['small', 'normal', 'large'], group=GP2)
var table dtrDisplay = table.new(i_tableYpos + '_' + i_tableXpos, 3, 3, frame_width=1, frame_color=color.black, border_width=1, border_color=color.black)
if barstate.islast
    // We only populate the table on the last bar.
    if show_header == true
        table.cell(dtrDisplay, 1, 0, 'YTD %', bgcolor=color.black, text_size=textsize, text_color=color.white)
        table.cell(dtrDisplay, 1, 1, str.tostring(math.round((YTD*100),1)) + '%', bgcolor= YTD>0 ? color.teal : color.red, text_size=textsize, text_color=color.white)
        table.cell(dtrDisplay, 2, 0, 'Drawdown %', bgcolor=color.black, text_size=textsize, text_color=color.white)
        table.cell(dtrDisplay, 2, 1, str.tostring(math.round((drawdown*100),1)) + '%', bgcolor= drawdown<0 ? color.red : color.teal, text_size=textsize, text_color=color.white)
