Light or Dark Mode Tutorial - Luminance Detection
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © upslidedown
//

notes = "As a colorblind trader, I think accessibility is a big deal. This script auto detects the chart background color and optimizes text color based on luminance.\n"+
  "Try changing the chart background color and see how this script changes the table printed on the chart.\n"+
  "Luminance detection based on pine script new chart.bg_color feature, allowing lines, tables, etc to be optimized knowing the output color.\n"+
  "This makes it simple to optimize scripts based off the knowledge that max luminance = 765, thus we skew TV to know that lum <= 383 is \"dark mode\" and lum > 383 is \"light mode\""

//@version=5
indicator("Light or Dark Mode Tutorial - Luminance Detection", overlay=true)

// --------------------------------
// this snippet is all you need! 
bgcolor = chart.bg_color
r = color.r(bgcolor)
g = color.g(bgcolor)
b = color.b(bgcolor)
lum = r+g+b
is_dark = lum <= 383

auto_color_based_on_bgcolor = is_dark ? color.white : color.black // auto_color_based_on_bgcolor will change based on final contrast


// --------------------------------
// nothing else below is necessary, just prints the table for a demo

// add some extra notes
notes := notes + "\nLuminance: " + str.tostring(lum) + " (of max 765)\n" + "Dark mode is: " + str.tostring(is_dark)

// print a demo table to showcase how this could be used
var table demo = table.new(position.bottom_right, 1, 1)

if barstate.islast
    // print a table cell with the notes above
    table.cell(demo, 0, 0, notes, text_color=auto_color_based_on_bgcolor, text_halign=text.align_left)

// debug info for users interested in inspecting lum in console
plotchar(lum, "luminance", "", location = location.top)