TPTR_Dynamic_Ratio_Correlator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © silver_efficiency

//@version=5
indicator('TPTR_Dynamic_Ratio_Correlator', overlay=true, precision=2)


// Dynamic symbol choice defaults to XLE and XLF
sec_1 = input.symbol('XLE')
sec_2 = input.symbol('XLK')
ratio_threshold = input(0.40)


// Computes Sec_1 and Sec_2's price by current period
close_D_sec_1 = request.security(sec_1, timeframe.period, close)
close_D_sec_2 = request.security(sec_2, timeframe.period, close)


//Computes the ratio between Sec_1 and Sec_2
ratio_D_sec_1_sec_2 = close_D_sec_1 / close_D_sec_2
// Computes Graphic display indicator in summary table for current candle ratio state
trendGraphic(trend) =>
    trend == 1 ? ' 🟢 ' : ' 🔴 '

// Plots the value of the ratio as a part of the study in header
plotchar(ratio_D_sec_1_sec_2, color=color.new(color.yellow, 0), char='')


// Summary table framework
var statsTable = table.new(position=position.bottom_right, columns=3, rows=2, bgcolor=color.black, border_width=1, border_color=color.white)
table.cell(table_id=statsTable, column=0, row=0, text=str.tostring(sec_1), text_color=color.white, text_halign=text.align_left, text_size=size.normal, bgcolor=#000004)
table.cell(table_id=statsTable, column=1, row=0, text=str.tostring(sec_2), text_color=color.white, text_halign=text.align_left, text_size=size.normal, bgcolor=#000004)
table.cell(table_id=statsTable, column=2, row=0, text='Ratio -' + str.tostring(sec_1) + " & " + str.tostring(sec_2), text_color=color.white, text_halign=text.align_left, text_size=size.normal, bgcolor=#000004)

table.cell(table_id=statsTable, column=0, row=1, text=str.tostring(close_D_sec_1), text_color=color.white, text_halign=text.align_left)
table.cell(table_id=statsTable, column=1, row=1, text=str.tostring(close_D_sec_2), text_color=color.white, text_halign=text.align_left)
table.cell(table_id=statsTable, column=2, row=1, text=trendGraphic(ratio_D_sec_1_sec_2 >= ratio_threshold) + str.tostring(ratio_D_sec_1_sec_2, '#.###'), text_color=color.white, text_halign=text.align_left)


// Generate Alert condition when sec_1 / sec_2 ratio cross above threshold (default 0.4)

ratioUp = ta.crossover(math.round(ratio_D_sec_1_sec_2, 2), ratio_threshold)

if ratioUp
    // Trigger the alert the first time a cross occurs during the real-time bar. 
    // If you want to change to once per bar close; alter the alert.freq_once_per_bar to alert.freq_once_per_bar_close
    alert('ratio_Sec_1_Sec_2 (' + str.tostring(ratio_D_sec_1_sec_2) + ') crossed over threshold (' + str.tostring(ratio_threshold) + ').', alert.freq_once_per_bar)

// Paint indicator above bar
plotchar(ratioUp, 'ratioUp', '▲', location.belowbar, size=size.tiny, color=color.new(color.yellow, 0))

