Trend Finder with Coefficient of Variation
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DojiEmoji

//@version=5
indicator("Trend Finder w/ COV [DojiEmoji]", overlay=true)

//------------------------------
// Source data && Stats.
//------------------------------
var string GROUP_BASIS = "Source of data"
var int length_n       = input.int(20, minval=1, group=GROUP_BASIS, title="Lookback (n)")
float src              = input(close, title="Source", group=GROUP_BASIS)

float mean  = ta.sma(src, length_n)
float stdev = ta.stdev(src, length_n)
float COV   = stdev / mean                  // Coefficient of variation

//------------------------------
// Visualizations:
//------------------------------
var string GROUP_COV = "Comparing COV(source, n)"

var int length_m = input.int(50, minval=1, group=GROUP_COV, title="Lookback (m)")
var bool display_bg = input.bool(true, title="Display background with color scale:", group=GROUP_COV)
var color col_min    =input.color(color.new(color.black,50), title="Low COV", group=GROUP_COV, inline="col")
var color col_max    =input.color(color.new(color.yellow,50), title="High COV", group=GROUP_COV, inline="col")

bool is_ranging = COV < ta.median(COV, length_m)
bgcolor(display_bg ? color.from_gradient(COV, ta.lowest(COV,length_m), ta.highest(COV,length_m), col_min, col_max) : na)

//------------------------------
// Signals
//------------------------------
bool uptrend = close > mean and not is_ranging
bool downtrend = close < mean and not is_ranging

bool uptrend_begins = uptrend and is_ranging[1]
bool downtrend_begins = downtrend and is_ranging[1]
plotshape(uptrend_begins, style=shape.triangleup, location=location.belowbar, title="Uptrend", color=color.blue, size=size.small)
plotshape(downtrend_begins, style=shape.triangledown, location=location.abovebar, title="Uptrend", color=color.red, size=size.small)

alertcondition(uptrend_begins, title = "Uptrend", message = "Trend Finder with COV -> Uptrend")
alertcondition(downtrend_begins, title = "Downtrend", message = "Trend Finder with COV -> Downtrend")
