TradingView策略入场信号与指标显示不一致问题排查
问题诊断与修复方案
核心错误1:Stochastic指标的D线计算错误
看你代码里Stochastic部分的stod计算:
stod = sma(k, periodD)
这里的k是Stochastic RSI指标的K线值,并非当前Stochastic指标的stok,正确写法应该用Stochastic自身的K线值计算D线:
stod = sma(stok, periodD)
这个错误会导致Stochastic的D线完全偏离预期,直接无法触发正确的交叉信号。
核心错误2:入场条件过于严苛
你的入场要求Stochastic RSI的K叉D和Stochastic的K叉D必须同时发生,两个独立指标的交叉信号同步出现的概率极低,在1小时黄金这类品种上几乎很难遇到,这是你看不到入场信号的主要原因。
如果坚持结合两个指标,可以调整条件为:其中一个指标完成交叉,另一个指标处于偏多状态,比如:
long_entry = crossover(k,d) and (stok > stod) // 或者 long_entry = crossover(stok, stod) and (k > d)
这样既结合了两个指标的多头逻辑,又不会因要求完全同步交叉而错过大部分机会。
其他优化点
止损止盈计算时,strategy.position_avg_price在无持仓时返回na,虽然当前逻辑是持仓后才判断,但可以加上strategy.opentrades > 0的判断,避免潜在计算异常:
if (strategy.opentrades > 0) profitAmount = strategy.position_avg_price + atr * 1.5 profit = close > profitAmount stoplossAmount = strategy.position_avg_price - atr * 1.5 stoploss = close < stoplossAmount
修复后的完整代码
//@version=4 strategy("Stochastic RSI", overlay=true) /// Stochastic RSI smoothK = input(5, "K", minval=1) smoothD = input(8, "D", minval=1) lengthRSI = input(14, "RSI Length", minval=1) lengthStoch = input(14, "Stochastic Length", minval=1) src = input(close, title="RSI Source") rsi1 = rsi(src, lengthRSI) k = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK) d = sma(k, smoothD) /// Stochastic periodK = input(14, title="%K Length", minval=1) smoothKSto = input(7, title="%K Smoothing", minval=1) periodD = input(3, title="%D Smoothing", minval=1) stok = sma(stoch(close, high, low, periodK), smoothKSto) stod = sma(stok, periodD) // 修复此处的错误 atr = atr(5) /// strategy // 调整入场条件,降低严苛度 long_entry = crossover(k,d) and (stok > stod) profitAmount = na stoplossAmount = na profit = false stoploss = false if (strategy.opentrades > 0) profitAmount = strategy.position_avg_price + atr * 1.5 profit = close > profitAmount stoplossAmount = strategy.position_avg_price - atr * 1.5 stoploss = close < stoplossAmount // Enter long trade if (long_entry) strategy.entry("Long", strategy.long) // Exit long trade if (profit or stoploss) strategy.close("Long")
内容的提问来源于stack exchange,提问作者Giovanni Dominoni
相关产品推荐
相关产品推荐

