如何在Pine Script策略中实现同趋势方向仅发起一次交易
Pine Script同方向单限制策略实现指导
你需要的「止盈/止损触发后不重复开同方向交易」需求,可通过提供的getLastPosSign()函数完美实现,具体修改方案如下:
逻辑规则说明
getLastPosSign()返回值定义:- 1:上一笔已平仓的交易为多单
- -1:上一笔已平仓的交易为空单
- na:无历史平仓记录(策略尚未完成任何一笔交易平仓)
- 开仓限制逻辑:
- 多单信号触发时,仅当无历史平仓记录或上一笔平仓为空单时才执行开多操作
- 空单信号触发时,仅当无历史平仓记录或上一笔平仓为多单时才执行开空操作
- 额外修复原代码bug:原代码中空单止盈止损的出场条件判断错误,
when=strategy.position_size>0仅会在持有多单时触发,已修正为空单对应判断strategy.position_size<0
策略逻辑示意图

完整可运行代码
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © DavydovEV //@version=5 strategy("My Strategy", overlay=true, margin_long=100, margin_short=100) // Input settings SLfixed = input.float(0.5, "Stop loss", minval=0.1, maxval=100, step=0.1) TPfixed = input.float(1, "Take profit", minval=0.1, maxval=100,step=0.1) // 获取上一笔平仓交易的方向 getLastPosSign() => strategy.closedtrades > 0 ? math.sign(strategy.closedtrades.size(strategy.closedtrades-1)) : na lastDir = getLastPosSign() // Long/short condition 添加同方向开单限制 longCondition = ta.sma(close, 14) > ta.sma(close, 28) if (longCondition and (na(lastDir) or lastDir == -1)) strategy.entry("My Long Entry Id", strategy.long) shortCondition = ta.sma(close, 14) < ta.sma(close, 28) if (shortCondition and (na(lastDir) or lastDir == 1)) strategy.entry("My Short Entry Id", strategy.short) longStop = strategy.position_avg_price*(100-SLfixed)/100 longProfit = strategy.position_avg_price*(100+TPfixed)/100 shortStop = strategy.position_avg_price*(100+SLfixed)/100 shortProfit = strategy.position_avg_price*(100-TPfixed)/100 // 修正空单出场的when条件 strategy.exit("Exit","My Long Entry Id", stop=longStop, limit=longProfit, when=strategy.position_size>0) strategy.exit("Exit","My Short Entry Id", stop=shortStop, limit=shortProfit, when=strategy.position_size<0) plot(ta.sma(close, 14), color=color.green) plot(ta.sma(close, 28), color=color.red) plot( getLastPosSign(), style = plot.style_linebr )
内容的提问来源于stack exchange,提问作者Evgeniy Davydov
相关产品推荐
相关产品推荐

