Indicator · Pine Script v5 · On the chart

HalfTrend

by 0xRadicalEd· code credited to Flapjackcoin

The indicator overlays HalfTrend trend-following lines and ATR channel bands on the main price chart.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code107
Settings6inputs
LicenceNone statedfile: MPL-2.0
Last update8 months ago26 Feb 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

107 lines of Pine Script v5 from pine/Halftrend-EMA-HMA.ps, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Halftrend-EMA-HMA.ps
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Flapjackcoin

//@version=5
indicator('HalfTrend', overlay=true)
amplitude = input(title='Amplitude', defval=6)
channelDeviation = input(title='Channel Deviation', defval=3)
showArrows = input(title='Show Arrows', defval=true)
showChannels = input(title='Show Channels', defval=true)
emaPeriod = input(title='EMA Period', defval=9)  // Add EMA period input

var int trend = 0
var int nextTrend = 0
var float maxLowPrice = nz(low[1], low)
var float minHighPrice = nz(high[1], high)

var float up = 0.0
var float down = 0.0
float atrHigh = 0.0
float atrLow = 0.0
float arrowUp = na
float arrowDown = na

atr2 = ta.atr(100) / 2
dev = channelDeviation * atr2

highPrice = high[math.abs(ta.highestbars(amplitude))]
lowPrice = low[math.abs(ta.lowestbars(amplitude))]
highma = ta.sma(high, amplitude)
lowma = ta.sma(low, amplitude)

emaLine = ta.ema(close, emaPeriod)  // Calculate EMA

if nextTrend == 1
    maxLowPrice := math.max(lowPrice, maxLowPrice)

    if highma < maxLowPrice and close < nz(low[1], low)
        trend := 1
        nextTrend := 0
        minHighPrice := highPrice
        minHighPrice
else
    minHighPrice := math.min(highPrice, minHighPrice)

    if lowma > minHighPrice and close > nz(high[1], high)
        trend := 0
        nextTrend := 1
        maxLowPrice := lowPrice
        maxLowPrice

if trend == 0
    if not na(trend[1]) and trend[1] != 0
        up := na(down[1]) ? down : down[1]
        arrowUp := up - atr2
        arrowUp
    else
        up := na(up[1]) ? maxLowPrice : math.max(maxLowPrice, up[1])
        up
    atrHigh := up + dev
    atrLow := up - dev
    atrLow
else
    if not na(trend[1]) and trend[1] != 1
        down := na(up[1]) ? up : up[1]
        arrowDown := down + atr2
        arrowDown
    else
        down := na(down[1]) ? minHighPrice : math.min(minHighPrice, down[1])
        down
    atrHigh := down + dev
    atrLow := down - dev
    atrLow

ht = trend == 0 ? up : down

var color buyColor = color.blue
var color sellColor = color.red

htColor = trend == 0 ? buyColor : sellColor
htPlot = plot(ht, title='HalfTrend', linewidth=2, color=htColor)

atrHighPlot = plot(showChannels ? atrHigh : na, title='ATR High', style=plot.style_circles, color=color.new(sellColor, 0))
atrLowPlot = plot(showChannels ? atrLow : na, title='ATR Low', style=plot.style_circles, color=color.new(buyColor, 0))

fill(htPlot, atrHighPlot, title='ATR High Ribbon', color=color.new(sellColor, 90))
fill(htPlot, atrLowPlot, title='ATR Low Ribbon', color=color.new(buyColor, 90))

buySignal = not na(arrowUp) and trend == 0 and trend[1] == 1
sellSignal = not na(arrowDown) and trend == 1 and trend[1] == 0

plotshape(showArrows and buySignal ? atrLow : na, title='Arrow Up', style=shape.triangleup, location=location.absolute, size=size.tiny, color=color.new(buyColor, 0))
plotshape(showArrows and sellSignal ? atrHigh : na, title='Arrow Down', style=shape.triangledown, location=location.absolute, size=size.tiny, color=color.new(sellColor, 0))

alertcondition(buySignal, title='Alert: HalfTrend Buy', message='HalfTrend Buy')
alertcondition(sellSignal, title='Alert: HalfTrend Sell', message='HalfTrend Sell')

// Hull Moving Average (HMA) Ribbon based on EMA
lengthHMA = input(9, title="HMA Length")
srcHMA = close
halfLength = (lengthHMA / 2)
ema1 = ta.ema(srcHMA, halfLength)
ema2 = ta.ema(srcHMA, lengthHMA)
diff = 2 * ema1 - ema2
hullMa = (diff)

plot(hullMa, color=color.rgb(11, 159, 144), title="HMA")
plot(emaLine, title='EMA', color=color.new(#fff200, 0))  // Plot EMA line

Overview

HalfTrend calculates trend reversals using high and low price channels over a user-defined amplitude, combined with Average True Range deviation channels. Directional arrows signal trend flips, while filled ribbons display dynamic resistance and support levels around the main trend line. Key settings allow customization of the calculation amplitude, channel deviation multiplier, visual toggles, EMA period, and HMA length.

Details

Published by

0xRadicalEd on GitHub

Code credit

Flapjackcoin, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages, Volatility & bands

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Amplitudeint6amplitude
Channel Deviationint3channelDeviation
Show ArrowsbooltrueshowArrows
Show ChannelsbooltrueshowChannels
EMA Periodint9emaPeriod
HMA Lengthint9lengthHMA
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

318 stars

This indicator plots four customizable moving averages directly on the main price chart using default lengths of 3, 8, 21, and 50 periods. It fills the space between adjacent averages in green or maroon depending on trend alignment. Additionally, it computes B

Indicator v5 Moving averagesTrend
Updated 2 months ago · MIT GitHub repository of Multiple Moving Averages

NVDA Trend Ribbon

by longsurf-ai
277 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated yesterday · MIT GitHub repository of NVDA Trend Ribbon

Bollinger Bands Force

by harryguiacorn
219 stars

This indicator modifies standard Bollinger Bands to measure directional trend force based on line alignment. It calculates a simple moving average basis along with upper and lower volatility bands. When all three lines move upward or downward simultaneously, i

Indicator v5 Volatility & bandsTrend
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Force

Adaptive MA Slope

by capissimo
114 stars

This indicator calculates Kaufman's Adaptive Moving Average (KAMA) on a chosen price source and determines trend direction based on the slope across a configurable lookback window. Signals can be filtered by short-term volatility expansion using ATR comparison

Indicator v4 Moving averagesTrend
Updated 1 year ago · None stated GitHub repository of Adaptive MA Slope

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers