Indicator · Pine Script v5 · On the chart

NSDT HAMA Candles with Bollinger Bands

by alexbibihere

This indicator overlays Bollinger Bands and smoothed HAMA candles directly on the main price chart.

View on GitHub

GitHub stars15on the repository
Pine versionv5runs as is
Lines of code247
Settings20inputs
LicenceApache-2.0
Last update4 months ago20 Jun 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

247 lines of Pine Script v5 from backend_api_python/file/hamaCandle.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

hamaCandle.txt
//@version=5
indicator("NSDT HAMA Candles with Bollinger Bands", overlay=true)

// ===== 布林带部分 =====
// 输入参数
bb_length = input(400, "布林带周期")
bb_mult = input(2.0, "布林带标准差倍数")

// 计算布林带
basis = ta.sma(close, bb_length)
dev = ta.stdev(close, bb_length)
upper = basis + dev * bb_mult
lower = basis - dev * bb_mult

// 绘制布林带
p1 = plot(upper, "上轨", color=color.orange)
p2 = plot(basis, "中轨", color=color.purple)
p3 = plot(lower, "下轨", color=color.red)
fill(p1, p3, color=color.new(color.white, 95), title="布林带区域")

// ===== HAMA蜡烛图部分 =====
// 渐变颜色系统
f_c_gradientAdvDecPro(_source, _center, _steps, _c_bearWeak, _c_bearStrong, _c_bullWeak, _c_bullStrong) =>
    var float _qtyAdvDec = 0.
    var float _maxSteps  = math.max(1, _steps)
    bool  _xUp     = ta.crossover(_source, _center)
    bool  _xDn     = ta.crossunder(_source, _center)
    float _chg     = ta.change(_source)
    bool  _up      = _chg > 0
    bool  _dn      = _chg < 0
    bool  _srcBull = _source > _center
    bool  _srcBear = _source < _center
    _qtyAdvDec :=
      _srcBull ? _xUp ? 1 : _up ? math.min(_maxSteps, _qtyAdvDec + 1) : _dn ? math.max(1, _qtyAdvDec - 1) : _qtyAdvDec :
      _srcBear ? _xDn ? 1 : _dn ? math.min(_maxSteps, _qtyAdvDec + 1) : _up ? math.max(1, _qtyAdvDec - 1) : _qtyAdvDec : _qtyAdvDec
    var color _return = na
    _return :=
      _srcBull ? color.from_gradient(_qtyAdvDec, 1, _maxSteps, _c_bullWeak, _c_bullStrong) :
      _srcBear ? color.from_gradient(_qtyAdvDec, 1, _maxSteps, _c_bearWeak, _c_bearStrong) : _return

// MA计算函数
mat(source, length, type) =>
    switch type
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "RMA" => ta.rma(source, length)
        "WMA" => ta.wma(source, length)
        "HMA" => ta.hma(source, length)
        => na

// HAMA输入参数
bull = input(color.rgb(0, 255, 0), "Bull Color")
bear = input(color.rgb(255, 0, 0), "Bear Color")
neutral = input(color.rgb(255, 255, 0, 0), "Neutral Color")
show_ma = input(true, "显示MA线")
ma_type = input.string("WMA", "MA类型", options=["EMA", "SMA", "WMA"])
ma_source = input(close, "MA源数据")
ma_length = input(100, "MA长度")
UseGradient = input(true, "使用渐变颜色")
stepn = input(5, "最大渐变步数")

// 计算HAMA MA
ma = mat(ma_source, ma_length, ma_type)
col = f_c_gradientAdvDecPro(ma, ta.ema(ma, 3), stepn, neutral, bear, neutral, bull)

