如何让ta.crossunder计算准确?——TradingView策略中ta.crossunder误触发均线交叉平仓信号的问题排查
问题分析与解决方案
嘿,我一眼就看到问题所在了——你代码里的变量名拼写错误了!
咱们来看这段关键代码:
你先定义了短周期均线:
shortMALong=ta.hma(close,ShortMALength)
但在写卖出信号的时候,你用了一个从来没定义过的变量shortMAShort:
LongCrossSell = ta.crossunder(shortMAShort,longMA)
在Pine Script里,引用未定义的变量会导致不可预测的行为——这个shortMAShort的值其实是na(无效值),当ta.crossunder用na和longMA做比较时,根本没法正确判断均线交叉,自然会乱发信号。
两种修正方案
方案1:如果你本来就想用之前定义的shortMALong来判断交叉
直接把变量名改对就行:
// 修正后的卖出信号 LongCrossSell = ta.crossunder(shortMALong, longMA)
方案2:如果你本来想定义另一条更短的均线(比如shortMAShort)
那得先补充这条均线的定义,比如:
// 先添加用户输入和均线计算 ShortMAShortLength = input.int(15, "Short MA (Shorter) Length", minval=1, maxval=300) shortMAShort = ta.hma(close, ShortMAShortLength) // 再用正确的变量计算卖出信号 LongCrossSell = ta.crossunder(shortMAShort, longMA)
调试小技巧
为了确认交叉信号是否正确,你可以把所有用到的均线都画在图表上,直观观察:
plot(shortMALong, color=color.blue, title="Short MA (100)") plot(mediumMA, color=color.purple, title="Medium MA (30)") plot(longMA, color=color.red, title="Long MA (200)") // 如果用了shortMAShort也加上 // plot(shortMAShort, color=color.orange, title="Short MA (15)")
这样你就能直接看到均线什么时候真的交叉,和信号是否对应了。
内容的提问来源于stack exchange,提问作者AwayTravelling
相关产品推荐
相关产品推荐

