Market Breadth: Trends & Breakouts
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © groks
//
// What percent of a market's constituents are participating in trends and breakouts? And can that
// give clues to market direction before it is reflected in the market price?
//
// Default data sourcees are for the S&P 500, but you can use data for another market, or change
// the length of trends or breakouts.
//
//@version=5
indicator("Market Breadth: Trends & Breakouts")


above_slow_avg_sym = input.symbol("S5TH", "% Above slow average")
above_fast_avg_sym = input.symbol("S5FI", "% Above fast average")
new_hi_sym         = input.symbol("MAHP", "# New highs")
new_lo_sym         = input.symbol("MALP", "# New lows")
denom              = input.int(500,       "Size of index", tooltip="Needed to convert number of new highs to percent of new highs")


// Most of this data seems to be only available at daily resolution or above. Using indicator(timeframe="1D") produces a glitchy display.
var tf = timeframe.ismonthly ? "1M" : timeframe.isweekly ? "1W" : "1D"

slow = request.security(above_slow_avg_sym, tf, close)
fast = request.security(above_fast_avg_sym, tf, close)
hi   = request.security(new_hi_sym,         tf, close)
lo   = request.security(new_lo_sym,         tf, close)



var gray2 = color.new(color.gray, 80)

zero = plot(0, "0", color=color.gray)
plot(50,   "50% line",   color=gray2)
plot(-50,  "-50% line",  color=gray2)
plot(100,  "100% line",  color=gray2)
plot(-100, "-100% line", color=gray2)

var blue = color.new(color.blue, 80)

a = plot(slow,       "Percent above slow moving average", color=blue)
b = plot(slow - 100, "Percent below slow moving average", color=blue)
fill(a, b, color=blue, title="Slow moving average fill")


var blue2 = color.new(color.blue, 60)

a2 = plot(fast,       "Percent above fast moving average", color=blue2)
b2 = plot(fast - 100, "Percent below fast moving average", color=blue2)
fill(a2, b2, color=color.new(blue2, 100), title="Fast moving average fill")


pct_hi = (100 / denom) * hi
hi_line = plot(pct_hi, "% New high", color=color.green)
fill(zero, hi_line, color=color.green, title="% New high fill")

pct_lo = ((100 / denom) * lo)
lo_line = plot(-pct_lo, "% New low", color=color.red)
fill(zero, lo_line, color=color.red, title="% New low fill")

