You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PineScript策略如何实现多空交替、避免连续两笔同向交易?

PineScript多空交替交易规则实现方案

问题根因

  1. 原有代码中strategy.closedtrades.size()的使用逻辑错误:该函数传入的参数为已平仓交易的索引,返回对应交易的头寸大小(正数代表做多平仓,负数代表做空平仓),原有判断strategy.closedtrades.size(0)>=0无法正确识别上一笔平仓的方向,也没有将限制逻辑加入入场判断条件。
  2. pyramiding=0仅能禁止同方向加仓操作,无法限制平仓后再次开同方向的仓位,因此不满足多空交替的需求。

实现方案

新增变量记录上一笔已平仓交易的方向,将方向限制加入多空入场条件即可实现交替开单的规则,修正后的完整代码如下:

// Davydov Strategy
//@version=5
strategy("Davydov Strategy", overlay=true, pyramiding=0)

// 止损止盈参数配置
SL = input.float(0.5, "Stop loss", minval=0.1, maxval=100, step=0.1)
TP = input.float(1, "Take profit", minval=0.1, maxval=100,step=0.1)

// 多空交替逻辑:记录上一笔平仓交易方向 1=多 -1=空 0=无平仓记录
var last_closed_dir = 0
if strategy.closedtrades > 0
    // 获取最近一笔已平仓交易的方向
    last_closed_dir := strategy.closedtrades.size(strategy.closedtrades - 1) > 0 ? 1 : -1

// 做多条件判断
long_cond = trend_strength > 0 and Greenbar1 and Greenbar2 == 1 and RsiMa2 - 50 and direction < 0 and supertrend
// 加多空交替限制:上一笔不是多单 或 还没有平仓记录
long_allowed = last_closed_dir != 1 or last_closed_dir == 0

if long_cond and long_allowed
    strategy.entry("Long", strategy.long)

// 多单止损止盈
longStop = strategy.position_avg_price*(100-SL)/100
longProfit = strategy.position_avg_price*(100+TP)/100
strategy.exit("Close Long","Long", stop=longStop, limit=longProfit)

// 做空条件判断
short_cond = trend_strength < 0 and Redbar1 and Redbar2 == 1 and RsiMa2 - 50 and direction > 0 and supertrend
// 加多空交替限制:上一笔不是空单 或 还没有平仓记录
short_allowed = last_closed_dir != -1 or last_closed_dir == 0

if short_cond and short_allowed
    strategy.entry("Short", strategy.short)

// 空单止损止盈
shortStop = strategy.position_avg_price*(100+SL)/100
shortProfit = strategy.position_avg_price*(100-TP)/100
strategy.exit("Close Short","Short", stop=shortStop,limit=shortProfit)

补充说明

  • 原有代码中条件判断嵌套的三目运算符逻辑冗余,已经合并为直接的布尔条件判断,逻辑完全一致且可读性更高。
  • 若需要允许首单可以是多或空,保留初始last_closed_dir == 0的判断即可;若需要固定首单方向,可修改该初始判断条件。

内容的提问来源于stack exchange,提问作者Evgeniy Davydov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 18:45:02