TradingView Strategy Tester与PineScript止盈止损设置失效求助
PineScript策略测试器止盈止损未按预期执行问题
问题描述
我是PineScript和TradingView策略测试器的新手,设置止盈止损时遇到异常:
- 多单止盈设为持仓平均开仓价×1.1,止损设为持仓平均开仓价×0.95
- 空单止盈设为持仓平均开仓价×0.9,止损设为持仓平均开仓价×1.05
但策略测试器并未按此规则执行,相关代码如下:
//@version=5 strategy("7", overlay=true) fast=input.int(14,"fast length",minval=2,maxval=200,step=5) slow=input.int(28,"slow length",minval=4,maxval = 400,step = 5) fastma=ta.sma(close,fast) slowma=ta.sma(close,slow) longcon=ta.crossover(fastma,slowma) shortcon=ta.crossunder(fastma,slowma) if(longcon) strategy.entry("Long",strategy.long) strategy.exit("exit","Long",limit=strategy.position_avg_price*1.1,stop=strategy.position_avg_price*0.95) if(shortcon) strategy.entry("Short",strategy.short) strategy.exit("exit","Short",limit=strategy.position_avg_price*0.9,stop=strategy.position_avg_price*1.05)
策略测试器结果未按预期触发止盈止损。
问题原因
核心问题出在调用strategy.exit的时机:在执行strategy.entry的同一根K线,strategy.position_avg_price还未更新为本次开仓的价格,无持仓时该值为0,有历史持仓时则保留上一次的均价。此时计算出的止盈止损价格完全无效,导致订单无法正确触发。
修正方案
将strategy.exit的逻辑与开仓操作分开,放在独立的条件判断中,确保在开仓完成后的下一根K线再计算并设置止盈止损。同时加入订单存在性检查,避免重复创建exit订单。
修正后的代码:
//@version=5 strategy("7", overlay=true) fast=input.int(14,"fast length",minval=2,maxval=200,step=5) slow=input.int(28,"slow length",minval=4,maxval = 400,step = 5) fastma=ta.sma(close,fast) slowma=ta.sma(close,slow) longcon=ta.crossover(fastma,slowma) shortcon=ta.crossunder(fastma,slowma) // 执行多单开仓 if(longcon) strategy.entry("Long", strategy.long) // 执行空单开仓 if(shortcon) strategy.entry("Short", strategy.short) // 为持有多单设置止盈止损(仅当无对应exit订单时执行) if(strategy.position_size > 0 and strategy.exit_id("exit") == na) strategy.exit("exit", "Long", limit=strategy.position_avg_price*1.1, stop=strategy.position_avg_price*0.95) // 为持有空单设置止盈止损(仅当无对应exit订单时执行) if(strategy.position_size < 0 and strategy.exit_id("exit") == na) strategy.exit("exit", "Short", limit=strategy.position_avg_price*0.9, stop=strategy.position_avg_price*1.05)
额外说明
strategy.position_avg_price会在开仓完成后的下一根K线更新为正确的持仓均价,此时计算的止盈止损价格才有效strategy.exit_id("exit") == na用于判断是否已存在对应exit订单,避免重复创建引发异常
内容的提问来源于stack exchange,提问作者LKY
相关产品推荐
相关产品推荐

