Pine Script策略中Take Profit失效仅触发Stop Loss问题求助
问题:Pine Script v5黄金交叉策略固定金额止盈失效,仅触发止损
我在Pine Script v5编写「黄金交叉」策略时,设置了固定金额的止盈,但策略总是跳过止盈只触发止损,脚本运行无报错。附上代码及图表示例,寻求解决方法。
//@version=5 strategy("Golden cross","GC", overlay = true) ma9 = ta.sma(close,9) ma50 = ta.sma(close,50) prevoiusma50 = ma50[1] < ma50 //plotting Moving averages on chart plot(ma9) plot(ma50,color = color.white) // when 50 ma crosses 200 ma upwards and previous ma level smaller new ma level crossover = ta.crossover(ma9,ma50) and prevoiusma50 plotshape(crossover,"co", color = color.green, text = "buy") //if statment stating strategy set to buy when ma9 crosses ma50 if crossover == true strategy.entry("Enter Long", strategy.long) strategy.exit("Exit Long", from_entry="Enter Long", profit=600) strategy.exit("Exit Long", from_entry="Enter Long", loss=250)

问题原因及解决方法
问题出在你两次调用strategy.exit且使用了相同的ID("Exit Long"),第二次调用会直接覆盖第一次的设置,导致只有止损参数生效,止盈被丢弃。
正确的做法是将止盈和止损参数放在同一个strategy.exit调用中,因为该函数支持同时指定这两个参数:
//@version=5 strategy("Golden cross","GC", overlay = true) ma9 = ta.sma(close,9) ma50 = ta.sma(close,50) prevoiusma50 = ma50[1] < ma50 // 绘制均线 plot(ma9) plot(ma50,color = color.white) // 黄金交叉条件:MA9上穿MA50且MA50呈上升趋势 crossover = ta.crossover(ma9,ma50) and prevoiusma50 plotshape(crossover,"co", color = color.green, text = "买入") // 开仓及同时设置止盈止损 if crossover == true strategy.entry("Enter Long", strategy.long) // 同一exit调用中同时指定止盈和止损金额 strategy.exit("Exit Long", from_entry="Enter Long", profit=600, loss=250)
这样修改后,策略会同时监控止盈和止损条件,不会再出现止盈被忽略的情况。
内容的提问来源于stack exchange,提问作者zessor
相关产品推荐
相关产品推荐

