Code: Select all
//@version=5
indicator("Hull Moving Average", overlay=true, shorttitle="HMA")
// Input parameters
timeFrame = input.timeframe("", title="Time Frame")
HMAPeriod = input.int(28, minval=2, title="HMA Period")
HMASpeed = input.float(3.0, title="HMA Speed")
colorUp = input.color(color.blue, title="Uptrend Color")
colorDown = input.color(color.red, title="Downtrend Color")
linesVisible = input.bool(false, title="Show Trend Lines")
linesNumber = input.int(5, title="Number of Trend Lines", minval=1)
// Calculations
HalfPeriod = math.floor(HMAPeriod / HMASpeed)
HullPeriod = math.floor(math.sqrt(HMAPeriod))
// Weighted moving average calculation
wma(src, length) =>
ta.wma(src, length)
// HMA Calculation
hma_work = 2 * wma(close, HalfPeriod) - wma(close, HMAPeriod)
hma = wma(hma_work, HullPeriod)
// Trend detection
trend = ta.valuewhen(hma > hma[1], 1, 0) - ta.valuewhen(hma < hma[1], 1, 0)
// Plot HMA
plot(hma, color=(hma > hma[1] ? colorUp : colorDown), linewidth=2, title="HMA")
// Optional: Draw trend lines
if linesVisible
for i = 1 to linesNumber
if na(trend[i])
break
else if trend[i] != trend[i - 1]
line.new(x1=bar_index[i], y1=hma[i], x2=bar_index[i - 1], y2=hma[i - 1],
color=(trend[i] > 0 ? colorUp : colorDown), width=1)
// Alerts
alertcondition(trend > 0 and trend[1] <= 0, title="HMA Uptrend", message="HMA trend changed to up.")
alertcondition(trend < 0 and trend[1] >= 0, title="HMA Downtrend", message="HMA trend changed to down.")