// HAMA蜡烛图参数
WickColor = input(color.rgb(80, 80, 80, 100), "Wick Color")
OpenLength = input(45, "开盘价长度")
OpenType = input.string('EMA', '开盘价类型', options=['EMA', 'SMA', 'WMA'])
HighLength = input(20, "最高价长度")
HighType = input.string("EMA", "最高价类型", options=['EMA', 'SMA', 'WMA'])
LowLength = input(20, "最低价长度")
LowType = input.string("EMA", "最低价类型", options=['EMA', 'SMA', 'WMA'])
CloseLength = input(40, "收盘价长度")
CloseType = input.string('WMA', '收盘价类型', options=['EMA', 'SMA', 'WMA'])

// HAMA蜡烛图计算函数
funcCalcOpen(TypeOpen, SourceOpen, LengthOpen) =>
    switch TypeOpen
        'EMA' => ta.ema(SourceOpen, LengthOpen)
        'SMA' => ta.sma(SourceOpen, LengthOpen)
        'WMA' => ta.wma(SourceOpen, LengthOpen)
        => na

funcCalcHigh(TypeHigh, SourceHigh, LengthHigh) =>
    switch TypeHigh
        'EMA' => ta.ema(SourceHigh, LengthHigh)
        'SMA' => ta.sma(SourceHigh, LengthHigh)
        'WMA' => ta.wma(SourceHigh, LengthHigh)
        => na

funcCalcLow(TypeLow, SourceLow, LengthLow) =>
    switch TypeLow
        'EMA' => ta.ema(SourceLow, LengthLow)
        'SMA' => ta.sma(SourceLow, LengthLow)
        'WMA' => ta.wma(SourceLow, LengthLow)
        => na

funcCalcClose(TypeClose, SourceClose, LengthClose) =>
    switch TypeClose
        'EMA' => ta.ema(SourceClose, LengthClose)
        'SMA' => ta.sma(SourceClose, LengthClose)
        'WMA' => ta.wma(SourceClose, LengthClose)
        => na

// 计算HAMA蜡烛图
SourceOpen = (open[1] + close[1]) / 2
SourceHigh = math.max(high, close)
SourceLow = math.min(low, close)
SourceClose = (open + high + low + close) / 4

CandleOpen = funcCalcOpen(OpenType, SourceOpen, OpenLength)
CandleHigh = funcCalcHigh(HighType, SourceHigh, HighLength)
CandleLow = funcCalcLow(LowType, SourceLow, LowLength)
CandleClose = funcCalcClose(CloseType, SourceClose, CloseLength)

// 绘制HAMA蜡烛图
BodyColor = CandleOpen > CandleOpen[1] ? color.green : color.red
plotcandle(CandleOpen, CandleHigh, CandleLow, CandleClose,
           color=UseGradient ? col : BodyColor,
           title="HAMA Candles",
           wickcolor=WickColor,
           bordercolor=na)

// ===== 新增:HAMA蜡烛图与MA线交叉信号 =====
// 计算HAMA蜡烛图与MA线的交叉
hama_cross_up = ta.crossover(CandleClose, ma)  // HAMA蜡烛图上穿MA线
hama_cross_down = ta.crossunder(CandleClose, ma)  // HAMA蜡烛图下穿MA线

// 移除调试信息,修复plotshape参数错误

// 标签创建已移至下方的交叉处理逻辑中
// plotshape(hama_cross_down, title="跌信号", text="跌", style=shape.labelup,
//           location=location.belowbar, color=color.red)
// 绘制HAMA MA线 - 使用条件显示而不是条件plot
ma_color = UseGradient ? col : BodyColor
plot(show_ma ? ma : na, title="HAMA MA Line", color=ma_color, linewidth=2)

// ===== 交易信号和警报 =====
// 布林带交易信号
bb_width = (upper - lower) / basis
bb_squeeze = bb_width < 0.1  // 布林带收缩
bb_expansion = bb_width > 0.15  // 布林带扩张

// 价格位置相对于布林带
price_position = (close - lower) / (upper - lower)

