回测无交易信号求助:带止盈止损的单仓位Pine Script策略排查
策略回测无交易信号的排查与修复
你要实现的策略逻辑:交易触发时设置13%止损、26%止盈,同一时间仅持有一个仓位,但添加代码后回测无任何信号,原代码如下:
// Buy when EMA 5 crosses above EMA 13 within 11 bars of a demand zone buy_condition = ta.crossover(ema5, ema13) and ta.barssince(l) <= 11 and strategy.opentrades==0 if buy_condition strategy.entry("Buy", strategy.long) strategy.close("Buy", stop_loss=strategy.position_avg_price * 0.87, take_profit=strategy.position_avg_price * 1.26) // Sell when EMA 5 crosses below EMA 13 within 11 bars of a supply zone sell_condition = ta.crossunder(ema5, ema13) and ta.barssince(h) <= 11 and strategy.opentrades==0 if sell_condition strategy.entry("Sell", strategy.short) strategy.close("Sell", stop_loss=strategy.position_avg_price * 1.13, take_profit=strategy.position_avg_price * 0.74)
无信号的核心原因及修复方案
止损止盈设置方式错误
用strategy.close()在开仓同bar设置止损止盈是无效的——strategy.position_avg_price在开仓bar未完成时,值为na或上一次持仓均价,无法正确计算止损止盈价位。正确做法是用strategy.exit()绑定开仓订单ID,在开仓时直接挂出止损止盈单。未处理
ta.barssince()返回na的情况
如果l(需求区标记)从未触发过,ta.barssince(l)会返回na,此时na <=11的判断结果为false,直接导致buy_condition永远不成立。同理sell_condition也会因h未触发失效,必须先判断ta.barssince()结果非na。冗余的持仓判断(可选保留)
strategy.entry()默认不会重复开仓(除非开启金字塔加仓),strategy.opentrades==0的判断可保留,但需确保逻辑无冲突。
修正后的代码
// 假设ema5、ema13、l、h已提前定义,以下为示例定义(请替换为你的实际逻辑) ema5 = ta.ema(close, 5) ema13 = ta.ema(close, 13) l = ta.low == ta.lowest(low, 20) // 示例需求区标记逻辑 h = ta.high == ta.highest(high, 20) // 示例供给区标记逻辑 // 买入条件:EMA5上穿EMA13,距离最近需求区≤11K线,无持仓 buy_condition = ta.crossover(ema5, ema13) and not na(ta.barssince(l)) and ta.barssince(l) <= 11 and strategy.opentrades == 0 if (buy_condition) strategy.entry("Buy", strategy.long) // 绑定开仓ID,设置13%止损、26%止盈 strategy.exit("Exit Buy", "Buy", stop=strategy.position_avg_price * 0.87, limit=strategy.position_avg_price * 1.26) // 卖出条件:EMA5下穿EMA13,距离最近供给区≤11K线,无持仓 sell_condition = ta.crossunder(ema5, ema13) and not na(ta.barssince(h)) and ta.barssince(h) <= 11 and strategy.opentrades == 0 if (sell_condition) strategy.entry("Sell", strategy.short) // 绑定开仓ID,设置13%止损、26%止盈(空单止损上浮13%,止盈下浮26%) strategy.exit("Exit Sell", "Sell", stop=strategy.position_avg_price * 1.13, limit=strategy.position_avg_price * 0.74)
额外排查点
- 验证
l和h的定义:可以用绘图函数把供需区标记到图表上,确认是否真有触发,比如:plot(l ? low : na, color=color.green, style=style.circles) - 检查策略设置:是否开启了金字塔加仓(默认关闭),滑点、佣金设置一般不会导致无信号,但可确认是否影响触发逻辑
- 回测时间范围:确保回测周期内存在满足EMA交叉+距离供需区11K线内的行情
内容的提问来源于stack exchange,提问作者Jose Santiago
相关产品推荐
相关产品推荐

