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

如何在Pine Script中限制日内多空单各1次开仓?

日内多空单各限1次开仓的Pine Script实现方案

核心思路

内置的strategy.risk.max_intraday_filled_orders()无法区分多空方向,因此需要手动实现分方向的日内计数控制:

  • 用ta.change(time("D"))识别新交易日,每日重置多空开仓计数器
  • 定义两个变量分别记录当日已成交的多单、空单次数
  • 在开仓条件中加入计数器判断,仅当对应方向当日未开仓时允许触发

修改后的完整代码

//@version=5
strategy("日内多空各1次开仓策略", overlay=true)

// 日内开仓次数限制配置
var int longTradesToday = 0
var int shortTradesToday = 0

// 每日重置计数器
if ta.change(time("D"))
    longTradesToday := 0
    shortTradesToday := 0

// Take Profit & Stop Loss
stopPercent  = input.float(defval = 1.0, title = "Stop Loss %", step = 0.1) / 100
takePercent =  input.float(defval = 2.0, title = "Take Profit %", step = 0.1) / 100

// 多单止损止盈
LongStop = strategy.position_avg_price * (1 - stopPercent)
LongTakeProfit = strategy.position_avg_price * (1 + takePercent)

// 空单止损止盈(修正原代码逻辑错误)
ShortStop = strategy.position_avg_price * (1 + stopPercent)
ShortTakeProfit = strategy.position_avg_price * (1 - takePercent)

// 多单逻辑
if strategy.position_size > 0
    strategy.exit(id = "Exit Long", stop = LongStop, limit = LongTakeProfit)

// 开仓条件:LongEntry触发 + 当日多单未开仓
if LongEntry and longTradesToday == 0
    // 开仓成功后更新计数
    if strategy.entry(id = "Long", direction = strategy.long)
        longTradesToday := longTradesToday + 1

// 空单逻辑
if strategy.position_size < 0
    strategy.exit(id = "Exit Short", stop = ShortStop, limit = ShortTakeProfit)

// 开仓条件:ShortEntry触发 + 当日空单未开仓
if ShortEntry and shortTradesToday == 0
    // 开仓成功后更新计数
    if strategy.entry(id = "Short", direction = strategy.short)
        shortTradesToday := shortTradesToday + 1

关键细节说明

  • var关键字确保计数器变量不会在每次K线刷新时重置,仅在每日初始化时重置
  • strategy.entry()返回布尔值,指示订单是否成功提交,以此确保只有开仓成功时才更新计数
  • 修正了原代码中空单止损止盈的逻辑错误:空单止损应为价格上涨至成本价上方,止盈为价格下跌至成本价下方

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:20:19