// 警报条件 - 新增HAMA交叉警报
alertcondition(hama_cross_up, "HAMA蜡烛图上穿MA线", "HAMA蜡烛图上穿MA线,显示涨信号")
alertcondition(hama_cross_down, "HAMA蜡烛图下穿MA线", "HAMA蜡烛图下穿MA线,显示跌信号")
alertcondition(ta.crossover(close, upper), "价格突破上轨", "布林带上轨突破")
alertcondition(ta.crossunder(close, lower), "价格跌破下轨", "布林带下轨突破")
alertcondition(bb_squeeze, "布林带收缩", "布林带收缩,可能即将突破")
alertcondition(ta.rising(ma, 2), "HAMA MA上升", "HAMA MA开始上升")
alertcondition(ta.falling(ma, 2), "HAMA MA下降", "HAMA MA开始下降")

// ===== 改进的HAMA状态判断 =====
// 记录最近一次交叉方向和时间
var int last_cross_direction = 0  // 0:无, 1:上穿, -1:下穿
var int last_cross_time = na       // 上次交叉的Unix时间戳
var int last_cross_bar = na        // 上次交叉的K线索引
var string last_cross_signal = "" // 上次交叉的信号类型(涨/跌)

// 确保每次交叉信号都会更新时间
if hama_cross_up or hama_cross_down
    // 记录最新的交叉时间
    last_cross_time := time
    last_cross_bar := bar_index

    if hama_cross_up
        last_cross_direction := 1
        last_cross_signal := "涨"
        label.new(bar_index, ma, "涨",
                  color=color.green,
                  textcolor=color.white,
                  style=label.style_label_down,
                  yloc=yloc.price)
    else
        last_cross_direction := -1
        last_cross_signal := "跌"
        label.new(bar_index, ma, "跌",
                  color=color.red,
                  textcolor=color.white,
                  style=label.style_label_up,
                  yloc=yloc.price)

// 判断当前是否维持趋势
maintain_bullish = last_cross_direction == 1 and CandleClose >= ma
maintain_bearish = last_cross_direction == -1 and CandleClose <= ma

// 可选:添加确认条件(比如价格偏离MA一定幅度)
deviation_pct = math.abs(CandleClose - ma) / ma * 100
min_deviation = 0.1  // 最小偏离0.1%

maintain_bullish := maintain_bullish and deviation_pct >= min_deviation
maintain_bearish := maintain_bearish and deviation_pct >= min_deviation

