MACD HTF - Dynamic Smoothing
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Harrocop

////////////////////////////////////////////////////////////////////////////////////////
// HTF Trend Filter - Dynamic Smoothing
// - Option to change high time frame settings
// - Option to choose from different moving average types to calculate MACD
// - The Dynamic smoothing makes a sleek line, taking the ratio of minutes of the higher time frame to the current time frame
// - Color green with uptrend, color red with downtrend
// - options for notification in case of crossover / crossunder of MACD
////////////////////////////////////////////////////////////////////////////////////////

//@version=5
indicator("MACD HTF - Dynamic Smoothing", "MACD HTF", overlay = false)

//////////////////////////////////////////////////////
//////////         Input MACD HTF         ////////////
//////////////////////////////////////////////////////
MACD_settings = "Higher Time Frame MACD Settings"
MA_Type  = input.string(defval="EMA" , options=["EMA","DEMA","TEMA","SMA","WMA", "HMA"], title="MA type", inline = "1", group = MACD_settings)
TimeFrame_MACD = input.timeframe(title='Higher Time Frame', defval='240', inline = "1", group = MACD_settings)
fastlength = input.int(12, title="Fast MA Length", minval=1, inline = "2", group = MACD_settings)
slowlength = input.int(26, title="Slow MA Length", minval=1, inline = "2", group = MACD_settings)
signallength = input.int(9, title="Length Signal MA", minval=1, inline = "3", group = MACD_settings)
Plot_Signal = input.bool(true, title = "Plot Signal?", inline = "3", group = MACD_settings)

ma(type, src, length) =>
    float result = 0
    if type == 'TMA' // Triangular Moving Average
        result := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
        result
    if type == 'LSMA' // Least Squares Moving Average
        result := ta.linreg(src, length, 0)
        result
    if type == 'SMA'  // Simple Moving Average
        result := ta.sma(src, length)
        result
    if type == 'EMA'  // Exponential Moving Average
        result := ta.ema(src, length)
        result
    if type == 'DEMA'  // Double Exponential Moving Average
        e = ta.ema(src, length)
        result := 2 * e - ta.ema(e, length)
        result
    if type == 'TEMA'  // Triple Exponentiale
        e = ta.ema(src, length)
        result := 3 * (e - ta.ema(e, length)) + ta.ema(ta.ema(e, length), length)
        result
    if type == 'WMA'  // Weighted Moving Average
        result := ta.wma(src, length)
        result
    if type == 'HMA'  // Hull Moving Average
        result := ta.wma(2 * ta.wma(src, length / 2) - ta.wma(src, length), math.round(math.sqrt(length)))
        result
    result

// MACD function for calculation higher timeframe
macd_function() =>
    fast_ma = ma(MA_Type, close, fastlength)
    slow_ma = ma(MA_Type, close, slowlength)
    macd = fast_ma - slow_ma
    macd
    
signal_function() =>
    fast_ma = ma(MA_Type, close, fastlength)
    slow_ma = ma(MA_Type, close, slowlength)
    macd = fast_ma - slow_ma
    signal = ma(MA_Type, macd, signallength)
    signal

hist_function() =>
    fast_ma = ma(MA_Type, close, fastlength)
    slow_ma = ma(MA_Type, close, slowlength)
    macd = fast_ma - slow_ma
    signal = ma(MA_Type, macd, signallength)
    hist = macd - signal
    hist

MACD_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, macd_function())
SIGNAL_Value_HTF = request.security(syminfo.ticker, TimeFrame_MACD, signal_function())
HIST_Value_HTF = MACD_Value_HTF - SIGNAL_Value_HTF

// Get minutes for current and higher timeframes
// Function to convert a timeframe string to its equivalent in minutes
timeframeToMinutes(tf) =>
    multiplier = 1
    if (str.endswith(tf, "D"))
        multiplier := 1440
    else if (str.endswith(tf, "W"))
        multiplier := 10080
    else if (str.endswith(tf, "M"))
        multiplier := 43200
    else if (str.endswith(tf, "H"))
        multiplier := int(str.tonumber(str.replace(tf, "H", "")))
    else
        multiplier := int(str.tonumber(str.replace(tf, "m", "")))
    multiplier

// Get minutes for current and higher timeframes
currentTFMinutes = timeframeToMinutes(timeframe.period)
higherTFMinutes = timeframeToMinutes(TimeFrame_MACD)

// Calculate the smoothing factor
dynamicSmoothing = math.round(higherTFMinutes / currentTFMinutes)
MACD_Value_HTF_Smooth = ta.sma(MACD_Value_HTF, dynamicSmoothing)
SIGNAL_Value_HTF_Smooth = ta.sma(SIGNAL_Value_HTF, dynamicSmoothing)
HIST_Value_HTF_Smooth = ta.sma(HIST_Value_HTF, dynamicSmoothing)

// Determin Long and Short Conditions
LongCondition = ta.crossover(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth < 0
ShortCondition = ta.crossunder(MACD_Value_HTF_Smooth, SIGNAL_Value_HTF_Smooth) and MACD_Value_HTF_Smooth > 0

/////////////////////////////////////////////////
///////////         Plots        ////////////////
/////////////////////////////////////////////////
hline(0, "Zero Line", color=color.new(#787B86, 50))
plot(HIST_Value_HTF_Smooth, title="Histogram", style=plot.style_columns, color=(HIST_Value_HTF_Smooth>=0 ? (HIST_Value_HTF_Smooth[1] < HIST_Value_HTF_Smooth ? color.rgb(0, 255, 8) : color.rgb(0, 100, 5)) : (HIST_Value_HTF_Smooth[1] < HIST_Value_HTF_Smooth ? color.rgb(150, 35, 35) : color.rgb(255, 0, 0))))
plot(SIGNAL_Value_HTF_Smooth, title="Signal", color=color.orange)
plot(MACD_Value_HTF_Smooth, title="MACD", color=color.blue)
plot(Plot_Signal ? LongCondition ? MACD_Value_HTF_Smooth : na : na, "Long Condition", style = plot.style_circles, color = color.rgb(0, 255, 8), linewidth = 4)
plot(Plot_Signal ? ShortCondition ? MACD_Value_HTF_Smooth : na : na, "Short Condition", style = plot.style_circles, color = color.rgb(255, 0, 0), linewidth = 4)

//////////////////////////////////////////////////
///////////         Alerts        ////////////////
//////////////////////////////////////////////////
// Alert conditions for Crossover
alertcondition(LongCondition, title="Long Condition MACD", message="MACD Crossover!")
alertcondition(ShortCondition, title="Short Condition MACD", message="MACD Crossunder!")