策略为何在K线收盘时平仓而非实时?如何实现即时止损?
Pine Script v5 实时触发止盈止损的解决办法
你现在的问题出在两点:一是用close做止盈止损的判断条件,即便开了calc_on_every_tick=true,手动判断收盘价的逻辑还是会拖到K线收盘才触发;二是lastEntryPrice的获取在无持仓时会报错,而且手动调用strategy.close不如用平台原生的止盈止损函数可靠。
修改后的完整代码
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ //@version=5 strategy( "My Strategy", overlay=true, calc_on_every_tick=true, currency=currency.USD, default_qty_type=strategy.cash, default_qty_value=10000 ) // 输入EMA参数 emaFast = input.int(title="Fast EMA", defval=10, minval=1, maxval=9999) emaSlow = input.int(title="Slow EMA", defval=20, minval=1, maxval=9999) // 计算两条EMA均线 fastEMA = ta.ema(close, emaFast) slowEMA = ta.ema(close, emaSlow) // 开仓时直接绑定止盈止损 if ta.crossover(fastEMA, slowEMA) strategy.entry("Enter", strategy.long) // 用strategy.exit设置3%止盈、3%止损,价格触及实时触发平仓 strategy.exit("Exit", "Enter", limit=close*1.03, stop=close*0.97)
核心修改说明
- 用
strategy.exit替代手动判断:在开仓的同时调用strategy.exit,绑定开仓订单的ID(这里是"Enter"),设置止盈价(limit)和止损价(stop)。这个函数是平台原生的订单管理工具,会在价格触及目标价的瞬间触发平仓,不用等K线收盘。 - 规避
lastEntryPrice的错误:原代码里没持仓时,strategy.opentrades - 1会变成-1,调用entry_price直接报错。用strategy.exit就绕开了这个问题,无需手动获取开仓价。 - 保留
calc_on_every_tick=true:这个参数必须开着,确保策略每个tick都计算一次,保证止盈止损的实时性。
备选方案(手动判断方式)
如果一定要用手动判断的逻辑,得先加持仓判断,再用实时价格(close在实时bar里就是最新tick价格)触发,修改后的退出代码如下:
// 先确认有持仓再执行判断 if strategy.position_size > 0 lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1) // 用实时最新价判断,不再等收盘价 if close > lastEntryPrice * 1.03 or close < lastEntryPrice * 0.97 strategy.close("Enter", immediately = true)
不过还是更推荐用strategy.exit,原生函数的稳定性和执行效率都更高。
内容的提问来源于stack exchange,提问作者Samuel
相关产品推荐
相关产品推荐