// ===== 信息显示 - 添加价格字段 =====
var table info_table = table.new(position.bottom_right, 2, 10, bgcolor=color.white, border_width=1)
if barstate.islast
    table.cell(info_table, 0, 0, "价格", text_color=color.black)
    table.cell(info_table, 1, 0, str.tostring(close, "#.##"), text_color=color.black)
    // table.cell(info_table, 0, 1, "价格位置", text_color=color.black)
    // table.cell(info_table, 1, 1, str.tostring(price_position, "#.##%"), text_color=color.black)
    // table.cell(info_table, 0, 2, "布林带宽度", text_color=color.black)
    // table.cell(info_table, 1, 2, str.tostring(bb_width, "#.#####"), text_color=color.black)
    // table.cell(info_table, 0, 3, "上轨", text_color=color.black)
    // table.cell(info_table, 1, 3, str.tostring(upper, "#.##"), text_color=color.black)
    // table.cell(info_table, 0, 4, "中轨", text_color=color.black)
    // table.cell(info_table, 1, 4, str.tostring(basis, "#.##"), text_color=color.black)
    // table.cell(info_table, 0, 5, "下轨", text_color=color.black)
    // table.cell(info_table, 1, 5, str.tostring(lower, "#.##"), text_color=color.black)
    // 新增HAMA相关信息
    table.cell(info_table, 0, 6, "HAMA状态", text_color=color.black)
    hama_status = maintain_bullish ? "上涨趋势" : maintain_bearish ? "下跌趋势" : "盘整"
    hama_status_color = maintain_bullish ? color.green : maintain_bearish ? color.red : color.gray
    table.cell(info_table, 1, 6, hama_status, text_color=hama_status_color)
    table.cell(info_table, 0, 7, "蜡烛/MA", text_color=color.black)
    candle_ma_relation = CandleClose > ma ? "蜡烛在MA上" : CandleClose < ma ? "蜡烛在MA下" : "重合"
    table.cell(info_table, 1, 7, candle_ma_relation, text_color=color.black)
    table.cell(info_table, 0, 8, "状态", text_color=color.black)
    status_text = bb_squeeze ? "收缩" : bb_expansion ? "扩张" : "正常"
    status_color = bb_squeeze ? color.orange : bb_expansion ? color.green : color.gray
    table.cell(info_table, 1, 8, status_text, text_color=status_color)
    // 新增最近交叉信息
    table.cell(info_table, 0, 9, "最近交叉", text_color=color.black)
    if na(last_cross_time)
        table.cell(info_table, 1, 9, "无", text_color=color.gray)
    else
        // 手动计算并格式化时间组件,确保正确显示
        y = year(last_cross_time)
        m = month(last_cross_time)
        d = dayofmonth(last_cross_time)
        h = hour(last_cross_time)
        min = minute(last_cross_time)

        // 确保月份、日期、小时、分钟为两位数
        m_str = m < 10 ? "0" + str.tostring(m) : str.tostring(m)
        d_str = d < 10 ? "0" + str.tostring(d) : str.tostring(d)
        h_str = h < 10 ? "0" + str.tostring(h) : str.tostring(h)
        min_str = min < 10 ? "0" + str.tostring(min) : str.tostring(min)

        // 构建格式化字符串
        time_str = str.tostring(y) + "-" + m_str + "-" + d_str + " " + h_str + ":" + min_str
        cross_info = last_cross_signal + "(" + time_str + ")"
        cross_color = last_cross_signal == "涨" ? color.green : color.red
        table.cell(info_table, 1, 9, cross_info, text_color=cross_color)

Overview

NSDT HAMA Candles with Bollinger Bands calculates standard Bollinger Bands using a simple moving average and standard deviation, alongside custom smoothed open, high, low, and close values. A central moving average features multi-step gradient coloring based on directional changes relative to an exponential moving average. Users can customize band periods, standard deviation multipliers, moving average types, and individual smoothing lengths for candle calculation. Because this script functions as an overlay indicator, it provides visual trend representation without trade execution or strategy logic.

Details

Published by

alexbibihere on GitHub

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Trend, Moving averages, Volatility & bands, Candlestick patterns

Markets

Crypto

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
布林带周期int400bb_length
布林带标准差倍数float2.0bb_mult
Bull Colorcolorcolor.rgb(0, 255, 0)bull
Bear Colorcolorcolor.rgb(255, 0, 0)bear
Neutral Colorcolorcolor.rgb(255, 255, 0, 0)neutral
显示MA线booltrueshow_ma
MA类型stringWMAma_type
MA源数据sourceclosema_source
MA长度int100ma_length
使用渐变颜色booltrueUseGradient
最大渐变步数int5stepn
Wick Colorcolorcolor.rgb(80, 80, 80, 100)WickColor
Show all 20 settings
SettingTypeDefaultVariable
开盘价长度int45OpenLength
开盘价类型stringEMAOpenType
最高价长度int20HighLength
最高价类型stringEMAHighType
最低价长度int20LowLength
最低价类型stringEMALowType
收盘价长度int40CloseLength
收盘价类型stringWMACloseType
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

Calculates adaptive arithmetic candles by blending price data with Kaufman Efficiency Ratio smoothing and a linear regression anchor. It measures trend health using a zero-to-hundred Quality Score derived from market efficiency, regression slope, and normalize

Indicator v6 TrendCandlestick patterns
Updated yesterday · MIT GitHub repository of Adaptive Arithmetic Candles + Quality Score [WavesUnchained]
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

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