You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:修复TradingView Pine Script中MACD线颜色切换错误

修复Pine Script中MACD线颜色随涨跌变化的问题

你的代码存在两个核心错误,导致MACD线颜色逻辑完全失效:

  • 错误用输入参数的长度差值(fast_length - slow_length)代替了实际的MACD线数值,这个值是固定常量(比如12-26=-14),根本无法反映MACD线的涨跌
  • 颜色赋值代码位置错误(在MACD数值计算前就调用了未定义的变量),且语法冗余

以下是修复后的完整代码:

indicator(title="Moving Average Convergence Divergence", shorttitle="MACD", timeframe="", timeframe_gaps=true)

fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing",  minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type",  defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])

col_macd = input(#2962FF, "MACD Line  ", group="Color Settings", inline="MACD")
col_signal = input(#FF6D00, "Signal Line  ", group="Color Settings", inline="Signal")
col_grow_above = input(#26A69A, "Above   Grow", group="Histogram", inline="Above")
col_fall_above = input(#B2DFDB, "Fall", group="Histogram", inline="Above")
col_grow_below = input(#FFCDD2, "Below Grow", group="Histogram", inline="Below")
col_fall_below = input(#FF5252, "Fall", group="Histogram", inline="Below")

// 先计算MACD核心数值
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal

// 正确判断MACD线涨跌并赋值颜色
macdlinecolor = if macd > macd[1]
    color.green
else
    color.red

hline(0, "Zero Line", color=color.new(#787B86, 50))
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below)))
plot(macd, title="MACD", color=macdlinecolor)
plot(signal, title="Signal", color=col_signal)

关键修改说明:

  1. 调整代码顺序:把MACD数值计算逻辑移到颜色判断之前,确保判断时macd变量已被正确定义
  2. 修正颜色判断逻辑:直接用计算好的macd(当前K线MACD值)和macd[1](前一根K线MACD值)对比,实现涨绿跌红的效果
  3. 移除冗余代码:删除了错误的macdline = fast_length - slow_length定义,简化了颜色赋值语法

内容的提问来源于stack exchange,提问作者Lewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 17:15:47