Market Condition Detector
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Fred6724

//@version=5
indicator(title="Market Condition Detector", overlay=true)

// Net High Lows
ref = input("SP:SPX", title = 'Reference Ticker') // Changed to SP:SPX
NNH = input("HIGQ", title = 'Net New High Ticker')
NNL = input("LOWQ", title = 'Net New Low Ticker')

hi_q = request.security(NNH, 'D', close)
lo_q = request.security(NNL, 'D', close)

//Input.
//i_plotBoth = input(false, title='Plot New Highs and Lows Separately')
// i_upColor = input(color.green, title='Color Up')
// i_dnColor = input(color.red, title='Color Down')
i_posBackgroundColor = input(color.rgb(76, 175, 80, 85), title='Background Color Up')
i_negBackgroundColor = input(color.rgb(255, 82, 82, 85), title='Background Color Down')

h_q = hi_q
l_q = lo_q

hi_lo = h_q - l_q
//mycolor = hi_lo > 0 ? i_upColor:i_dnColor


// Add color to the script
// Conditions
condGreen = hi_lo > 0 and hi_lo[1] > 0 and hi_lo[2] > 0 ? true:false
condRed   = hi_lo < 0 and hi_lo[1] < 0 and hi_lo[2] < 0 ? true:false



// EMA 10 & 20 Da
// SMA/EMA Calculation
ema10  = request.security(ref,'D',ta.ema(close,10))
ema20  = request.security(ref,'D',ta.ema(close,20))


// Da
daEma10 = request.security(ref, 'D', ema10)
daEma20 = request.security(ref, 'D', ema20)

// Da Close
closeDa = request.security(ref, 'D', close)


// hi_lo > 0 = bar net high verte

// Conditions
condUp = hi_lo > 0 and daEma10 > daEma20 and closeDa > daEma20
condDn = hi_lo < 0 and daEma10 < daEma20 and closeDa < daEma20
//Exceptions
// BULLISH
// If the daily close stays above the 20Ema and Net Highs in Red in a previously good condition
if(closeDa > daEma20 and hi_lo <= 0 and condUp[1] == true and condUp[2] == true and condUp[3] == true and daEma10 > daEma20)
    condUp := true
// If the close is under 20 EMA but the Net High Low is still in the good color (still with previously good conditions))
if(closeDa < daEma20 and hi_lo > 0 and condUp[1] == true and condUp[2] == true and condUp[3] == true and daEma10 > daEma20)
    condUp := true
// BEARISH
if(closeDa < daEma20 and hi_lo >= 0 and condDn[1] == true and condDn[2] == true and condDn[3] == true and daEma10 < daEma20)
    condDn := true
if(closeDa > daEma20 and hi_lo < 0 and condDn[1] == true and condDn[2] == true and condDn[3] == true and daEma10 < daEma20)
    condDn := true

// Background Color
// COLOR WHEN GOOD
bgcolor(condUp and timeframe.isdaily ? i_posBackgroundColor:na)
// COLOR WHEN NOT GOOD
bgcolor(condDn and timeframe.isdaily ? i_negBackgroundColor:na)