Market Trend
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Trading Ninjaa

//@version=5
indicator(title="Market Trend", shorttitle="Market Trend", overlay=true)

// Input for MA period
maPeriod = input.int(9, title="MA Period", minval=1)

// Define higher timeframe
higherTf = ""
if (timeframe.isintraday)
    if (timeframe.multiplier == 1)
        higherTf := "5"
    else if (timeframe.multiplier <= 5)
        higherTf := "15"
    else if (timeframe.multiplier <= 15)
        higherTf := "30"
    else if (timeframe.multiplier <= 30)
        higherTf := "60"
    else if (timeframe.multiplier <= 60)
        higherTf := "120"
    else if (timeframe.multiplier <= 120)
        higherTf := "180"
    else 
        higherTf := "D"
else if (timeframe.multiplier == 1)
    higherTf := "W"
else 
    higherTf := "M"

// Fetching the higher timeframe MA
htMA = request.security(syminfo.tickerid, higherTf, ta.sma(close, maPeriod))

// Trend identification
upTrend = close > htMA
downTrend = close < htMA

// Determine color for MA line
maColor = upTrend ? color.new(color.green, 0) : downTrend ? color.new(color.red, 0) : color.new(color.blue, 0)

// Plotting
plot(htMA, color=maColor, linewidth=2, title="Higher Timeframe MA9")

// Identifying Sideways market: Using ATR
atrValue = ta.atr(14)
isDecreasingATR = atrValue < ta.sma(atrValue, 50)

// Using the current close range to define a sideways movement
isSideways = isDecreasingATR and not upTrend and not downTrend

// Background Coloring
bgcolor(upTrend ? color.new(color.green, 90) : downTrend ? color.new(color.red, 90) : isSideways ? color.new(color.gray, 90) : na)
